Просмотр исходного кода

Merge pull request #2 from gnacho/feat/topology-redesign

feat(topology): rediseño v5 del mapa — chips, distribución FDB, CTs anidados
Nacho 4 месяцев назад
Родитель
Сommit
6762295917

+ 27 - 1
app/public/locales/en/translation.json

@@ -405,7 +405,11 @@
       "summary": "{{online}} clients online · {{peers}} VPN peers · {{links}} active links",
       "title": "Legend",
       "wired": "Wired",
-      "wgTunnel": "WireGuard tunnel"
+      "wgTunnel": "WireGuard tunnel",
+      "wiredLink": "Physical cable (WAN, uplinks, devices)",
+      "wifiUplink": "WiFi uplink (wireless backhaul)",
+      "lldpIdentified": "Identified via LLDP",
+      "inferredSwitch": "Inferred switch or bridge (no IP)"
     },
     "links": {
       "colLink": "Link",
@@ -437,6 +441,28 @@
       "caption": "Band-steering mesh between APs",
       "clients": "{{count}} clients",
       "util": "{{pct}}% util."
+    },
+    "port": "Port",
+    "signal": "Signal",
+    "traffic": "Traffic",
+    "connection": "Connection",
+    "viaInternet": "via Internet → gateway",
+    "peerVia": "VPN · via Internet",
+    "lldpIdentified": "Identified via LLDP: chassis \"{{chassis}}\" · mgmt {{mgmt}} · caps {{caps}} · remote port {{port}}",
+    "dist": {
+      "title": "Switch or bridge",
+      "inferred": "inferred",
+      "noIp": "no IP · not directly queryable",
+      "port": "Gateway port",
+      "macs": "Learned MACs",
+      "fdbNote": "FDB: {{count}} heterogeneous MACs on a single physical port. Probably a switch; we cannot tell for sure without LLDP."
+    },
+    "host": {
+      "hypervisor": "hypervisor"
+    },
+    "ct": {
+      "pill": "CT",
+      "note": "Container on the hypervisor · its traffic rides the host's cable"
     }
   },
   "settings": {

+ 27 - 1
app/public/locales/es/translation.json

@@ -405,7 +405,11 @@
       "summary": "{{online}} clientes online · {{peers}} peers VPN · {{links}} enlaces activos",
       "title": "Leyenda",
       "wired": "Cable",
-      "wgTunnel": "Túnel WireGuard"
+      "wgTunnel": "Túnel WireGuard",
+      "wiredLink": "Cable físico (WAN, uplinks, equipos)",
+      "wifiUplink": "Uplink wifi (backhaul inalámbrico)",
+      "lldpIdentified": "Identificado vía LLDP",
+      "inferredSwitch": "Switch o bridge inferido (sin IP)"
     },
     "links": {
       "colLink": "Enlace",
@@ -437,6 +441,28 @@
       "caption": "Malla de band-steering entre APs",
       "clients": "{{count}} clientes",
       "util": "{{pct}}% util."
+    },
+    "port": "Puerto",
+    "signal": "Señal",
+    "traffic": "Tráfico",
+    "connection": "Conexión",
+    "viaInternet": "vía Internet → gateway",
+    "peerVia": "VPN · vía Internet",
+    "lldpIdentified": "Identificado vía LLDP: chasis \"{{chassis}}\" · mgmt {{mgmt}} · caps {{caps}} · puerto remoto {{port}}",
+    "dist": {
+      "title": "Switch o bridge",
+      "inferred": "inferido",
+      "noIp": "sin IP · no consultable directamente",
+      "port": "Puerto del gateway",
+      "macs": "MACs aprendidas",
+      "fdbNote": "FDB: {{count}} MACs heterogéneas en un solo puerto físico. Probablemente un switch; no podemos afirmarlo sin LLDP."
+    },
+    "host": {
+      "hypervisor": "hipervisor"
+    },
+    "ct": {
+      "pill": "CT",
+      "note": "Contenedor en el hipervisor · su tráfico viaja por el cable del host"
     }
   },
   "settings": {

+ 2 - 0
app/src/components/DeviceRow.tsx

@@ -5,6 +5,7 @@ import {
   Laptop,
   Lightbulb,
   Monitor,
+  Network,
   Server,
   SignalHigh,
   SignalLow,
@@ -36,6 +37,7 @@ export const DEVICE_ICONS: Record<DeviceType, LucideIcon> = {
   camara: Camera,
   altavoz: Speaker,
   servidor: Server,
+  switch: Network,
   desconocido: HelpCircle,
 }
 

+ 47 - 0
app/src/components/topology/LegendCard.tsx

@@ -36,6 +36,32 @@ function RingSample({ color }: { color: string }) {
   )
 }
 
+/** Muestras de enlaces de la topología v5 */
+function LineSample({ color, dash }: { color: string; dash?: string }) {
+  return (
+    <svg width="26" height="8" viewBox="0 0 26 8" aria-hidden="true">
+      <line x1="1" y1="4" x2="25" y2="4" stroke={color} strokeWidth="2" strokeLinecap="round" strokeDasharray={dash} />
+    </svg>
+  )
+}
+
+function LldpSample() {
+  return (
+    <svg width="26" height="14" viewBox="0 0 26 14" aria-hidden="true">
+      <rect x="1" y="1" width="24" height="12" rx="4" fill="none" stroke={COLOR.accent} strokeWidth="1.4" />
+      <text x="13" y="10" textAnchor="middle" fontSize="7" fontWeight="800" fill={COLOR.accent}>L</text>
+    </svg>
+  )
+}
+
+function InferredSample() {
+  return (
+    <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true">
+      <circle cx="8" cy="8" r="6" fill="none" stroke="rgb(var(--text-muted))" strokeWidth="1.4" strokeDasharray="3 3" />
+    </svg>
+  )
+}
+
 /** Muestra de línea dashed WireGuard, auto-animada en loop */
 function WgSample() {
   const reduce = useReducedMotion()
@@ -88,6 +114,27 @@ export function LegendContent({ model, compact = false }: { model: TopologyModel
           </motion.li>
         </ul>
       </div>
+      <div>
+        <div className="mb-2 text-label uppercase text-text-muted">{t('topology.links.title')}</div>
+        <ul className="grid grid-cols-1 gap-x-4 gap-y-2">
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <LineSample color={COLOR.ok} />
+            {t('topology.legend.wiredLink')}
+          </motion.li>
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <LineSample color={COLOR.warn} dash="6 4" />
+            {t('topology.legend.wifiUplink')}
+          </motion.li>
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <LldpSample />
+            {t('topology.legend.lldpIdentified')}
+          </motion.li>
+          <motion.li className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <InferredSample />
+            {t('topology.legend.inferredSwitch')}
+          </motion.li>
+        </ul>
+      </div>
       <div>
         <div className="mb-2 text-label uppercase text-text-muted">{t('routers.colStatus')}</div>
         <ul className="grid grid-cols-3 gap-x-4 gap-y-2">

+ 336 - 192
app/src/components/topology/TopologyMap.tsx

@@ -1,8 +1,10 @@
 /**
- * NetPulse — Mapa SVG animado de la red (topology.md §②).
- * Pan (drag) + zoom (wheel/pinch 0.5×–2×) manipulando el viewBox,
- * flujo de paquetes SMIL, túneles WG dashed violeta, tooltips y
- * coordinación hover con la tabla de enlaces.
+ * NetPulse — Mapa SVG animado de la red (v5, mockup aprobado 2-Ago-2026).
+ * Chips por dispositivo (cable 26px / wifi 24px con badge de banda), nodos de
+ * distribución inferidos del FDB (círculo dashed), CTs anidados bajo su
+ * hipervisor (badge +N), túneles WG trazados peer → Internet, flujo de
+ * paquetes SMIL ∝ Mbps, pan (drag) + zoom (wheel/pinch) sobre el viewBox,
+ * tooltips y coordinación hover con la tabla de enlaces.
  */
 import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import type { PointerEvent as ReactPointerEvent, RefObject } from 'react'
@@ -11,11 +13,12 @@ import { animate, motion, useReducedMotion } from 'framer-motion'
 import { Cloud, Laptop, Router as RouterIcon, Smartphone } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import { relTime } from '@/i18n'
-import type { Router, WanInfo, WGPeer } from '@/data/mock'
+import type { DistributionNode, Router, WanInfo, WGPeer } from '@/data/mock'
 import { StatusPill } from '@/components/StatusPill'
+import { DEVICE_ICONS } from '@/components/DeviceRow'
 import { cn } from '@/lib/utils'
-import type { ClientDot, Cluster, RouterNode, TopoLink, TopologyModel } from './model'
-import { COLOR, VB_H, VB_W, bandColor, statusColor } from './model'
+import type { ChipNode, DistNodeView, RouterNode, TopologyModel } from './model'
+import { COLOR, VB_H, VB_W, bandColor, linkColor, statusColor } from './model'
 
 // ---------------------------------------------------------------------------
 // API imperativa expuesta a la página (botones de zoom del header)
@@ -62,7 +65,8 @@ type TooltipData =
   | { kind: 'router'; id: string; router: Router; x: number; y: number }
   | { kind: 'internet'; id: string; x: number; y: number }
   | { kind: 'peer'; id: string; peer: WGPeer; x: number; y: number }
-  | { kind: 'dot'; id: string; dot: ClientDot; x: number; y: number }
+  | { kind: 'chip'; id: string; chip: ChipNode; x: number; y: number }
+  | { kind: 'dist'; id: string; node: DistributionNode; x: number; y: number }
 
 type TooltipState = TooltipData & { left: number; top: number; below: boolean }
 
@@ -80,7 +84,7 @@ function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; w
   return (
     <div
       className={cn(
-        'pointer-events-none absolute z-20 w-56 -translate-x-1/2 rounded-xl border border-border-strong bg-elevated p-3 shadow-lg',
+        'pointer-events-none absolute z-20 w-60 -translate-x-1/2 rounded-xl border border-border-strong bg-elevated p-3 shadow-lg',
         tip.below ? 'translate-y-[14px]' : '-translate-y-[calc(100%+14px)]',
       )}
       style={{ left: tip.left, top: tip.top }}
@@ -127,7 +131,9 @@ function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; w
             <span className="font-display text-sm font-semibold text-text-primary">{tip.peer.name}</span>
             <StatusPill tone="tunnel" label={t('common.active')} pulse />
           </div>
-          <div className="mt-0.5 font-mono text-caption text-text-muted">{tip.peer.tunnelIp} · wg0</div>
+          <div className="mt-0.5 font-mono text-caption text-text-muted">
+            {tip.peer.tunnelIp} · wg0 · {t('topology.viaInternet')}
+          </div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
             <MiniStat label="Handshake" value={relTime(tip.peer.lastHandshake)} />
             <MiniStat label={t('topology.tunnel')} value="WireGuard" />
@@ -136,22 +142,72 @@ function TooltipCard({ tip, touch, wan }: { tip: TooltipState; touch: boolean; w
           </div>
         </div>
       )}
-      {tip.kind === 'dot' && (
+      {tip.kind === 'chip' && <ChipTooltip chip={tip.chip} touch={touch} />}
+      {tip.kind === 'dist' && (
         <div>
-          <div className="font-display text-sm font-semibold text-text-primary">
-            {tip.dot.device?.name ?? t('topology.connectedClient')}
+          <div className="flex items-center justify-between gap-2">
+            <span className="font-display text-sm font-semibold text-text-primary">{t('topology.dist.title')}</span>
+            <StatusPill tone="muted" label={t('topology.dist.inferred')} />
           </div>
-          <div className="mt-0.5 font-mono text-caption text-text-muted">
-            {tip.dot.device?.ip ?? tip.dot.band}
-            {tip.dot.device ? ` · ${tip.dot.band}` : ''}
-            {tip.dot.device?.signalDbm != null ? ` · ${tip.dot.device.signalDbm} dBm` : ''}
+          <div className="mt-0.5 text-caption text-text-muted">{t('topology.dist.noIp')}</div>
+          <div className="mt-2 grid grid-cols-2 gap-1.5">
+            <MiniStat label={t('topology.dist.port')} value={tip.node.port} />
+            <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
-          {tip.dot.weak && <div className="mt-1 text-caption font-semibold text-warn">{t('topology.weakSignal')}</div>}
-          {tip.dot.device && (
-            <div className="mt-2 text-caption font-semibold text-accent">
-              {touch ? t('topology.tapAgainDevice') : t('topology.clickDevice')}
-            </div>
-          )}
+          <div className="mt-2 text-caption leading-snug text-text-secondary">
+            {t('topology.dist.fdbNote', { count: tip.node.macCount })}
+          </div>
+        </div>
+      )}
+    </div>
+  )
+}
+
+/** Tooltip de un chip de dispositivo (cliente, hub, host hipervisor o CT). */
+function ChipTooltip({ chip, touch }: { chip: ChipNode; touch: boolean }) {
+  const { t } = useTranslation()
+  const d = chip.device
+  return (
+    <div>
+      <div className="flex items-center justify-between gap-2">
+        <span className="font-display text-sm font-semibold text-text-primary">{d.name}</span>
+        <StatusPill
+          tone={chip.isCt ? 'muted' : chip.wired ? 'ok' : chip.weak ? 'warn' : 'ok'}
+          label={chip.isCt ? t('topology.ct.pill') : chip.wired ? t('common.cable') : d.band}
+        />
+      </div>
+      <div className="mt-0.5 font-mono text-caption text-text-muted">
+        {d.manufacturer} · {d.mac}
+      </div>
+      <div className="mt-2 grid grid-cols-2 gap-1.5">
+        <MiniStat label="IP" value={d.ip} />
+        <MiniStat
+          label={chip.wired ? t('topology.port') : t('topology.signal')}
+          value={chip.wired ? (d.port ?? '—') : `${d.signalDbm ?? '—'} dBm`}
+          hot={!chip.wired && chip.weak}
+        />
+        <MiniStat label={t('topology.traffic')} value={`${d.trafficMbps} Mbps`} />
+        <MiniStat label={t('topology.connection')} value={chip.wired ? 'Ethernet' : 'Wi-Fi'} />
+      </div>
+      {d.lldp && (
+        <div className="mt-2 text-caption font-semibold text-accent">
+          {t('topology.lldpIdentified', {
+            chassis: d.lldp.chassis ?? '—',
+            mgmt: d.lldp.mgmt ?? '—',
+            caps: d.lldp.caps ?? '—',
+            port: d.lldp.portDesc ?? '—',
+          })}
+        </div>
+      )}
+      {chip.isCt && (
+        <div className="mt-2 text-caption leading-snug text-text-secondary">{t('topology.ct.note')}</div>
+      )}
+      {!chip.isCt && chip.weak && (
+        <div className="mt-1 text-caption font-semibold text-warn">{t('topology.weakSignal')}</div>
+      )}
+      {!chip.isCt && (
+        <div className="mt-2 text-caption font-semibold text-accent">
+          {touch ? t('topology.tapAgainDevice') : t('topology.clickDevice')}
         </div>
       )}
     </div>
@@ -174,7 +230,7 @@ const PacketDot = memo(function PacketDot({
   color: string
 }) {
   return (
-    <circle r={3} fill={color} opacity={0.95}>
+    <circle r={2.6} fill={color} opacity={0.95}>
       <animateMotion dur={`${dur}s`} begin={`${begin}s`} repeatCount="indefinite">
         <mpath href={`#${pathId}`} />
       </animateMotion>
@@ -225,7 +281,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const navigate = useNavigate()
-  const { clusters, internetNode, links, peerNodes, relatedTo, routerNodes, wan } = model
+  const { chips, ctsByHost, ctCountByHost, distNodes, internetNode, links, peerNodes, relatedTo, routerNodes, wan } = model
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const viewRef = useRef<View>({ ...INITIAL_VIEW })
@@ -408,7 +464,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
     const v = viewRef.current
     // nodos en la zona superior del mapa: tooltip hacia abajo
     const below = data.kind === 'internet' || data.kind === 'peer'
-    const left = clamp(((data.x - v.x) / v.w) * rect.width, 120, rect.width - 120)
+    const left = clamp(((data.x - v.x) / v.w) * rect.width, 130, rect.width - 130)
     const rawTop = ((data.y - v.y) / v.h) * rect.height
     const top = below ? clamp(rawTop, 16, rect.height - 190) : clamp(rawTop, 190, rect.height - 20)
     setTooltip({ ...data, left, top, below })
@@ -476,17 +532,14 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   // delays de la coreografía de montaje (0 si reduced-motion)
   const T = reduce ? 0 : 1
 
-  // ---------------------------------------------------------------------------
-  // Render
-  // ---------------------------------------------------------------------------
-
   const springPop = (delay: number) =>
     reduce
       ? { duration: 0 }
       : { delay, type: 'spring' as const, stiffness: 260, damping: 20 }
 
-  const linkStroke = (link: TopoLink) =>
-    link.kind === 'wg' ? COLOR.tunnel : 'rgb(var(--border-strong))'
+  // ---------------------------------------------------------------------------
+  // Render
+  // ---------------------------------------------------------------------------
 
   return (
     <div
@@ -511,22 +564,40 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
         }}
       >
         <defs>
-          <linearGradient id="topo-wan-grad" x1="0" y1="0" x2="0" y2="1">
-            <stop offset="0%" stopColor={COLOR.accent} stopOpacity="0.9" />
-            <stop offset="100%" stopColor={COLOR.accent} stopOpacity="0.35" />
-          </linearGradient>
           <linearGradient id="topo-gw-grad" x1="0" y1="0" x2="1" y2="1">
             <stop offset="0%" stopColor={COLOR.accent} stopOpacity="0.28" />
             <stop offset="100%" stopColor={COLOR.tunnel} stopOpacity="0.28" />
           </linearGradient>
         </defs>
 
+        {/* ------------------------- Anillos guía wifi ------------------------- */}
+        <g aria-hidden>
+          {routerNodes.map((node) =>
+            (node.id === model.gatewayNode?.id ? [88, 118] : [74, 108]).map((r) => (
+              <circle
+                key={`${node.id}-ring-${r}`}
+                cx={node.x}
+                cy={node.y}
+                r={r}
+                fill="none"
+                stroke="rgb(var(--border-strong))"
+                strokeWidth={1}
+                strokeDasharray="2 6"
+                opacity={0.3}
+              />
+            )),
+          )}
+        </g>
+
         {/* ------------------------- Enlaces ------------------------- */}
         <g>
           {links.map((link, i) => {
             const highlighted = linkHighlighted(link.id)
             const isWg = link.kind === 'wg'
-            const drawDelay = link.kind === 'wan' ? 0.25 : link.kind === 'uplink' ? 0.8 + i * 0.15 : 1.7
+            const isWifiUp = link.kind === 'uplink' && link.wifi
+            const drawDelay = link.kind === 'wan' ? 0.25 : link.kind === 'uplink' ? 0.8 + i * 0.12 : 1.5
+            const stroke = linkColor(link)
+            const baseOpacity = link.kind === 'wired' ? 0.45 : link.kind === 'dist' ? 0.55 : isWifiUp ? 0.8 : link.kind === 'uplink' ? 0.55 : 0.9
             return (
               <g key={link.id}>
                 {/* base */}
@@ -534,11 +605,11 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                   id={`topo-link-${link.id}`}
                   d={link.d}
                   fill="none"
-                  stroke={link.kind === 'wan' ? 'url(#topo-wan-grad)' : linkStroke(link)}
+                  stroke={stroke}
                   strokeWidth={link.width}
                   strokeLinecap="round"
-                  strokeDasharray={isWg ? '7 7' : undefined}
-                  opacity={link.kind === 'cluster' ? 0.5 : 0.9}
+                  strokeDasharray={isWg ? '7 7' : isWifiUp ? '8 6' : undefined}
+                  opacity={baseOpacity}
                   initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}
                   animate={{ pathLength: 1 }}
                   transition={reduce ? { duration: 0 } : { delay: drawDelay * T, duration: 0.4, ease: 'easeOut' }}
@@ -577,7 +648,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                   d={link.d}
                   fill="none"
                   stroke="transparent"
-                  strokeWidth={16}
+                  strokeWidth={link.kind === 'wired' ? 8 : 16}
                   className="cursor-pointer"
                   onPointerEnter={(e) => {
                     if (e.pointerType === 'mouse') onHoverLink(link.id)
@@ -590,7 +661,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             )
           })}
 
-          {/* paquetes animados */}
+          {/* paquetes animados (∝ Mbps, color del enlace) */}
           {showFlow &&
             links
               .filter((l) => l.packets > 0)
@@ -601,7 +672,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                     pathId={`topo-link-${l.id}`}
                     dur={l.packetDur}
                     begin={-((l.packetDur / l.packets) * i)}
-                    color={l.kind === 'wg' ? COLOR.tunnel : COLOR.accent}
+                    color={linkColor(l)}
                   />
                 )),
               )}
@@ -634,31 +705,17 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             transition={reduce ? { duration: 0.2 } : { ...springPop(0), opacity: { duration: 0.2 } }}
             style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
           >
-          {!reduce && (
-            <motion.circle
-              r={48}
-              fill={COLOR.ok}
-              initial={{ opacity: 0.08 }}
-              animate={{ opacity: [0.06, 0.16, 0.06] }}
-              transition={{ duration: 5, repeat: Infinity, ease: 'easeInOut' }}
-            />
-          )}
-          <circle
-            r={40}
-            fill="rgb(var(--elevated))"
-            stroke={COLOR.ok}
-            strokeWidth={2}
-          />
-          <circle
-            r={45}
-            fill="none"
-            stroke={COLOR.ok}
-            strokeWidth={2.5}
-            strokeDasharray={`${(2 * Math.PI * 45) * 0.85} ${(2 * Math.PI * 45) * 0.15}`}
-            strokeLinecap="round"
-            transform="rotate(-90)"
-          />
-          <Cloud x={-18} y={-15} width={36} height={30} className="text-ok" strokeWidth={1.75} aria-hidden />
+            {!reduce && (
+              <motion.circle
+                r={42}
+                fill={COLOR.ok}
+                initial={{ opacity: 0.08 }}
+                animate={{ opacity: [0.05, 0.15, 0.05] }}
+                transition={{ duration: 5, repeat: Infinity, ease: 'easeInOut' }}
+              />
+            )}
+            <circle r={28} fill="rgb(var(--elevated))" stroke={COLOR.ok} strokeWidth={2} />
+            <Cloud x={-12} y={-10} width={24} height={20} className="text-ok" strokeWidth={1.75} aria-hidden />
           </motion.g>
         </g>
 
@@ -699,7 +756,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                 }
               }}
             >
-              {/* halo permanente del gateway / pulso de aviso del Patio */}
+              {/* halo permanente del gateway / pulso de aviso */}
               {isGw && !reduce && (
                 <motion.circle
                   r={node.r + 18}
@@ -747,14 +804,12 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           const PeerIcon = node.peer.type === 'movil' ? Smartphone : Laptop
           return (
             <g key={node.id} transform={`translate(${node.x} ${node.y})`}>
-              {/* entrada escalonada */}
               <motion.g
                 initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.6 }}
                 animate={{ opacity: 1, scale: 1 }}
                 transition={reduce ? { duration: 0 } : { delay: 1.8 * T + i * 0.12, duration: 0.35 }}
                 style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
               >
-                {/* atenuación por hover */}
                 <motion.g
                   className="cursor-pointer outline-none"
                   role="button"
@@ -778,41 +833,55 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                 >
                   {!reduce && (
                     <circle r={22} fill="none" stroke={COLOR.tunnel} strokeWidth={1.5}>
-                      <animate attributeName="r" values="20;30" dur="2.2s" repeatCount="indefinite" />
+                      <animate attributeName="r" values="18;27" dur="2.2s" repeatCount="indefinite" />
                       <animate attributeName="opacity" values="0.5;0" dur="2.2s" repeatCount="indefinite" />
                     </circle>
                   )}
-                  <rect x={-20} y={-20} width={40} height={40} rx={12} fill="rgb(var(--elevated))" stroke={COLOR.tunnel} strokeWidth={1.5} />
-                  <PeerIcon x={-10} y={-10} width={20} height={20} className="text-tunnel" strokeWidth={1.75} aria-hidden />
+                  <rect x={-18} y={-18} width={36} height={36} rx={11} fill="rgb(var(--elevated))" stroke={COLOR.tunnel} strokeWidth={1.5} />
+                  <PeerIcon x={-9} y={-9} width={18} height={18} className="text-tunnel" strokeWidth={1.75} aria-hidden />
                 </motion.g>
               </motion.g>
             </g>
           )
         })}
 
-        {/* ------------------------- Clusters de clientes ------------------------- */}
-        {clusters.map((cluster, ci) => (
-          <ClusterGroup
-            key={cluster.id}
-            cluster={cluster}
-            routerPos={(() => {
-              const rn = routerNodes.find((n) => n.id === cluster.routerId)
-              return rn ? { x: rn.x, y: rn.y } : null
-            })()}
-            baseDelay={(1.4 + ci * 0.15) * T}
+        {/* ------------------------- Nodos de distribución (switch inferido) --- */}
+        {distNodes.map((dv, i) => (
+          <DistNodeGroup
+            key={dv.id}
+            dv={dv}
+            delay={(1.5 + i * 0.1) * T}
             reduce={reduce ?? false}
-            opacity={nodeOpacity(cluster.id) * nodeOpacity(cluster.routerId)}
-            onDotHover={(dot, e) => {
-              if (e.pointerType !== 'mouse') return
-              setHoverNode(cluster.routerId)
-              openTooltip({ kind: 'dot', id: dot.id, dot, x: dot.x, y: dot.y - 10 })
-            }}
-            onDotLeave={closeHover}
-            onDotClick={(dot, e) => {
-              if (moved.current) return
-              const data: TooltipData = { kind: 'dot', id: dot.id, dot, x: dot.x, y: dot.y - 10 }
-              const navTo = dot.device ? `/devices?q=${encodeURIComponent(dot.device.mac ?? dot.device.name)}` : undefined
-              nodeClick(e, data, navTo)
+            opacity={nodeOpacity(dv.id)}
+            onHover={(e) => handleNodeHover({ kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 }, e)}
+            onLeave={closeHover}
+            onClick={(e) => nodeClick(e, { kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 })}
+          />
+        ))}
+
+        {/* ------------------------- Chips de dispositivos ------------------------- */}
+        {chips.map((chip, i) => (
+          <ChipGroup
+            key={chip.id}
+            chip={chip}
+            ctCount={ctCountByHost.get(chip.id) ?? 0}
+            delay={(1.6 + Math.min(i * 0.02, 0.8)) * T}
+            reduce={reduce ?? false}
+            opacity={nodeOpacity(chip.id)}
+            onHover={(e) =>
+              handleNodeHover({ kind: 'chip', id: chip.id, chip, x: chip.x, y: chip.y - chip.size / 2 - 6 }, e)
+            }
+            onLeave={closeHover}
+            onClick={(e) => {
+              if (chip.isCt) {
+                nodeClick(e, { kind: 'chip', id: chip.id, chip, x: chip.x, y: chip.y - chip.size / 2 - 6 })
+                return
+              }
+              nodeClick(
+                e,
+                { kind: 'chip', id: chip.id, chip, x: chip.x, y: chip.y - chip.size / 2 - 6 },
+                `/devices?q=${encodeURIComponent(chip.device.mac ?? chip.device.name)}`,
+              )
             }}
           />
         ))}
@@ -826,23 +895,46 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           aria-hidden={!showLabels}
         >
           {/* Internet */}
-          <LabelText x={internetNode.x} y={internetNode.y + 56} anchor="middle" delay={2.0 * T} reduce={reduce ?? false}
+          <LabelText x={548} y={54} anchor="start" delay={2.0 * T} reduce={reduce ?? false}
             title={`Internet · ${wan.isp}`} sub={t('routerDetail.wan.fiber', { plan: wan.plan })} />
           {/* Gateway */}
           {model.gatewayNode && (
-            <LabelText x={556} y={240} anchor="start" delay={2.05 * T} reduce={reduce ?? false}
-              title={model.gatewayNode.router.name} sub={`${model.gatewayNode.router.modelShort} · ${t('common.clientsCount', { count: model.gatewayNode.router.clients })}`} />
+            <LabelText x={model.gatewayNode.label.x} y={model.gatewayNode.label.y} anchor={model.gatewayNode.label.anchor}
+              delay={2.05 * T} reduce={reduce ?? false}
+              title={model.gatewayNode.router.name}
+              sub={`${model.gatewayNode.router.modelShort} · ${model.gatewayNode.router.roleBadge} · ${t('common.clientsCount', { count: model.gatewayNode.router.clients })}`} />
           )}
           {/* APs */}
-          {routerNodes.slice(1).map((node, i) => (
+          {model.apNodes.map((node, i) => (
             <LabelText key={node.id} x={node.label.x} y={node.label.y} anchor={node.label.anchor}
               delay={(2.1 + i * 0.03) * T} reduce={reduce ?? false}
-              title={node.router.name} sub={t('common.clientsCount', { count: node.router.clients })} />
+              title={node.router.name}
+              sub={node.router.status === 'warn'
+                ? `${t('common.clientsCount', { count: node.router.clients })} · ${t('common.status.warn')}`
+                : t('common.clientsCount', { count: node.router.clients })}
+              subColor={node.router.status === 'warn' ? COLOR.warn : undefined} />
           ))}
+          {/* Distnodes inferidos */}
+          {distNodes.map((dv, i) => (
+            <LabelText key={dv.id} x={dv.x} y={dv.y - 34} anchor="middle" delay={(2.15 + i * 0.03) * T}
+              reduce={reduce ?? false} title={t('topology.dist.title')}
+              sub={`${t('topology.dist.inferred')} · ${dv.node.port}`} />
+          ))}
+          {/* Hosts hipervisores (badge +N ya en el chip; etiqueta con puerto y nº CTs) */}
+          {[...ctsByHost.keys()].map((hostId, i) => {
+            const host = chips.find((c) => c.id === hostId)
+            if (!host) return null
+            return (
+              <LabelText key={hostId} x={host.x} y={host.y - 38} anchor="middle" delay={(2.18 + i * 0.03) * T}
+                reduce={reduce ?? false} title={host.device.name}
+                sub={`${t('topology.host.hypervisor')} · ${host.device.port ?? ''} · ${ctCountByHost.get(hostId) ?? 0} CT`} />
+            )
+          })}
           {/* Peers */}
           {peerNodes.map((node, i) => (
-            <LabelText key={node.id} x={node.x + 28} y={node.y - 2} anchor="start" delay={(2.2 + i * 0.03) * T}
-              reduce={reduce ?? false} title={node.peer.name} sub="VPN" subColor={COLOR.tunnel} />
+            <LabelText key={node.id} x={node.x + (i % 2 ? -26 : 26)} y={node.y - 4} anchor={i % 2 ? 'end' : 'start'}
+              delay={(2.2 + i * 0.03) * T} reduce={reduce ?? false}
+              title={node.peer.name} sub={t('topology.peerVia')} subColor={COLOR.tunnel} />
           ))}
           {/* Etiquetas de enlace */}
           {links
@@ -915,107 +1007,159 @@ function LabelText({
 }
 
 // ---------------------------------------------------------------------------
-// Cluster de clientes
+// Nodo de distribución inferido (círculo dashed, sin IP)
+// ---------------------------------------------------------------------------
+
+const DistNodeGroup = memo(function DistNodeGroup({
+  dv,
+  delay,
+  reduce,
+  opacity,
+  onHover,
+  onLeave,
+  onClick,
+}: {
+  dv: DistNodeView
+  delay: number
+  reduce: boolean
+  opacity: number
+  onHover: (e: ReactPointerEvent) => void
+  onLeave: () => void
+  onClick: (e: { stopPropagation: () => void }) => void
+}) {
+  const { t } = useTranslation()
+  const SwitchIcon = DEVICE_ICONS.switch
+  return (
+    <motion.g
+      transform={`translate(${dv.x} ${dv.y})`}
+      className="cursor-pointer outline-none"
+      role="button"
+      tabIndex={0}
+      aria-label={`${t('topology.dist.title')}, ${t('topology.dist.inferred')}, ${dv.node.port}`}
+      animate={{ opacity }}
+      transition={{ duration: 0.2 }}
+      onPointerEnter={onHover}
+      onPointerLeave={onLeave}
+      onClick={onClick}
+      onKeyDown={(e) => {
+        if (e.key === 'Enter' || e.key === ' ') {
+          e.preventDefault()
+          onClick(e)
+        }
+      }}
+    >
+      <motion.g
+        initial={reduce ? { scale: 1 } : { scale: 0 }}
+        animate={{ scale: 1 }}
+        transition={reduce ? { duration: 0 } : { delay, type: 'spring', stiffness: 260, damping: 20 }}
+        style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
+      >
+        <circle r={dv.r + 5} fill="none" stroke="rgb(var(--text-muted))" strokeWidth={1} strokeDasharray="2 5" opacity={0.6} />
+        <circle r={dv.r} fill="rgb(var(--elevated) / 0.65)" stroke="rgb(var(--text-muted))" strokeWidth={1.5} strokeDasharray="4 4" />
+        <SwitchIcon x={-10} y={-10} width={20} height={20} className="text-text-secondary" strokeWidth={1.75} aria-hidden />
+      </motion.g>
+    </motion.g>
+  )
+})
+
+// ---------------------------------------------------------------------------
+// Chip de dispositivo (cliente wifi/cable, hub, host hipervisor o CT)
 // ---------------------------------------------------------------------------
 
-const ClusterGroup = memo(function ClusterGroup({
-  cluster,
-  routerPos,
-  baseDelay,
+const ChipGroup = memo(function ChipGroup({
+  chip,
+  ctCount,
+  delay,
   reduce,
   opacity,
-  onDotHover,
-  onDotLeave,
-  onDotClick,
+  onHover,
+  onLeave,
+  onClick,
 }: {
-  cluster: Cluster
-  routerPos: { x: number; y: number } | null
-  baseDelay: number
+  chip: ChipNode
+  ctCount: number
+  delay: number
   reduce: boolean
   opacity: number
-  onDotHover: (dot: ClientDot, e: ReactPointerEvent) => void
-  onDotLeave: () => void
-  onDotClick: (dot: ClientDot, e: { stopPropagation: () => void }) => void
+  onHover: (e: ReactPointerEvent) => void
+  onLeave: () => void
+  onClick: (e: { stopPropagation: () => void }) => void
 }) {
+  const d = chip.device
+  const S = chip.size
+  const half = S / 2
+  const Icon = DEVICE_ICONS[d.type] ?? DEVICE_ICONS.desconocido
+  const stroke = d.lldp ? COLOR.accent : chip.wired ? COLOR.ok : 'rgb(var(--border-strong))'
   return (
-    <motion.g animate={{ opacity }} transition={{ duration: 0.2 }}>
-      {/* Cableados: línea desde el router hasta cada dot (wifi va suelto) */}
-      {routerPos &&
-        cluster.dots
-          .filter((dot) => dot.band === 'cable')
-          .map((dot) => (
-            <line
-              key={`${dot.id}-link`}
-              x1={routerPos.x}
-              y1={routerPos.y}
-              x2={dot.x}
-              y2={dot.y}
-              stroke={COLOR.ok}
-              strokeWidth={1}
-              strokeOpacity={0.35}
-            />
-          ))}
-      {cluster.dots.map((dot, i) => (
-        <motion.circle
-          key={dot.id}
-          cx={dot.x}
-          cy={dot.y}
-          r={dot.r ?? 5}
-          fill={bandColor(dot.band, dot.weak)}
+    <motion.g
+      transform={`translate(${chip.x} ${chip.y})`}
+      className="cursor-pointer outline-none"
+      role="button"
+      tabIndex={0}
+      aria-label={`${d.name}, ${chip.wired ? 'cable' : d.band}`}
+      initial={reduce ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0 }}
+      animate={{ opacity, scale: 1 }}
+      transition={reduce ? { duration: 0 } : { delay, type: 'spring', stiffness: 300, damping: 18 }}
+      style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
+      onPointerEnter={onHover}
+      onPointerLeave={onLeave}
+      onClick={onClick}
+      onKeyDown={(e) => {
+        if (e.key === 'Enter' || e.key === ' ') {
+          e.preventDefault()
+          onClick(e)
+        }
+      }}
+    >
+      <rect
+        x={-half}
+        y={-half}
+        width={S}
+        height={S}
+        rx={7}
+        fill="rgb(var(--elevated))"
+        stroke={stroke}
+        strokeWidth={chip.wired ? 1.3 : 1.1}
+      />
+      <Icon
+        x={-7}
+        y={-7}
+        width={14}
+        height={14}
+        style={{ color: chip.wired ? COLOR.ok : 'rgb(var(--text-primary))' }}
+        strokeWidth={1.9}
+        aria-hidden
+      />
+      {/* badge de banda (wifi): esquina inferior derecha */}
+      {!chip.wired && (
+        <circle
+          cx={half - 2}
+          cy={half - 2}
+          r={3.8}
+          fill={bandColor(chip.band, chip.weak)}
           stroke="rgb(var(--canvas))"
-          strokeWidth={1.5}
-          className="cursor-pointer outline-none"
-          role="button"
-          tabIndex={0}
-          aria-label={dot.device ? `${dot.device.name}, ${dot.band}` : `Cliente ${dot.band}`}
-          initial={reduce ? { scale: 1 } : { scale: 0 }}
-          animate={{ scale: 1 }}
-          transition={
-            reduce
-              ? { duration: 0 }
-              : { delay: baseDelay + i * 0.02, type: 'spring', stiffness: 300, damping: 18 }
-          }
-          style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
-          onPointerEnter={(e) => onDotHover(dot, e)}
-          onPointerLeave={onDotLeave}
-          onClick={(e) => onDotClick(dot, e)}
-          onKeyDown={(e) => {
-            if (e.key === 'Enter' || e.key === ' ') {
-              e.preventDefault()
-              onDotClick(dot, e)
-            }
-          }}
-        >
-          <title>{dot.device?.name ?? `Cliente ${dot.band}`}</title>
-        </motion.circle>
-      ))}
-      {cluster.extra > 0 && (
-        <motion.g
-          initial={reduce ? { opacity: 1 } : { opacity: 0 }}
-          animate={{ opacity: 1 }}
-          transition={{ delay: baseDelay + 0.3, duration: reduce ? 0 : 0.3 }}
-        >
-          <rect
-            x={cluster.cx - 17}
-            y={cluster.cy + 56}
-            width={34}
-            height={18}
-            rx={9}
-            fill="rgb(var(--elevated))"
-            stroke="rgb(var(--border-strong))"
-          />
-          <text
-            x={cluster.cx}
-            y={cluster.cy + 69}
-            textAnchor="middle"
-            fontSize={10}
-            fontWeight={600}
-            className="fill-text-secondary font-mono"
-          >
-            +{cluster.extra}
+          strokeWidth={1.4}
+        />
+      )}
+      {/* badge LLDP: esquina superior derecha */}
+      {d.lldp && (
+        <g aria-hidden>
+          <rect x={half - 4} y={-half - 4} width={22} height={10} rx={5} fill="rgb(var(--elevated))" stroke={COLOR.accent} strokeWidth={1} />
+          <text x={half + 7} y={-half + 3.4} textAnchor="middle" fontSize={6.5} fontWeight={800} fill={COLOR.accent} letterSpacing="0.04em">
+            LLDP
           </text>
-        </motion.g>
+        </g>
+      )}
+      {/* badge +N de CTs (host hipervisor) */}
+      {ctCount > 0 && (
+        <g aria-hidden>
+          <circle cx={half + 1} cy={-half - 1} r={8} fill="rgb(var(--elevated))" stroke={COLOR.ok} strokeWidth={1.2} />
+          <text x={half + 1} y={-half + 2} textAnchor="middle" fontSize={8} fontWeight={700} fill={COLOR.ok}>
+            +{ctCount}
+          </text>
+        </g>
       )}
+      <title>{d.name}</title>
     </motion.g>
   )
 })

+ 469 - 129
app/src/components/topology/model.ts

@@ -1,24 +1,33 @@
 /**
- * NetPulse — Modelo del mapa de topología (topology.md §②).
+ * NetPulse — Modelo del mapa de topología (v5, mockup aprobado 2-Ago-2026).
+ *
  * `buildTopologyModel` deriva todo del bundle del DataProvider (mock en demo,
- * API en live). Las posiciones del lienzo son fijas por rol: gateway al
- * centro y hasta 3 APs en las coordenadas canónicas.
+ * API en live). Vocabulario visual:
+ *   - Chip por dispositivo: 26px cable (con puerto FDB) / 24px wifi (badge de
+ *     banda; ámbar si señal débil). Badge "LLDP" si el vecino se anuncia.
+ *   - Verde sólido = cable físico (WAN, uplinks cableados, cableados, CTs);
+ *     discontinuo = inalámbrico (uplink wifi ámbar) o túnel (WG violeta).
+ *   - DistributionNode: puerto con varias MACs en el FDB → OUI heterogéneo =
+ *     "Switch o bridge (inferido)" (círculo dashed); OUI de hipervisor =
+ *     host con badge +N y sus CTs/VMs anidados en grid.
+ *   - Túneles WG trazados peer → Internet (el camino físico real es la nube).
+ * Layout: gateway/APs en coordenadas canónicas; wifi en anillos concéntricos
+ * con arcos prohibidos (uplink, etiqueta, WAN, abanico cableado); cableados
+ * en abanicos por hub; CTs en grid bajo el host.
  */
-import type { Band, Device, Router, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
+import type { Band, Device, DistributionNode, Router, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
 
 /** viewBox del lienzo SVG */
 export const VB_W = 1000
 export const VB_H = 680
 
-export const MAX_CLUSTER_DOTS = 12
-
 // ---------------------------------------------------------------------------
 // Tipos
 // ---------------------------------------------------------------------------
 
 export interface RouterNode {
   kind: 'router'
-  id: string // router id
+  id: string
   router: Router
   x: number
   y: number
@@ -35,44 +44,51 @@ export interface PeerNode {
   y: number
 }
 
-export interface ClientDot {
-  id: string
+/** Chip de un dispositivo cliente (wifi o cableado). */
+export interface ChipNode {
+  kind: 'chip'
+  id: string // device id
+  device: Device
   x: number
   y: number
+  /** lado del chip en px (26 cable, 24/22 wifi según anillo) */
+  size: number
+  wired: boolean
   band: Band
   weak: boolean
-  device?: Device
-  /** radio del dot (menor cuantos más clientes) */
-  r?: number
+  /** hub del que cuelga: router id | distnode id | device id (host/switch) */
+  hubId: string
+  /** CT/VM anidado bajo un hipervisor (grid, sin enlace propio al router) */
+  isCt: boolean
 }
 
-export interface Cluster {
-  id: string // `cluster-${routerId}`
-  routerId: string
-  cx: number
-  cy: number
-  dots: ClientDot[]
-  /** clientes no representados (badge "+N") */
-  extra: number
+/** Vista de un DistributionNode kind=inferred (círculo dashed, sin IP). */
+export interface DistNodeView {
+  kind: 'dist'
+  id: string
+  node: DistributionNode
+  x: number
+  y: number
+  r: number
 }
 
-export type TopoLinkKind = 'wan' | 'uplink' | 'cluster' | 'wg'
+export type TopoLinkKind = 'wan' | 'uplink' | 'wired' | 'dist' | 'wg'
 
 export interface TopoLink {
   id: string
   kind: TopoLinkKind
   d: string
-  /** posición de la etiqueta del enlace */
+  /** uplink inalámbrico (backhaul wifi): dashed ámbar */
+  wifi?: boolean
+  /** posición de la etiqueta del enlace (sin etiqueta si label='') */
   lx: number
   ly: number
   label: string
-  /** grosor ∝ tráfico (2px base, hasta ~5px) */
   width: number
-  /** nº de paquetes animados simultáneos (guardrail ≤14 total) */
+  /** nº de paquetes animados simultáneos (∝ Mbps; guardrail global ≤60) */
   packets: number
   /** duración del viaje del paquete (s); menor = más tráfico */
   packetDur: number
-  /** nodos extremos (para coordinación hover) */
   from: string
   to: string
 }
@@ -97,6 +113,7 @@ export interface TopologyInput {
   devices: Device[]
   wan: WanInfo
   wireguard: WireGuardStats
+  distributionNodes?: DistributionNode[]
 }
 
 export interface TopologyModel {
@@ -105,7 +122,12 @@ export interface TopologyModel {
   routerNodes: RouterNode[]
   internetNode: { id: 'internet'; x: number; y: number }
   peerNodes: PeerNode[]
-  clusters: Cluster[]
+  chips: ChipNode[]
+  distNodes: DistNodeView[]
+  /** CTs/VMs anidados por host hipervisor (hostId → chips en grid) */
+  ctsByHost: Map<string, ChipNode[]>
+  /** nº de CTs por host (badge +N) */
+  ctCountByHost: Map<string, number>
   links: TopoLink[]
   totalPackets: number
   activeLinkCount: number
@@ -141,167 +163,482 @@ export function statusColor(status: Router['status']): string {
   return COLOR.ok
 }
 
+/** Color del enlace según tipo (verde = cable físico; ámbar = uplink wifi). */
+export function linkColor(link: Pick<TopoLink, 'kind' | 'wifi'>): string {
+  if (link.kind === 'wg') return COLOR.tunnel
+  if (link.kind === 'uplink' && link.wifi) return COLOR.warn
+  return COLOR.ok
+}
+
 // ---------------------------------------------------------------------------
-// Coordenadas canónicas del lienzo (gateway centrado + 3 APs + 2 peers VPN)
+// Coordenadas canónicas del lienzo (mockup v5: QA de colisiones hecha)
 // ---------------------------------------------------------------------------
 
-const GATEWAY_COORD = { x: 500, y: 246, r: 40, label: { x: 556, y: 240, anchor: 'start' as const } }
+const GATEWAY_COORD = { x: 500, y: 250, r: 40, label: { x: 446, y: 312, anchor: 'end' as const } }
 const AP_COORDS = [
-  { x: 210, y: 452, r: 32, label: { x: 158, y: 446, anchor: 'end' as const } },
-  { x: 500, y: 478, r: 32, label: { x: 546, y: 472, anchor: 'start' as const } },
-  { x: 790, y: 452, r: 32, label: { x: 836, y: 446, anchor: 'start' as const } },
-]
-const CLUSTER_COORDS = [
-  { cx: 210, cy: 580 },
-  { cx: 500, cy: 606 },
-  { cx: 790, cy: 580 },
+  { x: 195, y: 470, r: 32, label: { x: 124, y: 464, anchor: 'end' as const } },
+  { x: 500, y: 505, r: 32, label: { x: 554, y: 500, anchor: 'start' as const } },
+  { x: 805, y: 470, r: 32, label: { x: 858, y: 464, anchor: 'start' as const } },
 ]
-const GATEWAY_CLUSTER = { cx: 210, cy: 246 }
+const INTERNET_COORD = { x: 500, y: 58 }
 const PEER_COORDS = [
-  { x: 96, y: 120 },
-  { x: 240, y: 56 },
+  { x: 265, y: 26 },
+  { x: 735, y: 26 },
+  { x: 140, y: 26 },
+  { x: 860, y: 26 },
 ]
+/** Uplinks canónicos gateway→AP (cúbicas QA-das en el mockup) */
 const UPLINK_PATHS = [
-  { d: 'M 468 276 C 400 330, 300 380, 224 420', lx: 322, ly: 340, width: 4.5, packets: 3, packetDur: 2.8 },
-  { d: 'M 500 288 C 500 350, 500 390, 500 434', lx: 514, ly: 360, width: 2.5, packets: 2, packetDur: 3.4 },
-  { d: 'M 532 276 C 600 330, 700 380, 776 420', lx: 668, ly: 340, width: 2, packets: 1, packetDur: 4 },
-]
-const CLUSTER_PATHS = [
-  'M 210 492 C 210 516, 210 528, 210 550',
-  'M 500 518 C 500 542, 500 554, 500 576',
-  'M 790 492 C 790 516, 790 528, 790 550',
+  { d: 'M 464 282 C 390 340, 290 400, 224 440', lx: 292, ly: 366 },
+  { d: 'M 500 292 C 500 360, 500 420, 500 468', lx: 514, ly: 418 },
+  { d: 'M 536 282 C 610 340, 710 400, 776 440', lx: 664, ly: 366 },
 ]
+/** Túneles WG canónicos peer→Internet */
 const WG_PATHS = [
-  { d: 'M 120 134 C 240 210, 360 220, 458 236', lx: 268, ly: 200, packetDur: 3 },
-  { d: 'M 264 70 C 360 110, 430 160, 468 210', lx: 356, ly: 122, packetDur: 3.4 },
+  { d: 'M 272 44 C 330 82, 410 94, 474 80', dur: 3 },
+  { d: 'M 728 44 C 670 82, 590 94, 526 80', dur: 3.4 },
+]
+/** Anillos wifi (v5: separados de los nodos; chips no "tocan" el router) */
+const GATEWAY_RINGS = [
+  { r: 88, cap: 5 },
+  { r: 118, cap: 8 },
+]
+const AP_RINGS = [
+  { r: 74, cap: 7 },
+  { r: 108, cap: 13 },
 ]
+/** Abanicos cableados: gateway tiene sector este (switch inferido) y oeste */
+const GW_EAST_FAN: [number, number] = [336, 24] // wrap (a1 < a0)
+const GW_WEST_FAN: [number, number] = [150, 210]
+const AP_WIRED_FAN: [number, number] = [50, 130]
+const DIST_FAN_RADIUS = 82
+const HUB_FAN_RADIUS = 56
+const ROUTER_FAN_RADIUS = 134
+/** Hosts hipervisores del gateway: lejos (su grid de CTs necesita espacio) */
+const HYPERVISOR_FAN_RADIUS = 300
+/** Grid de CTs bajo el host hipervisor */
+const CT_COLS = 5
+const CT_DX = 42
+const CT_DY = 38
+const CT_OFFSET_Y = 56
+
+// ---------------------------------------------------------------------------
+// Utilidades de ángulos y layout (portadas del mockup aprobado)
+// ---------------------------------------------------------------------------
+
+const rad = (d: number) => (d * Math.PI) / 180
+const norm = (a: number) => ((a % 360) + 360) % 360
+const angleTo = (x: number, y: number, tx: number, ty: number) => norm((Math.atan2(ty - y, tx - x) * 180) / Math.PI)
+const pos = (cx: number, cy: number, degA: number, r: number) => ({
+  x: Math.round((cx + r * Math.cos(rad(degA))) * 10) / 10,
+  y: Math.round((cy + r * Math.sin(rad(degA))) * 10) / 10,
+})
+
+/** Arco [±half] alrededor de `center`, como hasta 2 intervalos sin wrap. */
+function arcAround(center: number, half: number): [number, number][] {
+  const s = norm(center - half)
+  const e = norm(center + half)
+  return s <= e ? [[s, e]] : [[s, 360], [0, e]]
+}
+
+/** arcos libres = [0,360) menos exclusiones (intervalos sin wrap) */
+function freeArcs(excludes: [number, number][]): [number, number][] {
+  const ex = excludes
+    .map(([s, e]): [number, number] => [Math.max(0, s), Math.min(360, e)])
+    .filter(([s, e]) => e > s)
+    .sort((a, b) => a[0] - b[0])
+  const free: [number, number][] = []
+  let cur = 0
+  for (const [s, e] of ex) {
+    if (s > cur) free.push([cur, s])
+    cur = Math.max(cur, e)
+  }
+  if (cur < 360) free.push([cur, 360])
+  return free
+}
+
+/** reparte items en anillos concéntricos evitando arcos prohibidos */
+function ringLayout<T extends { x: number; y: number }>(
+  items: T[],
+  node: { x: number; y: number },
+  rings: { r: number; cap: number }[],
+  excludes: [number, number][],
+): void {
+  const free = freeArcs(excludes)
+  const total = free.reduce((a, [s, e]) => a + (e - s), 0)
+  if (total <= 0) return
+  let idx = 0
+  for (const ring of rings) {
+    if (idx >= items.length) break
+    const n = Math.min(ring.cap, items.length - idx)
+    let placed = 0
+    for (let ai = 0; ai < free.length && placed < n; ai++) {
+      const [s, e] = free[ai]
+      let k = Math.min(Math.round((n * (e - s)) / total), n - placed)
+      if (ai === free.length - 1) k = n - placed
+      for (let i = 0; i < k; i++) {
+        const a = s + ((e - s) * (i + 0.5)) / k
+        const p = pos(node.x, node.y, a, ring.r)
+        Object.assign(items[idx++], p)
+        placed++
+      }
+    }
+  }
+}
+
+/** abanico de items en un arco (soporta wrap: a1 < a0) */
+function fanLayout<T extends { x: number; y: number }>(
+  items: T[],
+  node: { x: number; y: number },
+  r: number,
+  a0: number,
+  a1: number,
+): void {
+  if (a1 < a0) a1 += 360
+  const n = items.length
+  items.forEach((d, i) => {
+    const a = a0 + ((a1 - a0) * (n === 1 ? 0.5 : i / (n - 1)))
+    Object.assign(d, pos(node.x, node.y, norm(a), r))
+  })
+}
+
+/** flujo de paquetes ∝ tráfico (mockup: umbrales 35/15/2 Mbps, guardrail 60) */
+function flowFor(mbps: number): { packets: number; packetDur: number } {
+  const packets = mbps >= 35 ? 3 : mbps >= 15 ? 2 : mbps >= 2 ? 1 : 0
+  return { packets, packetDur: Math.max(1.6, 5 - mbps / 12) }
+}
 
 // ---------------------------------------------------------------------------
 // Builder
 // ---------------------------------------------------------------------------
 
-export function buildTopologyModel({ routers, devices, wan, wireguard }: TopologyInput): TopologyModel {
+export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [] }: TopologyInput): TopologyModel {
   const gateway = routers.find((r) => r.roleBadge === 'Principal') ?? routers[0]
   const aps = routers.filter((r) => r.id !== gateway?.id).slice(0, AP_COORDS.length)
 
   const gatewayNode: RouterNode | null = gateway
-    ? { kind: 'router', id: gateway.id, router: gateway, x: GATEWAY_COORD.x, y: GATEWAY_COORD.y, r: GATEWAY_COORD.r, label: GATEWAY_COORD.label }
+    ? { kind: 'router', id: gateway.id, router: gateway, ...GATEWAY_COORD }
     : null
-  const apNodes: RouterNode[] = aps.map((router, i) => ({
-    kind: 'router',
-    id: router.id,
-    router,
-    x: AP_COORDS[i].x,
-    y: AP_COORDS[i].y,
-    r: AP_COORDS[i].r,
-    label: AP_COORDS[i].label,
-  }))
+  const apNodes: RouterNode[] = aps.map((router, i) => ({ kind: 'router', id: router.id, router, ...AP_COORDS[i] }))
   const routerNodes: RouterNode[] = gatewayNode ? [gatewayNode, ...apNodes] : apNodes
+  const routerById = new Map(routerNodes.map((n) => [n.id, n]))
+
+  const internetNode = { id: 'internet' as const, ...INTERNET_COORD }
+
+  const online = devices.filter((d) => d.online)
+  const deviceById = new Map(online.map((d) => [d.id, d]))
+  const distById = new Map(distributionNodes.map((n) => [n.id, n]))
+  /** hub al que cuelga un dispositivo: attachTo (si existe y resuelve) o su router */
+  const hubOf = (d: Device): string => {
+    if (d.attachTo && (routerById.has(d.attachTo) || distById.has(d.attachTo) || deviceById.has(d.attachTo))) {
+      return d.attachTo
+    }
+    return d.routerId
+  }
+  const childrenOf = (hubId: string) => online.filter((d) => hubOf(d) === hubId)
+  const isWired = (d: Device) => d.band === 'cable'
+
+  /** Hubs que son dispositivos con hijos propios (switch gestionado, hipervisor) */
+  const deviceHubs = new Set<string>()
+  for (const d of online) {
+    const h = d.attachTo
+    if (h && deviceById.has(h)) deviceHubs.add(h)
+  }
 
-  const internetNode = { id: 'internet' as const, x: 500, y: 132 }
+  // -- posicionamiento de hubs cableados (distnodes + device-hubs) y anchors --
+  const distNodes: DistNodeView[] = []
+  const anchorPos = new Map<string, { x: number; y: number }>() // hubId → pos
+  const fanArcByRouter = new Map<string, [number, number][]>() // arcos ocupados por cableados (prohibidos para wifi)
+  /** hosts hipervisores (distnode kind=hypervisor con hostDeviceId) */
+  const hypervisorHosts = new Set(
+    distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId!),
+  )
+
+  for (const node of routerNodes) {
+    const isGw = node.id === gatewayNode?.id
+    // Solo los distnodes inferidos son anchors propios (círculo dashed); el
+    // hipervisor se posiciona vía su device host (hub), el distnode solo
+    // aporta metadatos (puerto, macCount).
+    const dists = distributionNodes.filter((n) => n.routerId === node.id && n.kind === 'inferred')
+    const directWired = childrenOf(node.id).filter(isWired)
+    const hubs = directWired.filter((d) => deviceHubs.has(d.id))
+    const plain = directWired.filter((d) => !deviceHubs.has(d.id))
+
+    // Anchors: todo cuelga de abanicos; gateway separa este/oeste
+    const anchors: { id: string; kind: 'dist' | 'hub' | 'dev'; ref: DistributionNode | Device }[] = [
+      ...dists.map((n) => ({ id: n.id, kind: 'dist' as const, ref: n })),
+      ...hubs.map((d) => ({ id: d.id, kind: 'hub' as const, ref: d })),
+      ...plain.map((d) => ({ id: d.id, kind: 'dev' as const, ref: d })),
+    ]
+    if (anchors.length === 0) continue
+
+    const placed: { id: string; kind: 'dist' | 'hub' | 'dev'; ref: DistributionNode | Device; x: number; y: number }[] = []
+    if (isGw) {
+      // distnodes (switch inferido) al ESTE r134; hosts hipervisores al OESTE
+      // r300 (su grid de CTs necesita espacio, mockup: pve a ~310px); resto OESTE r134
+      const east = anchors.filter((a) => a.kind === 'dist')
+      const farWest = anchors.filter((a) => a.kind === 'hub' && hypervisorHosts.has(a.id))
+      const west = anchors.filter((a) => a.kind !== 'dist' && !farWest.includes(a))
+      const eastItems = east.map((a) => ({ ...a, x: 0, y: 0 }))
+      const farWestItems = farWest.map((a) => ({ ...a, x: 0, y: 0 }))
+      const westItems = west.map((a) => ({ ...a, x: 0, y: 0 }))
+      fanLayout(eastItems, node, ROUTER_FAN_RADIUS, GW_EAST_FAN[0], GW_EAST_FAN[1])
+      fanLayout(farWestItems, node, HYPERVISOR_FAN_RADIUS, 160, 200)
+      fanLayout(westItems, node, ROUTER_FAN_RADIUS, GW_WEST_FAN[0], GW_WEST_FAN[1])
+      placed.push(...eastItems, ...farWestItems, ...westItems)
+      fanArcByRouter.set(node.id, [...arcAround(0, 26), [GW_WEST_FAN[0] - 8, GW_WEST_FAN[1] + 8]])
+    } else {
+      const items = anchors.map((a) => ({ ...a, x: 0, y: 0 }))
+      fanLayout(items, node, ROUTER_FAN_RADIUS, AP_WIRED_FAN[0], AP_WIRED_FAN[1])
+      placed.push(...items)
+      fanArcByRouter.set(node.id, [[AP_WIRED_FAN[0] - 8, AP_WIRED_FAN[1] + 8]])
+    }
 
+    for (const p of placed) {
+      anchorPos.set(p.id, { x: p.x, y: p.y })
+      if (p.kind === 'dist') {
+        const dn = p.ref as DistributionNode
+        distNodes.push({ kind: 'dist', id: dn.id, node: dn, x: p.x, y: p.y, r: 20 })
+      }
+    }
+  }
+
+  // -- chips de dispositivos --------------------------------------------------
+  const chips: ChipNode[] = []
+  const mkChip = (d: Device, hubId: string, isCt = false): ChipNode => ({
+    kind: 'chip',
+    id: d.id,
+    device: d,
+    x: 0,
+    y: 0,
+    size: isWired(d) ? 26 : 24,
+    wired: isWired(d),
+    band: d.band,
+    weak: d.signalDbm != null && d.signalDbm <= -65,
+    hubId,
+    isCt,
+  })
+
+  // wifi: anillos con arcos prohibidos (uplink, etiqueta, WAN, fan cableado)
+  for (const node of routerNodes) {
+    const isGw = node.id === gatewayNode?.id
+    const wifi = childrenOf(node.id).filter((d) => !isWired(d)).map((d) => mkChip(d, node.id))
+    if (wifi.length === 0) continue
+    const excludes: [number, number][] = []
+    if (isGw) {
+      excludes.push(...arcAround(270, 14)) // WAN hacia Internet
+      if (gatewayNode) excludes.push(...arcAround(angleTo(gatewayNode.x, gatewayNode.y, gatewayNode.label.x, gatewayNode.label.y), 22))
+      for (const ap of apNodes) excludes.push(...arcAround(angleTo(node.x, node.y, ap.x, ap.y), 15))
+    } else {
+      if (gatewayNode) excludes.push(...arcAround(angleTo(node.x, node.y, gatewayNode.x, gatewayNode.y), 27))
+      excludes.push(...arcAround(angleTo(node.x, node.y, node.label.x, node.label.y), 22))
+    }
+    excludes.push(...(fanArcByRouter.get(node.id) ?? []))
+    const baseRings = isGw ? GATEWAY_RINGS : AP_RINGS
+    // anillos extra si el wifi supera el aforo de los dos primeros
+    const rings = [...baseRings]
+    let cap = rings.reduce((a, r) => a + r.cap, 0)
+    while (cap < wifi.length) {
+      const last = rings[rings.length - 1]
+      rings.push({ r: last.r + 30, cap: last.cap + 5 })
+      cap = rings.reduce((a, r) => a + r.cap, 0)
+    }
+    ringLayout(wifi, node, rings, excludes)
+    // chips algo menores en anillos externos
+    wifi.forEach((c, i) => {
+      if (i >= baseRings[0].cap) c.size = 22
+    })
+    chips.push(...wifi)
+  }
+
+  // cableados directos del router: ya tienen anchorPos
+  for (const node of routerNodes) {
+    for (const d of childrenOf(node.id).filter(isWired)) {
+      if (deviceHubs.has(d.id)) continue // el hub se renderiza como chip con hijos
+      const p = anchorPos.get(d.id)
+      if (!p) continue
+      const c = mkChip(d, node.id)
+      Object.assign(c, p)
+      chips.push(c)
+    }
+  }
+
+  // hijos de device-hubs (switch gestionado): abanico alrededor del hub
+  const hubChips: ChipNode[] = []
+  for (const hubId of deviceHubs) {
+    const hubDev = deviceById.get(hubId)
+    if (!hubDev) continue
+    const parentHub = hubOf(hubDev)
+    const p = anchorPos.get(hubId)
+    if (!p) continue
+    const hc = mkChip(hubDev, parentHub)
+    Object.assign(hc, p)
+    hubChips.push(hc)
+    const kids = childrenOf(hubId).map((d) => mkChip(d, hubId))
+    const center = angleTo(routerById.get(parentHub)?.x ?? p.x, routerById.get(parentHub)?.y ?? p.y, p.x, p.y)
+    fanLayout(kids, p, HUB_FAN_RADIUS, center - 45, center + 45)
+    chips.push(...kids)
+  }
+  chips.push(...hubChips)
+
+  // hijos de distnodes inferidos: abanico alrededor del círculo dashed
+  for (const dv of distNodes) {
+    const kids = childrenOf(dv.id).map((d) => mkChip(d, dv.id))
+    const rn = routerById.get(dv.node.routerId)
+    const center = rn ? angleTo(rn.x, rn.y, dv.x, dv.y) : 0
+    fanLayout(kids, dv, DIST_FAN_RADIUS, center - 68, center + 68)
+    chips.push(...kids)
+  }
+
+  // CTs de hipervisores: grid bajo el host (badge +N en el chip del host)
+  const ctsByHost = new Map<string, ChipNode[]>()
+  const ctCountByHost = new Map<string, number>()
+  for (const dn of distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId)) {
+    const hostId = dn.hostDeviceId!
+    const hostChip = chips.find((c) => c.id === hostId)
+    const kids = childrenOf(hostId).map((d) => mkChip(d, hostId, true))
+    if (!hostChip || kids.length === 0) continue
+    kids.forEach((c, i) => {
+      c.x = hostChip.x - ((Math.min(kids.length, CT_COLS) - 1) * CT_DX) / 2 + (i % CT_COLS) * CT_DX
+      c.y = hostChip.y + CT_OFFSET_Y + Math.floor(i / CT_COLS) * CT_DY
+      c.size = 22
+    })
+    ctsByHost.set(hostId, kids)
+    ctCountByHost.set(hostId, kids.length)
+    chips.push(...kids)
+  }
+
+  // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------
   const activePeers = wireguard.peers.filter((p) => p.active)
   const peerNodes: PeerNode[] = activePeers.slice(0, PEER_COORDS.length).map((peer, i) => ({
     kind: 'peer',
     id: `peer-${peer.id}`,
     peer,
-    x: PEER_COORDS[i].x,
-    y: PEER_COORDS[i].y,
+    ...PEER_COORDS[i],
   }))
 
-  // Clusters de clientes: UN DOT POR CLIENTE (sin cap), tamaño según densidad
-  const mkCluster = (node: RouterNode, cx: number, cy: number): Cluster => {
-    const named = devices.filter((d) => d.routerId === node.id && d.online)
-    const count = named.length
-    const dotR = count <= 8 ? 6 : count <= 16 ? 5 : count <= 30 ? 4 : 3
-    const dots: ClientDot[] = named.map((device, j) => {
-      // 8 en el anillo interior, el resto en el exterior
-      const inner = j >= 8
-      const idx = inner ? j - 8 : j
-      const n = inner ? Math.max(count - 8, 1) : Math.min(count, 8)
-      const radius = inner ? 26 : 54
-      const angle = (-90 + (360 / n) * idx + (inner ? 20 : 0)) * (Math.PI / 180)
-      const weak = device?.signalDbm != null ? device.signalDbm <= -65 : false
-      return {
-        id: `${node.id}-dot-${j}`,
-        x: Math.round((cx + radius * Math.cos(angle)) * 10) / 10,
-        y: Math.round((cy + radius * Math.sin(angle)) * 10) / 10,
-        band: device?.band ?? 'cable',
-        weak,
-        device,
-        r: dotR,
-      }
-    })
-    return {
-      id: `cluster-${node.id}`,
-      routerId: node.id,
-      cx,
-      cy,
-      dots,
-      extra: 0,
+  // -- tráfico agregado de un sub-árbol (para el flujo ∝ Mbps) ----------------
+  const subtreeTraffic = (hubId: string, seen = new Set<string>()): number => {
+    if (seen.has(hubId)) return 0
+    seen.add(hubId)
+    let sum = 0
+    for (const d of childrenOf(hubId)) {
+      sum += d.trafficMbps + subtreeTraffic(d.id, seen)
     }
+    const dn = distById.get(hubId)
+    if (dn?.kind === 'hypervisor' && dn.hostDeviceId) {
+      const host = deviceById.get(dn.hostDeviceId)
+      if (host) sum += host.trafficMbps
+    }
+    return sum
   }
 
-  const clusters: Cluster[] = apNodes.map((node, i) => {
-    const { cx, cy } = CLUSTER_COORDS[i]
-    return mkCluster(node, cx, cy)
-  })
-  // El gateway también tiene clientes (cable + wifi)
-  if (gatewayNode) {
-    clusters.unshift(mkCluster(gatewayNode, GATEWAY_CLUSTER.cx, GATEWAY_CLUSTER.cy))
-  }
-
-  // Enlaces
+  // -- enlaces -----------------------------------------------------------------
   const links: TopoLink[] = []
   if (gatewayNode) {
     links.push({
       id: 'wan', kind: 'wan',
-      d: 'M 500 164 C 500 178, 500 190, 500 204',
+      d: 'M 500 92 C 500 122, 500 162, 500 208',
       lx: 518, ly: 162, label: `Fibra ${wan.plan} · ${wan.latencyMs} ms`,
-      width: 3, packets: 3, packetDur: 2.4,
+      width: 3, ...flowFor(600),
       from: 'internet', to: gatewayNode.id,
     })
-    // Enlace gateway → su cluster de clientes
-    links.push({
-      id: `cluster-${gatewayNode.id}`, kind: 'cluster',
-      d: `M ${GATEWAY_COORD.x - GATEWAY_COORD.r} ${GATEWAY_COORD.y} L ${GATEWAY_CLUSTER.cx + 46} ${GATEWAY_CLUSTER.cy}`,
-      lx: 0, ly: 0, label: '',
-      width: 1.5, packets: 0, packetDur: 0,
-      from: gatewayNode.id, to: `cluster-${gatewayNode.id}`,
-    })
   }
   apNodes.forEach((node, i) => {
     const p = UPLINK_PATHS[i]
     const isWifi = node.id === 'patio'
+    const traffic = subtreeTraffic(node.id)
     links.push({
-      id: `uplink-${node.id}`, kind: 'uplink',
+      id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
       d: p.d, lx: p.lx, ly: p.ly,
       label: isWifi ? 'WiFi uplink −58 dBm' : 'Cable 1G',
-      width: p.width, packets: p.packets, packetDur: p.packetDur,
+      width: isWifi ? 2 : 3, ...flowFor(Math.max(traffic, isWifi ? 40 : 120)),
       from: gatewayNode?.id ?? 'internet', to: node.id,
     })
+  })
+  // enlaces router → distnode / device-hub / cableado directo
+  for (const dv of distNodes) {
+    const rn = routerById.get(dv.node.routerId)
+    if (!rn) continue
+    const edge = pos(rn.x, rn.y, angleTo(rn.x, rn.y, dv.x, dv.y), rn.r + 2)
+    const mid = { x: (edge.x + dv.x) / 2, y: (edge.y + dv.y) / 2 }
     links.push({
-      id: `cluster-${node.id}`, kind: 'cluster',
-      d: CLUSTER_PATHS[i], lx: 0, ly: 0, label: '',
-      width: 1.5, packets: 0, packetDur: 0,
-      from: node.id, to: `cluster-${node.id}`,
+      id: `dist-${dv.id}`, kind: 'dist',
+      d: `M ${edge.x} ${edge.y} Q ${mid.x + 6} ${mid.y - 6}, ${dv.x} ${dv.y}`,
+      lx: 0, ly: 0, label: '',
+      width: 2.5, ...flowFor(subtreeTraffic(dv.id)),
+      from: dv.node.routerId, to: dv.id,
     })
-  })
+  }
+  const chipById = new Map(chips.map((c) => [c.id, c]))
+  const hubPos = (hubId: string): { x: number; y: number; r: number } | null => {
+    const rn = routerById.get(hubId)
+    if (rn) return { x: rn.x, y: rn.y, r: rn.r }
+    const dv = distNodes.find((n) => n.id === hubId)
+    if (dv) return { x: dv.x, y: dv.y, r: dv.r }
+    const c = chipById.get(hubId)
+    if (c) return { x: c.x, y: c.y, r: c.size / 2 }
+    return null
+  }
+  for (const chip of chips) {
+    if (chip.isCt || !chip.wired) continue // wifi "va suelto" (sin línea); CTs cuelgan del host
+    const hub = hubPos(chip.hubId)
+    if (!hub) continue
+    const a = angleTo(hub.x, hub.y, chip.x, chip.y)
+    const edge = pos(hub.x, hub.y, a, hub.r + 2)
+    const dx = chip.x - edge.x
+    const dy = chip.y - edge.y
+    const c1x = edge.x + dx * 0.5 - dy * 0.1
+    const c1y = edge.y + dy * 0.5 + dx * 0.1
+    const mbps = deviceHubs.has(chip.id) ? chip.device.trafficMbps + subtreeTraffic(chip.id) : chip.device.trafficMbps
+    links.push({
+      id: `wired-${chip.id}`, kind: 'wired',
+      d: `M ${edge.x} ${edge.y} Q ${c1x} ${c1y}, ${chip.x} ${chip.y}`,
+      lx: 0, ly: 0, label: '',
+      width: 1.4, ...flowFor(mbps),
+      from: chip.hubId, to: chip.id,
+    })
+  }
+  // CTs: línea sólida desde el host (su tráfico viaja por el cable del host)
+  for (const [hostId, cts] of ctsByHost) {
+    const hostChip = chipById.get(hostId)
+    if (!hostChip) continue
+    for (const ct of cts) {
+      links.push({
+        id: `wired-${ct.id}`, kind: 'wired',
+        d: `M ${hostChip.x} ${hostChip.y + hostChip.size / 2} L ${ct.x} ${ct.y - ct.size / 2}`,
+        lx: 0, ly: 0, label: '',
+        width: 1.2, ...flowFor(ct.device.trafficMbps),
+        from: hostId, to: ct.id,
+      })
+    }
+  }
   peerNodes.forEach((node, i) => {
-    const p = WG_PATHS[i]
+    const p = WG_PATHS[i] ?? { d: '', dur: 3.2 }
+    const d = p.d || `M ${node.x + 7} ${node.y + 18} C ${node.x + 60} ${node.y + 56}, ${internetNode.x - 40} ${internetNode.y + 36}, ${internetNode.x - 26} ${internetNode.y + 22}`
     links.push({
       id: `wg-${node.peer.id}`, kind: 'wg',
-      d: p.d, lx: p.lx, ly: p.ly, label: 'VPN',
-      width: 2, packets: 1, packetDur: p.packetDur,
-      from: node.id, to: gatewayNode?.id ?? 'internet',
+      d, lx: 0, ly: 0, label: '',
+      width: 2, packets: 1, packetDur: p.dur,
+      from: node.id, to: 'internet',
     })
   })
 
-  /** Guardrail de rendimiento: máx ~14 dots de paquetes simultáneos */
-  const totalPackets = links.reduce((acc, l) => acc + l.packets, 0)
+  /** Guardrail de rendimiento: máx ~60 paquetes simultáneos (mockup) */
+  let totalPackets = links.reduce((acc, l) => acc + l.packets, 0)
+  if (totalPackets > 60) {
+    for (const l of [...links].sort((a, b) => b.packets - a.packets)) {
+      if (totalPackets <= 60) break
+      const cut = Math.min(l.packets - 1, totalPackets - 60)
+      if (cut > 0) {
+        l.packets -= cut
+        totalPackets -= cut
+      }
+    }
+  }
 
-  /** Enlaces activos de la red (WAN + uplinks), sin túneles */
-  const activeLinkCount = links.filter((l) => l.kind === 'wan' || l.kind === 'uplink').length
+  /** Enlaces activos de la red (WAN + uplinks + distribución), sin túneles */
+  const activeLinkCount = links.filter((l) => l.kind === 'wan' || l.kind === 'uplink' || l.kind === 'dist').length
 
   // Tabla de backhauls (topology.md §④)
   const backhauls: BackhaulRow[] = []
@@ -365,7 +702,10 @@ export function buildTopologyModel({ routers, devices, wan, wireguard }: Topolog
     routerNodes,
     internetNode,
     peerNodes,
-    clusters,
+    chips,
+    distNodes,
+    ctsByHost,
+    ctCountByHost,
     links,
     totalPackets,
     activeLinkCount,

+ 6 - 0
app/src/data/DataProvider.tsx

@@ -20,6 +20,7 @@ import type {
   Device,
   DeviceQuery,
   DeviceTotals,
+  DistributionNode,
   HealthScore,
   OverviewBundle,
   Paged,
@@ -34,6 +35,7 @@ import {
   alerts as mockAlerts,
   devices as mockDevices,
   deviceTotals as mockDeviceTotals,
+  distributionNodes as mockDistributionNodes,
   healthScore as mockHealth,
   routers as mockRouters,
   trafficByRange as mockTraffic,
@@ -68,6 +70,7 @@ export interface NetPulseData {
   routers: Router[]
   devices: Device[]
   deviceTotals: DeviceTotals
+  distributionNodes: DistributionNode[]
   topDevices: Device[]
   alerts: AlertEvent[]
   unreadAlerts: number
@@ -98,6 +101,7 @@ function initialBundle(): NetPulseData {
     routers: mockRouters,
     devices: mockDevices,
     deviceTotals: mockDeviceTotals,
+    distributionNodes: mockDistributionNodes,
     topDevices: [...mockDevices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
     alerts: mockAlerts,
     unreadAlerts: mockAlerts.filter((a) => !a.read).length,
@@ -144,6 +148,7 @@ function emptyBundle(): NetPulseData {
     routers: [],
     devices: [],
     deviceTotals: { total: 0, online: 0, knownOffline: 0, newToday: 0 },
+    distributionNodes: [],
     topDevices: [],
     alerts: [],
     unreadAlerts: 0,
@@ -275,6 +280,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       wireguard: o.wireguard,
       routers: o.routers,
       deviceTotals: o.deviceTotals,
+      distributionNodes: o.distributionNodes ?? [],
       topDevices: o.topDevices,
       alerts: o.alerts,
       unreadAlerts: o.unreadAlerts,

+ 94 - 8
app/src/data/mock.ts

@@ -14,6 +14,7 @@ import type {
   AdGuardStats,
   AlertEvent,
   Device,
+  DistributionNode,
   HealthScore,
   Router,
   TimeRange,
@@ -30,7 +31,9 @@ export type {
   Device,
   DeviceTotals,
   DeviceType,
+  DistributionNode,
   HealthScore,
+  LldpInfo,
   PeerType,
   Router,
   Status,
@@ -66,7 +69,7 @@ export const routers: Router[] = [
     ram: 41,
     temp: 54,
     uptime: '32d 14h',
-    clients: 14,
+    clients: 33,
     sparkline: [8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40],
   },
   {
@@ -83,7 +86,7 @@ export const routers: Router[] = [
     ram: 38,
     temp: 47,
     uptime: '32d 14h',
-    clients: 18,
+    clients: 22,
     sparkline: [4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28],
   },
   {
@@ -210,8 +213,8 @@ export const healthScore: HealthScore = {
 // ---------------------------------------------------------------------------
 
 export const deviceTotals = {
-  total: 47,
-  online: 39,
+  total: 67,
+  online: 59,
   knownOffline: 8,
   newToday: 3,
 }
@@ -244,7 +247,7 @@ export const devices: Device[] = [
   {
     id: 'ps5', name: 'PS5', type: 'consola', manufacturer: 'Sony',
     ip: '192.168.8.31', mac: '78:C8:81:0A:6B:D4', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 12.7, online: true,
+    signalDbm: null, trafficMbps: 12.7, online: true, port: 'lan2',
     sparkline: [4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13],
   },
   {
@@ -268,7 +271,7 @@ export const devices: Device[] = [
   {
     id: 'nas-synology', name: 'NAS Synology', type: 'servidor', manufacturer: 'Synology',
     ip: '192.168.8.10', mac: '00:11:32:9C:51:B7', routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: 2.3, online: true,
+    signalDbm: null, trafficMbps: 2.3, online: true, port: 'lan1',
     sparkline: [1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3],
   },
   {
@@ -283,6 +286,89 @@ export const devices: Device[] = [
     signalDbm: -50, trafficMbps: 1.8, online: true, isNew: true,
     sparkline: [0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1.2, 1.6, 1.8],
   },
+
+  // -- Fixtures de topología v5 (mockup aprobado: switch gestionado LLDP, --
+  // -- hipervisor con CTs anidados, switch/bridge inferido vía FDB) ----------
+
+  // Switch gestionado identificado por LLDP + 3 clientes detrás (Salón, lan3)
+  {
+    id: 'switch-netgear', name: 'Switch Netgear', type: 'switch', manufacturer: 'Netgear GS308E',
+    ip: '192.168.8.2', mac: 'D8:B3:70:1A:2B:3C', routerId: 'living', band: 'cable',
+    signalDbm: null, trafficMbps: 3.4, online: true, port: 'lan3',
+    lldp: { chassis: 'GS308E', mgmt: '192.168.8.2', caps: 'Bridge', portDesc: 'ge5' },
+    sparkline: [2, 2.4, 2.8, 3.1, 3.3, 3.6, 3.4, 3.2, 3.4, 3.5, 3.4, 3.4],
+  },
+  {
+    id: 'xbox-series-s', name: 'Xbox Series S', type: 'consola', manufacturer: 'Microsoft',
+    ip: '192.168.8.35', mac: '7C:ED:8D:4A:11:22', routerId: 'living', band: 'cable',
+    signalDbm: null, trafficMbps: 9.8, online: true, attachTo: 'switch-netgear',
+    sparkline: [3, 5, 7, 9, 11, 12, 10, 9, 10, 9, 10, 9.8],
+  },
+  {
+    id: 'apple-tv-4k', name: 'Apple TV 4K', type: 'tv', manufacturer: 'Apple',
+    ip: '192.168.8.36', mac: 'F0:18:98:2B:33:44', routerId: 'living', band: 'cable',
+    signalDbm: null, trafficMbps: 15.2, online: true, attachTo: 'switch-netgear',
+    sparkline: [6, 8, 10, 12, 14, 16, 15, 14, 15, 15, 15, 15.2],
+  },
+  {
+    id: 'receptor-denon', name: 'Receptor Denon', type: 'altavoz', manufacturer: 'Denon',
+    ip: '192.168.8.37', mac: '00:05:CD:55:66:77', routerId: 'living', band: 'cable',
+    signalDbm: null, trafficMbps: 0.6, online: true, attachTo: 'switch-netgear',
+    sparkline: [0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
+  },
+
+  // Hipervisor Proxmox (gateway lan2) + 10 CTs anidados (MACs OUI BC:24:11)
+  {
+    id: 'pve', name: 'Proxmox pve', type: 'servidor', manufacturer: 'Supermicro',
+    ip: '192.168.8.5', mac: '3C:52:82:10:20:30', routerId: 'flint2', band: 'cable',
+    signalDbm: null, trafficMbps: 12.3, online: true, port: 'lan2',
+    sparkline: [8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3],
+  },
+  ...([
+    ['ct-pihole', 'Pi-hole', 'servidor', 8.41, 6.1],
+    ['ct-home-assistant', 'Home Assistant', 'iot', 8.42, 4.2],
+    ['ct-nextcloud', 'Nextcloud', 'servidor', 8.43, 7.8],
+    ['ct-jellyfin', 'Jellyfin', 'servidor', 8.44, 9.4],
+    ['ct-immich', 'Immich', 'servidor', 8.45, 3.3],
+    ['ct-gitea', 'Gitea', 'servidor', 8.46, 1.2],
+    ['ct-uptime-kuma', 'Uptime Kuma', 'iot', 8.47, 0.4],
+    ['ct-adguard-sync', 'AdGuard sync', 'servidor', 8.48, 0.8],
+    ['ct-postgres', 'Postgres', 'servidor', 8.49, 2.1],
+    ['ct-redis', 'Redis', 'servidor', 8.50, 0.9],
+  ] as const).map(([id, name, type, ipSuffix, mbps], i): Device => ({
+    id, name, type: type as Device['type'], manufacturer: 'Proxmox VE (CT)',
+    ip: `192.168.${ipSuffix}`, mac: `BC:24:11:00:2${i}:${(0x10 + i).toString(16).toUpperCase().padStart(2, '0')}`,
+    routerId: 'flint2', band: 'cable', signalDbm: null, trafficMbps: mbps, online: true,
+    attachTo: 'pve',
+    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.1, mbps - 2 + ((i + j) % 5))),
+  })),
+
+  // Tras el switch/bridge inferido (gateway lan3, OUI heterogéneo, sin IP)
+  ...([
+    ['pc-sobremesa', 'PC Desktop', 'ordenador', 'Intel NIC', '78:2B:CB:AA:01:01', 8.60, 18.9],
+    ['tv-salon-cable', 'TV Living (wired)', 'tv', 'Samsung', '8C:EA:48:AA:02:02', 8.61, 24.4],
+    ['impresora-hp', 'HP Printer', 'iot', 'HP', '3C:D9:2B:AA:03:03', 8.62, 0.1],
+    ['raspberry-pi', 'Raspberry Pi', 'servidor', 'Raspberry Pi Ltd', 'DC:A6:32:AA:04:04', 8.63, 1.7],
+    ['xbox-one', 'Xbox One', 'consola', 'Microsoft', '7C:ED:8D:AA:05:05', 8.64, 4.2],
+    ['receptor-av', 'AV Receiver', 'altavoz', 'Denon', '00:05:CD:AA:06:06', 8.65, 0.3],
+    ['deco-orange', 'Orange STB', 'tv', 'Sagemcom', '48:83:B4:AA:07:07', 8.66, 1.1],
+    ['pc-invitado', 'Guest PC', 'ordenador', '—', 'A2:F4:11:AA:08:08', 8.67, 0.8],
+  ] as const).map(([id, name, type, man, mac, ipSuffix, mbps], i): Device => ({
+    id, name, type: type as Device['type'], manufacturer: man,
+    ip: `192.168.${ipSuffix}`, mac, routerId: 'flint2', band: 'cable',
+    signalDbm: null, trafficMbps: mbps, online: true, attachTo: 'dist-flint2-lan3',
+    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.05, mbps - 1.5 + ((i + j) % 4) * 0.5)),
+  })),
+]
+
+// ---------------------------------------------------------------------------
+// Nodos de distribución (topología v5): inferidos del FDB en live; en demo,
+// fixtures equivalentes al mockup aprobado (switch lan3 + hipervisor lan2).
+// ---------------------------------------------------------------------------
+
+export const distributionNodes: DistributionNode[] = [
+  { id: 'dist-flint2-lan3', kind: 'inferred', routerId: 'flint2', port: 'lan3', macCount: 8 },
+  { id: 'dist-pve', kind: 'hypervisor', routerId: 'flint2', port: 'lan2', macCount: 11, hostDeviceId: 'pve', name: 'Proxmox pve' },
 ]
 
 // ---------------------------------------------------------------------------
@@ -298,8 +384,8 @@ export const adguard: AdGuardStats = {
   blockedPct: 18.6,
   trackersBlocked: 9204,
   dnsLatencyMs: 14,
-  clientsUsing: 41,
-  clientsTotal: 47,
+  clientsUsing: 60,
+  clientsTotal: 67,
   topBlocked: [
     { domain: 'graph.facebook.com', count: 1204 },
     { domain: 'adservice.google.com', count: 986 },

+ 46 - 0
app/src/data/types.ts

@@ -118,10 +118,19 @@ export type DeviceType =
   | 'altavoz'
   | 'servidor'
   | 'tablet'
+  | 'switch'
   | 'desconocido'
 
 export type Band = '5 GHz' | '2.4 GHz' | 'cable' | '—'
 
+/** Identificación LLDP de un vecino (switch gestionado, AP, host…). */
+export interface LldpInfo {
+  chassis?: string
+  mgmt?: string
+  caps?: string
+  portDesc?: string
+}
+
 export interface Device {
   id: string
   name: string
@@ -138,6 +147,37 @@ export interface Device {
   online: boolean
   isNew?: boolean
   sparkline: number[]
+  /** Puerto físico del router/switch donde se aprende la MAC (cableados; FDB). */
+  port?: string | null
+  /** Datos LLDP cuando el vecino se anuncia (switch gestionado identificado). */
+  lldp?: LldpInfo | null
+  /**
+   * De qué hub cuelga en el mapa de topología: id de un router (defecto,
+   * = routerId), de un DistributionNode (switch inferido) o de otro Device
+   * (hipervisor / switch gestionado identificado).
+   */
+  attachTo?: string
+}
+
+/**
+ * Nodo de distribución entre un router y varios cableados, inferido del FDB:
+ * un puerto físico con varias MACs aprendidas. `inferred` = OUI heterogéneo
+ * (switch o bridge desconocido, sin IP); `hypervisor` = OUI de hipervisor
+ * (Proxmox/VMware/Hyper-V/KVM) → sus CTs/VMs se anidan bajo el host.
+ */
+export interface DistributionNode {
+  id: string
+  kind: 'inferred' | 'hypervisor'
+  routerId: string
+  /** Puerto físico del router donde cuelga (lan3…). */
+  port: string
+  /** MACs aprendidas en ese puerto (FDB). */
+  macCount: number
+  /** Hypervisor: id del Device host (Proxmox…), si existe como cliente. */
+  hostDeviceId?: string
+  /** Nombre descriptivo (host o futura identificación LLDP). */
+  name?: string
+  lldp?: LldpInfo | null
 }
 
 export type AlertSeverity = 'warn' | 'critical' | 'info' | 'ok'
@@ -177,6 +217,12 @@ export interface OverviewBundle {
   topDevices: Device[]
   alerts: AlertEvent[]
   unreadAlerts: number
+  /**
+   * Nodos de distribución inferidos del FDB (switches/hipervisores entre un
+   * router y sus cableados). Ausente/vacío si aún no hay datos FDB (live sin
+   * colector o primera pasada): el mapa cuelga los cableados del router.
+   */
+  distributionNodes?: DistributionNode[]
   ts: number
 }
 

+ 3 - 3
app/src/pages/Topology.tsx

@@ -43,10 +43,10 @@ function ControlButton({
 export default function Topology() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { routers, devices, wan, wireguard } = useNetPulse()
+  const { routers, devices, wan, wireguard, distributionNodes } = useNetPulse()
   const model = useMemo(
-    () => buildTopologyModel({ routers, devices, wan, wireguard }),
-    [routers, devices, wan, wireguard],
+    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes }),
+    [routers, devices, wan, wireguard, distributionNodes],
   )
   const [showLabels, setShowLabels] = useState(true)
   const [flow, setFlow] = useState(true)

+ 1 - 0
app/src/pages/devices-data.ts

@@ -402,6 +402,7 @@ const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
   camara: 'iot',
   altavoz: 'iot',
   servidor: 'red',
+  switch: 'red',
   desconocido: 'otros',
 }
 

+ 4 - 4
server-go/internal/adapters/adapters_test.go

@@ -29,7 +29,7 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	if *flint.CPU != 23 || *flint.RAM != 41 || *flint.Temp != 54 {
 		t.Fatalf("flint2 cpu/ram/temp: %v/%v/%v", *flint.CPU, *flint.RAM, *flint.Temp)
 	}
-	if flint.Clients != 14 || flint.Health != 98 {
+	if flint.Clients != 33 || flint.Health != 98 {
 		t.Fatalf("flint2 clients/health: %v/%v", flint.Clients, flint.Health)
 	}
 	// WAN
@@ -52,7 +52,7 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 		t.Fatalf("peer0: %+v", p0)
 	}
 	// DeviceTotals
-	if ov.DeviceTotals != (DeviceTotals{Total: 47, Online: 39, KnownOffline: 8, NewToday: 3}) {
+	if ov.DeviceTotals != (DeviceTotals{Total: 67, Online: 59, KnownOffline: 8, NewToday: 3}) {
 		t.Fatalf("deviceTotals: %+v", ov.DeviceTotals)
 	}
 	// Health
@@ -69,10 +69,10 @@ func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
 	}
 }
 
-func TestDemoDevices47YTop(t *testing.T) {
+func TestDemoDevices67YTop(t *testing.T) {
 	d := NewDemo()
 	devs := d.GetDevices(context.Background())
-	if len(devs) != 47 {
+	if len(devs) != 67 {
 		t.Fatalf("devices: %d", len(devs))
 	}
 	offline := 0

+ 3 - 2
server-go/internal/adapters/demo.go

@@ -178,11 +178,12 @@ func (d *Demo) buildOverview() *Overview {
 		Adguard:      d.adguard,
 		Wireguard:    d.wireguardSnapshot(),
 		Routers:      d.routersCopy(),
-		DeviceTotals: DeviceTotals{Total: 47, Online: 39, KnownOffline: 8, NewToday: 3},
+		DeviceTotals: DeviceTotals{Total: 67, Online: 59, KnownOffline: 8, NewToday: 3},
 		TopDevices:   d.topDevices(5),
 		Alerts:       d.alertsCopy(),
 		UnreadAlerts: unread,
-		Ts:           time.Now().Unix(),
+		DistributionNodes: canonDistributionNodes(),
+		Ts:                time.Now().Unix(),
 	}
 }
 

+ 119 - 11
server-go/internal/adapters/demo_dataset.go

@@ -22,11 +22,11 @@ func canonRouters() []Router {
 	return []Router{
 		{ID: "flint2", Name: "Gateway", Model: "GL.iNet Flint 2 (GL-MT6000)", ModelShort: "GL.iNet Flint 2",
 			Role: "Gateway principal", RoleBadge: "Principal", IP: "192.168.8.1", Status: "online",
-			Health: 98, CPU: iptr(23), RAM: iptr(41), Temp: iptr(54), Uptime: "32d 14h", Clients: 14,
+			Health: 98, CPU: iptr(23), RAM: iptr(41), Temp: iptr(54), Uptime: "32d 14h", Clients: 33,
 			Sparkline: []float64{8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40}},
 		{ID: "living", Name: "Salón", Model: "OpenWrt AP (Xiaomi AX3000T)", ModelShort: "Xiaomi AX3000T",
 			Role: "Punto de acceso", RoleBadge: "AP", IP: "192.168.8.2", Status: "online",
-			Health: 95, CPU: iptr(12), RAM: iptr(38), Temp: iptr(47), Uptime: "32d 14h", Clients: 18,
+			Health: 95, CPU: iptr(12), RAM: iptr(38), Temp: iptr(47), Uptime: "32d 14h", Clients: 22,
 			Sparkline: []float64{4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28}},
 		{ID: "estudio", Name: "Estudio", Model: "OpenWrt (NanoPi R4S)", ModelShort: "NanoPi R4S",
 			Role: "AP + switch", RoleBadge: "AP", IP: "192.168.8.3", Status: "online",
@@ -94,7 +94,7 @@ func canonAdguard() AdGuardStats {
 	return AdGuardStats{
 		Host: "192.168.8.1", Port: 3000, Status: "active",
 		Queries24h: 84312, Blocked24h: 15687, BlockedPct: 18.6, TrackersBlocked: 9204,
-		DNSLatencyMs: 14, ClientsUsing: 41, ClientsTotal: 47,
+		DNSLatencyMs: 14, ClientsUsing: 60, ClientsTotal: 67,
 		TopBlocked: []TopBlocked{
 			{Domain: "graph.facebook.com", Count: 1204},
 			{Domain: "adservice.google.com", Count: 986},
@@ -212,7 +212,7 @@ func canonDevices() []Device {
 			Traffic24hRx: "18 GB", Traffic24hTx: "2,2 GB", Adguard: boolp(true), Group: "ordenadores"},
 		{ID: "ps5", Name: "PS5", Type: "consola", Manufacturer: "Sony",
 			IP: "192.168.8.31", MAC: "78:C8:81:0A:6B:D4", RouterID: "living", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 12.7, Online: true,
+			SignalDbm: nil, TrafficMbps: 12.7, Online: true, Port: "lan2",
 			Sparkline: []float64{4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13},
 			Hostname:  "ps5-salon", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 300 días",
 			Traffic24hRx: "92 GB", Traffic24hTx: "4,8 GB", Adguard: boolp(true), Group: "tv"},
@@ -236,7 +236,7 @@ func canonDevices() []Device {
 			Traffic24hRx: "1,4 GB", Traffic24hTx: "88 MB", Adguard: boolp(true), Group: "iot"},
 		{ID: "nas-synology", Name: "NAS Synology", Type: "servidor", Manufacturer: "Synology",
 			IP: "192.168.8.10", MAC: "00:11:32:9C:51:B7", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 2.3, Online: true,
+			SignalDbm: nil, TrafficMbps: 2.3, Online: true, Port: "lan1",
 			Sparkline: []float64{1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3},
 			Hostname:  "diskstation", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 320 días",
 			Traffic24hRx: "96 GB", Traffic24hTx: "1,1 TB", Adguard: boolp(true), Group: "red"},
@@ -263,15 +263,17 @@ func additionalDevices() []Device {
 			"macbook-pro-marc", "renueva en 4 h 16 min", "hace 230 días", "12,4 GB", "1,9 GB", true, "ordenadores", ""),
 		withDetails(devExtra(Device{ID: "pc-sobremesa", Name: "PC de sobremesa", Type: "ordenador", Manufacturer: "ASUSTeK",
 			IP: "192.168.8.11", MAC: "04:D4:C4:8B:30:A7", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 21.3, Online: true}, 13, 0),
+			SignalDbm: nil, TrafficMbps: 21.3, Online: true, AttachTo: "dist-flint2-lan3"}, 13, 0),
 			"desktop-8f2k1", "IP fija (reserva)", "hace 310 días", "84 GB", "6,2 GB", true, "ordenadores", ""),
 		withDetails(devExtra(Device{ID: "raspberry-pi", Name: "Raspberry Pi 4", Type: "servidor", Manufacturer: "Raspberry Pi",
 			IP: "192.168.8.12", MAC: "DC:A6:32:4F:77:02", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 0.8, Online: true}, 14, 0),
+			SignalDbm: nil, TrafficMbps: 0.8, Online: true, AttachTo: "dist-flint2-lan3"}, 14, 0),
 			"raspberrypi", "IP fija (reserva)", "hace 320 días", "3,4 GB", "890 MB", true, "red", ""),
-		withDetails(devExtra(Device{ID: "switch-netgear", Name: "Switch Netgear 8p", Type: "servidor", Manufacturer: "Netgear",
-			IP: "192.168.8.13", MAC: "28:C6:8E:1D:90:44", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 0.02, Online: true}, 15, 0.04),
+		// Switch gestionado identificado por LLDP (topología v5: type switch + Salón lan3)
+		withDetails(devExtra(Device{ID: "switch-netgear", Name: "Switch Netgear", Type: "switch", Manufacturer: "Netgear GS308E",
+			IP: "192.168.8.13", MAC: "28:C6:8E:1D:90:44", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.02, Online: true, Port: "lan3",
+			Lldp: &LldpInfo{Chassis: "GS308E", Mgmt: "192.168.8.13", Caps: "Bridge", PortDesc: "ge5"}}, 15, 0.04),
 			"gs308e", "IP fija (reserva)", "hace 300 días", "64 MB", "12 MB", false, "red", "Network"),
 		withDetails(devExtra(Device{ID: "timbre-nest", Name: "Timbre Nest", Type: "camara", Manufacturer: "Google",
 			IP: "192.168.8.72", MAC: "F4:F5:D8:66:01:B8", RouterID: "flint2", Band: "2.4 GHz",
@@ -405,13 +407,119 @@ func withDetails(d Device, hostname, lease, firstSeen, rx, tx string, adguard bo
 	return d
 }
 
-// canonAllDevices: los 47 clientes (canon expandido + adicionales).
+// canonAllDevices: los 67 clientes (canon expandido + adicionales + fixtures
+// de topología v5: switch gestionado LLDP, hipervisor con CTs, switch
+// inferido FDB — espejo del mock front app/src/data/mock.ts).
 func canonAllDevices() []Device {
 	out := canonDevices()
 	out = append(out, additionalDevices()...)
+	out = append(out, topologyDevices()...)
 	return out
 }
 
+// topologyDevices: fixtures NUEVAS de topología v5 (mockup aprobado
+// 2-Ago-2026). Los 3 clientes preexistentes (switch-netgear, pc-sobremesa,
+// raspberry-pi) se enriquecen in situ en additionalDevices — no se duplican.
+func topologyDevices() []Device {
+	out := []Device{
+		// 3 clientes detrás del switch gestionado (Salón)
+		withDetails(Device{ID: "xbox-series-s", Name: "Xbox Series S", Type: "consola", Manufacturer: "Microsoft",
+			IP: "192.168.8.35", MAC: "7C:ED:8D:4A:11:22", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 9.8, Online: true, AttachTo: "switch-netgear",
+			Sparkline: []float64{3, 5, 7, 9, 11, 12, 10, 9, 10, 9, 10, 9.8}},
+			"xbox-series-s", "renueva en 4 h 12 min", "hace 140 días", "31 GB", "1,9 GB", true, "tv", ""),
+		withDetails(Device{ID: "apple-tv-4k", Name: "Apple TV 4K", Type: "tv", Manufacturer: "Apple",
+			IP: "192.168.8.36", MAC: "F0:18:98:2B:33:44", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 15.2, Online: true, AttachTo: "switch-netgear",
+			Sparkline: []float64{6, 8, 10, 12, 14, 16, 15, 14, 15, 15, 15, 15.2}},
+			"apple-tv-4k", "renueva en 6 h 3 min", "hace 210 días", "88 GB", "3,4 GB", true, "tv", ""),
+		withDetails(Device{ID: "receptor-denon", Name: "Receptor Denon", Type: "altavoz", Manufacturer: "Denon",
+			IP: "192.168.8.37", MAC: "00:05:CD:55:66:77", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.6, Online: true, AttachTo: "switch-netgear",
+			Sparkline: []float64{0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6}},
+			"denon-avr", "IP fija (reserva)", "hace 320 días", "640 MB", "42 MB", true, "iot", ""),
+		// Hipervisor Proxmox (gateway lan2); sus 10 CTs se anidan (OUI BC:24:11)
+		withDetails(Device{ID: "pve", Name: "Proxmox pve", Type: "servidor", Manufacturer: "Supermicro",
+			IP: "192.168.8.5", MAC: "3C:52:82:10:20:30", RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 12.3, Online: true, Port: "lan2",
+			Sparkline: []float64{8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3}},
+			"pve", "IP fija (reserva)", "hace 400 días", "1,2 TB", "96 GB", true, "red", ""),
+	}
+	cts := []struct {
+		id, name, typ, ip string
+		mbps              float64
+	}{
+		{"ct-pihole", "Pi-hole", "servidor", "192.168.8.41", 6.1},
+		{"ct-home-assistant", "Home Assistant", "iot", "192.168.8.42", 4.2},
+		{"ct-nextcloud", "Nextcloud", "servidor", "192.168.8.43", 7.8},
+		{"ct-jellyfin", "Jellyfin", "servidor", "192.168.8.44", 9.4},
+		{"ct-immich", "Immich", "servidor", "192.168.8.45", 3.3},
+		{"ct-gitea", "Gitea", "servidor", "192.168.8.46", 1.2},
+		{"ct-uptime-kuma", "Uptime Kuma", "iot", "192.168.8.47", 0.4},
+		{"ct-adguard-sync", "AdGuard sync", "servidor", "192.168.8.48", 0.8},
+		{"ct-postgres", "Postgres", "servidor", "192.168.8.49", 2.1},
+		{"ct-redis", "Redis", "servidor", "192.168.8.50", 0.9},
+	}
+	for i, c := range cts {
+		mbps := c.mbps
+		sp := make([]float64, 12)
+		for j := range sp {
+			sp[j] = max(0.1, mbps-2+float64((i+j)%5))
+		}
+		out = append(out, withDetails(Device{
+			ID: c.id, Name: c.name, Type: c.typ, Manufacturer: "Proxmox VE (CT)",
+			IP: c.ip, MAC: fmt.Sprintf("BC:24:11:00:2%d:%02X", i, 0x10+i), RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: mbps, Online: true, AttachTo: "pve", Sparkline: sp},
+			c.id, "renueva en 3 h 10 min", "hace 90 días", "1,1 GB", "88 MB", true, "red", ""))
+	}
+	// Tras el switch/bridge inferido (gateway lan3, OUI heterogéneo, sin IP).
+	// pc-sobremesa y raspberry-pi ya existen (enriquecidos con AttachTo en
+	// additionalDevices): aquí solo los 6 nuevos.
+	behind := []struct {
+		id, name, typ, man, mac, ip string
+		mbps                        float64
+	}{
+		{"tv-salon-cable", "TV Salón (cable)", "tv", "Samsung", "8C:EA:48:AA:02:02", "192.168.8.61", 24.4},
+		{"impresora-hp", "Impresora HP", "iot", "HP", "3C:D9:2B:AA:03:03", "192.168.8.62", 0.1},
+		{"xbox-one", "Xbox One", "consola", "Microsoft", "7C:ED:8D:AA:05:05", "192.168.8.64", 4.2},
+		{"receptor-av", "Receptor AV", "altavoz", "Denon", "00:05:CD:AA:06:06", "192.168.8.65", 0.3},
+		{"deco-orange", "Deco Orange", "tv", "Sagemcom", "48:83:B4:AA:07:07", "192.168.8.66", 1.1},
+		{"pc-invitado", "PC invitado", "ordenador", "—", "A2:F4:11:AA:08:08", "192.168.8.67", 0.8},
+	}
+	for i, b := range behind {
+		mbps := b.mbps
+		sp := make([]float64, 12)
+		for j := range sp {
+			sp[j] = max(0.05, mbps-1.5+float64((i+j)%4)*0.5)
+		}
+		grp := "otros"
+		switch b.typ {
+		case "ordenador":
+			grp = "ordenadores"
+		case "tv":
+			grp = "tv"
+		case "iot":
+			grp = "iot"
+		case "altavoz":
+			grp = "iot"
+		}
+		out = append(out, withDetails(Device{
+			ID: b.id, Name: b.name, Type: b.typ, Manufacturer: b.man,
+			IP: b.ip, MAC: b.mac, RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: mbps, Online: true, AttachTo: "dist-flint2-lan3", Sparkline: sp},
+			b.id, "renueva en 5 h 22 min", "hace 60 días", "2,4 GB", "120 MB", true, grp, ""))
+	}
+	return out
+}
+
+// canonDistributionNodes: distnodes demo (en live los infiere el colector FDB).
+func canonDistributionNodes() []DistributionNode {
+	return []DistributionNode{
+		{ID: "dist-flint2-lan3", Kind: "inferred", RouterID: "flint2", Port: "lan3", MacCount: 8},
+		{ID: "dist-pve", Kind: "hypervisor", RouterID: "flint2", Port: "lan2", MacCount: 11, HostDeviceID: "pve", Name: "Proxmox pve"},
+	}
+}
+
 // boolp: los literales demo fijan adguard explícito (true/false) como en el
 // dataset JS; live lo deja nil para omitir el campo.
 func boolp(b bool) *bool { return &b }

+ 4 - 1
server-go/internal/adapters/live.go

@@ -951,6 +951,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		routerList = append(routerList, router)
 	}
 	devices := l.buildDevices(polled)
+	// Topología v5: puertos FDB + switches/hipervisores inferidos
+	devices, distNodes := inferTopology(polled, devices)
 	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
 	for _, d := range devices {
 		if d.Online && d.SignalDbm != nil && *d.SignalDbm < -70 {
@@ -1038,7 +1040,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 			Total: len(devices), Online: online, KnownOffline: len(devices) - online, NewToday: 0,
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
-		Ts: time.Now().Unix(),
+		DistributionNodes: distNodes,
+		Ts:                time.Now().Unix(),
 	}, nil
 }
 

+ 153 - 0
server-go/internal/adapters/topology.go

@@ -0,0 +1,153 @@
+package adapters
+
+import (
+	"fmt"
+	"sort"
+	"strings"
+)
+
+// ---------------------------------------------------------------------------
+// Inferencia de topología v5 (FDB): puertos físicos, switches/bridges e
+// hipervisores. Función pura (sin SSH ni BD) para ser testeable.
+//
+// Reglas (plan 2-Ago-2026):
+//   - Un puerto físico (lanN) con UNA MAC aprendida = cableado directo →
+//     Device.Port.
+//   - Un puerto con VARIAS MACs = algo multiplexándolo (switch, hipervisor,
+//     PLC…). El FDB no dice qué: OUI heterogéneo → "inferred" (círculo
+//     dashed, sin afirmar); alguna MAC con OUI de hipervisor y exactamente
+//     un host → "hypervisor" (sus VMs se anidan bajo el host).
+//   - Se excluyen las MACs de los propios routers (su bridge br-lan) y las
+//     de clientes atribuidos a OTROS routers (los clientes wifi de un AP
+//     aparecen en el FDB del gateway por el puerto del uplink).
+// ---------------------------------------------------------------------------
+
+// hypervisorOUI: prefijos de MAC de hipervisores conocidos.
+var hypervisorOUI = []string{
+	"BC:24:11", // Proxmox VE
+	"00:50:56", // VMware (ESXi/Workstation)
+	"00:0C:29", // VMware
+	"00:15:5D", // Hyper-V
+	"52:54:00", // KVM/QEMU
+}
+
+func isHypervisorMAC(mac string) bool {
+	for _, p := range hypervisorOUI {
+		if strings.HasPrefix(mac, p) {
+			return true
+		}
+	}
+	return false
+}
+
+// inferTopology enriquece devices con Port/AttachTo e infiere los
+// DistributionNode del FDB sondeado. `polled` lleva fdb (MAC→puerto, ya
+// filtrado a lanN/wan por parseBridgeFdb) y brMac por router.
+func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device, []DistributionNode) {
+	byMAC := make(map[string]int, len(devices))
+	for i, d := range devices {
+		byMAC[d.MAC] = i
+	}
+	routerMACs := map[string]bool{}
+	for _, p := range polled {
+		if p.brMac != "" {
+			routerMACs[p.brMac] = true
+		}
+	}
+
+	var dists []DistributionNode
+	// routers en orden determinista (el mapa polled no lo es)
+	routerIDs := make([]string, 0, len(polled))
+	for id := range polled {
+		routerIDs = append(routerIDs, id)
+	}
+	sort.Strings(routerIDs)
+
+	for _, routerID := range routerIDs {
+		p := polled[routerID]
+		// invertir fdb: puerto → MACs (el WAN no es distribución LAN)
+		byPort := map[string][]string{}
+		for mac, port := range p.fdb {
+			if port == "wan" {
+				continue
+			}
+			byPort[port] = append(byPort[port], mac)
+		}
+		ports := make([]string, 0, len(byPort))
+		for port := range byPort {
+			ports = append(ports, port)
+		}
+		sort.Strings(ports)
+
+		for _, port := range ports {
+			var kept []string
+			for _, mac := range byPort[port] {
+				if routerMACs[mac] {
+					continue // el propio router/AP no es un cliente
+				}
+				if idx, ok := byMAC[mac]; ok {
+					d := devices[idx]
+					if d.RouterID != routerID {
+						continue // cliente de otro router (visto por el uplink)
+					}
+					if d.Band != "cable" && d.Band != "—" {
+						continue // wifi no cuelga de un puerto físico
+					}
+				}
+				kept = append(kept, mac)
+			}
+			if len(kept) == 0 {
+				continue
+			}
+			setPort := func() {
+				for _, mac := range kept {
+					if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+						devices[idx].Port = port
+					}
+				}
+			}
+			if len(kept) == 1 {
+				// cableado directo: puerto conocido, sin nodo de distribución
+				setPort()
+				continue
+			}
+
+			// puerto multi-MAC → nodo de distribución
+			setPort()
+			id := fmt.Sprintf("dist-%s-%s", routerID, port)
+			var vmMACs, hostMACs []string
+			for _, mac := range kept {
+				if isHypervisorMAC(mac) {
+					vmMACs = append(vmMACs, mac)
+				} else {
+					hostMACs = append(hostMACs, mac)
+				}
+			}
+			if len(vmMACs) > 0 && len(hostMACs) == 1 {
+				if hidx, ok := byMAC[hostMACs[0]]; ok && devices[hidx].RouterID == routerID {
+					// hipervisor con host identificado: VMs anidadas bajo él
+					dists = append(dists, DistributionNode{
+						ID: id, Kind: "hypervisor", RouterID: routerID, Port: port,
+						MacCount: len(kept), HostDeviceID: devices[hidx].ID, Name: devices[hidx].Name,
+					})
+					for _, mac := range vmMACs {
+						if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+							devices[idx].AttachTo = devices[hidx].ID
+						}
+					}
+					continue
+				}
+			}
+			// OUI heterogéneo (o hipervisor ambiguo sin host claro): inferido
+			dists = append(dists, DistributionNode{
+				ID: id, Kind: "inferred", RouterID: routerID, Port: port, MacCount: len(kept),
+			})
+			for _, mac := range kept {
+				if idx, ok := byMAC[mac]; ok && devices[idx].RouterID == routerID {
+					devices[idx].AttachTo = id
+				}
+			}
+		}
+	}
+	return devices, dists
+}

+ 120 - 0
server-go/internal/adapters/topology_test.go

@@ -0,0 +1,120 @@
+package adapters
+
+import "testing"
+
+// FDB/port helpers para los tests de inferencia.
+func polledWithFDB(routerID, brMac string, fdb map[string]string) map[string]*routerPolled {
+	return map[string]*routerPolled{
+		routerID: {cfg: RouterConfig{ID: routerID}, brMac: brMac, fdb: fdb},
+	}
+}
+
+func dev(mac, routerID, band string) Device {
+	return Device{ID: "d-" + mac, MAC: mac, RouterID: routerID, Band: band, Online: true}
+}
+
+func TestInferTopologyCableadoDirecto(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"00:11:32:9C:51:B7": "lan1",
+	})
+	devices := []Device{dev("00:11:32:9C:51:B7", "flint2", "cable")}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("no debería haber distnodes: %+v", dists)
+	}
+	if devices[0].Port != "lan1" {
+		t.Fatalf("port: %q", devices[0].Port)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("attachTo debería estar vacío: %q", devices[0].AttachTo)
+	}
+}
+
+func TestInferTopologySwitchInferido(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"78:2B:CB:AA:01:01": "lan3",
+		"8C:EA:48:AA:02:02": "lan3",
+		"3C:D9:2B:AA:03:03": "lan3",
+	})
+	devices := []Device{
+		dev("78:2B:CB:AA:01:01", "flint2", "cable"),
+		dev("8C:EA:48:AA:02:02", "flint2", "cable"),
+		// la 3ª MAC es desconocida (sin device): solo cuenta en macCount
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	if dn.ID != "dist-flint2-lan3" || dn.Kind != "inferred" || dn.RouterID != "flint2" || dn.Port != "lan3" || dn.MacCount != 3 {
+		t.Fatalf("distnode: %+v", dn)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-flint2-lan3" {
+			t.Fatalf("attachTo de %s: %q", d.MAC, d.AttachTo)
+		}
+		if d.Port != "lan3" {
+			t.Fatalf("port de %s: %q", d.MAC, d.Port)
+		}
+	}
+}
+
+func TestInferTopologyHipervisor(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"3C:52:82:10:20:30": "lan2", // host (OUI normal)
+		"BC:24:11:00:20:10": "lan2", // CT1 (OUI Proxmox)
+		"BC:24:11:00:20:11": "lan2", // CT2
+	})
+	devices := []Device{
+		dev("3C:52:82:10:20:30", "flint2", "cable"),
+		dev("BC:24:11:00:20:10", "flint2", "cable"),
+		dev("BC:24:11:00:20:11", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	hostID := devices[0].ID
+	if dn.Kind != "hypervisor" || dn.HostDeviceID != hostID || dn.MacCount != 3 {
+		t.Fatalf("distnode hipervisor: %+v", dn)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("el host cuelga del router, no del distnode: %q", devices[0].AttachTo)
+	}
+	for _, d := range devices[1:] {
+		if d.AttachTo != hostID {
+			t.Fatalf("CT %s attachTo: %q (esperaba host %s)", d.MAC, d.AttachTo, hostID)
+		}
+	}
+}
+
+func TestInferTopologyExclusiones(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"94:83:C4:00:00:02": "lan1", // bridge MAC de un AP (no es cliente)
+		"F2:6D:19:A8:44:C2": "lan1", // cliente wifi del AP (otro routerId)
+	})
+	// El AP también aparece en polled con su propia brMac
+	polled["living"] = &routerPolled{cfg: RouterConfig{ID: "living"}, brMac: "94:83:C4:00:00:02", fdb: map[string]string{}}
+	devices := []Device{
+		dev("F2:6D:19:A8:44:C2", "living", "5 GHz"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 0 {
+		t.Fatalf("no debería inferir nada del uplink: %+v", dists)
+	}
+	if devices[0].Port != "" || devices[0].AttachTo != "" {
+		t.Fatalf("cliente wifi del AP tocado: port=%q attachTo=%q", devices[0].Port, devices[0].AttachTo)
+	}
+}
+
+func TestInferTopologyWanIgnorado(t *testing.T) {
+	polled := polledWithFDB("flint2", "94:83:C4:00:00:01", map[string]string{
+		"A0:B1:C2:D3:E4:F5": "wan",
+		"A0:B1:C2:D3:E4:F6": "wan",
+	})
+	devices, dists := inferTopology(polled, nil)
+	if len(dists) != 0 || len(devices) != 0 {
+		t.Fatalf("el puerto WAN no genera distribución: %+v %+v", dists, devices)
+	}
+}

+ 38 - 1
server-go/internal/adapters/types.go

@@ -154,6 +154,14 @@ type Device struct {
 	TrafficMbps  float64   `json:"trafficMbps"`
 	Online       bool      `json:"online"`
 	Sparkline    []float64 `json:"sparkline"`
+	// --- topología v5 (FDB/LLDP; omitempty: ausentes si no hay datos) ---
+	// Port: puerto físico del bridge donde se aprende la MAC (cableados, FDB).
+	Port string `json:"port,omitempty"`
+	// Lldp: identificación del vecino cuando se anuncia por LLDP.
+	Lldp *LldpInfo `json:"lldp,omitempty"`
+	// AttachTo: hub del que cuelga en el mapa (router por defecto; id de
+	// DistributionNode inferido o de otro Device — hipervisor/switch).
+	AttachTo string `json:"attachTo,omitempty"`
 	// --- extras demo (omitempty = ausentes en live) ---
 	Hostname     string `json:"hostname,omitempty"`
 	DHCPLease    string `json:"dhcpLease,omitempty"`
@@ -167,6 +175,31 @@ type Device struct {
 	IconOverride string `json:"iconOverride,omitempty"`
 }
 
+// LldpInfo identifica un vecino que se anuncia por LLDP (switch gestionado,
+// AP, host…). Campos del `lldpcli -f json show neighbors`.
+type LldpInfo struct {
+	Chassis  string `json:"chassis,omitempty"`
+	Mgmt     string `json:"mgmt,omitempty"`
+	Caps     string `json:"caps,omitempty"`
+	PortDesc string `json:"portDesc,omitempty"`
+}
+
+// DistributionNode: puerto físico con varias MACs aprendidas en el FDB.
+// "inferred" = OUI heterogéneo (switch o bridge desconocido, sin IP);
+// "hypervisor" = OUI de hipervisor (Proxmox/VMware/Hyper-V/KVM) → sus
+// CTs/VMs se anidan bajo el host en el mapa.
+type DistributionNode struct {
+	ID       string    `json:"id"`
+	Kind     string    `json:"kind"` // "inferred"|"hypervisor"
+	RouterID string    `json:"routerId"`
+	Port     string    `json:"port"`
+	MacCount int       `json:"macCount"`
+	// HostDeviceID: hipervisor → id del Device host (Proxmox…), si es cliente.
+	HostDeviceID string    `json:"hostDeviceId,omitempty"`
+	Name         string    `json:"name,omitempty"`
+	Lldp         *LldpInfo `json:"lldp,omitempty"`
+}
+
 // AlertEvent (máx 100 en memoria, más recientes primero).
 type AlertEvent struct {
 	ID          string `json:"id"`
@@ -190,7 +223,11 @@ type Overview struct {
 	TopDevices   []Device       `json:"topDevices"` // 5 por trafficMbps desc
 	Alerts       []AlertEvent   `json:"alerts"`
 	UnreadAlerts int            `json:"unreadAlerts"`
-	Ts           int64          `json:"ts"` // floor(now/1000) — SEGUNDOS
+	// DistributionNodes: switches/hipervisores inferidos del FDB (topología
+	// v5). Vacío/ausente si aún no hay datos FDB: el mapa cuelga los
+	// cableados del router (degradación amable).
+	DistributionNodes []DistributionNode `json:"distributionNodes,omitempty"`
+	Ts                int64              `json:"ts"` // floor(now/1000) — SEGUNDOS
 }
 
 // ---------------------------------------------------------------------------

+ 8 - 8
server-go/internal/httpapi/httpapi_test.go

@@ -490,22 +490,22 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	srv := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
 
-	// Paginación: 47 dispositivos del dataset canónico (port devices.test.js)
+	// Paginación: 67 dispositivos del dataset canónico (47 base + 20 fixtures topología v5)
 	res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
 	body := readJSON(t, res)
-	if body["total"].(float64) != 47 || len(body["items"].([]any)) != 10 {
+	if body["total"].(float64) != 67 || len(body["items"].([]any)) != 10 {
 		t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
 	}
 	if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
 		t.Fatalf("page/pageSize: %v", body)
 	}
-	res = get(t, srv.URL, "/api/devices?page=5&pageSize=10", cookie)
+	res = get(t, srv.URL, "/api/devices?page=7&pageSize=10", cookie)
 	body = readJSON(t, res)
 	if len(body["items"].([]any)) != 7 {
-		t.Fatalf("page5 (resto): %v", len(body["items"].([]any)))
+		t.Fatalf("page7 (resto): %v", len(body["items"].([]any)))
 	}
 	// Sin solape con la página anterior
-	res = get(t, srv.URL, "/api/devices?page=4&pageSize=10", cookie)
+	res = get(t, srv.URL, "/api/devices?page=6&pageSize=10", cookie)
 	prev := readJSON(t, res)
 	prevIDs := map[string]bool{}
 	for _, it := range prev["items"].([]any) {
@@ -513,7 +513,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	}
 	for _, it := range body["items"].([]any) {
 		if prevIDs[it.(map[string]any)["id"].(string)] {
-			t.Fatalf("solape entre page4 y page5: %v", it)
+			t.Fatalf("solape entre page6 y page7: %v", it)
 		}
 	}
 	// Defaults: pageSize=50
@@ -525,7 +525,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 	// Filtros
 	res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
 	body = readJSON(t, res)
-	if body["total"].(float64) != 18 {
+	if body["total"].(float64) != 22 { // 18 base + switch-netgear + 3 clientes detrás
 		t.Fatalf("routerId=living: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?band=cable", cookie)
@@ -535,7 +535,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 			t.Fatalf("band=cable con item de otra banda: %v", it)
 		}
 	}
-	if body["total"].(float64) != 7 { // ps5, nas, pc-sobremesa, raspberry, switch, mac-mini, hue-hub
+	if body["total"].(float64) != 27 { // 7 base + 20 fixtures cable (3 netgear + pve + 10 CTs + 6 tras switch)
 		t.Fatalf("band=cable: %v", body["total"])
 	}
 	res = get(t, srv.URL, "/api/devices?status=offline", cookie)