Răsfoiți Sursa

fix(topology): keep down WireGuard peers on the map (#1440) (#1447)

The model kept only `peers.filter(p => p.active)`, so a configured peer
without a recent handshake vanished from the map and a site-to-site outage
was only visible in the alert log.

- Render every configured peer: active first, down after, so a down peer
  never evicts a live tunnel from one of the four canonical coordinates and
  the visible slots still match the `wg` links sent by the server-side
  topology semantics.
- A down peer is dimmed, has a dashed border, no tunnel link and no packet
  flow, plus a visible "down" label and its own aria-label (state is not
  colour-only).
- Peer card keeps last handshake and rx/tx and swaps the status pill;
  the overflow "+N" chip marks the peers that are down too.
- Counters: activePeerCount still counts only active peers. New
  totalPeerCount feeds the legend summary ("N of M VPN peers").
- The links table tunnel row now follows the first active peer and shows
  "down" when none is up.
- i18n keys added in es/en.

Decided down peers DO occupy a canonical coordinate (same block, dimmed),
because hiding them is exactly the bug. Overflow keeps working with the
remaining peers.

Refs #1440
Nacho 1 lună în urmă
părinte
comite
9d0b59fadf

+ 9 - 2
app/public/locales/en/translation.json

@@ -1220,10 +1220,11 @@
       "healthy": "Healthy",
       "hide": "Hide legend",
       "show": "Show legend",
-      "summary": "{{online}} clients online · {{peers}} VPN peers · {{links}} active links",
+      "summary": "{{online}} clients online · {{peers}} of {{peersTotal}} VPN peers · {{links}} active links",
       "title": "Legend",
       "wired": "Wired",
       "wgTunnel": "WireGuard tunnel",
+      "peerDown": "Peer with no tunnel (down)",
       "wiredLink": "Physical cable (WAN, uplinks, units)",
       "wifiUplink": "WiFi uplink (wireless backhaul)",
       "lldpIdentified": "Identified via LLDP",
@@ -1247,6 +1248,11 @@
     },
     "mapAria": "Network map: Internet connected to the Flint 2 Gateway, three access points (Living Room, Study and Patio) with their clients, and two active WireGuard tunnels.",
     "peerAria": "{{name}}, active WireGuard tunnel, {{ip}}",
+    "peerAriaDown": "{{name}}, WireGuard tunnel down, {{ip}}",
+    "peer": {
+      "down": "Down",
+      "downHint": "No active tunnel: no recent handshake"
+    },
     "plan": "Plan",
     "received": "Received",
     "refreshNow": "Refresh now",
@@ -1299,7 +1305,8 @@
     },
     "peers": {
       "overflowTitle": "{{count}} more peers",
-      "overflowAria": "{{count}} additional WireGuard peers"
+      "overflowAria": "{{count}} additional WireGuard peers",
+      "overflowAriaDown": "{{count}} additional WireGuard peers, {{down}} down"
     },
     "ring": {
       "overflowAria": "{{count}} more clients on {{router}}",

+ 9 - 2
app/public/locales/es/translation.json

@@ -1220,10 +1220,11 @@
       "healthy": "Saludable",
       "hide": "Ocultar leyenda",
       "show": "Mostrar leyenda",
-      "summary": "{{online}} clientes online · {{peers}} peers VPN · {{links}} enlaces activos",
+      "summary": "{{online}} clientes online · {{peers}} de {{peersTotal}} peers VPN · {{links}} enlaces activos",
       "title": "Leyenda",
       "wired": "Cable",
       "wgTunnel": "Túnel WireGuard",
+      "peerDown": "Peer sin túnel (caído)",
       "wiredLink": "Cable físico (WAN, uplinks, equipos)",
       "wifiUplink": "Uplink wifi (backhaul inalámbrico)",
       "lldpIdentified": "Identificado vía LLDP",
@@ -1247,6 +1248,11 @@
     },
     "mapAria": "Mapa de la red: Internet conectado al Gateway Flint 2, tres puntos de acceso (Salón, Estudio y Patio) con sus clientes, y dos túneles WireGuard activos.",
     "peerAria": "{{name}}, túnel WireGuard activo, {{ip}}",
+    "peerAriaDown": "{{name}}, túnel WireGuard caído, {{ip}}",
+    "peer": {
+      "down": "Caído",
+      "downHint": "Sin túnel activo: no hay handshake reciente"
+    },
     "plan": "Plan",
     "received": "Recibido",
     "refreshNow": "Refrescar ahora",
@@ -1299,7 +1305,8 @@
     },
     "peers": {
       "overflowTitle": "{{count}} peers más",
-      "overflowAria": "{{count}} peers WireGuard adicionales"
+      "overflowAria": "{{count}} peers WireGuard adicionales",
+      "overflowAriaDown": "{{count}} peers WireGuard adicionales, {{down}} caídos"
     },
     "ring": {
       "overflowAria": "{{count}} clientes más en {{router}}",

+ 21 - 2
app/src/components/topology/LegendCard.tsx

@@ -108,11 +108,21 @@ function WgSample() {
   )
 }
 
+/** Muestra de peer WireGuard caído: recuadro discontinuo + aspa (#1440) */
+function WgDownSample() {
+  return (
+    <svg width="26" height="14" viewBox="0 0 26 14" aria-hidden="true">
+      <rect x="5" y="1" width="16" height="12" rx="4" fill="none" stroke={COLOR.danger} strokeWidth="1.5" strokeDasharray="3 2" />
+      <path d="M10 5 L16 9 M16 5 L10 9" stroke={COLOR.danger} strokeWidth="1.5" strokeLinecap="round" />
+    </svg>
+  )
+}
+
 export function LegendContent({ model, compact = false, horizontal = false }: { model: TopologyModel; compact?: boolean; horizontal?: boolean }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const { deviceTotals, routers, devices } = useNetPulse()
-  const { activeLinkCount, activePeerCount } = model
+  const { activeLinkCount, activePeerCount, totalPeerCount } = model
   // #991: la fila 6 GHz desaparece si la red no tiene 6 GHz (networkHasBand6).
   const hasBand6 = networkHasBand6(routers, devices)
   const bandRows = hasBand6 ? BAND_ROWS : BAND_ROWS.filter((r) => r.band !== '6 GHz')
@@ -140,6 +150,10 @@ export function LegendContent({ model, compact = false, horizontal = false }: {
             <WgSample />
             {t('topology.legend.wgTunnel')}
           </motion.li>
+          <motion.li className="col-span-2 flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
+            <WgDownSample />
+            {t('topology.legend.peerDown')}
+          </motion.li>
         </ul>
       </div>
       <div className={cn(horizontal && 'col-span-2')}>
@@ -186,7 +200,12 @@ export function LegendContent({ model, compact = false, horizontal = false }: {
         className={cn('border-t border-border pt-3 text-caption text-text-muted', horizontal && 'col-span-full')}
         {...row(i++)}
       >
-        {t('topology.legend.summary', { online: deviceTotals.online, peers: activePeerCount, links: activeLinkCount })}
+        {t('topology.legend.summary', {
+          online: deviceTotals.online,
+          peers: activePeerCount,
+          peersTotal: totalPeerCount,
+          links: activeLinkCount,
+        })}
       </motion.p>
     </div>
   )

+ 2 - 0
app/src/components/topology/LinksTable.tsx

@@ -144,6 +144,7 @@ export function LinksTable({ model, hoverLink, onHoverLink }: LinksTableProps) {
                 className={cn(
                   'cursor-default border-b border-border/60 transition-colors duration-150 last:border-0',
                   row.tone === 'warn' && 'bg-warn/5',
+                  row.tone === 'danger' && 'bg-danger/5',
                   hoverLink === row.id && 'bg-hover',
                 )}
               >
@@ -177,6 +178,7 @@ export function LinksTable({ model, hoverLink, onHoverLink }: LinksTableProps) {
             className={cn(
               'rounded-xl border border-border/60 bg-elevated/50 p-3 transition-colors duration-150',
               row.tone === 'warn' && 'border-warn/30 bg-warn/5',
+              row.tone === 'danger' && 'border-danger/30 bg-danger/5',
               hoverLink === row.id && 'bg-hover',
             )}
           >

+ 90 - 12
app/src/components/topology/TopologyMap.tsx

@@ -219,14 +219,21 @@ function TooltipCard({
         <div>
           <div className="flex items-center justify-between gap-2">
             <span className="font-display text-sm font-semibold text-text-primary">{tip.peer.name}</span>
-            <StatusPill tone="tunnel" label={t('common.active')} pulse />
+            {tip.peer.active ? (
+              <StatusPill tone="tunnel" label={t('common.active')} pulse />
+            ) : (
+              <StatusPill tone="danger" label={t('topology.peer.down')} />
+            )}
           </div>
           <div className="mt-0.5 font-mono text-caption text-text-muted">
             {tip.peer.tunnelIp} · wg0 · {t('topology.viaInternet')}
           </div>
+          {!tip.peer.active && (
+            <div className="mt-1 text-caption text-danger">{t('topology.peer.downHint')}</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" />
+            <MiniStat label={t('topology.tunnel')} value={tip.peer.active ? 'WireGuard' : '—'} />
             <MiniStat label={t('topology.received')} value={`↓ ${tip.peer.rx}`} />
             <MiniStat label={t('topology.sent')} value={`↑ ${tip.peer.tx}`} />
           </div>
@@ -238,13 +245,19 @@ function TooltipCard({
             <span className="font-display text-sm font-semibold text-text-primary">
               {t('topology.peers.overflowTitle', { count: tip.peers.length })}
             </span>
-            <StatusPill tone="tunnel" label={t('common.active')} pulse />
+            {tip.peers.some((p) => p.active) ? (
+              <StatusPill tone="tunnel" label={t('common.active')} pulse />
+            ) : (
+              <StatusPill tone="danger" label={t('topology.peer.down')} />
+            )}
           </div>
           <div className="mt-2 space-y-1.5">
             {tip.peers.map((p) => (
               <div key={p.id} className="flex items-center justify-between gap-3 text-caption">
                 <span className="font-semibold text-text-primary">{p.name}</span>
-                <span className="font-mono text-text-muted">Handshake {relTime(p.lastHandshake)}</span>
+                <span className="font-mono text-text-muted">
+                  {p.active ? `Handshake ${relTime(p.lastHandshake)}` : t('topology.peer.down')}
+                </span>
               </div>
             ))}
           </div>
@@ -524,6 +537,8 @@ export function TopologyMap({
   const reduce = useReducedMotion()
   const navigate = useNavigate()
   const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, hypervisorSourceByHost, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
+  /** peers caídos dentro del chip "+N" (#1440): el chip lo dice en el aria-label */
+  const hiddenDownCount = hiddenPeers.filter((p) => !p.active).length
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const [initialView] = useState<View | null>(() => loadSavedView())
@@ -1268,8 +1283,12 @@ export function TopologyMap({
         })}
 
         {/* ------------------------- Peers WireGuard ------------------------- */}
+        {/* #1440: se dibujan TODOS los peers configurados. Un peer sin
+            handshake reciente sigue en el mapa, atenuado, con borde discontinuo
+            y sin túnel: una caída site-to-site ya no queda invisible. */}
         {peerNodes.map((node, i) => {
           const PeerIcon = node.peer.type === 'movil' ? Smartphone : Laptop
+          const down = !node.peer.active
           return (
             <g key={node.id} transform={`translate(${node.x} ${node.y})`}>
               <motion.g
@@ -1282,8 +1301,12 @@ export function TopologyMap({
                   className="cursor-pointer outline-none"
                   role="button"
                   tabIndex={0}
-                  aria-label={t('topology.peerAria', { name: node.peer.name, ip: node.peer.tunnelIp })}
-                  animate={{ opacity: nodeOpacity(node.id) }}
+                  aria-label={
+                    down
+                      ? t('topology.peerAriaDown', { name: node.peer.name, ip: node.peer.tunnelIp })
+                      : t('topology.peerAria', { name: node.peer.name, ip: node.peer.tunnelIp })
+                  }
+                  animate={{ opacity: nodeOpacity(node.id) * (down ? 0.55 : 1) }}
                   transition={{ duration: 0.2 }}
                   onPointerEnter={(e) =>
                     handleNodeHover({ kind: 'peer', id: node.id, peer: node.peer, x: node.x, y: node.y + 30 }, e)
@@ -1301,15 +1324,49 @@ export function TopologyMap({
                     }
                   }}
                 >
-                  {!reduce && (
+                  {!reduce && !down && (
                     <circle r={22} fill="none" stroke={COLOR.tunnel} strokeWidth={1.5}>
                       <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={-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 />
+                  <rect
+                    x={-18}
+                    y={-18}
+                    width={36}
+                    height={36}
+                    rx={11}
+                    fill="rgb(var(--elevated))"
+                    stroke={down ? COLOR.danger : COLOR.tunnel}
+                    strokeWidth={1.5}
+                    strokeDasharray={down ? '4 3' : undefined}
+                  />
+                  <PeerIcon
+                    x={-9}
+                    y={-9}
+                    width={18}
+                    height={18}
+                    className={down ? 'text-danger' : 'text-tunnel'}
+                    strokeWidth={1.75}
+                    aria-hidden
+                  />
                 </motion.g>
+                {/* Estado caído sin depender del color: texto + trazo discontinuo
+                    (el aria-label del grupo ya lo dice para lectores de pantalla). */}
+                {down && (
+                  <text
+                    x={0}
+                    y={34}
+                    textAnchor="middle"
+                    fontSize={9}
+                    fontWeight={700}
+                    letterSpacing="0.04em"
+                    fill={COLOR.danger}
+                    aria-hidden
+                  >
+                    {`× ${t('topology.peer.down')}`}
+                  </text>
+                )}
               </motion.g>
             </g>
           )
@@ -1328,7 +1385,11 @@ export function TopologyMap({
                 className="cursor-pointer outline-none"
                 role="button"
                 tabIndex={0}
-                aria-label={t('topology.peers.overflowAria', { count: hiddenPeers.length })}
+                aria-label={
+                  hiddenDownCount > 0
+                    ? t('topology.peers.overflowAriaDown', { count: hiddenPeers.length, down: hiddenDownCount })
+                    : t('topology.peers.overflowAria', { count: hiddenPeers.length })
+                }
                 onPointerEnter={(e) =>
                   handleNodeHover(
                     { kind: 'peersOverflow', id: 'peers-overflow', peers: hiddenPeers, x: PEERS_OVERFLOW_COORD.x, y: PEERS_OVERFLOW_COORD.y + 30 },
@@ -1365,8 +1426,25 @@ export function TopologyMap({
                   }
                 }}
               >
-                <rect x={-15} y={-11} width={30} height={22} rx={8} fill="rgb(var(--elevated))" stroke={COLOR.tunnel} strokeWidth={1.5} />
-                <text x={0} y={3.5} textAnchor="middle" fontSize={9.5} fontWeight={700} fill={COLOR.tunnel}>
+                <rect
+                  x={-15}
+                  y={-11}
+                  width={30}
+                  height={22}
+                  rx={8}
+                  fill="rgb(var(--elevated))"
+                  stroke={hiddenDownCount === hiddenPeers.length ? COLOR.danger : COLOR.tunnel}
+                  strokeWidth={1.5}
+                  strokeDasharray={hiddenDownCount > 0 ? '3 2' : undefined}
+                />
+                <text
+                  x={0}
+                  y={3.5}
+                  textAnchor="middle"
+                  fontSize={9.5}
+                  fontWeight={700}
+                  fill={hiddenDownCount === hiddenPeers.length ? COLOR.danger : COLOR.tunnel}
+                >
                   +{hiddenPeers.length}
                 </text>
               </g>

+ 37 - 11
app/src/components/topology/model.ts

@@ -106,7 +106,7 @@ export interface BackhaulRow {
   /** Latencia del extremo destino en ms, formateada (#1384); "—" sin dato. */
   ping: string
   signal: string
-  tone: 'ok' | 'warn' | 'tunnel'
+  tone: 'ok' | 'warn' | 'tunnel' | 'danger'
   statusLabel: string
   note?: string
   spark: number[]
@@ -156,8 +156,13 @@ export interface TopologyModel {
   switchNodes: RouterNode[]
   routerNodes: RouterNode[]
   internetNode: { id: 'internet'; x: number; y: number }
+  /**
+   * Peers WireGuard visibles, TODOS los configurados (issue #1440): activos
+   * primero y caídos después, atenuados y sin túnel. Un peer sin handshake
+   * reciente sigue en el mapa para que una caída site-to-site no sea invisible.
+   */
   peerNodes: PeerNode[]
-  /** Peers activos que exceden las coordenadas canónicas (chip "+N") */
+  /** Peers configurados que exceden las coordenadas canónicas (chip "+N") */
   hiddenPeers: WGPeer[]
   chips: ChipNode[]
   distNodes: DistNodeView[]
@@ -178,7 +183,10 @@ export interface TopologyModel {
   totalPackets: number
   activeLinkCount: number
   backhauls: BackhaulRow[]
+  /** Peers con túnel levantado (handshake reciente). NO cuenta los caídos. */
   activePeerCount: number
+  /** Peers WireGuard configurados en total (activos + caídos), #1440. */
+  totalPeerCount: number
   wan: WanInfo
   relatedTo: (nodeId: string) => { nodes: Set<string>; links: Set<string> }
 }
@@ -1308,16 +1316,23 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   }
 
   // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------
-  // Hay 4 coordenadas canónicas: los activos que exceden se agrupan en el
-  // chip "+N" (antes se descartaban silenciosamente).
+  // Hay 4 coordenadas canónicas. #1440: se dibujan TODOS los peers
+  // configurados, no solo los activos: un túnel caído era invisible en el
+  // mapa. Orden: activos primero y caídos después, ambos en el orden del API.
+  // Así un peer caído nunca desplaza a un túnel vivo de su coordenada y los
+  // 4 slots visibles coinciden con los que el servidor manda como enlaces
+  // `wg` en la semántica (primeros 4 activos). Los caídos ocupan el mismo
+  // bloque, atenuados y sin enlace de túnel. Los que exceden van al chip "+N".
   const activePeers = wireguard.peers.filter((p) => p.active)
-  const peerNodes: PeerNode[] = activePeers.slice(0, PEER_COORDS.length).map((peer, i) => ({
+  const downPeers = wireguard.peers.filter((p) => !p.active)
+  const orderedPeers = [...activePeers, ...downPeers]
+  const peerNodes: PeerNode[] = orderedPeers.slice(0, PEER_COORDS.length).map((peer, i) => ({
     kind: 'peer',
     id: `peer-${peer.id}`,
     peer,
     ...PEER_COORDS[i]!,
   }))
-  const hiddenPeers = activePeers.slice(PEER_COORDS.length)
+  const hiddenPeers = orderedPeers.slice(PEER_COORDS.length)
 
   // -- tráfico agregado de un sub-árbol (para el flujo ∝ Mbps) ----------------
   const subtreeTraffic = (hubId: string, seen = new Set<string>()): number => {
@@ -1479,6 +1494,9 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     }
   }
   peerNodes.forEach((node, i) => {
+    // #1440: un peer caído no tiene túnel. Sin enlace no hay camino hacia
+    // Internet que dibujar (ni paquetes que animar).
+    if (!node.peer.active) return
     links.push({
       id: `wg-${node.peer.id}`, kind: 'wg',
       d: wgTunnelPath(node), lx: 0, ly: 0, label: '',
@@ -1582,7 +1600,8 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
         }
         case 'wg': {
           const pn = peerNodes.find((p) => p.id === sl.from)
-          if (!pn) return null
+          // #1440: sin túnel no hay enlace que dibujar.
+          if (!pn || !pn.peer.active) return null
           return {
             id: `wg-${pn.peer.id}`, kind: 'wg',
             d: wgTunnelPath(pn), lx: 0, ly: 0, label: '',
@@ -1803,18 +1822,24 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       spark: host.sparkline, sparkColor: COLOR.ok,
     })
   }
-  // La tabla canónica muestra un único túnel (el más reciente)
-  for (const node of peerNodes.slice(0, 1)) {
+  // La tabla canónica muestra un único túnel (el más reciente): el primer
+  // peer ACTIVO; si no hay ninguno, el primero configurado, ya marcado caído
+  // (#1440: antes se pintaba como "activo" aunque estuviera sin handshake).
+  const backhaulPeer = peerNodes.find((n) => n.peer.active) ?? peerNodes[0]
+  if (backhaulPeer) {
+    const node = backhaulPeer
     const device = devices.find((d) => d.id === node.peer.id)
     backhauls.push({
       id: `wg-${node.peer.id}`, a: 'Internet', b: node.peer.name, kind: 'wg',
       type: 'WireGuard', speed: '—', ping: '—', signal: '—',
-      tone: 'tunnel', statusLabel: 'common.active',
-      spark: device?.sparkline ?? [0, 0], sparkColor: COLOR.tunnel,
+      tone: node.peer.active ? 'tunnel' : 'danger',
+      statusLabel: node.peer.active ? 'common.active' : 'topology.peer.down',
+      spark: device?.sparkline ?? [0, 0], sparkColor: node.peer.active ? COLOR.tunnel : COLOR.danger,
     })
   }
 
   const activePeerCount = activePeers.length
+  const totalPeerCount = wireguard.peers.length
 
   // Adyacencia (hover: atenuar nodos no relacionados)
   const adjacency = new Map<string, { nodes: Set<string>; links: Set<string> }>()
@@ -1922,6 +1947,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     activeLinkCount,
     backhauls,
     activePeerCount,
+    totalPeerCount,
     wan,
     relatedTo,
   }