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

fix(routers,topology,devices): integrate the fork's routers/topology/devices fixes

Integrate the "Routers / topology / devices" group of the borky/netpulse community fork.

Cherry-picked 12 fixes (ports and WAN uplink inference, ARP neighbour states, stale-neighbour devices, router client counts, topology port ownership and measured link speeds, unknown-device location, agent-to-router matching) plus the generic AP/switch role field they depend on.

Skipped: UniFi, WAN multi-connection and VLANs, docs(fork), telemetry unwiring.

Refs #936 #938 #937 #943
Nacho 2 месяцев назад
Родитель
Сommit
198e423cf4

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.3
+3.0.4

+ 28 - 6
agent/probe/local.go

@@ -10,6 +10,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"os/exec"
+	"sort"
 	"strings"
 	"sync"
 	"time"
@@ -169,7 +170,7 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	pl.Data.Wireless = p.probeWireless(ctx, true)
 	pl.Data.DHCP = p.probeDHCP(ctx)
 	pl.Data.FDB = p.probeFDB(ctx)
-	pl.Data.Arp = p.probeArp(ctx)
+	pl.Data.Arp, pl.Data.ArpStale = p.probeArp(ctx)
 	pl.Data.Dawn = p.probeDawn(ctx)
 	pl.Data.Usteer = p.probeUsteer(ctx)
 	pl.Data.LuCI = p.probeLuCI(ctx)
@@ -202,7 +203,7 @@ func (p *Prober) BuildWireless(ctx context.Context, router, version string) *Pay
 	}
 	pl.Data.Wireless = p.probeWireless(ctx, false)
 	pl.Data.DHCP = p.probeDHCP(ctx)
-	pl.Data.Arp = p.probeArp(ctx)
+	pl.Data.Arp, pl.Data.ArpStale = p.probeArp(ctx)
 	return pl
 }
 
@@ -457,7 +458,13 @@ func (p *Prober) probeFDB(ctx context.Context) *FDBData {
 				ifaces[name] = IfRate{IfCounters: c}
 			}
 		}
-		fd.Ports = BuildEthPorts(layout, states, members, ifaces)
+		// Boca del uplink: la marca como WAN cuando el layout no trae
+		// ninguna (PPPoE sobre una boca "lan" y demás).
+		uplink := ""
+		if out := p.runBest(ctx, CmdNetworkDump, 0); out != "" {
+			uplink = ParseWanStatus([]byte(out)).Port
+		}
+		fd.Ports = BuildEthPorts(layout, states, members, ifaces, uplink)
 		any = true
 	}
 	if !any {
@@ -757,14 +764,29 @@ func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *Di
 
 // probeArp: tabla ARP del kernel (#377). nil si no hay fichero (equipo sin
 // ARP, p. ej. contenedor); mapa vacío es resultado real.
-func (p *Prober) probeArp(ctx context.Context) map[string]string {
+//
+// Reads `ip neigh` first, which carries the state of each entry, and only
+// falls back to /proc/net/arp where `ip` is missing -- there the states are
+// unknowable and the returned stale set is empty, the behaviour agents had
+// before. stale lists the MACs the kernel remembers without confirming.
+func (p *Prober) probeArp(ctx context.Context) (arp map[string]string, stale []string) {
+	if out := p.runBest(ctx, CmdIpNeigh, 3*time.Second); out != "" {
+		m, st := ParseIPNeigh(out)
+		if len(m) > 0 {
+			for mac := range st {
+				stale = append(stale, mac)
+			}
+			sort.Strings(stale) // stable payloads, so a diff means a change
+			return m, stale
+		}
+	}
 	out := p.runBest(ctx, CmdProcArp, 3*time.Second)
 	if out == "" {
-		return nil
+		return nil, nil
 	}
 	m := ParseArp(out)
 	if m == nil {
 		m = map[string]string{}
 	}
-	return m
+	return m, nil
 }

+ 8 - 1
agent/probe/payload.go

@@ -33,7 +33,14 @@ type PayloadData struct {
 	// Resuelve IPs donde el DHCP no está en el equipo sondeado (APs tontos
 	// con el dnsmasq en otro router): cualquier router de la flota que
 	// enrute la LAN conoce el mapa completo.
-	Arp    map[string]string `json:"arp,omitempty"`
+	Arp map[string]string `json:"arp,omitempty"`
+	// ArpStale: the MACs of Arp whose neighbour entries are all unconfirmed
+	// (STALE/FAILED/INCOMPLETE). Their address is still the best one known
+	// for the host, but their presence in the table proves nothing: the
+	// kernel keeps a stale neighbour long after the device has gone. An
+	// older agent omits this, and the server then trusts the whole table as
+	// it always did.
+	ArpStale []string `json:"arpStale,omitempty"`
 	Dawn   *DawnData         `json:"dawn,omitempty"`   // Fase 14: DAWN roaming (solo si instalado; compat rollback)
 	Usteer *UsteerData       `json:"usteer,omitempty"` // usteer roaming (solo si instalado)
 	// LuCI: etiquetas de puertos/VLANs del router (issue #258), si están

+ 287 - 48
agent/probe/probe.go

@@ -87,14 +87,33 @@ const (
 	// CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
 	// resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
 	CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`
-	// CmdPortStates: "<name> <operstate> <speed> <dsa?>" por interfaz. El
-	// 4º campo marca "dsa" cuando la interfaz es un conduit DSA (tiene el
-	// directorio /sys/class/net/<i>/dsa): es el puerto CPU interno del
-	// switch, no una boca usable, y se excluye del panel (#847).
+	// CmdPortStates: "<name> <operstate> <speed> <dsa> <type> <conduit>" por
+	// interfaz.
+	//   - dsa: "dsa" cuando la interfaz es un conduit DSA (tiene el directorio
+	//     /sys/class/net/<i>/dsa): el puerto CPU interno del switch, no una
+	//     boca usable (#847); "-" si no.
+	//   - type: el ARPHRD del kernel (1 = ethernet). FORK: para no tomar por
+	//     boca un uplink que no lo es (wwan0 de un módem celular).
+	//   - conduit: FORK. La interfaz inferior (lower_*) cuando la hay: en un
+	//     switch DSA las bocas cuelgan de la interfaz de CPU (lan1/lan2 →
+	//     lower_eth0). "-" cuando no hay ninguna.
+	// Los campos a partir del tercero son opcionales para ParsePortStates.
 	CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
-		`echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1) $([ -d $d/dsa ] && echo dsa || echo -)"; done`
+		`o=$(cat "$d/operstate" 2>/dev/null || echo unknown); ` +
+		`s=$(cat "$d/speed" 2>/dev/null || echo -1); ` +
+		`x=$([ -d "$d/dsa" ] && echo dsa || echo -); ` +
+		`t=$(cat "$d/type" 2>/dev/null || echo -1); ` +
+		`c=-; for l in "$d"/lower_*; do [ -e "$l" ] || continue; c=${l##*/lower_}; break; done; ` +
+		`echo "$i $o $s $x $t $c"; done`
 	// CmdProcArp (#377): tabla ARP del kernel, "IP dev mac ..." por línea.
-	CmdProcArp     = "cat /proc/net/arp 2>/dev/null"
+	CmdProcArp = "cat /proc/net/arp 2>/dev/null"
+	// CmdIpNeigh: the same neighbour table, but with the state of each entry,
+	// which /proc/net/arp cannot express -- its flags say ATF_COM for
+	// REACHABLE and for STALE alike. A STALE neighbour is one the kernel has
+	// not confirmed since the device last spoke, and it survives long after
+	// the device is gone, so treating it as presence draws hosts that are no
+	// longer there. Falls back to /proc/net/arp when `ip` is missing.
+	CmdIpNeigh     = "ip -4 neigh show 2>/dev/null"
 	CmdBoardJSON   = "cat /etc/board.json 2>/dev/null"
 	CmdBrifMembers = "BR=br-lan; [ -d /sys/class/net/$BR ] || BR=br0; ls /sys/class/net/$BR/brif/ 2>/dev/null"
 	// CmdBridgeFDB: "==PORTS==" (port_no ifname) + "==MACS==" (port mac).
@@ -121,8 +140,12 @@ const (
 	CmdLuCILabels = "cat /etc/config/luci 2>/dev/null"
 	// CmdWanStatus: estado de la interfaz WAN (solo gateway) vía ubus.
 	// Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276).
-	CmdWanStatus  = "ubus call network.interface.wan status 2>/dev/null || true"
-	CmdBridgeVlan = "bridge vlan show 2>/dev/null || true"
+	CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true"
+	// CmdNetworkDump: estado de TODAS las interfaces, para elegir el uplink
+	// por la ruta por defecto en vez de por el nombre "wan" (ver pickUplink)
+	// y saber por qué boca sale internet.
+	CmdNetworkDump = "ubus call network.interface dump 2>/dev/null || true"
+	CmdBridgeVlan  = "bridge vlan show 2>/dev/null || true"
 
 	// CmdMdnsBrowse (#338): mDNS service discovery via umdns (OpenWrt's
 	// lightweight mDNS daemon). Returns JSON with hostname -> services.
@@ -170,10 +193,14 @@ type BoardInfo struct {
 // los campos vacíos significan "sin datos WAN" (APs/desconocido).
 type WanInfo struct {
 	Proto   string   `json:"proto,omitempty"`   // "pppoe"|"dhcp"|"static"...
-	Device  string   `json:"device,omitempty"`  // interfaz física (p.ej. "eth1.20")
+	Device  string   `json:"device,omitempty"`  // interfaz L3 (p.ej. "pppoe-wan")
 	IP      string   `json:"ip,omitempty"`      // dirección IPv4 pública
 	Gateway string   `json:"gateway,omitempty"` // puerta de enlace (nexthop/ptpaddress)
 	DNS     []string `json:"dns,omitempty"`     // servidores DNS
+	// Port es la interfaz por debajo del protocolo: la boca por la que sale
+	// internet ("lan1" para un PPPoE sobre esa boca, "eth1.20" con VLAN).
+	// Vacía cuando el uplink no pasa por ninguna (módem celular).
+	Port string `json:"port,omitempty"`
 }
 
 // DhcpLease es {mac, ip, hostname} (mac en mayúsculas) + señales de huella
@@ -209,6 +236,13 @@ type PortState struct {
 	// /sys/class/net/<i>/dsa presente). No es una boca usable: se excluye
 	// de los puertos del panel (#847).
 	DSA bool `json:"dsa,omitempty"`
+	// Type es el ARPHRD de /sys/class/net/<i>/type: 1 = ethernet. 0 o
+	// negativo = desconocido (salida antigua), y entonces no se descarta
+	// nada por el tipo. FORK.
+	Type int `json:"type,omitempty"`
+	// Conduit es la interfaz inferior (lower_*), vacío si no hay. En un
+	// switch DSA es el puerto de CPU del que cuelga la boca. FORK.
+	Conduit string `json:"conduit,omitempty"`
 }
 
 // fmtSpeedMbps (#847) formatea la velocidad de enlace: Gbps con decimales
@@ -224,6 +258,9 @@ func fmtSpeedMbps(mbps int) string {
 	return strconv.Itoa(mbps) + " Mbps"
 }
 
+// ARPHRDEther es el /sys/class/net/<i>/type de una interfaz ethernet.
+const ARPHRDEther = 1
+
 // PortLayout es una boca del layout canónico (/etc/board.json).
 type PortLayout struct {
 	ID    string `json:"id"`
@@ -494,48 +531,95 @@ func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
 	return out, nil
 }
 
-// ParseWanStatus parsea `ubus call network.interface.wan status` (issue #276).
-// Extrae proto, interfaz física, IP pública, gateway (nexthop de la ruta por
-// defecto, con fallback al ptpaddress) y DNS. Devuelve un WanInfo con los
-// campos vacíos si el JSON no tiene datos utilizables.
-func ParseWanStatus(raw []byte) WanInfo {
-	var data struct {
-		Proto  string `json:"proto"`
-		Device string `json:"l3_device"`
-		IPV4   []struct {
-			Address    string `json:"address"`
-			PtpAddress string `json:"ptpaddress"`
-		} `json:"ipv4-address"`
-		Route []struct {
-			Target  string `json:"target"`
-			Mask    int    `json:"mask"`
-			Nexthop string `json:"nexthop"`
-		} `json:"route"`
-		DNS []string `json:"dns-server"`
-	}
-	info := WanInfo{}
-	if json.Unmarshal(raw, &data) != nil {
-		return info
-	}
-	info.Proto = data.Proto
-	info.Device = data.Device
-	if len(data.IPV4) > 0 {
-		info.IP = data.IPV4[0].Address
-		if data.IPV4[0].PtpAddress != "" {
-			info.Gateway = data.IPV4[0].PtpAddress
+// ifaceStatus es una interfaz de `ubus call network.interface[.<x>] status`,
+// y cada entrada de `... dump`.
+type ifaceStatus struct {
+	Interface string `json:"interface"`
+	Up        bool   `json:"up"`
+	Proto     string `json:"proto"`
+	L3Device  string `json:"l3_device"`
+	// Device es la interfaz de debajo: para un PPPoE, la boca física.
+	Device string `json:"device"`
+	IPV4   []struct {
+		Address    string `json:"address"`
+		PtpAddress string `json:"ptpaddress"`
+	} `json:"ipv4-address"`
+	Route []struct {
+		Target  string `json:"target"`
+		Mask    int    `json:"mask"`
+		Nexthop string `json:"nexthop"`
+	} `json:"route"`
+	DNS []string `json:"dns-server"`
+}
+
+func (s ifaceStatus) defaultNexthop() string {
+	for _, r := range s.Route {
+		if r.Target == "0.0.0.0" && r.Mask == 0 && r.Nexthop != "" {
+			return r.Nexthop
 		}
 	}
-	// El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
-	for _, r := range data.Route {
-		if r.Target == "0.0.0.0" && r.Nexthop != "" {
-			info.Gateway = r.Nexthop
-			break
+	return ""
+}
+
+// pickUplink elige la interfaz que lleva internet. No vale fiarse del nombre
+// "wan": en un router multi-WAN el uplink vivo puede llamarse de cualquier
+// forma (un PPPoE llamado "isp" junto a un módem celular que sí se llama
+// "wan" y que además reporta up=true estando ocioso), así que manda la ruta
+// por defecto. Sin ninguna con ruta, cae a la llamada "wan" para que un
+// router normal con el enlace caído siga saliendo como WAN caída y no como
+// router sin WAN.
+func pickUplink(ifaces []ifaceStatus) (ifaceStatus, bool) {
+	for _, i := range ifaces {
+		if i.Up && i.defaultNexthop() != "" {
+			return i, true
 		}
 	}
-	info.DNS = data.DNS
+	for _, i := range ifaces {
+		if i.Interface == "wan" {
+			return i, true
+		}
+	}
+	return ifaceStatus{}, false
+}
+
+func wanInfoFrom(s ifaceStatus) WanInfo {
+	info := WanInfo{Proto: s.Proto, Device: s.L3Device, Port: s.Device, DNS: s.DNS}
+	if len(s.IPV4) > 0 {
+		info.IP = s.IPV4[0].Address
+		if s.IPV4[0].PtpAddress != "" {
+			info.Gateway = s.IPV4[0].PtpAddress
+		}
+	}
+	// El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
+	if nh := s.defaultNexthop(); nh != "" {
+		info.Gateway = nh
+	}
 	return info
 }
 
+// ParseWanStatus parsea el estado de la WAN (issue #276). Acepta las dos
+// formas: `ubus call network.interface dump` (y entonces elige el uplink
+// activo, ver pickUplink) y el status de una sola interfaz. Extrae proto,
+// interfaz L3, boca física, IP pública, gateway y DNS; campos vacíos si el
+// JSON no trae datos utilizables.
+func ParseWanStatus(raw []byte) WanInfo {
+	var dump struct {
+		Interface []ifaceStatus `json:"interface"`
+	}
+	if err := json.Unmarshal(raw, &dump); err == nil && len(dump.Interface) > 0 {
+		s, ok := pickUplink(dump.Interface)
+		if !ok {
+			return WanInfo{}
+		}
+		return wanInfoFrom(s)
+	}
+	var one ifaceStatus
+	if json.Unmarshal(raw, &one) != nil {
+		return WanInfo{}
+	}
+	return wanInfoFrom(one)
+}
+
 // ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
 // <expiry> <mac> <ip> <hostname> <clientid>
 func ParseDhcpLeasesFile(out string) []DhcpLease {
@@ -667,7 +751,9 @@ func ParseWirelessUplink(raw []byte) (bool, error) {
 // Puertos
 // ---------------------------------------------------------------------------
 
-// ParsePortStates parsea líneas "<name> <operstate> <speed> [dsa]".
+// ParsePortStates parsea líneas "<name> <operstate> <speed> [dsa] [type]
+// [conduit]". Los campos opcionales que falten dejan su valor por defecto:
+// sin type no se descarta ninguna boca por él.
 func ParsePortStates(out string) []PortState {
 	ports := []PortState{}
 	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
@@ -687,6 +773,12 @@ func ParsePortStates(out string) []PortState {
 		if len(p) > 3 && p[3] == "dsa" {
 			st.DSA = true
 		}
+		if len(p) > 4 {
+			st.Type, _ = strconv.Atoi(p[4])
+		}
+		if len(p) > 5 && p[5] != "-" {
+			st.Conduit = p[5]
+		}
 		ports = append(ports, st)
 	}
 	return ports
@@ -718,12 +810,56 @@ func ParsePortLayout(out string) ([]PortLayout, error) {
 	return ports, nil
 }
 
+// phyRe/skipRe: nombres que pueden ser una boca física y nombres que nunca lo
+// son (bridges, VLANs, túneles, wireless, módems).
+var (
+	phyRe  = regexp.MustCompile(`^(eth|sfp|en|swp)[0-9a-zA-Z_\-]*$|^(lan|wan)[0-9]+$`)
+	skipRe = regexp.MustCompile(`^(lo|br[-_]?|br-lan|br0|docker|veth|wg|tun|tap|ifb|pppoe|wlan|wpan|phy|gre|gretap|erspan|ip6tnl|sit|teql|bond|dummy|nat64|rmnet|usb|wwan)`)
+)
+
+// switchConduits: puertos de CPU de un switch, deducidos de las propias
+// bocas. En DSA cada boca cuelga de la interfaz de CPU (lan1 y lan2 tienen
+// lower_eth0), que no es una boca física por mucho que se llame eth0.
+//
+// Solo se mira el lower_* de interfaces que parecen bocas: el de un bridge
+// son sus miembros (br-lan → lower_lan2) y el de una VLAN su interfaz padre,
+// relaciones que no señalan ningún puerto de CPU.
+func switchConduits(states []PortState) map[string]bool {
+	conduits := map[string]bool{}
+	for _, st := range states {
+		if st.Conduit == "" || skipRe.MatchString(st.Name) || !phyRe.MatchString(st.Name) {
+			continue
+		}
+		conduits[st.Conduit] = true
+	}
+	return conduits
+}
+
+// isEthNetdev: el layout nombra una interfaz de red ethernet de verdad.
+// board.json declara como WAN lo que el router use de uplink, y no siempre es
+// una boca: en un router celular es "/dev/cdc-wdm0",
+// que ni siquiera aparece en /sys/class/net. Un tipo desconocido (salida
+// antigua, sin el campo) cuenta como ethernet: mejor enseñar una boca de más
+// que esconder una real.
+func isEthNetdev(st PortState, ok bool) bool {
+	return ok && (st.Type <= 0 || st.Type == ARPHRDEther)
+}
+
 // BuildEthPorts: layout + estado /sys → []EthPort listo para el detalle.
 // brMembers = miembros del bridge br-lan (AP en bridge re-etiqueta wan→LAN
 // N+1); sin layout, fallback heurístico. ifaces = contadores/rates por iface
 // física (issue #305; nil = sin datos, las bocas salen sin stats). Literal de
 // openwrt.go GetEthPorts.
-func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate) []EthPort {
+//
+// Descarta dos bocas que no existen: el uplink del layout cuando no es una
+// interfaz ethernet (módem celular) y el puerto de CPU del switch. Sin ellos
+// un router así pasa de enseñar cuatro bocas -- WAN (nunca conectada), LAN 1,
+// LAN 2 y ETH 0 -- a las dos que tiene.
+//
+// uplink es la boca por la que sale internet (WanInfo.Port); cuando ninguna
+// boca ha salido como WAN se promueve esa, ver promoteUplink. "" = sin dato,
+// y entonces no se promueve nada.
+func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string]bool, ifaces map[string]IfRate, uplink string) []EthPort {
 	applyStats := func(ep *EthPort, iface string) {
 		st, ok := ifaces[iface]
 		if !ok {
@@ -738,9 +874,14 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 	for _, p := range states {
 		byName[p.Name] = p
 	}
+	conduits := switchConduits(states)
 
 	used := map[string]bool{}
 	ports := make([]EthPort, 0, len(states))
+	// netdev de cada boca por id, para saber luego cuál lleva el uplink: el
+	// id no siempre es el nombre de la interfaz (en swconfig, "1" vs
+	// "eth0.1").
+	netdev := map[string]string{}
 
 	if len(layout) > 0 {
 		lanCount := 0
@@ -751,6 +892,9 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		}
 		for _, p := range layout {
 			st, ok := byName[p.Name]
+			if p.Role == "wan" && !isEthNetdev(st, ok) {
+				continue
+			}
 			up := ok && st.Up
 			label := p.Label
 			if p.Role == "wan" && brMembers[p.Name] {
@@ -762,6 +906,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 			}
 			applyStats(&ep, p.Name)
 			ports = append(ports, ep)
+			netdev[ep.ID] = p.Name
 			used[p.Name] = true
 		}
 	} else {
@@ -781,6 +926,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 			}
 			applyStats(&ep, p.Name)
 			ports = append(ports, ep)
+			netdev[ep.ID] = p.Name
 			used[p.Name] = true
 		}
 		wanName := ""
@@ -800,14 +946,13 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 			}
 			applyStats(&ep, wanName)
 			ports = append([]EthPort{ep}, ports...)
+			netdev[ep.ID] = wanName
 			used[wanName] = true
 		}
 	}
 
 	// Mejora #413/#416: añadir interfaces físicas que no estén ya cubiertas
 	// por el layout/fallback (p. ej. eth0, sfp+ en BPI-R4/UniFi).
-	phyRe := regexp.MustCompile(`^(eth|sfp|en|swp)[0-9a-zA-Z_\-]*$|^(lan|wan)[0-9]+$`)
-	skipRe := regexp.MustCompile(`^(lo|br[-_]?|br-lan|br0|docker|veth|wg|tun|tap|ifb|pppoe|wlan|wpan|phy|gre|gretap|erspan|ip6tnl|sit|teql|bond|dummy|nat64|rmnet|usb|wwan)`)
 	extras := make([]EthPort, 0)
 	for _, st := range states {
 		if used[st.Name] {
@@ -825,6 +970,9 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		if !phyRe.MatchString(st.Name) {
 			continue
 		}
+		if conduits[st.Name] {
+			continue // puerto de CPU del switch, no una boca
+		}
 		label := st.Name
 		if strings.HasPrefix(st.Name, "eth") {
 			label = "ETH " + strings.TrimPrefix(st.Name, "eth")
@@ -837,6 +985,7 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		}
 		applyStats(&ep, st.Name)
 		extras = append(extras, ep)
+		netdev[ep.ID] = st.Name
 		used[st.Name] = true
 	}
 	if len(extras) > 0 {
@@ -845,6 +994,38 @@ func BuildEthPorts(layout []PortLayout, states []PortState, brMembers map[string
 		ports = append(ports, extras...)
 	}
 
+	return promoteUplink(ports, netdev, uplink)
+}
+
+// promoteUplink marca como WAN la boca por la que sale internet cuando
+// ninguna ha salido ya como tal. Hay routers cuyo uplink no entra por una
+// boca WAN dedicada: el PPPoE puede ir sobre una boca llamada "lan1" y el
+// board.json solo declara un módem como WAN, así que sin esto ninguna boca
+// sale con id "wan" -- y la UI marca el uplink y cuelga los datos de la
+// conexión (proto, IP pública, gateway, DNS) justo de esa.
+//
+// La boca conserva su sitio y su iface: las estadísticas y la MAC siguen
+// siendo las suyas, solo cambia cómo se presenta.
+func promoteUplink(ports []EthPort, netdev map[string]string, uplink string) []EthPort {
+	if uplink == "" {
+		return ports
+	}
+	for _, p := range ports {
+		if p.ID == "wan" {
+			return ports // el layout ya trae una boca WAN
+		}
+	}
+	// El uplink puede llegar etiquetado ("lan1.7"): la boca es la de debajo.
+	base := uplink
+	if i := strings.LastIndexByte(base, '.'); i > 0 {
+		base = base[:i]
+	}
+	for i := range ports {
+		if n := netdev[ports[i].ID]; n == uplink || n == base {
+			ports[i].ID, ports[i].Label = "wan", "WAN"
+			break
+		}
+	}
 	return ports
 }
 
@@ -1498,6 +1679,64 @@ func ParseArp(out string) map[string]string {
 	return m
 }
 
+// neighConfirmed: the states in which the kernel vouches for the neighbour
+// being there right now. REACHABLE was confirmed within the reachable time;
+// DELAY and PROBE are on their way to being reconfirmed; PERMANENT and NOARP
+// were put there by hand or by a link that needs no resolution.
+//
+// Everything else -- STALE, FAILED, INCOMPLETE, NONE -- is an address the
+// kernel remembers without being able to say the host is still connected.
+var neighConfirmed = map[string]bool{
+	"REACHABLE": true, "DELAY": true, "PROBE": true,
+	"PERMANENT": true, "NOARP": true,
+}
+
+// ParseIPNeigh parses `ip neigh show`, whose lines read
+// "IP dev IFACE lladdr MAC STATE" (an entry being resolved has no lladdr).
+// It returns the same MAC→IP map as ParseArp plus the set of MACs whose
+// every entry is unconfirmed: remembered addresses, not present hosts.
+//
+// A MAC with several addresses counts as confirmed when any one of them is,
+// since one confirmed neighbour is enough to prove the host is there.
+func ParseIPNeigh(out string) (arp map[string]string, stale map[string]bool) {
+	arp, stale = map[string]string{}, map[string]bool{}
+	confirmed := map[string]bool{}
+	for _, line := range strings.Split(out, "\n") {
+		f := strings.Fields(line)
+		// "IP dev IFACE lladdr MAC STATE" is the shortest useful line.
+		if len(f) < 6 || net.ParseIP(f[0]) == nil {
+			continue
+		}
+		var mac string
+		for i := 1; i+1 < len(f); i++ {
+			if f[i] == "lladdr" {
+				mac = strings.ToUpper(f[i+1])
+				break
+			}
+		}
+		if mac == "" || mac == "00:00:00:00:00:00" {
+			continue
+		}
+		// The state is the last word of the line; an entry without one is
+		// not something to claim presence from.
+		if neighConfirmed[f[len(f)-1]] {
+			// Confirmed wins for good: a later unconfirmed address for the
+			// same host must not undo it.
+			arp[mac] = f[0]
+			confirmed[mac] = true
+			delete(stale, mac)
+			continue
+		}
+		if !confirmed[mac] {
+			if _, ok := arp[mac]; !ok {
+				arp[mac] = f[0]
+			}
+			stale[mac] = true
+		}
+	}
+	return arp, stale
+}
+
 // sumProcRSS returns the total VmRSS (bytes) of every user-space process
 // (/proc/<pid>/status): the memory actually held by processes, excluding the
 // kernel page cache that inflates (total-available) on ubifs/overlay routers.

+ 264 - 8
agent/probe/probe_test.go

@@ -120,7 +120,7 @@ func TestBuildEthPortsConIfaces(t *testing.T) {
 		"lan1":  {IfCounters: IfCounters{Rx: 1000, Tx: 2000, RxErr: 3}, RxBps: &rxb, TxBps: &txb},
 		"wlan0": {IfCounters: IfCounters{Rx: 99}}, // no es boca: se ignora
 	}
-	ports := BuildEthPorts(layout, states, nil, ifaces)
+	ports := BuildEthPorts(layout, states, nil, ifaces, "")
 	if len(ports) != 1 {
 		t.Fatalf("ports: %+v", ports)
 	}
@@ -132,7 +132,7 @@ func TestBuildEthPortsConIfaces(t *testing.T) {
 		t.Fatalf("rates: %+v", p)
 	}
 	// Fallback (sin layout) también enriquece
-	ports = BuildEthPorts(nil, []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}, nil, ifaces)
+	ports = BuildEthPorts(nil, []PortState{{Name: "lan1", Up: true, Speed: "1 Gbps"}}, nil, ifaces, "")
 	if len(ports) != 1 || ports[0].Iface != "lan1" || ports[0].RxBytes != 1000 {
 		t.Fatalf("fallback stats: %+v", ports)
 	}
@@ -179,7 +179,7 @@ func TestBuildEthPortsSkipsDsaConduit(t *testing.T) {
 		{Name: "lan1", Up: true, Speed: "1 Gbps"},
 		{Name: "eth1", Up: true, Speed: "150 Mbps", DSA: true},
 	}
-	ports := BuildEthPorts(nil, states, nil, nil)
+	ports := BuildEthPorts(nil, states, nil, nil, "")
 	if len(ports) != 1 || ports[0].ID != "lan1" {
 		t.Fatalf("el conduit DSA debe excluirse: %+v", ports)
 	}
@@ -287,8 +287,11 @@ func TestParseWireless(t *testing.T) {
 }
 
 func TestParsePortsYLayout(t *testing.T) {
-	states := ParsePortStates("eth0 up 2500\nlan1 up 1000\nlan2 down -1\nwlan0 up 0\n")
-	if len(states) != 4 || states[0].Speed != "2.5 Gbps" || states[2].Up || states[2].Speed != "—" {
+	// La boca WAN aparece en /sys aunque esté esclavizada al bridge: sin ella
+	// en los estados sería un device que no existe y BuildEthPorts la
+	// descartaría (ver TestBuildEthPortsUplinkNoEthernet).
+	states := ParsePortStates("eth0 up 2500\nlan1 up 1000\nlan2 down -1\nwlan0 up 0\nwan up 1000\n")
+	if len(states) != 5 || states[0].Speed != "2.5 Gbps" || states[2].Up || states[2].Speed != "—" {
 		t.Fatalf("states: %+v", states)
 	}
 	board := `{"network":{"lan":{"ports":["lan1","lan2","lan3","lan4"],"device":"br-lan"},"wan":{"device":"wan","protocol":"dhcp"}}}`
@@ -297,7 +300,7 @@ func TestParsePortsYLayout(t *testing.T) {
 		t.Fatalf("layout: %v %+v", err, layout)
 	}
 	// AP en bridge: wan en br-lan → se re-etiqueta LAN 5
-	ports := BuildEthPorts(layout, states, map[string]bool{"wan": true}, nil)
+	ports := BuildEthPorts(layout, states, map[string]bool{"wan": true}, nil, "")
 	if len(ports) != 6 || ports[0].Label != "LAN 5" {
 		t.Fatalf("ethports bridge: %+v", ports)
 	}
@@ -309,7 +312,7 @@ func TestParsePortsYLayout(t *testing.T) {
 		t.Fatalf("ethports bridge sin eth0 extra: %+v", ports)
 	}
 	// Sin layout: fallback heurístico + interfaces físicas no cubiertas (#413/#416)
-	ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\neth0 up 2500\n"), nil, nil)
+	ports = BuildEthPorts(nil, ParsePortStates("lan2 up 1000\nlan10 up 100\nwan down -1\neth0 up 2500\n"), nil, nil, "")
 	fallbackIDs := map[string]int{}
 	for i, p := range ports {
 		fallbackIDs[p.ID] = i
@@ -335,7 +338,7 @@ func TestParsePortsYLayout(t *testing.T) {
 		{Name: "lan4", Up: true, Speed: "1 Gbps"},
 		{Name: "eth0", Up: true, Speed: "2.5 Gbps"},
 		{Name: "sfp0", Up: true, Speed: "10 Gbps"},
-	}, nil, nil)
+	}, nil, nil, "")
 	if len(ports) != 7 {
 		t.Fatalf("layout + extras: %d ports, %+v", len(ports), ports)
 	}
@@ -1073,3 +1076,256 @@ func TestParseRadioSectionsEmpty(t *testing.T) {
 		t.Errorf("want empty map for unrelated config, got %v", got)
 	}
 }
+
+// portStatesDSASwitch es la salida de CmdPortStates en una placa con switch DSA
+// (ipq4019, switch DSA): dos bocas de verdad (lan1, lan2) colgando del puerto
+// de CPU eth0, el bridge con sus VLANs, y un módem celular en wwan0.
+const portStatesDSASwitch = `br-lan up 1000 - 1 lan2
+br-lan.10 up 1000 - 1 br-lan
+br-lan.16 up 1000 - 1 br-lan
+eth0 up 1000 dsa 1 -
+lan1 up 1000 - 1 eth0
+lan2 up 1000 - 1 eth0
+lo unknown -1 - 772 -
+phy2-ap0 up -1 - 1 -
+pppoe-isp unknown -1 - 512 -
+wg0 unknown -1 - 65534 -
+wwan0 unknown -1 - 65534 -`
+
+// boardWanIsAModem: board.json del mismo router. El WAN no es una boca, es el
+// device del módem QMI.
+const boardWanIsAModem = `{"network":{"lan":{"ports":["lan1","lan2"],"protocol":"static"},` +
+	`"wan":{"device":"/dev/cdc-wdm0","protocol":"qmi"}}}`
+
+func TestParsePortStatesTipoYConduit(t *testing.T) {
+	states := ParsePortStates(portStatesDSASwitch)
+	byName := map[string]PortState{}
+	for _, s := range states {
+		byName[s.Name] = s
+	}
+	if got := byName["lan1"]; got.Conduit != "eth0" || got.Type != ARPHRDEther {
+		t.Fatalf("lan1: %+v", got)
+	}
+	if got := byName["eth0"]; got.Conduit != "" {
+		t.Fatalf("eth0 no cuelga de nadie: %+v", got)
+	}
+	if got := byName["wwan0"]; got.Type == ARPHRDEther {
+		t.Fatalf("wwan0 no es ethernet: %+v", got)
+	}
+	// Forma antigua de tres campos: sin tipo ni conduit, y nada se descarta.
+	old := ParsePortStates("lan1 up 1000\neth0 up 2500\n")
+	if len(old) != 2 || old[0].Type != 0 || old[0].Conduit != "" {
+		t.Fatalf("tres campos: %+v", old)
+	}
+	if ports := BuildEthPorts(nil, old, nil, nil, ""); len(ports) != 2 {
+		t.Fatalf("tres campos no debe esconder bocas: %+v", ports)
+	}
+}
+
+func TestBuildEthPortsSoloLasBocasReales(t *testing.T) {
+	layout, err := ParsePortLayout(boardWanIsAModem)
+	if err != nil {
+		t.Fatalf("layout: %v", err)
+	}
+	ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, "")
+	ids := []string{}
+	for _, p := range ports {
+		ids = append(ids, p.ID)
+	}
+	// Antes salían cuatro: WAN (el módem, nunca conectada), LAN 1, LAN 2 y
+	// ETH 0 (el puerto de CPU del switch).
+	if len(ids) != 2 || ids[0] != "lan1" || ids[1] != "lan2" {
+		t.Fatalf("bocas: %v", ids)
+	}
+}
+
+func TestBuildEthPortsUplinkNoEthernet(t *testing.T) {
+	// board.json puede nombrar como WAN una interfaz que existe pero no es
+	// ethernet (el netdev del módem); tampoco es una boca.
+	layout := []PortLayout{
+		{ID: "wan", Name: "wwan0", Label: "WAN", Role: "wan"},
+		{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"},
+	}
+	ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, "")
+	ids := map[string]bool{}
+	for _, p := range ports {
+		ids[p.ID] = true
+	}
+	if ids["wan"] || ids["wwan0"] {
+		t.Fatalf("el módem no es una boca: %+v", ports)
+	}
+	// lan2 no está en el layout pero sí en /sys: entra como extra.
+	if len(ids) != 2 || !ids["lan1"] || !ids["lan2"] {
+		t.Fatalf("bocas: %+v", ports)
+	}
+}
+
+func TestBuildEthPortsMantieneEthSinSwitch(t *testing.T) {
+	// Caja sin switch DSA (x86, BPI-R4): nadie declara eth0 como puerto de
+	// CPU, así que sigue siendo una boca. Sin layout, el fallback toma eth1
+	// como WAN (comportamiento previo, aquí solo interesa que eth0 siga).
+	states := ParsePortStates("eth0 up 1000 - 1 -\neth1 up 2500 - 1 -\nlo unknown -1 - 772 -\n")
+	ports := BuildEthPorts(nil, states, nil, nil, "")
+	ids := map[string]bool{}
+	for _, p := range ports {
+		ids[p.ID] = true
+	}
+	if len(ids) != 2 || !ids["eth0"] {
+		t.Fatalf("eth0 sin switch debe seguir siendo boca: %+v", ports)
+	}
+}
+
+// dumpUplinkNotNamedWan: forma de `ubus call network.interface dump` en una placa cuyo enlace
+// recortada a lo que mira el parser y con la IP pública cambiada. El uplink
+// vivo es un PPPoE llamado "isp" sobre la boca lan1; la interfaz que SÍ se
+// llama "wan" es el módem celular, ocioso pero con up=true y sin ruta.
+const dumpUplinkNotNamedWan = `{"interface":[
+ {"interface":"lan","up":true,"proto":"static","l3_device":"br-lan.10","device":"br-lan.10",
+  "ipv4-address":[{"address":"192.0.2.1","mask":24}],"route":[]},
+ {"interface":"wan","up":true,"proto":"qmi","l3_device":"wwan0",
+  "ipv4-address":[],"route":[],"dns-server":[]},
+ {"interface":"isp","up":true,"proto":"pppoe","l3_device":"pppoe-isp","device":"lan1",
+  "ipv4-address":[{"address":"203.0.113.45","mask":32,"ptpaddress":"198.51.100.1"}],
+  "route":[{"target":"0.0.0.0","mask":0,"nexthop":"198.51.100.1"}],
+  "dns-server":["198.51.100.53","198.51.100.54"]}]}`
+
+func TestParseWanStatusDumpEligeElUplinkVivo(t *testing.T) {
+	info := ParseWanStatus([]byte(dumpUplinkNotNamedWan))
+	if info.Proto != "pppoe" || info.Device != "pppoe-isp" {
+		t.Fatalf("no eligió el PPPoE vivo: %+v", info)
+	}
+	if info.Port != "lan1" {
+		t.Fatalf("boca del uplink: %q, esperaba lan1", info.Port)
+	}
+	if info.IP != "203.0.113.45" || info.Gateway != "198.51.100.1" {
+		t.Fatalf("ip/gateway: %+v", info)
+	}
+	if len(info.DNS) != 2 {
+		t.Fatalf("dns: %+v", info.DNS)
+	}
+}
+
+func TestParseWanStatusDumpCaeALaLlamadaWan(t *testing.T) {
+	// Router normal con el enlace caído: ninguna tiene ruta por defecto, así
+	// que manda la que se llama "wan" (WAN caída, no router sin WAN).
+	dump := `{"interface":[{"interface":"lan","up":true,"proto":"static","route":[]},
+	 {"interface":"wan","up":false,"proto":"dhcp","l3_device":"eth1","device":"eth1","route":[]}]}`
+	info := ParseWanStatus([]byte(dump))
+	if info.Proto != "dhcp" || info.Port != "eth1" {
+		t.Fatalf("fallback a la llamada wan: %+v", info)
+	}
+	// Sin ninguna interfaz utilizable (AP puro) → vacío.
+	if got := ParseWanStatus([]byte(`{"interface":[{"interface":"lan","up":true,"route":[]}]}`)); got.Proto != "" || got.Port != "" {
+		t.Fatalf("AP sin wan: %+v", got)
+	}
+}
+
+func TestBuildEthPortsMarcaLaBocaDelUplink(t *testing.T) {
+	layout, err := ParsePortLayout(boardWanIsAModem)
+	if err != nil {
+		t.Fatalf("layout: %v", err)
+	}
+	uplink := ParseWanStatus([]byte(dumpUplinkNotNamedWan)).Port
+	ports := BuildEthPorts(layout, ParsePortStates(portStatesDSASwitch), nil, nil, uplink)
+	if len(ports) != 2 {
+		t.Fatalf("bocas: %+v", ports)
+	}
+	// lan1 lleva el PPPoE: sale como WAN sin moverse de sitio.
+	if ports[0].ID != "wan" || ports[0].Label != "WAN" {
+		t.Fatalf("la boca del uplink debía salir como WAN: %+v", ports[0])
+	}
+	if ports[1].ID != "lan2" {
+		t.Fatalf("el resto no se toca: %+v", ports[1])
+	}
+}
+
+func TestBuildEthPortsNoPisaUnaWanDelLayout(t *testing.T) {
+	// Router con boca WAN dedicada: el layout ya la trae y el uplink no
+	// debe promover ninguna otra.
+	layout := []PortLayout{
+		{ID: "wan", Name: "wan", Label: "WAN", Role: "wan"},
+		{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"},
+	}
+	states := ParsePortStates("wan up 1000 - 1 -\nlan1 up 1000 - 1 -\n")
+	ports := BuildEthPorts(layout, states, nil, nil, "lan1")
+	if len(ports) != 2 || ports[0].ID != "wan" || ports[1].ID != "lan1" {
+		t.Fatalf("bocas: %+v", ports)
+	}
+}
+
+func TestBuildEthPortsUplinkEtiquetado(t *testing.T) {
+	// Uplink sobre VLAN ("lan1.7"): la boca es la de debajo.
+	layout := []PortLayout{{ID: "lan1", Name: "lan1", Label: "LAN 1", Role: "lan"}}
+	states := ParsePortStates("lan1 up 1000 - 1 -\n")
+	ports := BuildEthPorts(layout, states, nil, nil, "lan1.7")
+	if len(ports) != 1 || ports[0].ID != "wan" {
+		t.Fatalf("bocas: %+v", ports)
+	}
+}
+
+// A neighbour table with every state that matters: what the kernel has
+// confirmed, and what it merely remembers.
+func TestParseIPNeighSeparatesConfirmedFromRemembered(t *testing.T) {
+	out := strings.Join([]string{
+		"192.0.2.10 dev br-lan lladdr 02:00:00:00:00:10 REACHABLE",
+		"192.0.2.11 dev br-lan lladdr 02:00:00:00:00:11 STALE",
+		"192.0.2.12 dev br-lan lladdr 02:00:00:00:00:12 DELAY",
+		"192.0.2.13 dev br-lan lladdr 02:00:00:00:00:13 PERMANENT",
+		"192.0.2.14 dev br-lan  FAILED",
+		"192.0.2.15 dev br-lan lladdr 02:00:00:00:00:15 FAILED",
+		"192.0.2.16 dev br-lan lladdr 00:00:00:00:00:00 REACHABLE",
+		"not-an-ip dev br-lan lladdr 02:00:00:00:00:17 REACHABLE",
+	}, "\n")
+	arp, stale := ParseIPNeigh(out)
+
+	if len(arp) != 5 {
+		t.Fatalf("arp: %+v", arp)
+	}
+	if arp["02:00:00:00:00:10"] != "192.0.2.10" || arp["02:00:00:00:00:11"] != "192.0.2.11" {
+		t.Fatalf("addresses: %+v", arp)
+	}
+	// A stale entry still resolves an IP; it just proves nothing.
+	for _, mac := range []string{"02:00:00:00:00:11", "02:00:00:00:00:15"} {
+		if !stale[mac] {
+			t.Fatalf("%s should be stale: %+v", mac, stale)
+		}
+	}
+	for _, mac := range []string{"02:00:00:00:00:10", "02:00:00:00:00:12", "02:00:00:00:00:13"} {
+		if stale[mac] {
+			t.Fatalf("%s is confirmed: %+v", mac, stale)
+		}
+	}
+	// An entry with no lladdr, a null MAC or a broken address is not a host.
+	if _, ok := arp["00:00:00:00:00:00"]; ok {
+		t.Fatalf("null MAC: %+v", arp)
+	}
+	if _, ok := arp["02:00:00:00:00:17"]; ok {
+		t.Fatalf("invalid IP: %+v", arp)
+	}
+}
+
+// One confirmed address is enough for a host with several of them, whatever
+// order the table lists them in.
+func TestParseIPNeighConfirmedWinsOverStale(t *testing.T) {
+	for _, out := range []string{
+		"192.0.2.20 dev br-lan lladdr 02:00:00:00:00:20 STALE\n" +
+			"192.0.2.21 dev br-lan lladdr 02:00:00:00:00:20 REACHABLE",
+		"192.0.2.21 dev br-lan lladdr 02:00:00:00:00:20 REACHABLE\n" +
+			"192.0.2.20 dev br-lan lladdr 02:00:00:00:00:20 STALE",
+	} {
+		arp, stale := ParseIPNeigh(out)
+		if stale["02:00:00:00:00:20"] {
+			t.Fatalf("a confirmed address must settle the host: %+v", stale)
+		}
+		if arp["02:00:00:00:00:20"] != "192.0.2.21" {
+			t.Fatalf("the confirmed address should be the one kept: %+v", arp)
+		}
+	}
+}
+
+func TestParseIPNeighOnGarbage(t *testing.T) {
+	arp, stale := ParseIPNeigh("ip: command not found\n\n")
+	if len(arp) != 0 || len(stale) != 0 {
+		t.Fatalf("garbage: %+v %+v", arp, stale)
+	}
+}

+ 6 - 3
app/public/locales/en/translation.json

@@ -213,7 +213,8 @@
       },
       "unknown-device": {
         "title": "Unknown device",
-        "description": "{{mac}} connected to {{router}}"
+        "description": "{{mac}} connected to {{router}}",
+        "descriptionWhere": "{{mac}} · {{ip}} connected to {{where}}"
       },
       "wan-down": {
         "title": "Internet down",
@@ -1090,6 +1091,7 @@
       "hypervisorCable": "Hypervisor cable",
       "inferredSwitch": "Inferred switch · {{port}}",
       "managedSwitch": "Managed switch",
+      "managedAp": "Access point",
       "throughput": "Link throughput",
       "title": "Links between devices",
       "wifiUplink": "WiFi uplink"
@@ -1131,9 +1133,10 @@
       "inferred": "inferred",
       "managed": "managed switch",
       "noIp": "no IP · not directly queryable",
-      "port": "Port on {{router}}",
+      "port": "Port on {{owner}}",
       "macs": "Learned MACs",
-      "fdbNote": "FDB: {{count}} heterogeneous MACs on a single physical port. Probably a switch; we cannot tell for sure without LLDP."
+      "fdbNote": "FDB: {{count}} heterogeneous MACs on a single physical port. Probably a switch; we cannot tell for sure without LLDP.",
+      "ap": "Access point"
     },
     "host": {
       "hypervisor": "hypervisor",

+ 6 - 3
app/public/locales/es/translation.json

@@ -213,7 +213,8 @@
       },
       "unknown-device": {
         "title": "Dispositivo desconocido",
-        "description": "{{mac}} se ha conectado a {{router}}"
+        "description": "{{mac}} se ha conectado a {{router}}",
+        "descriptionWhere": "{{mac}} · {{ip}} se ha conectado a {{where}}"
       },
       "wan-down": {
         "title": "Internet caído",
@@ -1090,6 +1091,7 @@
       "hypervisorCable": "Cable de hipervisor",
       "inferredSwitch": "Switch inferido · {{port}}",
       "managedSwitch": "Switch gestionado",
+      "managedAp": "Punto de acceso",
       "throughput": "Throughput del enlace",
       "title": "Enlaces entre equipos",
       "wifiUplink": "WiFi uplink"
@@ -1131,9 +1133,10 @@
       "inferred": "inferido",
       "managed": "switch gestionado",
       "noIp": "sin IP · no consultable directamente",
-      "port": "Puerto de {{router}}",
+      "port": "Puerto de {{owner}}",
       "macs": "MACs aprendidas",
-      "fdbNote": "FDB: {{count}} MACs heterogéneas en un solo puerto físico. Probablemente un switch; no podemos afirmarlo sin LLDP."
+      "fdbNote": "FDB: {{count}} MACs heterogéneas en un solo puerto físico. Probablemente un switch; no podemos afirmarlo sin LLDP.",
+      "ap": "Punto de acceso"
     },
     "host": {
       "hypervisor": "hipervisor",

+ 3 - 8
app/src/components/routers/AgentsSection.tsx

@@ -9,6 +9,7 @@ import type { AgentInfo, Router } from '@/data/types'
 import { relTimeFromTs } from '@/i18n'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { AgentUpgradeButton, activeUpgrade, upgradeStepText } from '@/components/routers/AgentUpgradeButton'
+import { agentMatchesRouter, findRouterFor } from '@/lib/agentMatch'
 import { cn, copyToClipboard } from '@/lib/utils'
 
 /**
@@ -518,10 +519,9 @@ export function AgentsSection() {
 
   // Filas: agentes registrados (por slug) + routers agent-only sin agente.
   const rows = useMemo(() => {
-    const routerBySlug = new Map(routers.map((r) => [r.id, r]))
     const out: { agent?: AgentInfo; router?: Router }[] = agents.map((a) => ({
       agent: a,
-      router: routerBySlug.get(a.slug),
+      router: findRouterFor(routers, a),
     }))
     // #483: también fila para TODO router nativo OpenWrt sin agente (no solo
     // agent-only): el botón Instalar registra el agente y lo despliega por
@@ -530,12 +530,7 @@ export function AgentsSection() {
     // de overview difiere del id de tabla.
     for (const r of routers) {
       if (!isOpenWrtType(r.type)) continue
-      const covered = agents.some(
-        (a) =>
-          a.routerId === r.id ||
-          a.slug === r.id ||
-          (a.hostname !== undefined && a.hostname.toLowerCase() === r.id.toLowerCase()),
-      )
+      const covered = agents.some((a) => agentMatchesRouter(a, r.id))
       if (!covered) out.push({ router: r })
     }
     return out

+ 9 - 16
app/src/components/routers/FleetTable.tsx

@@ -7,10 +7,10 @@ import { fmtUptime, numLocale } from '@/i18n'
 import type { Router } from '@/data/mock'
 import { fmtEs } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
-import type { AgentInfo } from '@/data/types'
 import { MetricBar } from '@/components/MetricBar'
 import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
+import { findAgentFor } from '@/lib/agentMatch'
 import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
@@ -102,19 +102,12 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
   const [sortKey, setSortKey] = useState<SortKey>('name')
   const [asc, setAsc] = useState(true)
   const [openId, setOpenId] = useState<string | null>(null)
-  // Índice por slug Y por routerId, con el mismo criterio que useAgentFor
-  // (#282): el servidor resuelve la asociación agente↔router (p. ej. por MAC
-  // de bridge) y el routerId puede NO coincidir con el slug. Indexar solo
-  // por slug dejaba "Agente no instalado" a agentes instalados cuyo slug
-  // difiere del id del router (#848). Primero en ganar, como find().
-  const agentBySlug = useMemo(() => {
-    const m = new Map<string, AgentInfo>()
-    for (const a of agents) {
-      if (!m.has(a.slug)) m.set(a.slug, a)
-      if (a.routerId && !m.has(a.routerId)) m.set(a.routerId, a)
-    }
-    return m
-  }, [agents])
+  // An agent's slug is not its router's id, so the lookup goes through the
+  // three-key matcher; keyed by router id, which is what the rows have.
+  const agentByRouter = useMemo(
+    () => new Map(routers.map((r) => [r.id, findAgentFor(agents, r.id)])),
+    [agents, routers],
+  )
 
   const sorted = useMemo(() => {
     const arr = [...routers]
@@ -199,7 +192,7 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                       <span>
                         <span className="flex items-center gap-2">
                           <span className="font-medium text-text-primary">{r.name}</span>
-                          <AgentBadge agent={agentBySlug.get(r.id)} agentOnly={r.agentOnly} deviceType={r.type} />
+                          <AgentBadge agent={agentByRouter.get(r.id)} agentOnly={r.agentOnly} deviceType={r.type} />
                         </span>
                         <span className="block text-caption text-text-muted">{r.modelShort}</span>
                       </span>
@@ -255,7 +248,7 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                   </span>
                   <span className="min-w-0">
                     <span className="block truncate font-medium text-text-primary">{r.name}</span>
-                    <AgentBadge agent={agentBySlug.get(r.id)} agentOnly={r.agentOnly} deviceType={r.type} className="mt-1" />
+                    <AgentBadge agent={agentByRouter.get(r.id)} agentOnly={r.agentOnly} deviceType={r.type} className="mt-1" />
                   </span>
                 </span>
                 <span className="flex shrink-0 items-center gap-2">

+ 32 - 8
app/src/components/topology/TopologyMap.tsx

@@ -140,7 +140,7 @@ function TooltipCard({
   tip,
   touch,
   wan,
-  routerName,
+  portOwnerName,
   onTagDevice,
   onPointerEnter,
   onPointerLeave,
@@ -148,8 +148,9 @@ function TooltipCard({
   tip: TooltipState
   touch: boolean
   wan: WanInfo
-  /** nombre visible del router del que cuelga un nodo (D8: tooltip dist) */
-  routerName: (id: string) => string
+  /** nombre del equipo dueño del puerto de un nodo (D8: tooltip dist): el
+   *  padre de la cadena si lo hay, y si no el router */
+  portOwnerName: (node: DistributionNode) => string
   /** etiquetar el dispositivo desde la propia tarjeta (#656 feedback: más
    *  sencillo que introducir la MAC a mano) */
   onTagDevice?: (device: Device) => void
@@ -296,7 +297,7 @@ function TooltipCard({
             {[tip.node.ip, portName(tip.node.port, tip.node.portLabel)].filter(Boolean).join(' · ')}
           </div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
-            <MiniStat label={t('topology.dist.port', { router: routerName(tip.node.routerId) })} value={portName(tip.node.port, tip.node.portLabel)} />
+            <MiniStat label={t('topology.dist.port', { owner: portOwnerName(tip.node) })} value={portName(tip.node.port, tip.node.portLabel)} />
             <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
           {tip.node.lldp && (
@@ -319,7 +320,7 @@ function TooltipCard({
           </div>
           <div className="mt-0.5 text-caption text-text-muted">{t('topology.dist.noIp')}</div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
-            <MiniStat label={t('topology.dist.port', { router: routerName(tip.node.routerId) })} value={portName(tip.node.port, tip.node.portLabel)} />
+            <MiniStat label={t('topology.dist.port', { owner: portOwnerName(tip.node) })} value={portName(tip.node.port, tip.node.portLabel)} />
             <MiniStat label={t('topology.dist.macs')} value={String(tip.node.macCount)} />
           </div>
           <div className="mt-2 text-caption leading-snug text-text-secondary">
@@ -890,6 +891,19 @@ export function TopologyMap({
     (id: string) => routerNodes.find((n) => n.id === id)?.router.name ?? id,
     [routerNodes],
   )
+  /**
+   * De quién es el puerto en el que cuelga un nodo. `port` es del PADRE, no
+   * del router: en una cadena (AP → switch → router) el puerto del AP es una
+   * boca del switch, y etiquetarlo "Puerto de <router>" señalaba un equipo
+   * que ni siquiera tiene esa boca.
+   */
+  const portOwnerName = useCallback(
+    (node: DistributionNode) => {
+      const parent = node.parent ? distNodes.find((n) => n.id === node.parent) : undefined
+      return parent ? (parent.node.name ?? parent.node.ip ?? t('topology.dist.managed')) : routerName(node.routerId)
+    },
+    [distNodes, routerName, t],
+  )
   /** datos del tooltip de un chip: +N si es host hipervisor, host si es CT */
   const chipTip = useCallback(
     (chip: ChipNode): TooltipData => ({
@@ -1470,8 +1484,8 @@ export function TopologyMap({
           {distNodes.map((dv, i) =>
             dv.node.kind === 'managed' ? (
               <LabelText key={dv.id} x={dv.x} y={dv.y - 34} anchor="middle" delay={(2.15 + i * 0.03) * T}
-                reduce={reduce ?? false} title={dv.node.name ?? t('topology.dist.managed')}
-                sub={`${[dv.node.ip ?? 'LLDP', portName(dv.node.port, dv.node.portLabel)].join(' · ')}`}
+                reduce={reduce ?? false} title={dv.node.name ?? t(dv.node.role === 'ap' ? 'topology.dist.ap' : 'topology.dist.managed')}
+                sub={[dv.node.ip ?? distBadge(dv.node), portName(dv.node.port, dv.node.portLabel)].filter(Boolean).join(' · ')}
                 subColor={COLOR.accent} />
             ) : (
               <LabelText key={dv.id} x={dv.x} y={dv.y - 34} anchor="middle" delay={(2.15 + i * 0.03) * T}
@@ -1532,7 +1546,7 @@ export function TopologyMap({
           tip={tooltip}
           touch={!hoverCapable}
           wan={wan}
-          routerName={routerName}
+          portOwnerName={portOwnerName}
           onTagDevice={
             onTagDevice
               ? (device) => {
@@ -1554,6 +1568,16 @@ export function TopologyMap({
 // Etiqueta de nodo (título + subtítulo)
 // ---------------------------------------------------------------------------
 
+/**
+ * Procedencia de una caja gestionada: LLDP si el router la vio anunciarse, y
+ * si no el integrador que la reportó (p. ej. "proxmox"). Antes decía "LLDP"
+ * en todas. "" = sin procedencia conocida.
+ */
+function distBadge(n: DistributionNode): string {
+  if (n.lldp) return 'LLDP'
+  return n.source ? n.source.toUpperCase() : ''
+}
+
 function LabelText({
   x,
   y,

+ 49 - 15
app/src/components/topology/model.ts

@@ -1434,10 +1434,36 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   ).length
 
   // Tabla de backhauls (topology.md §④)
+  /**
+   * Nombre del equipo del que cuelga un dispositivo, resuelto por el mismo
+   * hubOf que usa el mapa: un nodo de distribución (switch, AP, hipervisor),
+   * otro dispositivo que hace de hub, o el router. Nada de asumir el router:
+   * el host Proxmox cuelga del switch y la tabla lo anunciaba colgando del
+   * OpenWrt, que es el enlace de más arriba, no el suyo.
+   */
+  const hubNameOf = (d: Device): string => {
+    const id = hubOf(d)
+    const dn = distById.get(id)
+    if (dn) return dn.name ?? dn.ip ?? id
+    const rn = routerById.get(id)
+    if (rn) return rn.router.name
+    return deviceById.get(id)?.name ?? id
+  }
+  /**
+   * Velocidad de un enlace, o "—" si nadie la ha medido. La tabla escribía
+   * "1 Gbps" en toda fila de distribución y "866 Mbps PHY · −58 dBm" en un
+   * uplink wifi sin tener el dato de ninguno de los dos: números inventados
+   * con aspecto de medida. Hoy solo el controlador reporta velocidad real
+   * (la negociada en su boca) y solo eso se pinta.
+   */
+  const linkSpeed = (mbps?: number): string => {
+    if (!mbps || mbps <= 0) return '—'
+    return mbps >= 1000 ? `${(mbps / 1000).toFixed(mbps % 1000 === 0 ? 0 : 1)} Gbps` : `${mbps} Mbps`
+  }
   const backhauls: BackhaulRow[] = []
   if (gatewayNode) {
     backhauls.push({
-      id: 'wan', a: 'Gateway', b: 'Internet', kind: 'wan',
+      id: 'wan', a: gatewayNode.router.name, b: 'Internet', kind: 'wan',
       type: 'topology.links.fiberWan', speed: wan.plan, signal: `${wan.latencyMs} ms`,
       tone: 'ok', statusLabel: 'common.status.online',
       spark: gatewayNode.router.sparkline, sparkColor: COLOR.accent,
@@ -1446,13 +1472,15 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   for (const node of apNodes) {
     const isWifi = node.router.backhaul === 'wifi'
     backhauls.push({
-      id: `uplink-${node.id}`, a: 'Gateway', b: node.router.name, kind: 'uplink',
+      id: `uplink-${node.id}`, a: gatewayNode?.router.name ?? '', b: node.router.name, kind: 'uplink',
       type: isWifi ? 'topology.links.wifiUplink' : 'common.cable',
-      speed: isWifi ? '866 Mbps PHY' : '1 Gbps',
-      signal: isWifi ? '−58 dBm · 1 ms' : '<1 ms',
+      // El contrato no trae ni tasa PHY ni señal del backhaul de un AP, así
+      // que no se afirma ninguna. El tono sí es información real: un enlace
+      // por wifi merece mirarse más que uno por cable.
+      speed: '—',
+      signal: '—',
       tone: isWifi ? 'warn' : 'ok',
       statusLabel: isWifi ? 'common.status.warn' : 'common.status.online',
-      note: isWifi ? 'topology.links.congestedChannel' : undefined,
       spark: node.router.sparkline,
       sparkColor: isWifi ? COLOR.warn : COLOR.accent,
     })
@@ -1466,11 +1494,14 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const a = parent ? (parent.node.name ?? parent.node.ip ?? '') : (rn?.router.name ?? '')
     const spark = rn?.router.sparkline ?? []
     if (dv.node.kind === 'managed') {
+      // La procedencia es LLDP solo si el router vio el anuncio; una caja que
+      // solo conoce un integrador llevaba "LLDP" y el tipo "switch".
+      const via = dv.node.lldp ? 'LLDP' : (dv.node.source ? dv.node.source.toUpperCase() : '')
       backhauls.push({
         id: `dist-${dv.id}`, a,
-        b: [dv.node.name, dv.node.ip, 'LLDP', dv.node.portLabel ?? dv.node.port].filter(Boolean).join(' · '),
-        kind: 'dist', type: 'topology.links.managedSwitch',
-        speed: '1 Gbps', signal: '<1 ms',
+        b: [dv.node.name, dv.node.ip, via, dv.node.portLabel ?? dv.node.port].filter(Boolean).join(' · '),
+        kind: 'dist', type: dv.node.role === 'ap' ? 'topology.links.managedAp' : 'topology.links.managedSwitch',
+        speed: linkSpeed(dv.node.speedMbps), signal: '—',
         tone: 'ok', statusLabel: 'common.status.online',
         spark, sparkColor: COLOR.accent,
       })
@@ -1479,7 +1510,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
         id: `dist-${dv.id}`, a,
         b: '', bKey: 'topology.links.inferredSwitch', bVars: { port: dv.node.portLabel ?? dv.node.port },
         kind: 'dist', type: 'common.cable',
-        speed: '1 Gbps', signal: '<1 ms',
+        speed: linkSpeed(dv.node.speedMbps), signal: '—',
         tone: 'ok', statusLabel: 'common.status.online',
         spark, sparkColor: COLOR.ok,
       })
@@ -1488,13 +1519,16 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   // D7: cable del hipervisor (host con sus CTs/VMs anidados).
   for (const dn of distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId)) {
     const host = deviceById.get(dn.hostDeviceId!)
-    const rn = routerById.get(dn.routerId)
-    if (!host || !rn) continue
+    if (!host) continue
+    // La boca la manda el DEVICE, no el nodo: el nodo se crea con lo que el
+    // host tenía al sellar Proxmox y los sellos posteriores (UniFi) afinan
+    // la del device — nombre de boca incluido.
+    const port = host.portLabel ?? host.port ?? dn.portLabel ?? dn.port
     backhauls.push({
-      id: `wired-${host.id}`, a: rn.router.name,
-      b: `${host.name} · ${dn.portLabel ?? dn.port} · ${ctCountByHost.get(host.id) ?? 0} CT`,
+      id: `wired-${host.id}`, a: hubNameOf(host),
+      b: [host.name, port, `${ctCountByHost.get(host.id) ?? 0} CT`].filter(Boolean).join(' · '),
       kind: 'wired', type: 'topology.links.hypervisorCable',
-      speed: '—', signal: '—',
+      speed: linkSpeed(host.speedMbps), signal: '—',
       tone: 'ok', statusLabel: 'common.status.online',
       spark: host.sparkline, sparkColor: COLOR.ok,
     })
@@ -1504,7 +1538,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     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: '—', signal: '42 ms',
+      type: 'WireGuard', speed: '—', signal: '—',
       tone: 'tunnel', statusLabel: 'common.active',
       spark: device?.sparkline ?? [0, 0], sparkColor: COLOR.tunnel,
     })

+ 5 - 2
app/src/data/demo-canon.json

@@ -1794,6 +1794,7 @@
         12.3
       ],
       "port": "lan5",
+      "speedMbps": 2500,
       "infra": "hypervisor",
       "hostname": "pve",
       "dhcpLease": "IP fija (reserva)",
@@ -2387,7 +2388,8 @@
       "kind": "inferred",
       "routerId": "flint2",
       "port": "lan3",
-      "macCount": 8
+      "macCount": 8,
+      "speedMbps": 1000
     },
     {
       "id": "dist-pve",
@@ -2412,7 +2414,8 @@
         "mgmt": "192.168.8.13",
         "caps": "Bridge",
         "portDesc": "ge5"
-      }
+      },
+      "speedMbps": 1000
     }
   ],
   "adguard": {

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

@@ -199,6 +199,8 @@ export interface LldpInfo {
 }
 
 export interface Device {
+  /** Velocidad negociada (Mbps) de la boca donde está enchufado, si se sabe. */
+  speedMbps?: number
   id: string
   name: string
   type: DeviceType
@@ -283,6 +285,20 @@ export interface DistributionNode {
    * los Devices cuya MAC coincide con esta — se representa SOLO como nodo.
    */
   mac?: string
+  /**
+   * Qué es realmente la caja gestionada: "switch" o "ap". `kind` sigue
+   * siendo "managed" en ambos porque decide el layout (caja con MAC e IP,
+   * dibujada como nodo y no como chip de cliente), pero un punto de acceso
+   * no es un switch. Ausente = switch (lo único que la inferencia LLDP ha
+   * encontrado nunca).
+   */
+  role?: 'switch' | 'ap'
+  /**
+   * Velocidad negociada (Mbps) del enlace por el que cuelga, cuando alguien
+   * la sabe de verdad (hoy: la boca del switch, vía controlador). Ausente =
+   * desconocida, y la tabla escribe "—" en vez de inventarse un valor.
+   */
+  speedMbps?: number
 }
 
 export type AlertSeverity = 'warn' | 'critical' | 'info' | 'ok'

+ 2 - 1
app/src/hooks/useAgentFor.ts

@@ -1,10 +1,11 @@
 import { useNetPulse } from '@/data/DataProvider'
 import type { AgentInfo } from '@/data/types'
+import { findAgentFor } from '@/lib/agentMatch'
 
 /** Agente nativo registrado en un router. El backend resuelve la asociación
  *  por slug/hostname/MAC, así que preferimos `routerId` y caemos a `slug`
  *  para compatibilidad con configuraciones antiguas (#282). */
 export function useAgentFor(routerId: string): AgentInfo | undefined {
   const { agents } = useNetPulse()
-  return agents.find((a) => a.routerId === routerId || a.slug === routerId)
+  return findAgentFor(agents, routerId)
 }

+ 48 - 0
app/src/lib/agentMatch.ts

@@ -0,0 +1,48 @@
+/**
+ * Matching an agent to its router.
+ *
+ * An agent registers under its own slug, which is not the router's id: the
+ * slug comes from the board (its hostname), the id from the fleet table, and
+ * they only coincide when both were named the same. The server already knows
+ * the association and sends it as `routerId` (#282), with the hostname as a
+ * third key for older setups whose overview id differs from the table id
+ * (#483).
+ *
+ * Every screen that asks "does this router have an agent?" has to use all
+ * three keys, or it shows "agent not installed" next to a router that is
+ * being polled by its agent right now.
+ */
+import type { AgentInfo } from '@/data/types'
+
+/** The three keys the matching needs; anything agent-shaped can be passed. */
+export type AgentKeys = Pick<AgentInfo, 'slug' | 'routerId' | 'hostname'>
+
+/** True when this agent belongs to the router with that id. */
+export function agentMatchesRouter(a: AgentKeys, routerId: string): boolean {
+  return (
+    a.routerId === routerId ||
+    a.slug === routerId ||
+    (a.hostname !== undefined && a.hostname.toLowerCase() === routerId.toLowerCase())
+  )
+}
+
+/**
+ * The agent of a router, preferring the association the server states over
+ * the two name-based fallbacks, so a coincidence of names never wins over it.
+ */
+export function findAgentFor<T extends AgentKeys>(agents: T[], routerId: string): T | undefined {
+  return (
+    agents.find((a) => a.routerId === routerId) ??
+    agents.find((a) => a.slug === routerId) ??
+    agents.find((a) => a.hostname !== undefined && a.hostname.toLowerCase() === routerId.toLowerCase())
+  )
+}
+
+/** The router an agent belongs to: the inverse lookup, same three keys. */
+export function findRouterFor<T extends { id: string }>(routers: T[], agent: AgentKeys): T | undefined {
+  return (
+    routers.find((r) => r.id === agent.routerId) ??
+    routers.find((r) => r.id === agent.slug) ??
+    routers.find((r) => agent.hostname !== undefined && r.id.toLowerCase() === agent.hostname.toLowerCase())
+  )
+}

+ 7 - 0
app/src/lib/alerts-i18n.ts

@@ -41,6 +41,13 @@ export function alertDescription(t: TFunction, ev: AlertEvent): string {
     })
     if (translated !== '') return translated
   }
+  // An unknown device is found by where it is, not by its MAC: when the
+  // server sends the IP and what it is plugged into, use the variant that
+  // says so. The original key stays for alerts already stored without those
+  // vars, which would otherwise render the placeholders unsubstituted.
+  if (ev.type === 'unknown-device' && ev.vars?.ip && ev.vars?.where) {
+    return t(`alerts.types.${ev.type}.descriptionWhere`, { defaultValue: ev.description, ...ev.vars })
+  }
   return t(`alerts.types.${ev.type}.description`, { defaultValue: ev.description, ...(ev.vars ?? {}) })
 }
 

+ 18 - 8
app/src/lib/push-i18n.ts

@@ -13,7 +13,7 @@
 /** Subconjunto del catálogo de traducciones que necesita el push. */
 export interface PushCatalog {
   alerts?: {
-    types?: Record<string, { title?: string; description?: string; results?: Record<string, string> }>
+      types?: Record<string, { title?: string; description?: string; results?: Record<string, string>; descriptionWhere?: string }>
     hints?: Record<string, string>
   }
 }
@@ -41,6 +41,11 @@ export function interpolate(tpl: string, vars: Record<string, string> | undefine
   return tpl.replace(/\{\{(\w+)\}\}/g, (match, key: string) => (key in vars ? vars[key]! : match))
 }
 
+/** True when every `{{var}}` of the template has a value in `vars`. */
+function resolvable(tpl: string, vars: Record<string, string> | undefined): boolean {
+  return [...tpl.matchAll(/\{\{(\w+)\}\}/g)].every((m) => !!vars?.[m[1]!])
+}
+
 /**
  * Traduce title/description/hint de un evento tipado. Si no hay `type`, falta
  * la clave o el catálogo no cargó, cae a los literales del server (fallback).
@@ -55,13 +60,18 @@ export function localizePush(
 ): LocalizedPush {
   const entry = type ? catalog?.alerts?.types?.[type] : undefined
   const title = entry?.title ? interpolate(entry.title, vars) : fallback.title || 'NetPulse'
-  const resultKey = vars?.result
-  const resultTpl = resultKey ? entry?.results?.[resultKey] : undefined
-  const body = resultTpl
-    ? interpolate(resultTpl, vars)
-    : entry?.description
-      ? interpolate(entry.description, vars)
-      : (fallback.body ?? '')
+    // Upstream's per-result template wins when the event carries a result
+    // code; otherwise a richer variant (`descriptionWhere`, which names the IP
+    // and what the client is plugged into) when every value it needs is
+    // present; otherwise the plain description, which always resolves.
+    const resultKey = vars?.result
+    const resultTpl = resultKey ? entry?.results?.[resultKey] : undefined
+    const tpl =
+      resultTpl ??
+      (entry?.descriptionWhere && resolvable(entry.descriptionWhere, vars)
+        ? entry.descriptionWhere
+        : entry?.description)
+    const body = tpl ? interpolate(tpl, vars) : fallback.body ?? ''
   // El hint solo se muestra si el evento traía uno; se prefiere la clave i18n.
   const hint = fallback.hint ? (type ? catalog?.alerts?.hints?.[type] ?? fallback.hint : fallback.hint) : undefined
   return { title, body, hint }

+ 39 - 16
app/src/pages/Alerts.tsx

@@ -188,6 +188,16 @@ function ContextPanel({ ev, animateIn }: { ev: FeedEvent; animateIn: boolean })
   const { t } = useTranslation()
   const c = ev.context
   const PeerIcon = c?.wg ? PEER_ICONS[c.wg.peerType] : null
+  // Unknown device: the point of the alert is finding the thing, so the
+  // panel lists where it is (IP, the box it hangs off, the port) and links
+  // to it in the client list. The server only sends the facts it has.
+  const v = ev.type === 'unknown-device' ? (ev.vars ?? {}) : {}
+  const locate: { label: string; value: string }[] = []
+  if (v.ip) locate.push({ label: 'IP', value: v.ip })
+  if (v.mac) locate.push({ label: 'MAC', value: v.mac })
+  if (v.where) locate.push({ label: t('alerts.connectedTo'), value: v.where })
+  if (v.port) locate.push({ label: t('alerts.port'), value: v.port })
+  if (v.band) locate.push({ label: t('devices.colBand'), value: v.band })
   return (
     <div className="space-y-3 rounded-xl border border-border bg-elevated/60 p-4">
       {c?.spark && <ThresholdSpark spark={c.spark} animateIn={animateIn} />}
@@ -220,6 +230,14 @@ function ContextPanel({ ev, animateIn }: { ev: FeedEvent; animateIn: boolean })
         </div>
       )}
 
+      {locate.length > 0 && (
+        <div className="grid gap-2 sm:grid-cols-2">
+          {locate.map((f) => (
+            <Fact key={f.label} label={f.label} value={f.value} />
+          ))}
+        </div>
+      )}
+
       {c?.facts && (
         <div className="grid gap-2 sm:grid-cols-2">
           {c.facts.map((f) => (
@@ -230,20 +248,29 @@ function ContextPanel({ ev, animateIn }: { ev: FeedEvent; animateIn: boolean })
 
       {c?.note && <p className="text-caption leading-relaxed text-text-muted">{c.note}</p>}
 
+      {/* FORK: finding the device and identifying it are separate actions.
+          Upstream pointed this link at the identify dialog for unknown
+          devices, so there was no longer a way to see it in the list. */}
       {ev.vars?.mac && (
         <Link
-          to={
-            intakeMacOf(ev)
-              ? `/devices?intake=${encodeURIComponent(ev.vars.mac)}`
-              : `/devices?q=${encodeURIComponent(ev.vars.mac)}`
-          }
-          className="group inline-flex items-center gap-1 text-caption font-semibold text-accent transition-colors hover:text-accent/80"
+          to={`/devices?q=${encodeURIComponent(ev.vars.mac)}`}
+          className="group mr-4 inline-flex items-center gap-1 text-caption font-semibold text-accent transition-colors hover:text-accent/80"
         >
           {t('alerts.findDevice')}
           <ArrowRight className="h-3.5 w-3.5 transition-transform duration-150 group-hover:translate-x-0.5" strokeWidth={1.75} />
         </Link>
       )}
 
+      {intakeMacOf(ev) && (
+        <Link
+          to={`/devices?intake=${encodeURIComponent(intakeMacOf(ev) ?? '')}`}
+          className="group mr-4 inline-flex items-center gap-1 text-caption font-semibold text-accent transition-colors hover:text-accent/80"
+        >
+          {t('alerts.identifyDevice')}
+          <ArrowRight className="h-3.5 w-3.5 transition-transform duration-150 group-hover:translate-x-0.5" strokeWidth={1.75} />
+        </Link>
+      )}
+
       {ev.routerId && (
         <Link
           to={`/routers/${ev.routerId}`}
@@ -448,7 +475,6 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDis
 
 export default function Alerts() {
   const { t } = useTranslation()
-  const navigate = useNavigate()
   const reduce = useReducedMotion() ?? false
   const {
     alerts,
@@ -475,6 +501,7 @@ export default function Alerts() {
   const [kind, setKind] = useState<KindFilter>('todos')
   const [cats, setCats] = useState<ReadonlySet<AlertCategory>>(new Set())
   const [searchParams] = useSearchParams()
+  const navigate = useNavigate()
   const [onlyUnread, setOnlyUnread] = useState(() => searchParams.get('unread') === '1')
   const [expandedId, setExpandedId] = useState<string | null>(null)
   const [burst, setBurst] = useState(0)
@@ -496,15 +523,11 @@ export default function Alerts() {
 
   const toggleEvent = (ev: FeedEvent) => {
     if (!ev.read) markAlertsRead([ev.id])
-    // #827: la alerta de desconocido lleva directa al alta del dispositivo;
-    // el resto sigue desplegando el panel de contexto. La misma acción
-    // existe como icono en la fila (#833), junto a "limpiar alerta".
-    const mac = intakeMacOf(ev)
-    if (mac) {
-      setExpandedId(null)
-      navigate(`/devices?intake=${encodeURIComponent(mac)}`)
-      return
-    }
+    // FORK: every alert expands, the unknown-device one included. Upstream
+    // (#827) sent that one straight to the identify dialog, which hid where
+    // the device is and what to do about it. Identifying it is one of the
+    // actions in the expanded panel, and upstream's row icon (#833) still
+    // offers it as a shortcut.
     setExpandedId((cur) => (cur === ev.id ? null : ev.id))
   }
 

+ 27 - 11
app/src/pages/Devices.tsx

@@ -1225,19 +1225,10 @@ export default function Devices() {
     return { allDevices: list.map((d) => (infra.has(d.id) ? { ...d, group: 'infra' as const } : d)), infraById: infra }
   }, [devices, isDemo, distributionNodes, deviceOverrides])
 
-  const [searchParams] = useSearchParams()
+  const [searchParams, setSearchParams] = useSearchParams()
   const [query, setQuery] = useState(() => searchParams.get('q') ?? '')
   const [q, setQ] = useState(() => (searchParams.get('q') ?? '').trim().toLowerCase())
 
-  // Enlaces entrantes tipo /devices?q=<mac|ip|nombre> (p.ej. desde Puertos)
-  useEffect(() => {
-    const incoming = searchParams.get('q')
-    if (incoming !== null) {
-      setQuery(incoming)
-      setQ(incoming.trim().toLowerCase())
-    }
-  }, [searchParams])
-
   // Deep-link de onboarding (#772): /devices?intake=<mac> abre la tarjeta de
   // alta para ese dispositivo (la alerta "desconocido" lo enlaza).
   useEffect(() => {
@@ -1255,6 +1246,20 @@ export default function Devices() {
     setOnlineState(v)
   }, [])
   const [onlyWeak, setOnlyWeak] = useState(false)
+
+  // Enlaces entrantes tipo /devices?q=<mac|ip|nombre> (p.ej. desde Puertos)
+  useEffect(() => {
+    const incoming = searchParams.get('q')
+    if (incoming !== null) {
+      setQuery(incoming)
+      setQ(incoming.trim().toLowerCase())
+      // A deep link asks for one specific device, so the online-only default
+      // must not hide it: an alert about a device that has since dropped off
+      // would otherwise land on an empty list.
+      setOnline('all')
+    }
+  }, [searchParams, setOnline])
+
   const weakCount = useMemo(
     () => allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < -70).length,
     [allDevices],
@@ -1700,7 +1705,18 @@ export default function Devices() {
         open={intakeId !== null}
         device={allDevices.find((d) => d.id === intakeId) ?? null}
         isDemo={isDemo}
-        onClose={() => setIntakeId(null)}
+        onClose={() => {
+          setIntakeId(null)
+          // Drop ?intake= from the URL once the dialog is closed. The effect
+          // that opens it re-runs every time the device list refreshes, so
+          // leaving the parameter in place reopened the dialog after every
+          // dismissal, indefinitely.
+          if (searchParams.has('intake')) {
+            const next = new URLSearchParams(searchParams)
+            next.delete('intake')
+            setSearchParams(next, { replace: true })
+          }
+        }}
         onSaved={(outcome) => {
           refresh()
           showToast(t(outcome === 'dismissed' ? 'devices.onboarding.dismissed' : 'devices.onboarding.saved'))

+ 12 - 2
app/src/pages/Orchestration.tsx

@@ -5,6 +5,7 @@ import { motion } from 'framer-motion'
 import { ChevronRight, CheckCircle2, AlertCircle, ArrowUpRight, Loader2, Wand2, ShieldAlert, Plus, X, Sparkles } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
+import { agentMatchesRouter } from '@/lib/agentMatch'
 
 type Module = 'adguard' | 'guestwifi' | 'ddns' | 'sqm' | 'wireguard' | 'usteer'
 
@@ -112,10 +113,19 @@ export default function Orchestration() {
   // useMemo: identidad estable para no re-disparar el efecto de auto-select en
   // cada render (#225).
   const visibleRouters = useMemo(
-    () => (allowNonGateway ? agents : agents.filter((a) => a.slug === gatewayId)),
+    () => (allowNonGateway ? agents : agents.filter((a) => gatewayId !== undefined && agentMatchesRouter(a, gatewayId))),
     [agents, allowNonGateway, gatewayId],
   )
-  const nonGatewaySelected = allowNonGateway && routerId !== gatewayId
+  // The selector holds an agent slug and `gatewayId` is a router id; the two
+  // only look equal when the board happens to be named after the router, so
+  // the comparison goes through the matcher or the gateway itself raises the
+  // "this is not the gateway" warning.
+  const selected = agents.find((a) => a.slug === routerId)
+  const nonGatewaySelected =
+    allowNonGateway &&
+    routerId !== '' &&
+    gatewayId !== undefined &&
+    !(selected !== undefined && agentMatchesRouter(selected, gatewayId))
 
   // Poll de applyPlan: el id vive en un ref para limpiarlo en unmount y al
   // generar un plan nuevo / cambiar de módulo (#220).

+ 8 - 6
app/src/pages/Settings.tsx

@@ -49,6 +49,7 @@ import {
   CalendarClock,
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
+import { findAgentFor, type AgentKeys } from '@/lib/agentMatch'
 import { HealthRing } from '@/components/HealthRing'
 import { KnownMacsManager } from '@/components/KnownMacsManager'
 import { SegmentedControl } from '@/components/SegmentedControl'
@@ -389,9 +390,10 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [regenerating, setRegenerating] = useState<string | null>(null)
   // Aviso tras regenerar el token: "hot" (aplicado en caliente) o "manual".
   const [regenerateNotice, setRegenerateNotice] = useState<'hot' | 'netgrip' | 'ssh_failed' | 'no_agent' | null>(null)
-  // Slugs con agente nativo (GET /api/agents): marcan qué routers tienen
-  // acceso root para poder regenerar su token (Labs).
-  const [agentSlugs, setAgentSlugs] = useState<Set<string>>(new Set())
+  // Routers con agente nativo (GET /api/agents): marcan cuáles tienen
+  // acceso root para poder regenerar su token (Labs). Se guardan las claves
+  // del agente, no solo el slug: el slug no es el id del router.
+  const [agentKeys, setAgentKeys] = useState<AgentKeys[]>([])
   const [editing, setEditing] = useState<ConfigRouter | null>(null)
   const [editHost, setEditHost] = useState('')
   const [editName, setEditName] = useState('')
@@ -428,8 +430,8 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
       const json = (await rRes.json()) as { routers: ConfigRouter[] }
       setList(json.routers)
       if (aRes.ok) {
-        const { agents } = (await aRes.json()) as { agents: Array<{ slug: string }> }
-        setAgentSlugs(new Set(agents.map((a) => a.slug)))
+        const { agents } = (await aRes.json()) as { agents: AgentKeys[] }
+        setAgentKeys(agents)
       }
       setError(null)
     } catch {
@@ -759,7 +761,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   </td>
                   <td className="px-3.5 py-2.5">
                     <span className="flex items-center justify-end gap-1.5">
-                      {agentSlugs.has(r.id) && r.type !== 'managed-switch' && r.type !== 'external' && (
+                      {findAgentFor(agentKeys, r.id) !== undefined && r.type !== 'managed-switch' && r.type !== 'external' && (
                         <button
                           type="button"
                           onClick={() => setConfirmRotateFor(r.id)}

+ 6 - 0
server-go/internal/adapters/agent.go

@@ -608,6 +608,12 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	}
 	if p.Data.Arp != nil {
 		out.arp = p.Data.Arp
+		// An agent old enough not to send arpStale leaves this empty, and
+		// the whole table counts as presence, exactly as it used to.
+		out.arpStale = make(map[string]bool, len(p.Data.ArpStale))
+		for _, mac := range p.Data.ArpStale {
+			out.arpStale[strings.ToUpper(mac)] = true
+		}
 	}
 	if fd := p.Data.FDB; fd != nil {
 		if fd.MACs != nil {

+ 73 - 1
server-go/internal/adapters/alerts_i18n_test.go

@@ -17,7 +17,7 @@ func TestUnknownDeviceAlertCarriesType(t *testing.T) {
 	l.emitUnknownDevice(Device{
 		ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF",
 		RouterID: "gateway", Online: true,
-	})
+	}, nil, nil)
 	list := l.engine.List()
 	if len(list) != 1 {
 		t.Fatalf("esperado 1 alerta, got %d", len(list))
@@ -37,3 +37,75 @@ func TestUnknownDeviceAlertCarriesType(t *testing.T) {
 		t.Fatalf("los literales de fallback no deben vaciarse: %+v", ev)
 	}
 }
+
+// TestUnknownDeviceAlertCarriesLocation: the alert has to say where the
+// device is, not just its MAC — the IP, the box it hangs off and the port on
+// that box, so it can be found without hunting through the client list.
+func TestUnknownDeviceAlertCarriesLocation(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Gateway", IsGateway: true},
+	}, nil)
+	d := Device{
+		ID: "02-00-00-00-00-31", MAC: "02:00:00:00:00:31", Name: "02:00:00:00:00:31",
+		IP: "192.0.2.31", RouterID: "gateway", Online: true, Band: "cable",
+		AttachTo: "sw-desk", Port: "7", PortLabel: "Desk 7",
+	}
+	// The switch hangs off router port 3; the client is learnt on the switch's
+	// own port 7, so that one is the client's.
+	dists := []DistributionNode{{ID: "sw-desk", Kind: "managed", Name: "Desk switch", RouterID: "gateway", Port: "3"}}
+	l.emitUnknownDevice(d, []Device{d}, dists)
+	ev := l.engine.List()[0]
+	for k, want := range map[string]string{
+		"ip":    "192.0.2.31",
+		"where": "Desk switch",
+		"port":  "Desk 7", // the friendly label wins over the raw port number
+		"band":  "cable",
+	} {
+		if ev.Vars[k] != want {
+			t.Fatalf("Vars[%q]=%q (want %q)", k, ev.Vars[k], want)
+		}
+	}
+}
+
+// TestUnknownDeviceLocationFallsBackToRouter: a wireless client with nothing
+// between it and the router still gets a "where" — the router's visible name.
+func TestUnknownDeviceLocationFallsBackToRouter(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Gateway", IsGateway: true},
+	}, nil)
+	d := Device{
+		MAC: "02:00:00:00:00:32", Name: "02:00:00:00:00:32",
+		RouterID: "gateway", Online: true, Band: "5 GHz",
+	}
+	l.emitUnknownDevice(d, []Device{d}, nil)
+	ev := l.engine.List()[0]
+	if ev.Vars["where"] != "Gateway" {
+		t.Fatalf("Vars[where]=%q (want the router name)", ev.Vars["where"])
+	}
+	if _, ok := ev.Vars["ip"]; ok {
+		t.Fatalf("an unknown IP must be absent, not empty: %+v", ev.Vars)
+	}
+}
+
+// TestUnknownDeviceDropsUplinkPort: a client behind a switch is learnt on the
+// router port the switch hangs off. That port is the uplink, not the socket
+// the client is in, so the alert must not name it.
+func TestUnknownDeviceDropsUplinkPort(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Gateway", IsGateway: true},
+	}, nil)
+	d := Device{
+		MAC: "02:00:00:00:00:33", Name: "02:00:00:00:00:33", IP: "192.0.2.33",
+		RouterID: "gateway", Online: true, Band: "cable",
+		AttachTo: "sw-desk", Port: "3",
+	}
+	dists := []DistributionNode{{ID: "sw-desk", Kind: "managed", Name: "Desk switch", RouterID: "gateway", Port: "3"}}
+	l.emitUnknownDevice(d, []Device{d}, dists)
+	ev := l.engine.List()[0]
+	if ev.Vars["where"] != "Desk switch" {
+		t.Fatalf("Vars[where]=%q", ev.Vars["where"])
+	}
+	if p, ok := ev.Vars["port"]; ok {
+		t.Fatalf("the uplink port must not be shown as the client's: %q", p)
+	}
+}

+ 36 - 36
server-go/internal/adapters/alerts_live_test.go

@@ -350,7 +350,7 @@ func TestLiveWanDownTaxonomyAndDebounce(t *testing.T) {
 func TestLiveUnknownDeviceTaxonomy(t *testing.T) {
 	l := liveTestLive()
 	l.mu.Lock()
-	l.emitUnknownDevice(Device{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", RouterID: "living", Online: true})
+	l.emitUnknownDevice(Device{MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF", RouterID: "living", Online: true}, nil, nil)
 	l.mu.Unlock()
 	list := l.engine.List()
 	if len(list) != 1 {
@@ -374,28 +374,28 @@ func TestLiveTrackUnknownDevices(t *testing.T) {
 	named := Device{MAC: "77:88:99:AA:BB:CC", Name: "Galaxy Tab", RouterID: "living", Online: true}
 
 	// Primer ciclo: siembra de base, NUNCA alerta (anti-avalancha de arranque)
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("primer ciclo no debía alertar")
 	}
 	// Sigue online: no re-alerta
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("reconexión sin caída no debía alertar")
 	}
 	// Se desconecta y vuelve: la gracia de N ticks (issue #234) evita alertar
 	// mientras el lease aún no se resuelve tras reconectar.
-	l.trackUnknownDevices([]Device{named})
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{named}, nil)
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("1 tick nameless no debía alertar (gracia)")
 	}
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("2 ticks nameless no debían alertar (gracia)")
 	}
 	// Al tercer tick consecutivo online+sin nombre, el desconocido real alerta
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	list := l.engine.List()
 	if len(list) != 1 {
 		t.Fatalf("desconocido tras gracia: %d alertas", len(list))
@@ -404,16 +404,16 @@ func TestLiveTrackUnknownDevices(t *testing.T) {
 		t.Fatalf("taxonomía: %+v", list[0])
 	}
 	// Issue #248: la reconexión posterior de la MISMA MAC ya no alerta
-	l.trackUnknownDevices([]Device{named})
-	l.trackUnknownDevices([]Device{unknown, named})
-	l.trackUnknownDevices([]Device{unknown, named})
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{named}, nil)
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 1 {
 		t.Fatal("memoria per-MAC (#248): no debía re-alertar")
 	}
 	// El dispositivo CON nombre nunca alerta aunque se reconecte
-	l.trackUnknownDevices([]Device{unknown})
-	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown}, nil)
+	l.trackUnknownDevices([]Device{unknown, named}, nil)
 	if len(l.engine.List()) != 1 {
 		t.Fatal("dispositivo conocido no debía alertar")
 	}
@@ -425,31 +425,31 @@ func TestLiveTrackUnknownDevicesGraciaConocido(t *testing.T) {
 	l := liveTestLive()
 	d := Device{MAC: "77:88:99:AA:BB:CC", Name: "77:88:99:AA:BB:CC", RouterID: "living", Online: true}
 	// Siembra; desconexión; reconexión SIN lease resuelto durante 2 ticks…
-	l.trackUnknownDevices([]Device{d})
-	l.trackUnknownDevices([]Device{})
-	l.trackUnknownDevices([]Device{d}) // tick 1 sin nombre
-	l.trackUnknownDevices([]Device{d}) // tick 2 sin nombre
+	l.trackUnknownDevices([]Device{d}, nil)
+	l.trackUnknownDevices([]Device{}, nil)
+	l.trackUnknownDevices([]Device{d}, nil) // tick 1 sin nombre
+	l.trackUnknownDevices([]Device{d}, nil) // tick 2 sin nombre
 	if len(l.engine.List()) != 0 {
 		t.Fatal("no debía alertar antes de resolver el lease")
 	}
 	// …y al tercer tick el lease ya está (Name != MAC) → nunca llega al umbral
 	d.Name = "Galaxy Tab"
-	l.trackUnknownDevices([]Device{d})
+	l.trackUnknownDevices([]Device{d}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("con hostname resuelto no debía alertar")
 	}
 	// La gracia se reseteó al ver el nombre: una reconexión futura sin nombre
 	// parte de cero y vuelve a necesitar los N ticks completos (no 1).
-	l.trackUnknownDevices([]Device{})
-	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	l.trackUnknownDevices([]Device{}, nil)
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("tras reset, tick 1 no debía alertar")
 	}
-	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatal("tras reset, tick 2 no debía alertar")
 	}
-	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}}, nil)
 	if len(l.engine.List()) != 1 {
 		t.Fatalf("tras reset y gracia completa: %d alertas", len(l.engine.List()))
 	}
@@ -463,11 +463,11 @@ func TestLiveUnknownDeviceMemoryPersisted(t *testing.T) {
 	mac := "AA:BB:CC:DD:EE:0F"
 	unknown := Device{MAC: mac, Name: mac, RouterID: "living", Online: true}
 	// Reconexión simulada: siembra, caída, vuelve → tras la gracia alerta.
-	l.trackUnknownDevices([]Device{unknown})
-	l.trackUnknownDevices([]Device{})
-	l.trackUnknownDevices([]Device{unknown})
-	l.trackUnknownDevices([]Device{unknown})
-	l.trackUnknownDevices([]Device{unknown})
+	l.trackUnknownDevices([]Device{unknown}, nil)
+	l.trackUnknownDevices([]Device{}, nil)
+	l.trackUnknownDevices([]Device{unknown}, nil)
+	l.trackUnknownDevices([]Device{unknown}, nil)
+	l.trackUnknownDevices([]Device{unknown}, nil)
 	if len(l.engine.List()) != 1 {
 		t.Fatalf("primera alerta: %d", len(l.engine.List()))
 	}
@@ -476,11 +476,11 @@ func TestLiveUnknownDeviceMemoryPersisted(t *testing.T) {
 	if !l2.unknownAlerted[mac] {
 		t.Fatal("la memoria per-MAC no se cargó desde kv")
 	}
-	l2.trackUnknownDevices([]Device{unknown})
-	l2.trackUnknownDevices([]Device{})
-	l2.trackUnknownDevices([]Device{unknown})
-	l2.trackUnknownDevices([]Device{unknown})
-	l2.trackUnknownDevices([]Device{unknown})
+	l2.trackUnknownDevices([]Device{unknown}, nil)
+	l2.trackUnknownDevices([]Device{}, nil)
+	l2.trackUnknownDevices([]Device{unknown}, nil)
+	l2.trackUnknownDevices([]Device{unknown}, nil)
+	l2.trackUnknownDevices([]Device{unknown}, nil)
 	// #798: el log de alertas sobrevive al reinicio, así que la alerta
 	// histórica sigue visible; lo que no debe pasar es que se EMITA una nueva.
 	if len(l2.engine.List()) != 1 {
@@ -497,9 +497,9 @@ func TestLiveTrackUnknownDevicesTrustedAllowlist(t *testing.T) {
 	}
 	// Primer ciclo siembra; desconexión; reconexión: la MAC de la allowlist
 	// NUNCA alerta, aunque siga sin nombre/lease (issue #196).
-	l.trackUnknownDevices([]Device{trusted})
-	l.trackUnknownDevices([]Device{})
-	l.trackUnknownDevices([]Device{trusted})
+	l.trackUnknownDevices([]Device{trusted}, nil)
+	l.trackUnknownDevices([]Device{}, nil)
+	l.trackUnknownDevices([]Device{trusted}, nil)
 	if len(l.engine.List()) != 0 {
 		t.Fatalf("MAC confiable alertó: %d", len(l.engine.List()))
 	}
@@ -512,7 +512,7 @@ func TestLiveDismissUnknownDevice(t *testing.T) {
 	unknown := Device{MAC: "11:22:33:44:55:66", Name: "11:22:33:44:55:66", RouterID: "living", Online: true}
 	l.DismissUnknownDevice("11:22:33:44:55:66")
 	for i := 0; i < 5; i++ {
-		l.trackUnknownDevices([]Device{unknown})
+		l.trackUnknownDevices([]Device{unknown}, nil)
 	}
 	if len(l.engine.List()) != 0 {
 		t.Fatal("dismiss (#772): la MAC no debía alertar")

+ 192 - 0
server-go/internal/adapters/arp_test.go

@@ -2,9 +2,11 @@
 package adapters
 
 import (
+	"context"
 	"testing"
 
 	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 
 func TestBuildDevicesArpFallback(t *testing.T) {
@@ -97,3 +99,193 @@ func TestPolledFromAgentArp(t *testing.T) {
 		t.Fatalf("arp no propagada: %+v", p.arp)
 	}
 }
+
+// A MAC whose only evidence is a neighbour entry the kernel has NOT
+// confirmed is not a device: the entry outlives the host by minutes, and
+// with no port either the map hung it off the gateway bubble.
+func TestBuildDevicesIgnoresStaleArpOnlyHosts(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"patio": {
+			cfg: RouterConfig{ID: "patio", Name: "Patio", Host: "192.0.2.2"},
+			arp: map[string]string{
+				"02:00:00:00:00:10": "192.0.2.60", // confirmed
+				"02:00:00:00:00:11": "192.0.2.61", // only remembered
+			},
+			arpStale: map[string]bool{"02:00:00:00:00:11": true},
+		},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 1 || devs[0].MAC != "02:00:00:00:00:10" {
+		t.Fatalf("only the confirmed host is a device: %+v", devs)
+	}
+}
+
+// Stale is about presence, never about other evidence: a host with a lease
+// stays, and its address still comes from the stale entry.
+func TestBuildDevicesStaleArpStillResolvesIPs(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"patio": {
+			cfg:      RouterConfig{ID: "patio", Name: "Patio", Host: "192.0.2.2"},
+			wireless: map[string]WirelessClient{"02:00:00:00:00:11": {SignalDbm: -55, Band: "5 GHz"}},
+			arp:      map[string]string{"02:00:00:00:00:11": "192.0.2.61"},
+			arpStale: map[string]bool{"02:00:00:00:00:11": true},
+		},
+	}
+	devs := l.buildDevices(polled)
+	if len(devs) != 1 || devs[0].IP != "192.0.2.61" {
+		t.Fatalf("an associated client keeps its address: %+v", devs)
+	}
+}
+
+// Two routers see the same host: confirmed anywhere is confirmed.
+func TestBuildDevicesStaleOnOneRouterOnly(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"patio": {
+			cfg:      RouterConfig{ID: "patio", Name: "Patio", Host: "192.0.2.2"},
+			arp:      map[string]string{"02:00:00:00:00:10": "192.0.2.60"},
+			arpStale: map[string]bool{"02:00:00:00:00:10": true},
+		},
+		"salon": {
+			cfg: RouterConfig{ID: "salon", Name: "Salon", Host: "192.0.2.3"},
+			arp: map[string]string{"02:00:00:00:00:10": "192.0.2.60"},
+		},
+	}
+	if devs := l.buildDevices(polled); len(devs) != 1 {
+		t.Fatalf("confirmed by one router is enough: %+v", devs)
+	}
+}
+
+// A source that cannot report states (an older agent, or the /proc/net/arp
+// fallback) marks nothing stale, and the whole table counts as presence.
+func TestPolledFromAgentArpStale(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	pl := &probe.Payload{Router: "patio", Version: "0.1.0"}
+	pl.Data.System = &probe.SystemData{SysInfo: &probe.SysInfo{Uptime: 100}}
+	pl.Data.Arp = map[string]string{"02:00:00:00:00:10": "192.0.2.60"}
+	if p := l.polledFromAgent(RouterConfig{ID: "patio"}, pl); len(p.arpStale) != 0 {
+		t.Fatalf("an agent without arpStale marks nothing stale: %+v", p.arpStale)
+	}
+
+	pl.Data.ArpStale = []string{"02:00:00:00:00:10"}
+	p := l.polledFromAgent(RouterConfig{ID: "patio"}, pl)
+	if !p.arpStale["02:00:00:00:00:10"] {
+		t.Fatalf("arpStale not propagated: %+v", p.arpStale)
+	}
+}
+
+// A device_attrib row outlives the router it names: deleting a router, or an
+// integration that registered one per AP, used to leave its clients
+// attributed to an id nothing resolves, so no router counted them.
+func TestBuildDevicesReattributesDeletedRouters(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := NewLive(nil, d, nil, nil)
+	l.SetRouters([]RouterConfig{
+		{ID: "gateway", Name: "Gateway", Host: "192.0.2.1", IsGateway: true, AgentOnly: true},
+	})
+	// One client remembered on a router that still exists, one on a router
+	// that was deleted.
+	for _, r := range [][2]string{
+		{"02:00:00:00:00:01", "gateway"},
+		{"02:00:00:00:00:02", "ap-that-was-deleted"},
+	} {
+		if _, err := d.Exec(
+			`INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?,?,?,?,?)`,
+			r[0], r[1], "5 GHz", -50, db.NowMS()); err != nil {
+			t.Fatal(err)
+		}
+	}
+	polled := map[string]*routerPolled{
+		"gateway": {
+			cfg: RouterConfig{ID: "gateway", Name: "Gateway", Host: "192.0.2.1", IsGateway: true},
+			leases: []DhcpLease{
+				{MAC: "02:00:00:00:00:01", IP: "192.0.2.51", Hostname: "one"},
+				{MAC: "02:00:00:00:00:02", IP: "192.0.2.52", Hostname: "two"},
+			},
+		},
+	}
+	byMAC := map[string]Device{}
+	for _, dev := range l.buildDevices(polled) {
+		byMAC[dev.MAC] = dev
+	}
+	if len(byMAC) != 2 {
+		t.Fatalf("devices: %+v", byMAC)
+	}
+	for mac, dev := range byMAC {
+		if dev.RouterID != "gateway" {
+			t.Fatalf("%s should fall back to the gateway, got %q", mac, dev.RouterID)
+		}
+	}
+}
+
+// countClientsPerRouter: online devices attributed to each router, and
+// nothing else -- offline devices and devices attributed to a router that is
+// not in the list do not count anywhere.
+func TestCountClientsPerRouter(t *testing.T) {
+	routers := []Router{{ID: "gateway"}, {ID: "patio"}}
+	devices := []Device{
+		{MAC: "02:00:00:00:00:01", RouterID: "gateway", Band: "cable", Online: true},
+		{MAC: "02:00:00:00:00:02", RouterID: "gateway", Band: "5 GHz", Online: true},
+		{MAC: "02:00:00:00:00:03", RouterID: "gateway", Band: "2.4 GHz", Online: false},
+		{MAC: "02:00:00:00:00:04", RouterID: "patio", Band: "2.4 GHz", Online: true},
+		{MAC: "02:00:00:00:00:05", RouterID: "ghost", Band: "cable", Online: true},
+	}
+	countClientsPerRouter(routers, devices)
+
+	if routers[0].Clients != 2 || routers[1].Clients != 1 {
+		t.Fatalf("counts: %d %d", routers[0].Clients, routers[1].Clients)
+	}
+	if routers[0].BandSplit == nil || routers[0].BandSplit.Cable != 1 || routers[0].BandSplit.Band5 != 1 {
+		t.Fatalf("band split: %+v", routers[0].BandSplit)
+	}
+	// The offline 2.4 GHz device is not in the split either.
+	if routers[0].BandSplit.Band24 != 0 {
+		t.Fatalf("an offline device was counted: %+v", routers[0].BandSplit)
+	}
+}
+
+// GET /api/routers used to report the DHCP lease count while the overview
+// reported the real attribution, so the routers page and the map disagreed
+// about the same router.
+func TestGetRoutersCountsClientsNotLeases(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := NewLive(nil, d, nil, nil)
+	cfg := RouterConfig{ID: "gateway", Name: "Gateway", Host: "192.0.2.1", IsGateway: true, AgentOnly: true}
+	l.SetRouters([]RouterConfig{cfg})
+
+	// Three leases, but only two of those hosts are associated right now.
+	l.mu.Lock()
+	l.lastPolled = map[string]*routerPolled{"gateway": {
+		cfg: cfg,
+		leases: []DhcpLease{
+			{MAC: "02:00:00:00:00:01", IP: "192.0.2.51", Hostname: "one"},
+			{MAC: "02:00:00:00:00:02", IP: "192.0.2.52", Hostname: "two"},
+			{MAC: "02:00:00:00:00:03", IP: "192.0.2.53", Hostname: "gone"},
+		},
+		wireless: map[string]WirelessClient{
+			"02:00:00:00:00:01": {SignalDbm: -50, Band: "5 GHz"},
+			"02:00:00:00:00:02": {SignalDbm: -60, Band: "2.4 GHz"},
+		},
+	}}
+	l.mu.Unlock()
+
+	routers := l.GetRouters(context.Background())
+	if len(routers) != 1 {
+		t.Fatalf("routers: %+v", routers)
+	}
+	if routers[0].Clients != 2 {
+		t.Fatalf("clients: got %d, want 2 (the associated ones, not the 3 leases)", routers[0].Clients)
+	}
+	// And the same number the overview would report.
+	online := 0
+	for _, dev := range l.attributedDevices() {
+		if dev.Online && dev.RouterID == "gateway" {
+			online++
+		}
+	}
+	if online != routers[0].Clients {
+		t.Fatalf("routers endpoint says %d, attribution says %d", routers[0].Clients, online)
+	}
+}

+ 3 - 3
server-go/internal/adapters/demo_dataset.go

@@ -564,7 +564,7 @@ func topologyDevices() []Device {
 		// se anidan (OUI BC:24:11)
 		withDetails(Device{ID: "pve", Name: "Proxmox pve", Type: "servidor", Manufacturer: "Supermicro",
 			IP: "192.168.8.5", MAC: "3C:52:82:10:20:30", RouterID: "flint2", Band: "cable",
-			SignalDbm: nil, TrafficMbps: 12.3, Online: true, Port: "lan5", Infra: "hypervisor",
+			SignalDbm: nil, TrafficMbps: 12.3, Online: true, Port: "lan5", Infra: "hypervisor", SpeedMbps: 2500,
 			Sparkline: []float64{8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3}},
 			"pve", "IP fija (reserva)", "hace 400 días", "1,2 TB", "96 GB", true, "red", ""),
 	}
@@ -646,9 +646,9 @@ func topologyDevices() []Device {
 // (chassis-MAC) para que la app excluya el chip del Device del switch.
 func canonDistributionNodes() []DistributionNode {
 	return []DistributionNode{
-		{ID: "dist-flint2-lan3", Kind: "inferred", RouterID: "flint2", Port: "lan3", MacCount: 8},
+		{ID: "dist-flint2-lan3", Kind: "inferred", RouterID: "flint2", Port: "lan3", MacCount: 8, SpeedMbps: 1000},
 		{ID: "dist-pve", Kind: "hypervisor", RouterID: "flint2", Port: "lan5", MacCount: 11, HostDeviceID: "pve", Name: "Proxmox pve"},
-		{ID: "dist-living-lan3", Kind: "managed", RouterID: "living", Port: "lan3", MacCount: 4,
+		{ID: "dist-living-lan3", Kind: "managed", RouterID: "living", Port: "lan3", MacCount: 4, SpeedMbps: 1000,
 			Name: "GS308E", Ip: "192.168.8.13", Mac: "28:C6:8E:1D:90:44",
 			Lldp: &LldpInfo{Chassis: "GS308E", Mgmt: "192.168.8.13", Caps: "Bridge", PortDesc: "ge5"}},
 	}

+ 171 - 25
server-go/internal/adapters/live.go

@@ -107,7 +107,12 @@ type routerPolled struct {
 	glClients []DhcpLease
 	// arp: MAC→IP de /proc/net/arp (#377). Último recurso de resolución de
 	// IP cuando ni el lease ni gl-clients la tienen (DHCP en otro equipo).
-	arp       map[string]string
+	arp map[string]string
+	// arpStale: the subset of `arp` the kernel remembers without having
+	// confirmed (STALE/FAILED/INCOMPLETE). Good enough to resolve an IP,
+	// never enough to claim the host is connected -- an entry outlives the
+	// device by minutes. Empty when the source could not report states.
+	arpStale  map[string]bool
 	wireless  map[string]WirelessClient
 	ports     []EthPort
 	radios    []Radio
@@ -945,13 +950,13 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		net = &NetDevBps{}
 	}
 	leases := client.GetDhcpLeases()
-	arp := client.GetArp()
+	arp, arpStale := client.GetArp()
 	// gl-clients (GL.iNet): complementa la resolución de IP donde dnsmasq no
 	// tiene lease (issue #5 bug 1). En routers sin el objeto ubus sale vacío
 	// — coste: una llamada ubus local por poll.
 	glClients := client.GetGlClients()
 	wireless := client.GetWirelessClients()
-	ports := client.GetEthPorts(layout, ifRates)
+	ports := client.GetEthPorts(layout, ifRates, l.probeWanInfo(cfg.ID, client).Port)
 	radios := client.GetRadios()
 	fdb := client.GetBridgeFdb()
 	brMac := client.GetBridgeMac()
@@ -1047,7 +1052,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	return &routerPolled{
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
 		cpu: cpuV, ram: ramPct, temp: tempV,
-		uptimeSec: sysInfo.Uptime, net: net, leases: leases, arp: arp, glClients: glClients,
+		uptimeSec: sysInfo.Uptime, net: net, leases: leases, arp: arp, arpStale: arpStale, glClients: glClients,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
@@ -1629,7 +1634,7 @@ func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
 // NO alerta (evita la avalancha de arranque: todo lo ya conectado sería
 // "nuevo"). Las MAC de la allowlist known_macs (issue #196) nunca alertan,
 // haya alias o no. Toma l.mu internamente.
-func (l *Live) trackUnknownDevices(devices []Device) {
+func (l *Live) trackUnknownDevices(devices []Device, dists []DistributionNode) {
 	l.mu.Lock()
 	defer l.mu.Unlock()
 	// issue #196: MACs de la allowlist (confiables) → nunca "desconocido".
@@ -1672,7 +1677,7 @@ func (l *Live) trackUnknownDevices(devices []Device) {
 		if l.seenOnlineMacs && (counting || !l.onlineMacs[d.MAC]) {
 			l.unknownGrace[d.MAC]++
 			if l.unknownGrace[d.MAC] >= l.unknownGraceNum {
-				l.emitUnknownDevice(d)
+				l.emitUnknownDevice(d, devices, dists)
 				l.unknownAlerted[d.MAC] = true
 				l.persistUnknownAlerted(d.MAC)
 				delete(l.unknownGrace, d.MAC)
@@ -1716,15 +1721,36 @@ func (l *Live) routerDisplayName(id string) string {
 // clients, warn, NO urgente — issue #196). "Desconocido" = sin nombre/alias:
 // device_attrib no guarda alias, así que la señal práctica es un cliente sin
 // hostname DHCP (Name == MAC). Debe llamarse con l.mu tomado.
-func (l *Live) emitUnknownDevice(d Device) {
-	vars := map[string]string{"mac": d.MAC, "router": l.routerDisplayName(d.RouterID)}
-	if d.Band != "" {
+//
+// The alert has to be actionable: a MAC on its own tells nobody which box to
+// walk up to, so it also carries the IP, what the client hangs off and the
+// port there, when those are known. They are: this runs after the topology
+// pass and the Proxmox/UniFi seals, so AttachTo is already resolved.
+func (l *Live) emitUnknownDevice(d Device, devices []Device, dists []DistributionNode) {
+	where, port := l.deviceLocation(d, devices, dists)
+	vars := map[string]string{
+		"mac":    d.MAC,
+		"router": l.routerDisplayName(d.RouterID),
+		"where":  where,
+	}
+	// Only the facts we actually have: the app renders one row per var and an
+	// empty one would read as "we know this and it is blank".
+	if d.IP != "" {
+		vars["ip"] = d.IP
+	}
+	if port != "" {
+		vars["port"] = port
+	}
+	if d.Band != "" && d.Band != "—" {
 		vars["band"] = d.Band
 	}
 	if d.SignalDbm != nil {
 		vars["signal"] = fmt.Sprintf("%d", *d.SignalDbm)
 	}
-	desc := fmt.Sprintf("%s se ha conectado a %s", d.MAC, d.RouterID)
+	desc := fmt.Sprintf("%s se ha conectado a %s", d.MAC, where)
+	if d.IP != "" {
+		desc = fmt.Sprintf("%s · %s se ha conectado a %s", d.MAC, d.IP, where)
+	}
 	if d.Band != "" && d.Band != "cable" {
 		desc += " · " + d.Band
 	}
@@ -1759,6 +1785,56 @@ func (l *Live) DismissUnknownDevice(mac string) {
 	delete(l.unknownGrace, mac)
 }
 
+// deviceLocation: where a client is plugged in, as the two strings the alert
+// interpolates. `where` is the box it hangs off — the AP, switch or
+// hypervisor named by AttachTo, which may be a distribution node or another
+// device acting as a hub — falling back to its router, which is always known.
+// `port` is the physical port when the bridge FDB or the controller reports
+// one (empty for wireless clients). Must be called with l.mu held.
+func (l *Live) deviceLocation(d Device, devices []Device, dists []DistributionNode) (where, port string) {
+	port = d.PortLabel
+	if port == "" {
+		port = d.Port
+	}
+	if d.AttachTo != "" {
+		for _, n := range dists {
+			if n.ID != d.AttachTo {
+				continue
+			}
+			where = firstNonEmpty(n.Name, n.Ip)
+			// A client behind a switch is learnt on the router port that the
+			// switch itself hangs off, so that port describes the uplink, not
+			// the client: naming it next to the switch would send someone to
+			// the wrong socket.
+			if n.Port == d.Port {
+				port = ""
+			}
+			break
+		}
+		if where == "" {
+			for _, o := range devices {
+				if o.ID == d.AttachTo {
+					where = firstNonEmpty(o.Name, o.IP)
+					break
+				}
+			}
+		}
+	}
+	if where == "" {
+		where = l.routerDisplayName(d.RouterID)
+	}
+	return where, port
+}
+
+func firstNonEmpty(vals ...string) string {
+	for _, v := range vals {
+		if v != "" {
+			return v
+		}
+	}
+	return ""
+}
+
 // trackDevicePresence emite device_offline/device_online cuando una MAC
 // wireless pasa de vista a no-vista (N ticks) o viceversa (issue #184).
 // Solo se rastrean MACs wireless (Band != "cable"): el FDB de cableados es
@@ -2074,11 +2150,30 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	}
 	l.mu.Lock()
 	gw := l.gatewayCfg
+	registered := make(map[string]bool, len(l.routers))
+	for _, rc := range l.routers {
+		registered[rc.ID] = true
+	}
 	l.mu.Unlock()
 	gwID := ""
 	if gw != nil {
 		gwID = gw.ID
 	}
+	// A stored attribution outlives the router it names. Deleting a router --
+	// or an integration that registered some, as the UniFi scraper did for
+	// each AP -- leaves its clients in device_attrib pointing at an id that
+	// no longer exists, and every per-router count then attributes them to
+	// nothing: the gateway's card showed 18 of the 45 clients it serves.
+	// Hand them to the gateway, which is the router actually serving them
+	// once the one they remember is gone.
+	if gwID != "" {
+		for mac, k := range known {
+			if k.routerID != "" && !registered[k.routerID] {
+				k.routerID = gwID
+				known[mac] = k
+			}
+		}
+	}
 	// (2) FDB de satélites: pista solo de ESTE tick (no se guarda).
 	// 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
@@ -2134,13 +2229,31 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	}
 	// (4) ARP (#507): hosts cableados con IP estática visibles SOLO en la
 	// tabla ARP del router (ni wireless, ni FDB, ni lease, ni device_attrib).
-	// Presencia en la tabla = activo recientemente → online este tick. No se
-	// persiste: cuando la entrada envejece, el host desaparece del snapshot.
 	// Se itera en orden de router ID para atribuir deterministamente el
 	// RouterID correcto cuando varios routers ven la misma MAC (misma LAN).
 	// La exclusión de MACs de router/bridge se aplica en el bucle de
 	// dispositivos (routerMacs), igual que para leases/known: aquí no se
 	// duplica ese filtro.
+	//
+	// Presence needs a CONFIRMED neighbour, not merely an entry in the
+	// table: the kernel keeps a stale neighbour for minutes after the host
+	// has gone, and this branch is the last resort -- the host has no lease,
+	// no FDB entry and no wireless association, so nothing else would
+	// contradict it. The map then drew a device that is not there, and, with
+	// no port either, hung it off the gateway bubble. A host that really is
+	// connected answers, so the kernel reconfirms it and it stays; a host
+	// that is only remembered drops out on the next tick instead of waiting
+	// for the entry to age out. A source that cannot report states (old
+	// agent, /proc/net/arp fallback) marks nothing stale and keeps the old
+	// behaviour.
+	arpConfirmed := map[string]bool{}
+	for _, p := range polled {
+		for mac := range p.arp {
+			if !p.arpStale[mac] {
+				arpConfirmed[mac] = true
+			}
+		}
+	}
 	arpRouterIDs := make([]string, 0, len(polled))
 	for routerID := range polled {
 		arpRouterIDs = append(arpRouterIDs, routerID)
@@ -2157,6 +2270,9 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			if _, ok := known[mac]; ok {
 				continue
 			}
+			if !arpConfirmed[mac] {
+				continue
+			}
 			seen[mac] = seenInfo{routerID, "cable", nil}
 		}
 	}
@@ -2657,21 +2773,10 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 			l.mu.Unlock()
 		}
 	}
-	l.trackUnknownDevices(devices)
+	l.trackUnknownDevices(devices, distNodes)
 	l.trackDevicePresence(devices, time.Now().UnixMilli())
 	// Clientes reales por router (atribución wireless/FDB, no leases)
-	for i := range routerList {
-		n := 0
-		var split demoBandSplit
-		for _, d := range devices {
-			if d.RouterID == routerList[i].ID && d.Online {
-				n++
-				countBand(&split, d.Band)
-			}
-		}
-		routerList[i].Clients = n
-		routerList[i].BandSplit = &split
-	}
+	countClientsPerRouter(routerList, devices)
 	// Sparkline de la tarjeta para fuentes sin throughput bps (switch beacon/
 	// SNMP sin métricas agregadas): su línea de tráfico 24h sale de los fps de
 	// sus puertos (port_series), no de la tabla metrics (siempre 0 ahí).
@@ -2837,9 +2942,41 @@ func (l *Live) GetRouters(context.Context) []Router {
 		}
 		out = append(out, l.buildRouter(p, l.metricsHistory(cfg.ID, "24h")))
 	}
+	// buildRouter leaves Clients as the DHCP lease count, which is not the
+	// number the card means: it counts devices that are offline and misses
+	// every device without a lease. The overview has always corrected it;
+	// this endpoint did not, so the routers page and the map disagreed --
+	// 34 against 45 on the same router.
+	countClientsPerRouter(out, l.attributedDevices())
 	return out
 }
 
+// countClientsPerRouter sets each router's client count and band split to
+// the online devices attributed to it. Attribution is per router, not per
+// subtree: in a mesh each node counts its own stations, and clients of gear
+// that is not a NetPulse router (a UniFi AP, say) belong to the router that
+// serves them.
+func countClientsPerRouter(routers []Router, devices []Device) {
+	counts := make(map[string]int, len(routers))
+	splits := make(map[string]*demoBandSplit, len(routers))
+	for i := range routers {
+		splits[routers[i].ID] = &demoBandSplit{}
+	}
+	for _, d := range devices {
+		if !d.Online {
+			continue
+		}
+		if split, ok := splits[d.RouterID]; ok {
+			counts[d.RouterID]++
+			countBand(split, d.Band)
+		}
+	}
+	for i := range routers {
+		routers[i].Clients = counts[routers[i].ID]
+		routers[i].BandSplit = splits[routers[i].ID]
+	}
+}
+
 // liveExtras es el objeto extras del detalle live (index.js:677-700).
 type liveExtras struct {
 	MAC                 string        `json:"mac"`
@@ -3205,6 +3342,15 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 // GetDevices: buildDevices sobre el último sondeo (+ inferencia FDB de
 // topología: Port/AttachTo, como en buildOverview).
 func (l *Live) GetDevices(context.Context) []Device {
+	return l.attributedDevices()
+}
+
+// attributedDevices builds the device list with everything that decides who
+// a device belongs to and whether it is online: inference over the sticky
+// FDB overlay, then the Proxmox and UniFi seals. The seals are not optional
+// for a count -- the UniFi one is what marks a station on a controller AP as
+// online, and without it a router's clients come out short.
+func (l *Live) attributedDevices() []Device {
 	l.mu.Lock()
 	polled := l.lastPolled
 	l.mu.Unlock()

+ 27 - 9
server-go/internal/adapters/openwrt.go

@@ -371,10 +371,18 @@ func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
 	return parseDhcpLeasesFile(out)
 }
 
-// GetWanInfo: estado de la interfaz WAN (solo gateway, issue #276).
-// Via ubus network.interface.wan status; si el router no lo tiene (AP),
-// devuelve WanInfo vacío.
+// GetWanInfo: estado del uplink (issue #276). Via ubus network.interface
+// dump, que trae todas las interfaces y deja elegir la que lleva internet
+// por su ruta por defecto en vez de por llamarse "wan" (un PPPoE puede
+// llamarse de cualquier forma, y el nombre "wan" puede ser un módem ocioso).
+// Cae al status de la interfaz "wan" con los ubus antiguos; si el router no
+// tiene ninguna (AP), devuelve WanInfo vacío.
 func (c *OpenWrtClient) GetWanInfo() probe.WanInfo {
+	if raw, err := c.UbusCall("network.interface", "dump", nil); err == nil {
+		if info := probe.ParseWanStatus(raw); info.Proto != "" || info.IP != "" || info.Gateway != "" {
+			return info
+		}
+	}
 	raw, err := c.UbusCall("network.interface.wan", "status", nil)
 	if err == nil {
 		return probe.ParseWanStatus(raw)
@@ -545,7 +553,7 @@ func parsePortLayout(out string) ([]PortLayout, error) {
 // GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
 // fallback heurístico sin config. rates = contadores por iface (#305, de
 // GetNetDev; nil = sin stats). Devuelve []EthPort listo para el detalle.
-func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate) []EthPort {
+func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.IfRate, uplink string) []EthPort {
 	states := c.GetPortStates()
 	members := map[string]bool{}
 	if len(layout) > 0 {
@@ -557,7 +565,7 @@ func (c *OpenWrtClient) GetEthPorts(layout []PortLayout, rates map[string]probe.
 			}
 		}
 	}
-	return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates))
+	return ethPortsToAdapter(probe.BuildEthPorts(layout, states, members, rates, uplink))
 }
 
 // ethPortsToAdapter convierte el shape compartido al EthPort del contrato.
@@ -664,11 +672,21 @@ func radiosToAdapter(in []probe.Radio) []Radio {
 }
 
 // GetArp devuelve la tabla ARP del equipo (MAC→IP, #377). Fuente barata
-// (cat /proc/net/arp) para resolver IPs cuando el DHCP no es local.
-func (c *OpenWrtClient) GetArp() map[string]string {
+// para resolver IPs cuando el DHCP no es local.
+//
+// Reads `ip neigh` so the state of each entry comes with it, and returns the
+// MACs the kernel remembers without confirming (stale): their address is
+// still usable, but they are not evidence that the host is connected. Falls
+// back to /proc/net/arp, where no state is available and nothing is stale.
+func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool) {
+	if out, err := c.pool.Run(c.Host, probe.CmdIpNeigh, 0); err == nil {
+		if m, st := probe.ParseIPNeigh(out); len(m) > 0 {
+			return m, st
+		}
+	}
 	out, err := c.pool.Run(c.Host, probe.CmdProcArp, 0)
 	if err != nil {
-		return nil
+		return nil, nil
 	}
-	return probe.ParseArp(out)
+	return probe.ParseArp(out), nil
 }

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

@@ -396,6 +396,7 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 			}
 		}
 	}
+	fillNodeSpeeds(polled, dists)
 	return devices, dists
 }
 
@@ -478,3 +479,32 @@ func neighborIsRouter(nb *LldpNeighbor, routers []routerIdentity, selfID string)
 	}
 	return nil
 }
+
+// fillNodeSpeeds pone la velocidad del PRIMER salto: lo que cuelga de una
+// boca del router va a la velocidad que el propio router negoció en ella, y
+// eso ya lo mide el agente. El sello de UniFi cubre lo que hay más allá
+// (bocas del switch); entre los dos, la tabla de enlaces deja de escribir
+// "1 Gbps" por defecto en filas que nadie ha medido.
+//
+// Solo sobre nodos que cuelgan directamente de un router (sin Parent) y a
+// los que nadie ha dado ya una velocidad.
+func fillNodeSpeeds(polled map[string]*routerPolled, dists []DistributionNode) {
+	for i := range dists {
+		if dists[i].SpeedMbps > 0 || dists[i].Parent != "" || dists[i].Port == "" {
+			continue
+		}
+		p := polled[dists[i].RouterID]
+		if p == nil {
+			continue
+		}
+		for _, ep := range p.ports {
+			if ep.ID != dists[i].Port || !ep.Up {
+				continue
+			}
+			if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
+				dists[i].SpeedMbps = mbps
+			}
+			break
+		}
+	}
+}

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

@@ -437,3 +437,39 @@ func TestInferTopologyPortLabelLuCI(t *testing.T) {
 		t.Fatalf("sin etiquetas PortLabel vacío: %+v", devices[0])
 	}
 }
+
+// El primer salto lo mide el propio router: un nodo colgado de una boca
+// suya hereda la velocidad negociada en ella, en vez del "1 Gbps" que la
+// tabla de enlaces escribía por defecto.
+func TestFillNodeSpeedsFromTheRouterPort(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"gateway": {
+			cfg: RouterConfig{ID: "gateway"},
+			ports: []EthPort{
+				{ID: "lan2", Up: true, Speed: "1 Gbps"},
+				{ID: "lan3", Up: true, Speed: "2.5 Gbps"},
+				{ID: "lan4", Up: false, Speed: ""},
+			},
+		},
+	}
+	dists := []DistributionNode{
+		{ID: "a", RouterID: "gateway", Port: "lan2"},
+		{ID: "b", RouterID: "gateway", Port: "lan3"},
+		// Boca caída: nadie ha medido nada, y "—" es la respuesta honesta.
+		{ID: "c", RouterID: "gateway", Port: "lan4"},
+		// Cuelga de otro nodo, no del router: su velocidad la pone quien
+		// conozca esa boca (el sello del controlador), no el router.
+		{ID: "d", RouterID: "gateway", Port: "lan5", Parent: "a"},
+		// Una velocidad ya puesta no se toca.
+		{ID: "e", RouterID: "gateway", Port: "lan2", SpeedMbps: 100},
+		// Router desconocido.
+		{ID: "f", RouterID: "fantasma", Port: "lan2"},
+	}
+	fillNodeSpeeds(polled, dists)
+
+	for i, want := range []int{1000, 2500, 0, 0, 100, 0} {
+		if dists[i].SpeedMbps != want {
+			t.Errorf("dists[%d] %s: speed=%d (want %d)", i, dists[i].ID, dists[i].SpeedMbps, want)
+		}
+	}
+}

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

@@ -257,6 +257,9 @@ type Device struct {
 	// AttachTo: hub del que cuelga en el mapa (router por defecto; id de
 	// DistributionNode inferido o de otro Device — hipervisor/switch).
 	AttachTo string `json:"attachTo,omitempty"`
+	// SpeedMbps: velocidad negociada de la boca donde está enchufado, si la
+	// conocemos (boca del switch vía controlador). 0 = desconocida.
+	SpeedMbps int `json:"speedMbps,omitempty"`
 	// Infra: rol de infraestructura sellado server-side (Fase 4). La app NO
 	// infiere: pinta badge si viene. "hypervisor" (host Proxmox/VMware/…),
  
@@ -339,6 +342,18 @@ type DistributionNode struct {
 	// existe como Device Y como nodo managed, sin duplicar el render).
 	Mac  string    `json:"mac,omitempty"`
 	Lldp *LldpInfo `json:"lldp,omitempty"`
+	// SpeedMbps: velocidad negociada del enlace por el que cuelga, cuando
+	// alguien la sabe de verdad (hoy: la boca del switch que reporta el
+	// controlador UniFi). 0 = no se conoce, y la UI escribe "—" en vez de
+	// inventarse un "1 Gbps" que nadie ha medido.
+	SpeedMbps int `json:"speedMbps,omitempty"`
+	// Role: what the managed box actually is, "switch" or "ap". Kind stays
+	// "managed" for both because it drives the layout (a box known by MAC
+	// and IP, drawn as a node instead of a client chip), but an access point
+	// is not a switch and must not be labelled or drawn as one. Empty on a
+	// node whose role is unknown, which reads as a switch, the only thing
+	// LLDP inference has ever found.
+	Role string `json:"role,omitempty"`
 }
 
 // AlertEvent vive en internal/alerts (SPEC-ALERTAS §1: Category/Urgent/Ts);