Quellcode durchsuchen

fix(topology): dumb-AP wired attribution, stable map, editable layout, Proxmox hosts (#656) (#669)

* fix(topology): attribute dumb-AP wired hosts to the AP, stable order, lock layout

Wired hosts of a bridged dumb AP (no WAN, br-lan bridged into the main LAN)
were attributed to the main router because the reconciliation dropped any MAC
also seen by the gateway. A MAC learned on a satellite's local non-uplink port
is now attributed to that satellite (the physical port is the most specific
evidence); the uplink stays excluded as transit and agent-only switches keep
their specific source. Devices are also returned in deterministic MAC order so
topology rings stop shuffling on refresh, and a "lock layout" toggle freezes
chip positions across refreshes (persisted in the browser).

Closes #656

* feat(topology): add edit-layout mode to adjust node spacing (#656)

Add an explicit edit mode (admin-only) so the network owner can drag router
and device nodes to bring satellites closer/farther. Positions are persisted
in the browser and the layout stays frozen (no reordering on refresh) until
re-edited or reset to automatic. Dragging a router re-derives its subtree
around the moved position via the model seed; dragging a chip pins it.

Closes #656

* fix(topology): node drag did nothing in edit mode; add visual affordances

startNodeDrag stopped propagation so the container's onPointerDown never
ran, which meant the pointer was never registered in the pointers map and
onPointerMove early-returned: dragging a node moved nothing. Register the
pointer and clear pan/pinch state when a node drag starts. Also give
draggable nodes a grab cursor and show an edit-mode banner over the map so
the affordance is discoverable.

Closes #656

* feat(topology): drag inferred/managed switches in edit mode; format chip traffic

Distribution nodes (inferred switch/bridge, managed via LLDP, and chained
ones) are now draggable in edit mode like routers: their position is seeded
before their child chips are laid out, so the whole subtree re-derives
around the moved node, and the collision resolver already treats them as
fixed. Also format the traffic stat in the device tooltip with the same
convention as the rest of the app instead of printing the raw float.

Closes #656

* feat(topology): nest Proxmox CTs under their host, tag from the card, tooltip bridge

The PVE seal marked devices (infra=hypervisor/ct) but emitted no hypervisor
distnodes, so CTs rendered as a plain fan of chips and hosts had no Proxmox
identity. The seal now creates one distnode kind=hypervisor per PVE host
(Source=proxmox, host name, router/port metadata), which turns on the
frontend hypervisor machinery: CT grid under the host, +N badge, host->CT
links, and a "Proxmox <node>" label for API-sourced hosts (L2-inferred ones
keep the generic label).

Also, per feedback while validating: the device card now persists 1.2s after
leaving the chip (replaced instantly when hovering another node, stays open
while the cursor is on the card) and gains an inline "Tag" button so admins
can label a device straight from the card instead of typing its MAC. The
packet-flow header toggle is removed; flow now follows the existing
"reduce motion" preference (and OS-level reduced motion as before).

Closes #656

* fix(topology): device-card tag button click was swallowed by map pan; restyle

A pointerdown on the card bubbled to the map container, which starts a pan
(pointer capture + drag): the slightest movement while pressing "Tag" panned
the map, another chip slid under the cursor and its hover replaced the card,
so the click never landed. The card now stops pointerdown propagation.
Also make the button discreet (small outline, secondary tone) instead of a
full accent block.

Closes #656

* feat(topology): render Proxmox hosts as round mini-nodes that drag their CTs

Hypervisor hosts looked like any other square device chip, and dragging one
left its CTs behind: the host seed was applied after the CT grid was laid
out. The host seed is now applied before the CT grid (so the grid re-derives
around the moved host and the CTs travel with it, like routers and inferred
switches), and CTs of a seeded host are no longer pinned by their own stale
seeds. Hosts render as a round mini-node (server icon, accent for
Proxmox-sourced hosts, +N badge) with a larger collision size.

Closes #656

* fix(server): sticky FDB port memory stops quiet devices jumping off their switch

Bridge FDB entries age out after ~5 minutes, so quiet devices (AV gear: TV,
receiver, shield) lost their port evidence between refreshes while still
online via ARP, and the map re-anchored them to the gateway until they talked
again. The server now remembers the last real port each MAC was seen on
(30-minute TTL, in-memory) and feeds it to inferTopology as an overlay only
for MACs missing from the current FDB: the real FDB always wins, the memory
never creates presence, and moved devices self-correct as soon as they talk.

Closes #656

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho vor 2 Monaten
Ursprung
Commit
53c971acfa

+ 10 - 0
CHANGELOG.md

@@ -7,9 +7,19 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [2.28.17] - 2026-09-09
 
+### Added
+
+- **La topología se puede editar para ajustar las distancias (#656)**: un botón **Editar** (solo administrador) entra en modo edición que permite arrastrar routers/APs, switches o bridges inferidos y dispositivos para acercar o alejar los satélites (lo que cuelga de un nodo lo acompaña). Al guardar, las posiciones se persisten en el navegador y el layout queda **congelado** (ya no se reordena al refrescar); los nodos nuevos se colocan con el auto-layout. Un botón **Restablecer** vuelve al layout automático por defecto.
+
+### Fixed
+
+- **Los dispositivos callados ya no saltan del switch inferido al que están cableados (#656)**: las entradas del FDB caducan a los ~5 min sin tráfico, así que los equipos de AV (TV, receptor, shield…) perdían su evidencia de puerto entre refrescos y el mapa los re-anclaba al router principal hasta que volvían a hablar. El servidor recuerda ahora la última boca real donde se vio cada MAC (30 min de memoria, solo como respaldo del FDB actual) y conserva su atribución de puerto mientras el dispositivo siga conectado.
+- **El tráfico del tooltip de un dispositivo en la topología ya no muestra todos los decimales (#656)**: se formatea con la misma convención que el resto de la app (1 decimal a partir de 1 Mbps, 2 por debajo).
+
 ### Fixed
 
 - **Un router OpenWrt ya no cae en falso "host key changed" al sondearlo (#651)**: el descubrimiento (openssh con `accept-new`) registraba en `known_hosts` solo la host key que negociaba (ed25519), pero el sondeo Go negocia otra (ecdsa/rsa) con el mismo servidor; un host con varias host keys daba un falso "ssh host key changed" y exigía un re-onboard sin motivo. Ahora el descubrimiento pinas todas las host keys del router (ed25519, ecdsa y rsa), de forma que el sondeo siempre encuentra la suya sin debilitar la protección anti-MITM: si el router cambia todas sus claves (reflash), la detección de "host key changed" sigue intacta.
+- **Los hosts por cable de un punto de acceso puente (dumb AP) ya se atribuyen al AP, no al router principal (#656)**: cuando un nodo como un dumb AP (sin WAN, `br-lan` puentado a la LAN principal) tiene clientes conectados por cable a sus bocas, el router principal también los ve en su FDB porque comparten el mismo segmento L2. La reconciliación descartaba esas MACs del satélite y las colgaba del router principal. Ahora una MAC que el satélite aprende en una boca local que no es su uplink se atribuye a ese satélite (la boca física es la evidencia más específica); el uplink sigue excluido como tránsito y los routers con agente propio conservan su fuente específica. Además, el orden de los dispositivos es ahora determinista (por MAC), lo que evita que los iconos del mapa salten de posición al refrescar aunque ya no se use el bloqueo de layout.
 
 ## [2.28.16] - 2026-09-09
 

+ 7 - 0
app/public/locales/en/translation.json

@@ -815,6 +815,11 @@
     "interactiveMap": "Interactive network map",
     "internetAria": "Internet, {{isp}}, fiber {{plan}}",
     "labels": "Labels",
+    "edit": "Edit",
+    "editHint": "Edit the layout: drag routers and devices to adjust spacing. When saved, positions stay fixed and no longer reorder.",
+    "editBanner": "Edit mode: drag routers and devices to adjust the map",
+    "editSave": "Save",
+    "editReset": "Reset to automatic layout",
     "legend": {
       "bandConnection": "Band / connection",
       "healthy": "Healthy",
@@ -859,6 +864,7 @@
     "weakSignal": "Weak signal",
     "zoomControls": "Map zoom controls",
     "tagDevices": "Tag devices",
+    "tagThis": "Tag",
     "zoomIn": "Zoom in",
     "zoomOut": "Zoom out",
     "usteer": {
@@ -885,6 +891,7 @@
     },
     "host": {
       "hypervisor": "hypervisor",
+      "proxmox": "Proxmox",
       "note": "Hypervisor: {{count}} CTs/VMs behind its virtual bridge — not a switch"
     },
     "ct": {

+ 7 - 0
app/public/locales/es/translation.json

@@ -815,6 +815,11 @@
     "interactiveMap": "Mapa interactivo de la red",
     "internetAria": "Internet, {{isp}}, fibra {{plan}}",
     "labels": "Etiquetas",
+    "edit": "Editar",
+    "editHint": "Edita el layout: arrastra los routers y dispositivos para ajustar las distancias. Al guardar, las posiciones quedan fijas y no se reordenan.",
+    "editBanner": "Modo edición: arrastra los routers y dispositivos para ajustar el mapa",
+    "editSave": "Guardar",
+    "editReset": "Restablecer layout automático",
     "legend": {
       "bandConnection": "Banda / conexión",
       "healthy": "Saludable",
@@ -859,6 +864,7 @@
     "weakSignal": "Señal débil",
     "zoomControls": "Controles de zoom del mapa",
     "tagDevices": "Etiquetar dispositivos",
+    "tagThis": "Etiquetar",
     "zoomIn": "Acercar",
     "zoomOut": "Alejar",
     "usteer": {
@@ -885,6 +891,7 @@
     },
     "host": {
       "hypervisor": "hipervisor",
+      "proxmox": "Proxmox",
       "note": "Hipervisor: {{count}} CTs/VMs tras su bridge virtual — no es un switch"
     },
     "ct": {

+ 237 - 52
app/src/components/topology/TopologyMap.tsx

@@ -10,10 +10,11 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import type { PointerEvent as ReactPointerEvent, RefObject } from 'react'
 import { useNavigate } from 'react-router'
 import { animate, motion, useReducedMotion } from 'framer-motion'
-import { Cloud, Laptop, Router as RouterIcon, Smartphone } from 'lucide-react'
+import { Cloud, Laptop, Router as RouterIcon, Server, Smartphone, Tag } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import { relTime } from '@/i18n'
 import type { Device, DistributionNode, Router, WanInfo, WGPeer } from '@/data/mock'
+import { fmtEs } from '@/data/mock'
 import { StatusPill } from '@/components/StatusPill'
 import { DEVICE_ICONS } from '@/components/DeviceRow'
 import { cn } from '@/lib/utils'
@@ -105,6 +106,7 @@ function TooltipCard({
   touch,
   wan,
   routerName,
+  onTagDevice,
   onPointerEnter,
   onPointerLeave,
 }: {
@@ -113,6 +115,9 @@ function TooltipCard({
   wan: WanInfo
   /** nombre visible del router del que cuelga un nodo (D8: tooltip dist) */
   routerName: (id: string) => string
+  /** etiquetar el dispositivo desde la propia tarjeta (#656 feedback: más
+   *  sencillo que introducir la MAC a mano) */
+  onTagDevice?: (device: Device) => void
   /** puente de hover (issue #255): cancelar el cierre al entrar en el popup */
   onPointerEnter?: () => void
   onPointerLeave?: () => void
@@ -129,6 +134,11 @@ function TooltipCard({
       )}
       style={{ left: tip.left, top: tip.top }}
       role="tooltip"
+      // #656: el pointerdown NO debe burbujear al contenedor del mapa: si lo
+      // hace, arranca un pan (captura de puntero + drag) y cualquier micro
+      // movimiento al pulsar "Etiquetar" desplaza el mapa, un chip pasa bajo
+      // el cursor, su hover reemplaza esta tarjeta y el clic se pierde.
+      onPointerDown={(e) => e.stopPropagation()}
       onPointerEnter={onPointerEnter}
       onPointerLeave={onPointerLeave}
     >
@@ -231,7 +241,12 @@ function TooltipCard({
         </div>
       )}
       {tip.kind === 'chip' && (
-        <ChipTooltip chip={tip.chip} hostCtCount={tip.hostCtCount} ctHost={tip.ctHost} />
+        <ChipTooltip
+          chip={tip.chip}
+          hostCtCount={tip.hostCtCount}
+          ctHost={tip.ctHost}
+          onTag={onTagDevice ? () => onTagDevice(tip.chip.device) : undefined}
+        />
       )}
       {tip.kind === 'dist' && tip.node.kind === 'managed' && (
         <div>
@@ -285,12 +300,15 @@ function ChipTooltip({
   chip,
   hostCtCount = 0,
   ctHost,
+  onTag,
 }: {
   chip: ChipNode
   /** >0 si el chip es un host hipervisor (badge +N en el mapa) */
   hostCtCount?: number
   /** device host cuando el chip es un CT/VM anidado */
   ctHost?: Device
+  /** etiquetar el dispositivo desde la tarjeta (admin+live) */
+  onTag?: () => void
 }) {
   const { t } = useTranslation()
   const d = chip.device
@@ -323,7 +341,7 @@ function ChipTooltip({
             value={chip.wired ? portName(d.port ?? undefined, d.portLabel) : `${d.signalDbm ?? '—'} dBm`}
             hot={!chip.wired && chip.weak}
           />
-          <MiniStat label={t('topology.traffic')} value={`${d.trafficMbps} Mbps`} />
+          <MiniStat label={t('topology.traffic')} value={`${d.trafficMbps >= 1 ? fmtEs(d.trafficMbps, 1) : fmtEs(d.trafficMbps, 2)} Mbps`} />
         </div>
       </div>
       {d.lldp && (
@@ -351,6 +369,19 @@ function ChipTooltip({
       {!chip.isCt && chip.weak && (
         <div className="mt-1 text-caption font-semibold text-warn">{t('topology.weakSignal')}</div>
       )}
+      {onTag && (
+        <button
+          type="button"
+          onClick={(e) => {
+            e.stopPropagation()
+            onTag()
+          }}
+          className="mt-2.5 flex h-7 w-full items-center justify-center gap-1.5 rounded-lg border border-border bg-canvas/40 px-2.5 text-[11px] font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+        >
+          <Tag className="h-3 w-3" strokeWidth={1.75} />
+          {t('topology.tagThis')}
+        </button>
+      )}
     </div>
   )
 }
@@ -422,13 +453,32 @@ interface TopologyMapProps {
    * de overrides manuales. Ausente → comportamiento normal.
    */
   onTagDevice?: (device: Device) => void
+  /**
+   * Modo edición de layout (issue #656): si se pasa `editMode`, los nodos router
+   * y los chips se vuelven arrastrables para ajustar distancias (p. ej.
+   * alejar/acercar un satélite). `onMoveNode(id, x, y)` se notifica con la
+   * nueva posición (coordenadas del viewBox) durante el arrastre; la posición
+   * se persiste luego fuera.
+   */
+  editMode?: boolean
+  onMoveNode?: (id: string, x: number, y: number) => void
 }
 
-export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHoverLink, onTagDevice }: TopologyMapProps) {
+export function TopologyMap({
+  model,
+  apiRef,
+  showLabels,
+  flow,
+  hoverLink,
+  onHoverLink,
+  onTagDevice,
+  editMode = false,
+  onMoveNode,
+}: TopologyMapProps) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const navigate = useNavigate()
-  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
+  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, hypervisorSourceByHost, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const viewRef = useRef<View>({ ...INITIAL_VIEW })
@@ -439,6 +489,14 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   /** Retardo de cierre del tooltip (issue #255): el cursor debe poder viajar
    *  desde el nodo hasta el popup sin que este desaparezca. */
   const hoverCloseTimer = useRef<number | null>(null)
+  /** Arrastre de un nodo en modo edición (issue #656): posición base del nodo
+   *  y del cursor al empezar, para moverlo de forma relativa (sin salto). */
+  const dragNode = useRef<{ id: string; startX: number; startY: number; startCX: number; startCY: number } | null>(null)
+  /** Throttle a un cambio por frame: onPointerMove puede disparar muchas veces
+   *  por frame y el re-layout del modelo es caro; se acumula y se aplica una
+   *  vez por requestAnimationFrame. */
+  const dragFrame = useRef<number | null>(null)
+  const dragPending = useRef<{ id: string; x: number; y: number } | null>(null)
 
   const [hoverNode, setHoverNode] = useState<string | null>(null)
   const [tooltip, setTooltip] = useState<TooltipState | null>(null)
@@ -552,6 +610,41 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
     }
   }, [])
 
+  // -- arrastre de nodos en modo edición (issue #656) ------------------------
+  // En editMode, un pointerdown sobre un nodo router/chip inicia su arrastre
+  // (stopPropagation para no arrancar el pan del lienzo). Durante el move se
+  // re-laya el modelo con la posición del nodo (throttleado a 1/frame); al soltar
+  // se limpia el estado.
+  const startNodeDrag = useCallback(
+    (id: string, startX: number, startY: number, e: ReactPointerEvent) => {
+      if (!editMode || !onMoveNode) return
+      e.stopPropagation()
+      // Registrar el puntero y anular pan/pinch: el onPointerDown del
+      // contenedor NO corre (el stopPropagation lo impide) y sin registro el
+      // onPointerMove hace early-return → el arrastre no movía nada (bug
+      // encontrado al validar el preview).
+      pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY })
+      drag.current = null
+      pinch.current = null
+      dragNode.current = { id, startX, startY, startCX: e.clientX, startCY: e.clientY }
+      moved.current = true
+      containerRef.current?.setPointerCapture(e.pointerId)
+      setTooltip(null)
+      setHoverNode(null)
+    },
+    [editMode, onMoveNode],
+  )
+
+  const flushNodeDrag = useCallback(() => {
+    if (dragFrame.current !== null) {
+      cancelAnimationFrame(dragFrame.current)
+      dragFrame.current = null
+    }
+    const p = dragPending.current
+    dragPending.current = null
+    if (p) onMoveNode?.(p.id, Math.round(p.x), Math.round(p.y))
+  }, [onMoveNode])
+
   const onPointerMove = useCallback(
     (e: ReactPointerEvent<HTMLDivElement>) => {
       if (!pointers.current.has(e.pointerId)) return
@@ -560,6 +653,26 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       if (!el) return
       const rect = el.getBoundingClientRect()
 
+      // arrastre de nodo en edición: mover al nodo (y su subárbol, vía el
+      // layout del modelo) sin pan del lienzo.
+      if (dragNode.current) {
+        moved.current = true
+        const d = dragNode.current
+        const v = viewRef.current
+        const dx = ((e.clientX - d.startCX) / rect.width) * v.w
+        const dy = ((e.clientY - d.startCY) / rect.height) * v.h
+        dragPending.current = { id: d.id, x: d.startX + dx, y: d.startY + dy }
+        if (dragFrame.current === null) {
+          dragFrame.current = requestAnimationFrame(() => {
+            dragFrame.current = null
+            const p = dragPending.current
+            dragPending.current = null
+            if (p) onMoveNode?.(p.id, Math.round(p.x), Math.round(p.y))
+          })
+        }
+        return
+      }
+
       if (pinch.current && pointers.current.size >= 2) {
         const pts = [...pointers.current.values()]
         const mid = {
@@ -594,17 +707,24 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
         drag.current = { px: e.clientX, py: e.clientY }
       }
     },
-    [applyView],
+    [applyView, onMoveNode],
   )
 
-  const endPointer = useCallback((e: ReactPointerEvent<HTMLDivElement>) => {
-    pointers.current.delete(e.pointerId)
-    if (pointers.current.size < 2) pinch.current = null
-    if (pointers.current.size === 0) drag.current = null
-    if (containerRef.current?.hasPointerCapture(e.pointerId)) {
-      containerRef.current.releasePointerCapture(e.pointerId)
-    }
-  }, [])
+  const endPointer = useCallback(
+    (e: ReactPointerEvent<HTMLDivElement>) => {
+      if (dragNode.current) {
+        flushNodeDrag()
+        dragNode.current = null
+      }
+      pointers.current.delete(e.pointerId)
+      if (pointers.current.size < 2) pinch.current = null
+      if (pointers.current.size === 0) drag.current = null
+      if (containerRef.current?.hasPointerCapture(e.pointerId)) {
+        containerRef.current.releasePointerCapture(e.pointerId)
+      }
+    },
+    [flushNodeDrag],
+  )
 
   // -- tooltips ---------------------------------------------------------------
   const openTooltip = useCallback((data: TooltipData) => {
@@ -621,9 +741,11 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   }, [])
 
   // El cierre no es inmediato: si el cursor deja el nodo rumbo al popup (que
-  // flota sobre él), un retardo corto evita que el popup desaparezca antes de
+  // flota sobre él), un retardo evita que el popup desaparezca antes de
   // poder clicarlo (issue #255). Entrar en otro nodo o en el propio popup lo
-  // cancela.
+  // cancela (el tooltip nuevo reemplaza al viejo al instante). #656: 1,2 s
+  // para viajar hasta la tarjeta y usar su botón "Etiquetar"; si el puntero
+  // pasa por otro chip, ese chip abre su propia tarjeta sin esperar.
   const scheduleClose = useCallback(() => {
     if (!hoverCapable) return
     if (hoverCloseTimer.current !== null) return
@@ -631,7 +753,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       hoverCloseTimer.current = null
       setTooltip(null)
       setHoverNode(null)
-    }, 180)
+    }, 1200)
   }, [hoverCapable])
 
   const cancelClose = useCallback(() => {
@@ -645,6 +767,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   useEffect(
     () => () => {
       if (hoverCloseTimer.current !== null) window.clearTimeout(hoverCloseTimer.current)
+      if (dragFrame.current !== null) cancelAnimationFrame(dragFrame.current)
     },
     [],
   )
@@ -975,12 +1098,14 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             <motion.g
               key={node.id}
               transform={`translate(${node.x} ${node.y})`}
-              className="cursor-pointer outline-none"
+              className={editMode ? 'cursor-grab outline-none' : 'cursor-pointer outline-none'}
               role="button"
               tabIndex={0}
+              data-node-id={node.id}
               aria-label={t('topology.routerAria', { name: node.router.name, model: node.router.modelShort, clients: node.router.clients })}
               animate={{ opacity: nodeOpacity(node.id) }}
               transition={{ duration: 0.2 }}
+              onPointerDown={editMode ? (e) => startNodeDrag(node.id, node.x, node.y, e) : undefined}
               onPointerEnter={(e) =>
                 handleNodeHover({ kind: 'router', id: node.id, router: node.router, x: node.x, y: node.y - node.r - 10 }, e)
               }
@@ -1211,6 +1336,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             delay={(1.5 + i * 0.1) * T}
             reduce={reduce ?? false}
             opacity={nodeOpacity(dv.id)}
+            onDragStart={editMode ? (e) => startNodeDrag(dv.id, dv.x, dv.y, e) : undefined}
             onHover={(e) => handleNodeHover({ kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 }, e)}
             onLeave={closeHover}
             onFocus={() => handleNodeFocus({ kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 })}
@@ -1225,9 +1351,11 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             key={chip.id}
             chip={chip}
             ctCount={ctCountByHost.get(chip.id) ?? 0}
+            hostSource={hypervisorSourceByHost.get(chip.id)}
             delay={(1.6 + Math.min(i * 0.02, 0.8)) * T}
             reduce={reduce ?? false}
             opacity={nodeOpacity(chip.id)}
+            onDragStart={editMode ? (e) => startNodeDrag(chip.id, chip.x, chip.y, e) : undefined}
             onHover={(e) => handleNodeHover(chipTip(chip), e)}
             onLeave={closeHover}
             onFocus={() => handleNodeFocus(chipTip(chip))}
@@ -1296,10 +1424,16 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           {[...ctsByHost.keys()].map((hostId, i) => {
             const host = chips.find((c) => c.id === hostId)
             if (!host) return null
+            // #561: el host sellado vía API PVE se etiqueta "Proxmox"; el
+            // inferido por L2 mantiene la etiqueta genérica de hipervisor.
+            const hostKind =
+              hypervisorSourceByHost.get(hostId) === 'proxmox'
+                ? t('topology.host.proxmox')
+                : t('topology.host.hypervisor')
             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')} · ${portName(host.device.port ?? undefined, host.device.portLabel)} · ${ctCountByHost.get(hostId) ?? 0} CT`} />
+                sub={`${hostKind} · ${portName(host.device.port ?? undefined, host.device.portLabel)} · ${ctCountByHost.get(hostId) ?? 0} CT`} />
             )
           })}
           {/* Peers */}
@@ -1338,6 +1472,15 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           touch={!hoverCapable}
           wan={wan}
           routerName={routerName}
+          onTagDevice={
+            onTagDevice
+              ? (device) => {
+                  onTagDevice(device)
+                  setTooltip(null)
+                  setHoverNode(null)
+                }
+              : undefined
+          }
           onPointerEnter={cancelClose}
           onPointerLeave={scheduleClose}
         />
@@ -1401,6 +1544,7 @@ const DistNodeGroup = memo(function DistNodeGroup({
   onFocus,
   onBlur,
   onClick,
+  onDragStart,
 }: {
   dv: DistNodeView
   delay: number
@@ -1411,6 +1555,7 @@ const DistNodeGroup = memo(function DistNodeGroup({
   onFocus: () => void
   onBlur: () => void
   onClick: (e: { stopPropagation: () => void }) => void
+  onDragStart?: (e: ReactPointerEvent) => void
 }) {
   const { t } = useTranslation()
   const SwitchIcon = DEVICE_ICONS.switch
@@ -1418,9 +1563,10 @@ const DistNodeGroup = memo(function DistNodeGroup({
   return (
     <motion.g
       transform={`translate(${dv.x} ${dv.y})`}
-      className="cursor-pointer outline-none"
+      className={onDragStart ? 'cursor-grab outline-none' : 'cursor-pointer outline-none'}
       role="button"
       tabIndex={0}
+      data-node-id={dv.id}
       aria-label={
         managed
           ? `${dv.node.name ?? t('topology.dist.managed')}, LLDP, ${dv.node.ip ?? ''} ${portName(dv.node.port, dv.node.portLabel)}`
@@ -1428,6 +1574,7 @@ const DistNodeGroup = memo(function DistNodeGroup({
       }
       animate={{ opacity }}
       transition={{ duration: 0.2 }}
+      onPointerDown={onDragStart}
       onPointerEnter={onHover}
       onPointerLeave={onLeave}
       onFocus={onFocus}
@@ -1485,6 +1632,7 @@ const DistNodeGroup = memo(function DistNodeGroup({
 const ChipGroup = memo(function ChipGroup({
   chip,
   ctCount,
+  hostSource,
   delay,
   reduce,
   opacity,
@@ -1493,9 +1641,12 @@ const ChipGroup = memo(function ChipGroup({
   onFocus,
   onBlur,
   onClick,
+  onDragStart,
 }: {
   chip: ChipNode
   ctCount: number
+  /** origen del host hipervisores ("proxmox" = sellado vía API PVE, #561) */
+  hostSource?: string
   delay: number
   reduce: boolean
   opacity: number
@@ -1504,14 +1655,24 @@ const ChipGroup = memo(function ChipGroup({
   onFocus: () => void
   onBlur: () => void
   onClick: (e: { stopPropagation: () => void }) => void
+  onDragStart?: (e: ReactPointerEvent) => 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))'
+  // Host hipervisor (Proxmox…): mini NODO redondo con sus CTs detrás, no un
+  // chip cuadrado más (#656 feedback). Acento cuando viene de la API PVE.
+  const isHost = ctCount > 0 && !chip.isCt
+  const hostStroke = hostSource === 'proxmox' ? COLOR.accent : COLOR.ok
   return (
-    <g transform={`translate(${chip.x} ${chip.y})`}>
+    <g
+      transform={`translate(${chip.x} ${chip.y})`}
+      data-node-id={chip.id}
+      className={onDragStart ? 'cursor-grab' : undefined}
+      onPointerDown={onDragStart}
+    >
       <motion.g
         className="cursor-pointer outline-none"
         role="button"
@@ -1533,35 +1694,59 @@ const ChipGroup = memo(function ChipGroup({
           }
         }}
       >
-      <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.4}
-        />
+      {isHost ? (
+        <>
+          {/* halo suave + círculo del mini nodo */}
+          <circle r={half + 4} fill="none" stroke={hostStroke} strokeWidth={1} opacity={0.35} />
+          <circle
+            r={half}
+            fill="rgb(var(--elevated))"
+            stroke={hostStroke}
+            strokeWidth={1.6}
+          />
+          <Server
+            x={-8}
+            y={-8}
+            width={16}
+            height={16}
+            style={{ color: hostStroke }}
+            strokeWidth={1.75}
+            aria-hidden
+          />
+        </>
+      ) : (
+        <>
+          <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.4}
+            />
+          )}
+        </>
       )}
       {/* badge LLDP: esquina superior derecha */}
       {d.lldp && (
@@ -1575,8 +1760,8 @@ const ChipGroup = memo(function ChipGroup({
       {/* 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}>
+          <circle cx={half + 1} cy={-half - 1} r={8} fill="rgb(var(--elevated))" stroke={hostStroke} strokeWidth={1.2} />
+          <text x={half + 1} y={-half + 2} textAnchor="middle" fontSize={8} fontWeight={700} fill={hostStroke}>
             +{ctCount}
           </text>
         </g>

+ 100 - 1
app/src/components/topology/model.ts

@@ -126,6 +126,14 @@ export interface TopologyInput {
   topology?: TopoSemantics
   /** Versión del view-model (SPEC-65 D65-4): la semántica aplica si vm >= 1. */
   vm?: number
+  /**
+   * Posiciones fijadas por el usuario ("lock layout", issue #656): chipId →
+   * {x,y}. Si se pasan, se aplican sobre las calculadas por el layout para
+   * los chips que existan, ANTES de generar los enlaces (así los cables
+   * conectan con la posición real). Los chips sin posición guardada (p. ej.
+   * dispositivos nuevos) conservan su posición automática.
+   */
+  seedPositions?: Record<string, { x: number; y: number }>
 }
 
 /** Chip "+N" de un anillo desbordado (posición ya calculada, geometría local).
@@ -153,6 +161,8 @@ export interface TopologyModel {
   ctsByHost: Map<string, ChipNode[]>
   /** nº de CTs por host (badge +N) */
   ctCountByHost: Map<string, number>
+  /** origen del hipervisor por hostId ("" = L2; "proxmox" = API PVE, #561) */
+  hypervisorSourceByHost: Map<string, string>
   /** radios de los anillos wifi realmente usados por router (guías punteadas) */
   ringRadii: Map<string, number[]>
   /**
@@ -615,7 +625,7 @@ function flowFor(mbps: number, alive = false): { packets: number; packetDur: num
 // Builder
 // ---------------------------------------------------------------------------
 
-export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [], topology, vm }: TopologyInput): TopologyModel {
+export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [], topology, vm, seedPositions }: TopologyInput): TopologyModel {
   // SPEC-65 D65-3/D65-9 B2: la semántica server-side aplica con vm >= 1 y
   // `topology` presente; sin ella, fallback EXACTO al cálculo local.
   const sem = topology && (vm ?? 1) >= 1 ? topology : undefined
@@ -659,6 +669,27 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const routerNodes: RouterNode[] = gatewayNode ? [gatewayNode, ...apNodes, ...switchNodes] : [...apNodes, ...switchNodes]
   const routerById = new Map(routerNodes.map((n) => [n.id, n]))
 
+  // -- layout personalizado (issue #656): nodos router ------------------------
+  // Si el admin ha fijado la posición de un router (p. ej. alejar/acercar un
+  // AP/satélite), esa posición manda. Se aplica ANTES del cálculo de anillos y
+  // distnodes para que todo lo que cuelga de ese router (chips wifi/cable,
+  // switches) se RE-DERIVE alrededor de la posición movida. Los nodos sin
+  // semilla conservan el layout automático.
+  if (seedPositions) {
+    for (const rn of routerNodes) {
+      const p = seedPositions[rn.id]
+      if (!p) continue
+      rn.x = p.x
+      rn.y = p.y
+      const isLeft = rn.x < (gatewayNode?.x ?? 500)
+      rn.label = {
+        x: isLeft ? rn.x - rn.r - 6 : rn.x + rn.r + 6,
+        y: rn.y - 6,
+        anchor: isLeft ? ('end' as const) : ('start' as const),
+      }
+    }
+  }
+
   // D1: el switch gestionado existe como Device Y como distnode managed, pero
   // en el mapa se representa SOLO como nodo managed: se excluye de los chips
   // cualquier Device cuya MAC coincida con la chassis-MAC de un distnode.
@@ -726,6 +757,13 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const hypervisorHosts = new Set(
     distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId!),
   )
+  /** origen del hipervisor por host ("proxmox" = sellado vía API PVE, #561) */
+  const hypervisorSourceByHost = new Map<string, string>()
+  for (const n of distributionNodes) {
+    if (n.kind === 'hypervisor' && n.hostDeviceId && n.source) {
+      hypervisorSourceByHost.set(n.hostDeviceId, n.source)
+    }
+  }
 
   for (const node of routerNodes) {
     const isGw = node.id === gatewayNode?.id
@@ -843,6 +881,22 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     }
   }
 
+  // -- layout personalizado (issue #656): distnodes ---------------------------
+  // Igual que los routers: si el admin fijó la posición de un distnode (switch
+  // inferido/gestionado, incluidos los de cadena), se aplica ANTES de colocar
+  // sus chips hijos (abanico/anillos) para que se re-deriven alrededor de la
+  // posición movida. El resolver de colisiones los trata como fixed, así que
+  // nada los desplaza después.
+  if (seedPositions) {
+    for (const dv of distNodes) {
+      const p = seedPositions[dv.id]
+      if (!p) continue
+      dv.x = p.x
+      dv.y = p.y
+      if (anchorPos.has(dv.id)) anchorPos.set(dv.id, { x: p.x, y: p.y })
+    }
+  }
+
   // -- chips de dispositivos --------------------------------------------------
   const chips: ChipNode[] = []
   const mkChip = (d: Device, hubId: string, isCt = false): ChipNode => ({
@@ -927,6 +981,9 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       // APs y switches: a lo largo del vector desde el gateway hasta su posición
       // canónica, empujados hasta quedar a >= clearDist (fuera del círculo).
       const pushOut = (rn: RouterNode) => {
+        // Si el admin fijó este nodo en el layout personalizado, se respeta su
+        // posición (no se le empuja fuera del círculo virtual): la semilla manda.
+        if (seedPositions?.[rn.id]) return
         const dx = rn.x - gatewayNode.x
         const dy = rn.y - gatewayNode.y
         const d = Math.sqrt(dx * dx + dy * dy) || 1
@@ -1019,6 +1076,27 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     chips.push(...kids)
   }
 
+  // -- layout personalizado (issue #656): HOSTS hipervisores -----------------
+  // La semilla de un host se aplica ANTES de calcular el grid de sus CTs para
+  // que estos se re-deriven alrededor de la posición movida (arrastre del
+  // host = arrastras también sus CTs/VMs). Además el host se dibuja como mini
+  // nodo redondo: tamaño mayor que un chip normal.
+  if (seedPositions) {
+    for (const c of chips) {
+      if (!hypervisorHosts.has(c.id)) continue
+      c.size = 30
+      const p = seedPositions[c.id]
+      if (p) {
+        c.x = p.x
+        c.y = p.y
+      }
+    }
+  } else {
+    for (const c of chips) {
+      if (hypervisorHosts.has(c.id)) c.size = 30
+    }
+  }
+
   // 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>()
@@ -1037,6 +1115,26 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     chips.push(...kids)
   }
 
+  // -- lock layout (issue #656) --------------------------------------------
+  // Aplicar las posiciones fijadas por el usuario sobre las calculadas por el
+  // layout automático. Solo se aplican a los chips que existan en la semilla;
+  // los chips nuevos (sin posición guardada) se quedan en su posición actual,
+  // de modo que el mapa no se reordena aunque aparezcan/desaparezcan nodos.
+  // Va ANTES de la generación de enlaces: los cables se dibujan desde la
+  // posición real del chip tras el override.
+  if (seedPositions) {
+    for (const c of chips) {
+      // Los CTs de un host hipervisores con semilla NO se pinnean: siguen la
+      // posición del host (el grid ya se re-derivó alrededor de él arriba).
+      if (c.isCt && hypervisorHosts.has(c.hubId) && seedPositions[c.hubId]) continue
+      const p = seedPositions[c.id]
+      if (p) {
+        c.x = p.x
+        c.y = p.y
+      }
+    }
+  }
+
   // Chips "+N" de anillos desbordados (solo con semántica server-side):
   // posición en el anillo externo — geometría 100% local (ángulo libre:
   // gateway 60° entre el fan WAN y el uplink patio; AP 250° bajo el router).
@@ -1511,6 +1609,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     distNodes,
     ctsByHost,
     ctCountByHost,
+    hypervisorSourceByHost,
     ringRadii,
     ringOverflowChips,
     links,

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

@@ -263,6 +263,8 @@ export interface DistributionNode {
   hostDeviceId?: string
   /** Nombre descriptivo (host o chasis LLDP del switch gestionado). */
   name?: string
+  /** Origen del hipervisor: ausente = inferido L2; "proxmox" = API PVE (#561). */
+  source?: string
   /** Managed: IP de gestión anunciada por LLDP. */
   ip?: string
   lldp?: LldpInfo | null

+ 120 - 13
app/src/pages/Topology.tsx

@@ -6,7 +6,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
-import { ChevronRight, Maximize, RefreshCw, Tag, ZoomIn, ZoomOut } from 'lucide-react'
+import { Check, ChevronRight, Maximize, Pencil, RefreshCw, RotateCcw, Tag, ZoomIn, ZoomOut } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
 import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from '@/components/ui/sheet'
 import { LegendCard, LegendSheet } from '@/components/topology/LegendCard'
@@ -54,18 +54,26 @@ export default function Topology() {
   const auth = useAuth()
   const { routers, devices, wan, wireguard, distributionNodes, topology, vm, lastSnapshotAt, requestServerRefresh } =
     useNetPulse()
-  const model = useMemo(
-    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes, topology, vm }),
-    [routers, devices, wan, wireguard, distributionNodes, topology, vm],
-  )
   const [showLabels, setShowLabels] = useState(true)
-  const [flow, setFlow] = useState(true)
+  // Flujo de paquetes: sin toggle propio (feedback #656); lo gobierna el
+  // ajuste "Reducir animaciones" (netpulse-reduce-motion) y, dentro del mapa,
+  // el reduce-motion del SO. Además useReducedMotion del propio mapa apaga
+  // los SMIL si el SO lo pide.
+  const [flow] = useState(() => {
+    try {
+      return localStorage.getItem('netpulse-reduce-motion') !== 'true'
+    } catch {
+      return true
+    }
+  })
   const [hoverLink, setHoverLink] = useState<string | null>(null)
   const mapApi = useRef<TopologyMapApi>({})
 
   // Etiquetado manual (issue #142 Fase B): clic en un chip abre el panel de
   // overrides con esa MAC preseleccionada. Solo admin y modo live.
   const canTag = !isDemo && auth?.role === 'admin'
+  // Editar layout (issue #656): solo admin y modo live, como "Etiquetar".
+  const canEdit = !isDemo && auth?.role === 'admin'
   const [tagSheetOpen, setTagSheetOpen] = useState(false)
   const [tagMac, setTagMac] = useState<string | undefined>(undefined)
 
@@ -74,6 +82,61 @@ export default function Topology() {
     setTagSheetOpen(true)
   }
 
+  // -- editar layout (issue #656) --------------------------------------------
+  // Modo edición: el admin arrastra routers/APs y chips para ajustar distancias
+  // (p. ej. alejar/acercar un satélite). Las posiciones se persisten en el
+  // navegador, y fuera del modo edición el layout queda congelado a lo guardado
+  // (no se reordena); solo se re-edita al entrar de nuevo o al "Restablecer".
+  const LAYOUT_KEY = 'netpulse.topology.layout'
+  const [editMode, setEditMode] = useState(false)
+  const [layout, setLayout] = useState<Record<string, { x: number; y: number }>>(() => {
+    try {
+      return JSON.parse(localStorage.getItem(LAYOUT_KEY) || '{}')
+    } catch {
+      return {}
+    }
+  })
+
+  const model = useMemo(
+    () =>
+      buildTopologyModel({
+        routers,
+        devices,
+        wan,
+        wireguard,
+        distributionNodes,
+        topology,
+        vm,
+        seedPositions: Object.keys(layout).length > 0 ? layout : undefined,
+      }),
+    [routers, devices, wan, wireguard, distributionNodes, topology, vm, layout],
+  )
+
+  // Durante el arrastre, onMoveNode actualiza la posición del nodo en `layout`
+  // (vía semilla → el modelo recalcula y los hijos se re-derivan alrededor).
+  const handleMoveNode = (id: string, x: number, y: number) => {
+    setLayout((prev) => (prev[id] && prev[id]!.x === x && prev[id]!.y === y ? prev : { ...prev, [id]: { x, y } }))
+  }
+
+  const handleSaveLayout = () => {
+    try {
+      localStorage.setItem(LAYOUT_KEY, JSON.stringify(layout))
+    } catch {
+      /* si no cabe, se ignora */
+    }
+    setEditMode(false)
+  }
+
+  const handleResetLayout = () => {
+    setLayout({})
+    try {
+      localStorage.removeItem(LAYOUT_KEY)
+    } catch {
+      /* localStorage no disponible */
+    }
+    setEditMode(false)
+  }
+
   // Botón "Refrescar": POST /api/refresh → el backend sondea ya y empuja el
   // snapshot por SSE. El icono gira hasta que llega ese snapshot (sin recargar
   // ni re-montar el grafo) o hasta el timeout de seguridad de 10 s.
@@ -204,13 +267,45 @@ export default function Topology() {
             <Switch checked={showLabels} onCheckedChange={setShowLabels} aria-label={t('topology.showLabels')} />
             {t('topology.labels')}
           </motion.label>
-          <motion.label
-            {...controlMotion(3)}
-            className="flex cursor-pointer items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm font-medium text-text-secondary"
-          >
-            <Switch checked={flow} onCheckedChange={setFlow} aria-label={t('topology.animateFlow')} />
-            {t('topology.flow')}
-          </motion.label>
+          {canEdit && (
+            <motion.div
+              {...controlMotion(3)}
+              className="flex items-center gap-1.5 rounded-xl border border-border bg-surface p-1"
+            >
+              {editMode ? (
+                <>
+                  <button
+                    type="button"
+                    onClick={handleSaveLayout}
+                    className="flex h-9 items-center gap-1.5 rounded-lg bg-accent px-3 text-[13px] font-semibold text-canvas transition-opacity hover:opacity-90"
+                  >
+                    <Check className="h-4 w-4" strokeWidth={2} />
+                    {t('topology.editSave')}
+                  </button>
+                  <button
+                    type="button"
+                    onClick={handleResetLayout}
+                    aria-label={t('topology.editReset')}
+                    title={t('topology.editReset')}
+                    className="flex h-9 w-9 items-center justify-center rounded-lg text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+                  >
+                    <RotateCcw className="h-4 w-4" strokeWidth={1.75} />
+                  </button>
+                </>
+              ) : (
+                <button
+                  type="button"
+                  onClick={() => setEditMode(true)}
+                  aria-label={t('topology.edit')}
+                  title={t('topology.editHint')}
+                  className="flex h-9 items-center gap-1.5 rounded-lg px-3 text-[13px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-accent"
+                >
+                  <Pencil className="h-4 w-4" strokeWidth={1.75} />
+                  <span className="hidden sm:inline">{t('topology.edit')}</span>
+                </button>
+              )}
+            </motion.div>
+          )}
         </div>
       </header>
 
@@ -228,7 +323,19 @@ export default function Topology() {
           hoverLink={hoverLink}
           onHoverLink={setHoverLink}
           onTagDevice={canTag ? handleTagDevice : undefined}
+          editMode={canEdit && editMode}
+          onMoveNode={canEdit && editMode ? handleMoveNode : undefined}
         />
+        {/* Aviso de modo edición (issue #656): recordatorio visible de que los
+            nodos son arrastrables mientras se edita el layout. */}
+        {canEdit && editMode && (
+          <div
+            className="pointer-events-none absolute bottom-3 left-1/2 z-10 -translate-x-1/2 rounded-xl border border-accent/40 bg-elevated/95 px-4 py-2 text-caption font-medium text-accent shadow-lg backdrop-blur-md"
+            role="status"
+          >
+            {t('topology.editBanner')}
+          </div>
+        )}
         {/* Zoom flotante (móvil: los controles del header quedan lejos del mapa) */}
         <div
           className="absolute right-3 top-3 z-10 flex flex-col gap-0.5 rounded-xl border border-border bg-elevated/90 p-1 backdrop-blur-md lg:hidden"

+ 80 - 0
server-go/internal/adapters/fdbsticky.go

@@ -0,0 +1,80 @@
+// fdbsticky.go — memoria pegajosa del puerto FDB (issue #656).
+//
+// Problema: las entradas del bridge FDB caducan (~5 min) y los dispositivos
+// callados (AV: TV, receptor, shield…) pierden su evidencia de puerto entre
+// ticks aunque sigan online (ARP). El mapa los re-anclaba al gateway y
+// "saltaban" del switch inferido donde están cableados físicamente.
+//
+// Solución: recordar la última boca REAL donde se vio cada MAC (fdbMemo, con
+// TTL) y usar ese recuerdo como OVERLAY de inferTopology, SOLO para MACs que
+// el FDB actual ya no tiene. La memo nunca crea presencia: si el dispositivo
+// no está online por sí mismo (wireless/FDB/ARP), no se dibuja. El FDB real
+// siempre manda sobre el recuerdo.
+package adapters
+
+import "time"
+
+// fdbStickyTTL: frescura de la memo. Los dispositivos AV despiertan y hablan
+// (refrescando la memo) mucho antes; 30 min es un margen holgado que además
+// acota el efecto de un dispositivo cambiado de boca.
+const fdbStickyTTL = 30 * time.Minute
+
+// fdbPortMemo: última boca real donde el FDB vio una MAC.
+type fdbPortMemo struct {
+	routerID string
+	port     string
+	ts       int64 // epoch ms
+}
+
+// updateFdbMemo refresca la memo con el FDB real de este tick y poda las
+// entradas caducadas. Devuelve el snapshot de la memo (para el overlay).
+func (l *Live) updateFdbMemo(polled map[string]*routerPolled, nowMs int64) map[string]fdbPortMemo {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if l.fdbMemo == nil {
+		l.fdbMemo = map[string]fdbPortMemo{}
+	}
+	for routerID, p := range polled {
+		for mac, port := range p.fdb {
+			l.fdbMemo[mac] = fdbPortMemo{routerID: routerID, port: port, ts: nowMs}
+		}
+	}
+	ttlMs := fdbStickyTTL.Milliseconds()
+	for mac, m := range l.fdbMemo {
+		if nowMs-m.ts > ttlMs {
+			delete(l.fdbMemo, mac)
+		}
+	}
+	return l.fdbMemo
+}
+
+// overlayStickyFdb devuelve una copia de `polled` donde cada router lleva, ADEMÁS
+// de su FDB real, las MACs recordadas (memo fresca) que ya no estén presentes.
+// Función pura: no toca polled ni memo. Solo la usa inferTopology.
+func overlayStickyFdb(polled map[string]*routerPolled, memo map[string]fdbPortMemo, nowMs int64) map[string]*routerPolled {
+	out := make(map[string]*routerPolled, len(polled))
+	for id, p := range polled {
+		np := *p // shallow copy: solo se sustituye fdb (map propio)
+		nf := make(map[string]string, len(p.fdb)+4)
+		for k, v := range p.fdb {
+			nf[k] = v
+		}
+		np.fdb = nf
+		out[id] = &np
+	}
+	ttlMs := fdbStickyTTL.Milliseconds()
+	for mac, m := range memo {
+		if nowMs-m.ts > ttlMs {
+			continue
+		}
+		p, ok := out[m.routerID]
+		if !ok {
+			continue // el router ya no está en la flota
+		}
+		if _, exists := p.fdb[mac]; exists {
+			continue // el FDB real manda
+		}
+		p.fdb[mac] = m.port
+	}
+	return out
+}

+ 107 - 0
server-go/internal/adapters/fdbsticky_test.go

@@ -0,0 +1,107 @@
+// fdbsticky_test.go — memoria pegajosa del puerto FDB (issue #656).
+package adapters
+
+import (
+	"testing"
+)
+
+// TestOverlayStickyFdb: las MACs recordadas (frescas) que faltan en el FDB
+// actual se añaden al router correspondiente; las caducadas y las ya
+// presentes no se tocan (el FDB real manda); polled no se muta.
+func TestOverlayStickyFdb(t *testing.T) {
+	now := int64(1_700_000_000_000)
+	polled := map[string]*routerPolled{
+		"gateway": {cfg: RouterConfig{ID: "gateway", IsGateway: true}, brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{"GG:GG:GG:GG:GG:GG": "lan1", "11:11:11:11:11:11": "lan1"}},
+	}
+	memo := map[string]fdbPortMemo{
+		// fresca y ausente del FDB → se añade
+		"AA:AA:AA:AA:AA:AA": {routerID: "gateway", port: "lan1", ts: now - 60_000},
+		// caducada → fuera
+		"BB:BB:BB:BB:BB:BB": {routerID: "gateway", port: "lan2", ts: now - fdbStickyTTL.Milliseconds() - 1},
+		// ya presente con OTRA boca → el FDB real manda
+		"11:11:11:11:11:11": {routerID: "gateway", port: "lan3", ts: now},
+		// de un router que ya no existe → fuera
+		"CC:CC:CC:CC:CC:CC": {routerID: "borrado", port: "lan1", ts: now},
+	}
+	out := overlayStickyFdb(polled, memo, now)
+
+	gw := out["gateway"]
+	if gw.fdb["AA:AA:AA:AA:AA:AA"] != "lan1" {
+		t.Fatalf("la memo fresca debería añadirse: %+v", gw.fdb)
+	}
+	if _, ok := gw.fdb["BB:BB:BB:BB:BB:BB"]; ok {
+		t.Fatal("la memo caducada no debería añadirse")
+	}
+	if gw.fdb["11:11:11:11:11:11"] != "lan1" {
+		t.Fatalf("el FDB real manda sobre la memo: %q", gw.fdb["11:11:11:11:11:11"])
+	}
+	if _, ok := gw.fdb["CC:CC:CC:CC:CC:CC"]; ok {
+		t.Fatal("la memo de un router inexistente no debería añadirse")
+	}
+	// polled original intacto (no mutación)
+	if _, ok := polled["gateway"].fdb["AA:AA:AA:AA:AA:AA"]; ok {
+		t.Fatal("overlayStickyFdb no debe mutar polled")
+	}
+}
+
+// TestInferTopologyStickyKeepsSwitchAttach: un dispositivo callado (online por
+// ARP, RouterID=gateway) cuya entrada FDB caducó conserva su puesto bajo el
+// switch inferido de su boca gracias al overlay.
+func TestInferTopologyStickyKeepsSwitchAttach(t *testing.T) {
+	now := int64(1_700_000_000_000)
+	// FDB actual: el gateway solo ve la MAC del citadel en lan1 (la del
+	// marantz caducó por silencio).
+	polled := map[string]*routerPolled{
+		"gateway": {cfg: RouterConfig{ID: "gateway", Name: "GW", IsGateway: true}, brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{
+				"GG:GG:GG:GG:GG:GG": "lan1",
+				"04:D4:C4:8B:30:A7": "lan1",
+			}},
+	}
+	memo := map[string]fdbPortMemo{
+		"AA:BB:CC:DD:EE:FF": {routerID: "gateway", port: "lan1", ts: now - 5*60_000},
+	}
+	sticky := overlayStickyFdb(polled, memo, now)
+
+	devices := []Device{
+		// marantz: online vía ARP (RouterID gateway), sin entrada FDB propia
+		{ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "marantz", RouterID: "gateway", Band: "cable", Online: true},
+		{ID: "04-d4-c4-8b-30-a7", MAC: "04:D4:C4:8B:30:A7", Name: "shield", RouterID: "gateway", Band: "cable", Online: true},
+	}
+	devices, dists := inferTopology(sticky, devices)
+
+	if len(dists) == 0 || dists[0].ID != "dist-gateway-lan1" || dists[0].Kind != "inferred" {
+		t.Fatalf("esperado dist-gateway-lan1 inferred, got %+v", dists)
+	}
+	var marantz *Device
+	for i := range devices {
+		if devices[i].MAC == "AA:BB:CC:DD:EE:FF" {
+			marantz = &devices[i]
+		}
+	}
+	if marantz == nil {
+		t.Fatal("marantz no encontrado")
+	}
+	if marantz.Port != "lan1" || marantz.AttachTo != "dist-gateway-lan1" {
+		t.Fatalf("marantz debería conservar lan1/dist-gateway-lan1: port=%q attachTo=%q", marantz.Port, marantz.AttachTo)
+	}
+}
+
+// TestUpdateFdbMemoRefreshAndPrune: la memo se refresca con el FDB real y las
+// entradas viejas se podan.
+func TestUpdateFdbMemoRefreshAndPrune(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	now := int64(1_700_000_000_000)
+	l.fdbMemo["AA:AA:AA:AA:AA:AA"] = fdbPortMemo{routerID: "gateway", port: "lan1", ts: now - fdbStickyTTL.Milliseconds() - 5_000}
+	polled := map[string]*routerPolled{
+		"gateway": {cfg: RouterConfig{ID: "gateway"}, fdb: map[string]string{"BB:BB:BB:BB:BB:BB": "lan2"}},
+	}
+	memo := l.updateFdbMemo(polled, now)
+	if _, ok := memo["AA:AA:AA:AA:AA:AA"]; ok {
+		t.Fatal("la entrada caducada debería podarse")
+	}
+	if m, ok := memo["BB:BB:BB:BB:BB:BB"]; !ok || m.port != "lan2" || m.routerID != "gateway" {
+		t.Fatalf("la entrada fresca debería estar: %+v", memo)
+	}
+}

+ 49 - 26
server-go/internal/adapters/live.go

@@ -321,6 +321,13 @@ type Live struct {
 	pveInv    *pveInventory
 	pveInvAt  time.Time
 
+	// fdbMemo (#656): última boca REAL donde el FDB vio cada MAC (epoch ms).
+	// Los dispositivos callados (AV: TV, receptor, shield…) caducan su entrada
+	// FDB a los ~5 min sin hablar y "saltaban" del switch inferido al anchor
+	// del gateway entre ticks. La memo se usa SOLO como overlay de inferTopology
+	// (nunca para crear presencia/online) mientras la entrada sea fresca.
+	fdbMemo map[string]fdbPortMemo
+
 	sfMu   sync.Mutex
 	sfCall *sfCall
 }
@@ -372,6 +379,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		agentOutdatedAlerted: map[string]bool{},
 		routerMacs:           map[string]string{},
 		sshAuthFailAlerted:   map[string]bool{},
+		fdbMemo:              map[string]fdbPortMemo{},
 		portMon:              NewPortMonitor(cfg != nil && cfg.GhostPortEnabled),
 		suppression:          alerts.NewSuppressionGraph(),
 	}
@@ -1891,23 +1899,21 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		gwID = gw.ID
 	}
 	// (2) FDB de satélites: pista solo de ESTE tick (no se guarda).
-	// REGLA DE RECONCILIACIÓN: si una MAC cableada aparece tanto en el FDB
-	// del gateway como en el FDB de un satélite, el satélite la ve porque
-	// está bridged al mismo segmento L2 — NO es un cliente directo del
-	// satélite. Solo cuentan como clientes del satélite las MACs que el
-	// gateway NO ve (dispositivos realmente tras ese satélite, sin bridge
-	// al gateway).
-	// EXCEPCIÓN: los routers agent-only (switches con agente propio) son la
-	// fuente más específica — sus dispositivos se conservan con RouterID
-	// del switch, aunque el gateway también los vea en su FDB.
-	gwFDB := map[string]bool{}
-	if gwID != "" {
-		if gwPolled := polled[gwID]; gwPolled != nil {
-			for mac := range gwPolled.fdb {
-				gwFDB[mac] = true
-			}
-		}
-	}
+	// REGLA DE RECONCILIACIÓN (issue #656): una MAC aprendida por un satélite
+	// en una boca que NO es su uplink (boca no-infra) es un cliente cableado
+	// directo de ESE satélite — el FDB la aprendió en un puerto físico suyo.
+	// Aunque el gateway también la vea en su FDB (porque el satélite está
+	// bridged al mismo segmento L2, como un dumb AP/bridge), la boca local
+	// del satélite es la evidencia más específica de dónde va el cable, así
+	// que se atribuye al satélite.
+	// El uplink queda excluido por infraPorts (boca donde se aprende una MAC
+	// de bridge de otro router = tránsito); aquí NO se cuenta.
+	// (3) FDB del gateway: solo las MACs que ningún satélite haya reclamado
+	// en una boca local, para no quedarse fuera si el gateway las ve en su
+	// propio FDB (misma LAN bridged).
+	// EXCEPCIÓN preservada: los routers agent-only (switches con agente
+	// propio) son la fuente más específica — sus dispositivos se conservan
+	// con RouterID del switch (esta ruta ya los trataba por separado).
 	// MACs de bridge de todos los routers sondeados: una boca de satélite
 	// que aprende una de ellas es un UPLINK (enlaza con otro equipo de red),
 	// y lo que aprende por ahí es el resto de la LAN en tránsito, no clientes
@@ -1934,9 +1940,6 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 				continue // uplink: MACs en tránsito, no clientes de este equipo
 			}
 			if _, ok := seen[mac]; !ok {
-				if gwFDB[mac] && !p.cfg.AgentOnly {
-					continue // gateway bridge pasivo, no es cliente del satélite
-				}
 				seen[mac] = seenInfo{routerID, "cable", nil}
 			}
 		}
@@ -2159,6 +2162,12 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		}
 		devices = append(devices, d)
 	}
+	// Orden estable por MAC (issue #656): buildDevices itera un mapa de Go
+	// (allMacs), cuyo orden es aleatorio entre ticks. Ese orden llega al
+	// frontend y alimenta la asignación de ranuras de los anillos de la
+	// topología → los chips saltaban de posición al refrescar. Ordenar por
+	// MAC hace el contrato determinista para el mismo set de dispositivos.
+	sort.Slice(devices, func(i, j int) bool { return devices[i].MAC < devices[j].MAC })
 	return devices
 }
 
@@ -2341,7 +2350,12 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		routerList = append(routerList, router)
 	}
 	devices := l.buildDevices(polled)
-	devices, distNodes := inferTopology(polled, devices)
+	// #656: overlay sticky del FDB. La memo se refresca con el FDB real y se
+	// usa SOLO para inferTopology: los dispositivos callados (entrada FDB
+	// caducada) conservan su boca y no saltan del switch inferido al gateway.
+	nowMs := time.Now().UnixMilli()
+	stickyPolled := overlayStickyFdb(polled, l.updateFdbMemo(polled, nowMs), nowMs)
+	devices, distNodes := inferTopology(stickyPolled, devices)
 	// Capa 2 manual (issue #142): overrides de topología tras el autodiscover.
 	// Sin BD (tests/demo) → no-op.
 	if l.db != nil {
@@ -2349,9 +2363,11 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	}
 	// Capa 3 PVE (#561): si hay cluster Proxmox configurado, el inventario
 	// read-only sella hypervisor/ct con attachTo correcto (la relación
-	// CT→host no es deducible del L2). Va DESPUÉS de los overrides manuales:
-	// un override explícito del usuario tiene prioridad sobre el sello.
-	l.sealProxmoxInfra(devices)
+	// CT→host no es deducible del L2) y crea los distnodes kind=hypervisor
+	// para que el frontend anide los CTs bajo el host. Va DESPUÉS de los
+	// overrides manuales: un override explícito del usuario tiene prioridad
+	// sobre el sello.
+	distNodes = l.sealProxmoxInfra(devices, distNodes)
 	// Supresión topológica (#332): actualizar grafo parent→child.
 	// Todos los no-gateway cuelgan del gateway.
 	l.mu.Lock()
@@ -2930,9 +2946,16 @@ func (l *Live) GetDevices(context.Context) []Device {
 	l.mu.Lock()
 	polled := l.lastPolled
 	l.mu.Unlock()
-	devices, _ := inferTopology(polled, l.buildDevices(polled))
+	// #656: overlay sticky del FDB (paridad con el overview) ANTES del sellado
+	// PVE, que sobreescribe attachTo con ground truth del cluster.
+	detailNowMs := time.Now().UnixMilli()
+	devices, _ := inferTopology(
+		overlayStickyFdb(polled, l.updateFdbMemo(polled, detailNowMs), detailNowMs),
+		l.buildDevices(polled),
+	)
 	// #561: sellado de infraestructura con el inventario PVE (si configurado).
-	l.sealProxmoxInfra(devices)
+	// El detalle no consume distnodes, pero el sellado de devices sí corre.
+	l.sealProxmoxInfra(devices, nil)
 	return devices
 }
 

+ 52 - 10
server-go/internal/adapters/proxmox.go

@@ -168,19 +168,25 @@ func (l *Live) fetchPveInventory(client *pve.Client) *pveInventory {
 // "citadel-01"). Esto resuelve el caso real donde el host PVE está en la LAN
 // con su nombre y sus CTs (MACs BC:24:11 o locally-administered) ya visibles
 // como devices sin sellar.
-func (l *Live) sealProxmoxInfra(devices []Device) {
+//
+// Además devuelve los distnodes kind=hypervisor de cada host PVE (con
+// Source="proxmox"): sin ellos el frontend no usa la maquinaria de
+// hipervisor (grid de CTs bajo el host, badge +N, enlaces host→CT) y los CTs
+// quedan como un abanico de chips normales. Los hosts que ya tengan un
+// distnode hypervisor inferido por L2 no se duplican.
+func (l *Live) sealProxmoxInfra(devices []Device, dists []DistributionNode) []DistributionNode {
 	inv := l.pveInventoryCached()
 	if inv == nil {
-		return
+		return dists
 	}
-	applyPVEInfra(devices, inv)
+	return applyPVEInfra(devices, dists, inv)
 }
 
 // applyPVEInfra sella devices con un inventario dado (función pura, testeable
 // sin red ni kv). Ver sealProxmoxInfra para el diseño.
-func applyPVEInfra(devices []Device, inv *pveInventory) {
+func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory) []DistributionNode {
 	if inv == nil || len(inv.ctByMAC) == 0 {
-		return
+		return dists
 	}
 	// Índices. El host de un nodo se casa por IP del nodo (vmbr0, la que da
 	// el cluster) con prioridad, y por nombre del device como fallback. Un
@@ -230,14 +236,50 @@ func applyPVEInfra(devices []Device, inv *pveInventory) {
 	// Sellar los hosts y renombrarlos con el nombre del nodo cuando el device
 	// solo se conoce por MAC (p. ej. "FE:C9:95:97:15:30" → "citadel-01").
 	for node, id := range hostIDByNode {
-		if idx, ok := hostIdxByID[id]; ok {
-			devices[idx].Infra = "hypervisor"
-			if name, ok := nodeNameByID[id]; ok && looksLikeMACName(devices[idx].Name) {
-				devices[idx].Name = name
-				_ = node
+		idx, ok := hostIdxByID[id]
+		if !ok {
+			continue
+		}
+		devices[idx].Infra = "hypervisor"
+		if name, ok := nodeNameByID[id]; ok && looksLikeMACName(devices[idx].Name) {
+			devices[idx].Name = name
+			_ = node
+		}
+	}
+	// CTs por host (para el macCount informativo del distnode).
+	ctCountByHost := map[string]int{}
+	for mac := range inv.ctByMAC {
+		if idx, ok := hostIdxByID[macToDeviceID(mac)]; ok {
+			if h := devices[idx].AttachTo; h != "" {
+				ctCountByHost[h]++
 			}
 		}
 	}
+	// Distnodes kind=hypervisor por host PVE: activan en el frontend el grid
+	// de CTs, el badge +N y los enlaces host→CT. Se saltan los hosts que ya
+	// tengan uno inferido por L2 (no duplicar).
+	existingHost := map[string]bool{}
+	for _, dn := range dists {
+		if dn.Kind == "hypervisor" && dn.HostDeviceID != "" {
+			existingHost[dn.HostDeviceID] = true
+		}
+	}
+	for node, id := range hostIDByNode {
+		if existingHost[id] {
+			continue
+		}
+		idx, ok := hostIdxByID[id]
+		if !ok {
+			continue
+		}
+		dists = append(dists, DistributionNode{
+			ID: "dist-pve-" + node, Kind: "hypervisor",
+			RouterID: devices[idx].RouterID, Port: devices[idx].Port, PortLabel: devices[idx].PortLabel,
+			HostDeviceID: id, Name: node, MacCount: ctCountByHost[id],
+			Source: "proxmox",
+		})
+	}
+	return dists
 }
 
 // looksLikeMACName: true si el nombre del device es una MAC (no tiene nombre

+ 55 - 5
server-go/internal/adapters/proxmox_test.go

@@ -24,7 +24,7 @@ func TestSealProxmoxInfra(t *testing.T) {
 		{ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "homeassistant", RouterID: "gateway", Band: "cable", Port: "lan3", AttachTo: "dist-gateway-lan3"},
 		{ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "shield", RouterID: "gateway", Band: "cable", Port: "lan3"},
 	}
-	applyPVEInfra(devices, inv)
+	applyPVEInfra(devices, nil, inv)
 
 	if devices[0].Infra != "hypervisor" {
 		t.Fatalf("host citadel-01: infra=%q (want hypervisor)", devices[0].Infra)
@@ -55,7 +55,7 @@ func TestSealProxmoxInfra(t *testing.T) {
 // conocidos → no-op (los devices no cambian).
 func TestSealProxmoxInfraSinInventario(t *testing.T) {
 	devices := []Device{{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01"}}
-	applyPVEInfra(devices, nil)
+	applyPVEInfra(devices, nil, nil)
 	if devices[0].Infra != "" || devices[0].AttachTo != "" {
 		t.Fatalf("sin inventario no debe tocar devices: %+v", devices[0])
 	}
@@ -73,7 +73,7 @@ func TestSealProxmoxInfraHostSinDevice(t *testing.T) {
 	devices := []Device{
 		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway"},
 	}
-	applyPVEInfra(devices, inv)
+	applyPVEInfra(devices, nil, inv)
 	if devices[0].Infra != "ct" {
 		t.Fatalf("webs infra=%q (want ct aunque no haya host device)", devices[0].Infra)
 	}
@@ -97,7 +97,7 @@ func TestSealProxmoxInfraHostPorIP(t *testing.T) {
 		{ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "E8:FF:1E:DD:C7:ED", IP: "192.168.1.101", RouterID: "switch16"},
 		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", RouterID: "switch16", AttachTo: "dist-switch16-lan8"},
 	}
-	applyPVEInfra(devices, inv)
+	applyPVEInfra(devices, nil, inv)
 	if devices[0].Infra != "hypervisor" {
 		t.Fatalf("host por IP: infra=%q (want hypervisor)", devices[0].Infra)
 	}
@@ -128,7 +128,7 @@ func TestSealProxmoxInfraHostConflictoNICs(t *testing.T) {
 		{ID: "fe-c9-95-97-15-30", MAC: "FE:C9:95:97:15:30", Name: "FE:C9:95:97:15:30", IP: "192.168.1.100", Online: true},
 		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", Online: true},
 	}
-	applyPVEInfra(devices, inv)
+	applyPVEInfra(devices, nil, inv)
 	// El hypervisor debe ser el device con IP .100 (online), no el offline.
 	if devices[1].Infra != "hypervisor" || devices[1].Name != "citadel-01" {
 		t.Fatalf("host por IP debería ganar: %+v (infra=%q name=%q)", devices[1], devices[1].Infra, devices[1].Name)
@@ -148,3 +148,53 @@ func TestPVEMacToDeviceID(t *testing.T) {
 		t.Fatalf("macToDeviceID: %q", got)
 	}
 }
+
+// TestPVEHypervisorDistNodes: el sellado PVE crea un distnode kind=hypervisor
+// por host (con Source=proxmox y HostDeviceID del host) para que el frontend
+// anide los CTs bajo él (grid +N). Un host que ya tenga distnode hypervisor
+// inferido por L2 NO se duplica.
+func TestPVEHypervisorDistNodes(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc"},
+			"02:78:F4:02:8A:94": {Name: "pbs", Node: "citadel-02", Type: "lxc"},
+		},
+		nodeNames: map[string]bool{"citadel-02": true, "citadel-01": true},
+		nodeIPs:   map[string]string{"citadel-02": "192.168.1.101", "citadel-01": "192.168.1.100"},
+	}
+	devices := []Device{
+		{ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "E8:FF:1E:DD:C7:ED", IP: "192.168.1.101", RouterID: "switch16", Port: "lan8"},
+		{ID: "fe-c9-95-97-15-30", MAC: "FE:C9:95:97:15:30", Name: "FE:C9:95:97:15:30", IP: "192.168.1.100", RouterID: "gateway", Port: "lan1"},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs"},
+		{ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "pbs"},
+	}
+	// citadel-01 ya tiene distnode hypervisor inferido por L2: no duplicar.
+	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "hypervisor", RouterID: "gateway", HostDeviceID: "fe-c9-95-97-15-30"}}
+	dists = applyPVEInfra(devices, dists, inv)
+
+	if len(dists) != 2 {
+		t.Fatalf("esperado 2 distnodes (L2 + 1 PVE), got %d: %+v", len(dists), dists)
+	}
+	dn := dists[1]
+	if dn.ID != "dist-pve-citadel-02" || dn.Kind != "hypervisor" || dn.Source != "proxmox" {
+		t.Fatalf("distnode PVE mal construido: %+v", dn)
+	}
+	if dn.HostDeviceID != devices[0].ID {
+		t.Fatalf("HostDeviceID=%q (want %q)", dn.HostDeviceID, devices[0].ID)
+	}
+	if dn.Name != "citadel-02" || dn.RouterID != "switch16" || dn.Port != "lan8" {
+		t.Fatalf("distnode PVE con metadatos del host incorrectos: %+v", dn)
+	}
+	if dn.MacCount != 2 {
+		t.Fatalf("MacCount=%d (want 2 CTs sellados)", dn.MacCount)
+	}
+}
+
+// TestPVEHypervisorDistNodesSinHost: sin inventario los distnodes no cambian.
+func TestPVEHypervisorDistNodesSinHost(t *testing.T) {
+	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred"}}
+	out := applyPVEInfra([]Device{{ID: "x", MAC: "AA:BB:CC:DD:EE:FF"}}, dists, nil)
+	if len(out) != 1 || out[0].ID != "dist-gateway-lan1" {
+		t.Fatalf("sin inventario no debe añadir distnodes: %+v", out)
+	}
+}

+ 151 - 0
server-go/internal/adapters/topology656_test.go

@@ -0,0 +1,151 @@
+// topology656_test.go — Issue #656: reconciliación del FDB de satélites.
+//
+// Un dumb AP/bridge comparte el segmento L2 con el gateway, así que el
+// gateway también ve (en su FDB) las MACs de los clientes cableados del
+// satélite. Antes, ese solape descartaba al satélite y los clientes se
+// atribuían al router principal. El fix atribuye al satélite las MACs que
+// aprende en sus bocas locales NO-uplink, preservando la exclusión del
+// uplink (infraPorts) y la fuente específica de los routers agent-only.
+package adapters
+
+import (
+	"testing"
+)
+
+// busca un Device por MAC; falla si no existe.
+func mustDevice(t *testing.T, devs []Device, mac string) Device {
+	t.Helper()
+	for _, d := range devs {
+		if d.MAC == mac {
+			return d
+		}
+	}
+	t.Fatalf("dispositivo %s no encontrado en %+v", mac, devs)
+	return Device{}
+}
+
+// TestBuildDevicesDumbAPWiredClient: cliente Ethernet cableado a un dumb AP
+// (mismo L2 que el gateway) se atribuye al SATÉLITE, no al router principal.
+func TestBuildDevicesDumbAPWiredClient(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Main", Host: "192.168.1.1", IsGateway: true},
+	}, nil)
+	polled := map[string]*routerPolled{
+		"gateway": {
+			cfg:   RouterConfig{ID: "gateway", Name: "Main", IsGateway: true},
+			brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{
+				"GG:GG:GG:GG:GG:GG": "lan1", // bridge del gateway (excluida)
+				"11:11:11:11:11:11": "lan1", // cliente directo del gateway
+				"66:66:66:66:66:66": "lan2", // cliente del dumb AP (también vedo por el gateway)
+			},
+		},
+		"dumbap": {
+			cfg:   RouterConfig{ID: "dumbap", Name: "Luizjana2", Host: "192.168.1.2"},
+			brMac: "AA:AA:AA:AA:AA:AA",
+			fdb: map[string]string{
+				"66:66:66:66:66:66": "lan1", // boca LOCAL del dumb AP (no-infra)
+				"GG:GG:GG:GG:GG:GG": "lan2", // MAC bridge del gateway → uplink
+				"AA:AA:AA:AA:AA:AA": "lan2", // bridge propio → uplink
+				"11:11:11:11:11:11": "lan2", // cliente del gateway, tránsito por el uplink
+			},
+		},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 2 {
+		t.Fatalf("esperado 2 dispositivos, got %d: %+v", len(devs), devs)
+	}
+	// El cliente cableado al dumb AP debe atribuirse al dumb AP.
+	if d := mustDevice(t, devs, "66:66:66:66:66:66"); d.RouterID != "dumbap" {
+		t.Fatalf("cliente del dumb AP: RouterID esperado dumbap, got %q", d.RouterID)
+	}
+	// El cliente directo del gateway sigue en el gateway (aparece en el uplink
+	// del dumb AP, que es infra → tránsito, no se lo apropia).
+	if d := mustDevice(t, devs, "11:11:11:11:11:11"); d.RouterID != "gateway" {
+		t.Fatalf("cliente del gateway: RouterID esperado gateway, got %q", d.RouterID)
+	}
+}
+
+// TestBuildDevicesOwnBridgeExcluded: la MAC de bridge del propio satélite y la
+// del gateway no aparecen nunca como dispositivos.
+func TestBuildDevicesOwnBridgeExcluded(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Main", IsGateway: true},
+	}, nil)
+	polled := map[string]*routerPolled{
+		"gateway": {cfg: RouterConfig{ID: "gateway", IsGateway: true}, brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{"GG:GG:GG:GG:GG:GG": "lan1"}},
+		"dumbap": {cfg: RouterConfig{ID: "dumbap"}, brMac: "AA:AA:AA:AA:AA:AA",
+			fdb: map[string]string{"GG:GG:GG:GG:GG:GG": "lan2", "AA:AA:AA:AA:AA:AA": "lan2"}},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 0 {
+		t.Fatalf("esperado 0 dispositivos (todas las MACs son de bridge), got %d: %+v", len(devs), devs)
+	}
+}
+
+// TestBuildDevicesAgentOnlySpecific: un switch agent-only sigue siendo la
+// fuente más específica de sus clientes, aunque el gateway también los vea
+// (excepción preservada; #291).
+func TestBuildDevicesAgentOnlySpecific(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Main", IsGateway: true},
+	}, nil)
+	polled := map[string]*routerPolled{
+		"gateway": {
+			cfg:   RouterConfig{ID: "gateway", IsGateway: true},
+			brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{
+				"GG:GG:GG:GG:GG:GG": "lan1",
+				"77:77:77:77:77:77": "lan2", // cliente del switch (visto también por el gateway)
+			},
+		},
+		"switch16": {
+			cfg:       RouterConfig{ID: "switch16", Name: "SW-16", Host: "192.168.1.6", AgentOnly: true},
+			brMac:     "BB:BB:BB:BB:BB:BB",
+			agentKind: "external",
+			fdb: map[string]string{
+				"77:77:77:77:77:77": "lan3", // boca local del switch
+				"BB:BB:BB:BB:BB:BB": "lan1", // bridge propio → uplink
+				"GG:GG:GG:GG:GG:GG": "lan1", // MAC bridge del gateway → uplink
+			},
+		},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 1 {
+		t.Fatalf("esperado 1 dispositivo, got %d: %+v", len(devs), devs)
+	}
+	if d := mustDevice(t, devs, "77:77:77:77:77:77"); d.RouterID != "switch16" {
+		t.Fatalf("cliente del switch agent-only: RouterID esperado switch16, got %q", d.RouterID)
+	}
+}
+
+// TestBuildDevicesStableOrder: buildDevices devuelve los dispositivos en orden
+// determinista (por MAC), para que los anillos de la topología no salten al
+// refrescar (#656).
+func TestBuildDevicesStableOrder(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "gw", Name: "GW", IsGateway: true}}, nil)
+	polled := map[string]*routerPolled{
+		"gw": {
+			cfg:   RouterConfig{ID: "gw", Name: "GW", IsGateway: true},
+			brMac: "GG:GG:GG:GG:GG:GG",
+			fdb: map[string]string{
+				"GG:GG:GG:GG:GG:GG": "lan1",
+				"CC:CC:CC:CC:CC:CC": "lan1",
+				"AA:AA:AA:AA:AA:AA": "lan1",
+				"BB:BB:BB:BB:BB:BB": "lan1",
+			},
+		},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 3 {
+		t.Fatalf("esperado 3 dispositivos, got %d: %+v", len(devs), devs)
+	}
+	macs := []string{devs[0].MAC, devs[1].MAC, devs[2].MAC}
+	want := []string{"AA:AA:AA:AA:AA:AA", "BB:BB:BB:BB:BB:BB", "CC:CC:CC:CC:CC:CC"}
+	for i := range want {
+		if macs[i] != want[i] {
+			t.Fatalf("orden inestable: got %v, want %v", macs, want)
+		}
+	}
+}

+ 3 - 0
server-go/internal/adapters/types.go

@@ -308,6 +308,9 @@ type DistributionNode struct {
 	HostDeviceID string `json:"hostDeviceId,omitempty"`
 	Name         string `json:"name,omitempty"`
 	Ip           string `json:"ip,omitempty"` // managed: mgmt-ip anunciada por LLDP
+	// Source: origen del nodo de hipervisor. "" = inferido por L2 (OUI);
+	// "proxmox" = sellado con el inventario read-only de la API PVE (#561).
+	Source string `json:"source,omitempty"`
 	// Mac: chassis-MAC del vecino cuando kind='managed' (SPEC-CANON D1). La
 	// app la usa para excluir del mapa el chip del Device del switch (que
 	// existe como Device Y como nodo managed, sin duplicar el render).