ソースを参照

feat(routers): read the unit as openwrt networks, not only as a chassis (#1889) (#1912)

* feat(routers): read the unit as openwrt networks, not only as a chassis (#1889)

* docs(changelog): cover the openwrt networks view (#1889)
Nacho 4 週間 前
親
コミット
5c9c44e383

+ 2 - 0
CHANGELOG.md

@@ -8,6 +8,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ## [Unreleased]
 
 ### Added
+- The router page can now be read as the networks the unit declares, not only as a chassis with jacks (#1889). A networks card lists each OpenWrt network with its device, its subnet, its VLAN, its member ports, how many clients sit on it and the traffic of its device. Both ways of segmenting a box go through the same code: a bridge with VLAN filtering, where the network device is br_switch.999 and the members come from its bridge-vlan section, and one bridge per network fed by a tagged subinterface, where br-iot learns its VLAN from eth0.999. Traffic is the counter of the network device rather than a sum of its ports, a unit without per-interface counters shows no figure instead of an invented one, and clients are counted only when their VLAN is known. Reading the configuration also fixed a quiet parsing bug: a UCI list written as 'eth1 lan1 lan2' was being treated as one single port name.
+
 - A configuration backup no longer needs an agent on the unit (#1899). The button only rendered for a unit with an agent, so a router managed over plain SSH had no way to keep a copy of its config even though the server can already reach it. The server now builds the archive itself with `sysupgrade --create-backup`, brings it back base64 encoded over the SSH channel, always removes the temporary file on the unit, whose /tmp is RAM, and stores it where the agent backups already live, so one list and one download serve both kinds. A unit that does have an agent still prefers the event stream and only falls back to SSH when the agent is not connected.
 
 

+ 7 - 3
agent/probe/local.go

@@ -348,19 +348,23 @@ func (p *Prober) scanWithFallback(ctx context.Context, ifaces []IwDevIface, chos
 // the real layout. The two views are therefore merged always, the kernel
 // owning the flags and the configuration the names, subnets and the VLANs
 // that only exist as subinterfaces (#1757).
-func (p *Prober) probeVlans(ctx context.Context) []VlanPort {
+func (p *Prober) probeVlans(ctx context.Context) ([]VlanPort, []UciNetwork) {
 	var kernel []VlanPort
 	if out := p.runBest(ctx, CmdBridgeVlan, 0); out != "" {
 		kernel = ParseBridgeVlan(out)
 	}
 	var declared []VlanPort
+	var networks []UciNetwork
 	if out := p.runBest(ctx, CmdUciBridgeVlan, 0); out != "" {
+		// La misma configuracion alimenta las dos vistas (#1889): una sola
+		// lectura de `uci show network` por ronda.
 		// A router uses one model or the other, so the two UCI parsers
 		// never describe the same port: bridge-vlan sections name bridge
 		// ports, the subinterface model names bridges and their parents.
 		declared = MergeVlanPorts(ParseUciBridgeVlans(out), ParseUciNetworkVlans(out))
+		networks = ParseUciNetworks(out)
 	}
-	return MergeVlanPorts(kernel, declared)
+	return MergeVlanPorts(kernel, declared), networks
 }
 
 // runBest es best-effort: error → "" (la sección queda ausente).
@@ -382,7 +386,7 @@ func (p *Prober) Build(ctx context.Context, router, version string) *Payload {
 	}
 	// Wan antes que FDB: probeFDB usa la boca del uplink para marcarla.
 	pl.Data.Wan = p.probeWan(ctx)
-	pl.Data.Vlans = p.probeVlans(ctx)
+	pl.Data.Vlans, pl.Data.Networks = p.probeVlans(ctx)
 	pl.Data.System = p.probeSystem(ctx)
 	pl.Data.Wireless = p.probeWireless(ctx, true)
 	pl.Data.DHCP = p.probeDHCP(ctx)

+ 119 - 0
agent/probe/network_uci.go

@@ -0,0 +1,119 @@
+package probe
+
+import (
+	"strconv"
+	"strings"
+)
+
+// UciNetwork is one logical network as `uci show network` declares it (#1889):
+// the way the box is configured, not the way its jacks look. A segmented
+// OpenWrt router has one of these per network, with its own device, subnet and
+// member ports, and that is the view an operator recognises.
+type UciNetwork struct {
+	Name   string   `json:"name"`
+	Device string   `json:"device,omitempty"`
+	Proto  string   `json:"proto,omitempty"`
+	Subnet string   `json:"subnet,omitempty"`
+	Vlan   int      `json:"vlan,omitempty"`
+	Ports  []string `json:"ports,omitempty"`
+}
+
+// ParseUciNetworks reads the interface sections of `uci show network` and
+// resolves each one against the device sections, so a row carries the members
+// of its bridge and the VLAN it lives on. Both models are read the same way:
+// a bridge with VLAN filtering declares br_switch.999 as the device, and a box
+// that segments with subinterfaces declares br-iot fed by eth0.999.
+func ParseUciNetworks(out string) []UciNetwork {
+	sections, order := uciNetworkSections(out)
+	var nets []UciNetwork
+	for _, name := range order {
+		s := sections[name]
+		if s["@type"] != "interface" {
+			continue
+		}
+		dev := s["device"]
+		if dev == "" {
+			dev = s["ifname"]
+		}
+		if dev == "" {
+			continue
+		}
+		n := UciNetwork{
+			Name:   name,
+			Device: dev,
+			Proto:  s["proto"],
+			Subnet: vlanSubnet(s["ipaddr"], s["netmask"]),
+		}
+		// An address written as a prefix already says its subnet.
+		if ip := s["ipaddr"]; n.Subnet == "" && strings.Contains(ip, "/") {
+			n.Subnet = ip
+		}
+		n.Vlan = subifVlan(dev)
+		// The device section may name the device itself (br-iot) or its parent
+		// bridge when the network sits on a subinterface (br_switch.999).
+		base := dev
+		if i := strings.IndexByte(dev, '.'); i > 0 {
+			base = dev[:i]
+		}
+		var devSec uciSection
+		for _, dname := range order {
+			d := sections[dname]
+			if d["@type"] != "device" {
+				continue
+			}
+			if d["name"] == dev {
+				devSec = d
+				break
+			}
+			if d["name"] == base && devSec == nil {
+				devSec = d
+			}
+		}
+		if devSec != nil {
+			n.Ports = splitUciList(devSec["ports"])
+			// The bridge itself has no VLAN in its name: the tagged
+			// subinterface it is fed with says which one it carries.
+			if n.Vlan == 0 {
+				for _, port := range n.Ports {
+					if vid := subifVlan(port); vid > 0 {
+						n.Vlan = vid
+						break
+					}
+				}
+			}
+		}
+		// With bridge VLAN filtering the members of one network are the ports
+		// its bridge-vlan section lists, not every port of the bridge.
+		if n.Vlan > 0 && base != dev {
+			for _, bname := range order {
+				b := sections[bname]
+				if b["@type"] != "bridge-vlan" || b["device"] != base || b["vlan"] != strconv.Itoa(n.Vlan) {
+					continue
+				}
+				ports := splitUciList(b["ports"])
+				for i, port := range ports {
+					// eth1:t means tagged, eth1:u* untagged and primary.
+					if j := strings.IndexByte(port, ':'); j > 0 {
+						ports[i] = port[:j]
+					}
+				}
+				n.Ports = ports
+			}
+		}
+		nets = append(nets, n)
+	}
+	return nets
+}
+
+// subifVlan returns the VLAN id of an 802.1Q subinterface name, 0 otherwise.
+func subifVlan(name string) int {
+	m := vlanSubifRe.FindStringSubmatch(name)
+	if m == nil {
+		return 0
+	}
+	vid, err := strconv.Atoi(m[2])
+	if err != nil {
+		return 0
+	}
+	return vid
+}

+ 142 - 0
agent/probe/network_uci_test.go

@@ -0,0 +1,142 @@
+package probe
+
+import (
+	"reflect"
+	"testing"
+)
+
+// Config real del router x86 del reporter de #1757 (una bridge por red,
+// alimentada por una subinterfaz 802.1Q).
+const uciNetworksSubif = `
+network.globals=globals
+network.globals.packet_steering='1'
+network.Lan=interface
+network.Lan.device='br-lan'
+network.Lan.proto='static'
+network.Lan.ipaddr='192.168.1.1'
+network.Lan.netmask='255.255.255.0'
+network.@device[0]=device
+network.@device[0].type='bridge'
+network.@device[0].name='br-lan'
+network.@device[0].ports='eth0'
+network.Hack=interface
+network.Hack.device='br-hack'
+network.Hack.proto='static'
+network.Hack.ipaddr='10.0.99.1'
+network.Hack.netmask='255.255.255.0'
+network.@device[1]=device
+network.@device[1].type='bridge'
+network.@device[1].name='br-hack'
+network.@device[1].ports='eth0.888'
+network.IOT=interface
+network.IOT.device='br-iot'
+network.IOT.proto='static'
+network.IOT.ipaddr='192.168.111.1'
+network.IOT.netmask='255.255.255.0'
+network.@device[2]=device
+network.@device[2].type='bridge'
+network.@device[2].name='br-iot'
+network.@device[2].ports='eth0.999'
+`
+
+// Config real del AP Flint 2 del mismo reporter: una sola bridge con VLAN
+// filtering y una subinterfaz por red.
+const uciNetworksFiltering = `
+network.lan=interface
+network.lan.device='br_switch.1'
+network.lan.proto='static'
+network.lan.ipaddr='192.168.1.2'
+network.lan.netmask='255.255.255.0'
+network.Guest=interface
+network.Guest.proto='none'
+network.Guest.device='br_switch.777'
+network.Iot=interface
+network.Iot.proto='none'
+network.Iot.device='br_switch.999'
+network.@device[6]=device
+network.@device[6].type='bridge'
+network.@device[6].name='br_switch'
+network.@device[6].ports='eth1 lan1 lan2 lan3 lan4 lan5'
+network.@bridge-vlan[0]=bridge-vlan
+network.@bridge-vlan[0].device='br_switch'
+network.@bridge-vlan[0].vlan='1'
+network.@bridge-vlan[0].ports='eth1 lan1 lan2 lan3 lan4 lan5'
+network.@bridge-vlan[1]=bridge-vlan
+network.@bridge-vlan[1].device='br_switch'
+network.@bridge-vlan[1].vlan='777'
+network.@bridge-vlan[1].ports='eth1:t lan1:t lan2:t'
+network.@bridge-vlan[2]=bridge-vlan
+network.@bridge-vlan[2].device='br_switch'
+network.@bridge-vlan[2].vlan='999'
+network.@bridge-vlan[2].ports='eth1:t lan1:t lan2:t lan3:t'
+`
+
+func TestParseUciNetworksSubinterfaces(t *testing.T) {
+	nets := ParseUciNetworks(uciNetworksSubif)
+	if len(nets) != 3 {
+		t.Fatalf("redes = %d, quiero 3: %+v", len(nets), nets)
+	}
+	byName := map[string]UciNetwork{}
+	for _, n := range nets {
+		byName[n.Name] = n
+	}
+	lan := byName["Lan"]
+	if lan.Device != "br-lan" || lan.Subnet != "192.168.1.1/24" || lan.Vlan != 0 {
+		t.Fatalf("Lan = %+v", lan)
+	}
+	if !reflect.DeepEqual(lan.Ports, []string{"eth0"}) {
+		t.Fatalf("miembros de Lan = %v", lan.Ports)
+	}
+	hack := byName["Hack"]
+	if hack.Vlan != 888 || hack.Subnet != "10.0.99.1/24" {
+		t.Fatalf("Hack = %+v", hack)
+	}
+	if !reflect.DeepEqual(hack.Ports, []string{"eth0.888"}) {
+		t.Fatalf("miembros de Hack = %v", hack.Ports)
+	}
+	if iot := byName["IOT"]; iot.Vlan != 999 || iot.Subnet != "192.168.111.1/24" {
+		t.Fatalf("IOT = %+v", iot)
+	}
+	// El orden es el de la configuracion, no el alfabetico.
+	if nets[0].Name != "Lan" || nets[1].Name != "Hack" || nets[2].Name != "IOT" {
+		t.Fatalf("orden = %+v", nets)
+	}
+}
+
+func TestParseUciNetworksBridgeFiltering(t *testing.T) {
+	nets := ParseUciNetworks(uciNetworksFiltering)
+	if len(nets) != 3 {
+		t.Fatalf("redes = %d, quiero 3: %+v", len(nets), nets)
+	}
+	byName := map[string]UciNetwork{}
+	for _, n := range nets {
+		byName[n.Name] = n
+	}
+	lan := byName["lan"]
+	if lan.Vlan != 1 || lan.Subnet != "192.168.1.2/24" {
+		t.Fatalf("lan = %+v", lan)
+	}
+	guest := byName["Guest"]
+	if guest.Vlan != 777 || guest.Proto != "none" {
+		t.Fatalf("Guest = %+v", guest)
+	}
+	// Los miembros son los de SU bridge-vlan, sin el sufijo :t, no todos los
+	// puertos de la bridge.
+	if !reflect.DeepEqual(guest.Ports, []string{"eth1", "lan1", "lan2"}) {
+		t.Fatalf("miembros de Guest = %v", guest.Ports)
+	}
+	iot := byName["Iot"]
+	if iot.Vlan != 999 || !reflect.DeepEqual(iot.Ports, []string{"eth1", "lan1", "lan2", "lan3"}) {
+		t.Fatalf("Iot = %+v", iot)
+	}
+}
+
+func TestParseUciNetworksSinUci(t *testing.T) {
+	if nets := ParseUciNetworks(""); nets != nil {
+		t.Fatalf("vacio = %+v", nets)
+	}
+	// Una interfaz sin device no es una red que se pueda dibujar.
+	if nets := ParseUciNetworks("network.x=interface\nnetwork.x.proto='static'\n"); len(nets) != 0 {
+		t.Fatalf("sin device = %+v", nets)
+	}
+}

+ 3 - 0
agent/probe/payload.go

@@ -59,6 +59,9 @@ type PayloadData struct {
 	// #305). El servidor calcula los rates por boca con el delta entre
 	// payloads. nil = sonda fallida (conserva la última buena).
 	NetIf map[string]IfCounters `json:"netIf,omitempty"`
+	// Networks: las redes logicas de OpenWrt tal como las declara UCI
+	// (#1889), con su device, subred, VLAN y miembros.
+	Networks []UciNetwork `json:"networks,omitempty"`
 	// Vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sonda
 	// fallida o router sin bridge vlan filtering.
 	Vlans []VlanPort `json:"vlans,omitempty"`

+ 35 - 21
agent/probe/vlan_network.go

@@ -8,24 +8,17 @@ import (
 	"strings"
 )
 
-// vlanSubifRe matches an 802.1Q subinterface: the parent device and the VLAN
-// id in its name, the way Linux and OpenWrt build them (eth0.666).
-var vlanSubifRe = regexp.MustCompile(`^([^.]+)\.(\d{1,4})$`)
+// uciSection is one `network.<name>` section of `uci show network`, with the
+// section type kept under "@type". Anonymous sections keep their printed name
+// (@device[0]) so the declaration order is preserved.
+type uciSection map[string]string
 
-// ParseUciNetworkVlans derives the VLANs of a router that segments with
-// 802.1Q subinterfaces instead of bridge VLAN filtering (#1757).
-//
-// `bridge vlan show` only knows about bridges with vlan_filtering enabled. A
-// box that creates one bridge per network and feeds it a tagged subinterface
-// (eth0.999 into br-iot) reports every bridge on its default VLAN 1, so the
-// kernel view is blind to the real segmentation and the panel shows a flat
-// list of ports. The configuration is the only place that says which VLAN a
-// bridge carries, which interface it belongs to and what subnet it serves, so
-// it is read as a source of its own and merged with the kernel output, never
-// as a fallback.
-func ParseUciNetworkVlans(out string) []VlanPort {
-	type section map[string]string
-	sections := map[string]section{}
+// uciNetworkSections splits `uci show network` into its sections, in the order
+// the configuration declares them. Shared by the VLAN view (#1757) and the
+// networks view (#1889), which read the same configuration for different
+// purposes and must never disagree about what it says.
+func uciNetworkSections(out string) (map[string]uciSection, []string) {
+	sections := map[string]uciSection{}
 	order := []string{}
 	for _, line := range strings.Split(out, "\n") {
 		line = strings.TrimSpace(line)
@@ -39,7 +32,7 @@ func ParseUciNetworkVlans(out string) []VlanPort {
 		val = strings.Trim(val, "'")
 		name, attr, isAttr := strings.Cut(key, ".")
 		if _, seen := sections[name]; !seen {
-			sections[name] = section{}
+			sections[name] = uciSection{}
 			order = append(order, name)
 		}
 		if !isAttr {
@@ -48,6 +41,26 @@ func ParseUciNetworkVlans(out string) []VlanPort {
 		}
 		sections[name][attr] = val
 	}
+	return sections, order
+}
+
+// vlanSubifRe matches an 802.1Q subinterface: the parent device and the VLAN
+// id in its name, the way Linux and OpenWrt build them (eth0.666).
+var vlanSubifRe = regexp.MustCompile(`^([^.]+)\.(\d{1,4})$`)
+
+// ParseUciNetworkVlans derives the VLANs of a router that segments with
+// 802.1Q subinterfaces instead of bridge VLAN filtering (#1757).
+//
+// `bridge vlan show` only knows about bridges with vlan_filtering enabled. A
+// box that creates one bridge per network and feeds it a tagged subinterface
+// (eth0.999 into br-iot) reports every bridge on its default VLAN 1, so the
+// kernel view is blind to the real segmentation and the panel shows a flat
+// list of ports. The configuration is the only place that says which VLAN a
+// bridge carries, which interface it belongs to and what subnet it serves, so
+// it is read as a source of its own and merged with the kernel output, never
+// as a fallback.
+func ParseUciNetworkVlans(out string) []VlanPort {
+	sections, order := uciNetworkSections(out)
 
 	// Interfaces first: they carry the name and the subnet of whatever device
 	// they sit on.
@@ -262,7 +275,10 @@ func mergeVlanEntries(kernel, declared []VlanEntry) []VlanEntry {
 func splitUciList(val string) []string {
 	var out []string
 	for _, part := range strings.Split(val, "' '") {
-		if p := strings.TrimSpace(strings.Trim(part, "'")); p != "" {
+		// UCI imprime una lista como 'a' 'b' o como 'a b': las dos formas son
+		// la misma lista y quedarse con la cadena entera inventaba un puerto
+		// que no existe (#1889).
+		for _, p := range strings.Fields(strings.Trim(part, "'")) {
 			out = append(out, p)
 		}
 	}
@@ -286,8 +302,6 @@ func vlanSubnet(ip, mask string) string {
 	return fmt.Sprintf("%s/%d", ip, ones)
 }
 
-
-
 // vlanOnlyDefault: the kernel reported nothing but the default VLAN.
 func vlanOnlyDefault(entries []VlanEntry) bool {
 	if len(entries) == 0 {

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

@@ -1126,6 +1126,19 @@
       "untagged": "Untagged",
       "vlanId": "VLAN ID"
     },
+    "networks": {
+      "clients": "Clients",
+      "clientsTip": "Clients whose VLAN is known",
+      "device": "Device",
+      "members": "Members",
+      "network": "Network",
+      "noCounters": "This unit does not report per-interface counters",
+      "subnet": "Subnet",
+      "title": "Networks",
+      "toggleAria": "OpenWrt networks ({{count}})",
+      "traffic": "Traffic",
+      "vlan": "VLAN {{id}}"
+    },
     "wan": {
       "chartAria": "Gateway WAN traffic. Current download {{down}} Mbps, upload {{up}} Mbps.",
       "fiber": "Fiber {{plan}}",

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

@@ -1126,6 +1126,19 @@
       "untagged": "Untagged",
       "vlanId": "ID VLAN"
     },
+    "networks": {
+      "clients": "Clientes",
+      "clientsTip": "Clientes cuya VLAN se conoce",
+      "device": "Dispositivo",
+      "members": "Miembros",
+      "network": "Red",
+      "noCounters": "Esta unidad no reporta contadores por interfaz",
+      "subnet": "Subred",
+      "title": "Redes",
+      "toggleAria": "Redes de OpenWrt ({{count}})",
+      "traffic": "Tráfico",
+      "vlan": "VLAN {{id}}"
+    },
     "wan": {
       "chartAria": "Tráfico WAN de la puerta de enlace. Descarga actual {{down}} Mbps, subida {{up}} Mbps.",
       "fiber": "Fibra {{plan}}",

+ 127 - 0
app/src/components/routers/NetworksPanel.tsx

@@ -0,0 +1,127 @@
+import { useState } from 'react'
+import { ChevronDown, Network } from 'lucide-react'
+import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
+import { useTranslation } from 'react-i18next'
+import type { Device, NetworkInfo } from '@/data/types'
+import { SectionHeader } from '@/components/SectionHeader'
+import { cn } from '@/lib/utils'
+
+/** fmtBps: rate en humano ("12.4 Mbps" · "320 kbps" · "0"). */
+function fmtBps(bps?: number): string {
+  if (bps === undefined) return '-'
+  if (bps >= 1e6) return `${(bps / 1e6).toFixed(1)} Mbps`
+  if (bps >= 1e3) return `${(bps / 1e3).toFixed(0)} kbps`
+  return `${bps.toFixed(0)} bps`
+}
+
+/**
+ * NetworksPanel (#1889): la unidad tal como está configurada, una fila por red
+ * de OpenWrt con su device, su subred, sus miembros y su tráfico, en lugar de
+ * leerla solo como un chasis con bocas. Los dos modelos caben en la misma
+ * tabla: bridge con VLAN filtering (br_switch.999) y subinterfaces (br-iot
+ * alimentado por eth0.999).
+ *
+ * El tráfico es el del device de la red, no la suma de sus puertos, y una
+ * unidad sin contadores muestra "-" en lugar de una cifra inventada. Los
+ * clientes son los que tienen VLAN conocida; sin ese dato no se adivina.
+ */
+export function NetworksPanel({ networks, clients }: { networks: NetworkInfo[]; clients: Device[] }) {
+  const { t } = useTranslation()
+  const reduce = useReducedMotion()
+  const [open, setOpen] = useState(true)
+
+  if (!networks || networks.length === 0) return null
+
+  return (
+    <section className="rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-12" data-testid="networks-panel">
+      <button
+        type="button"
+        onClick={() => setOpen((v) => !v)}
+        className="flex w-full items-center justify-between gap-3"
+        aria-expanded={open}
+        aria-label={t('routerDetail.networks.toggleAria', { count: networks.length })}
+      >
+        <SectionHeader title={t('routerDetail.networks.title')} />
+        <div className="flex items-center gap-2">
+          <span className="rounded-full bg-accent/10 px-2 py-0.5 font-mono text-caption font-semibold text-accent">
+            {networks.length}
+          </span>
+          <ChevronDown
+            className={cn('h-4 w-4 text-text-muted transition-transform duration-200', open && 'rotate-180')}
+            strokeWidth={1.75}
+          />
+        </div>
+      </button>
+
+      <AnimatePresence initial={false}>
+        {open && (
+          <motion.div
+            key="networks-body"
+            initial={{ height: reduce ? 'auto' : 0, opacity: reduce ? 1 : 0 }}
+            animate={{ height: 'auto', opacity: 1 }}
+            exit={{ height: reduce ? 'auto' : 0, opacity: reduce ? 1 : 0 }}
+            transition={{ duration: 0.2, ease: 'easeInOut' }}
+            className="overflow-hidden"
+          >
+            <div className="mt-4 overflow-x-auto">
+              <table className="w-full text-left text-sm">
+                <thead>
+                  <tr className="border-b border-border/60 text-[10px] font-semibold uppercase tracking-[0.06em] text-text-muted">
+                    <th className="pb-2 pr-4">{t('routerDetail.networks.network')}</th>
+                    <th className="pb-2 pr-4">{t('routerDetail.networks.device')}</th>
+                    <th className="pb-2 pr-4">{t('routerDetail.networks.subnet')}</th>
+                    <th className="pb-2 pr-4">{t('routerDetail.networks.members')}</th>
+                    <th className="pb-2 pr-4">{t('routerDetail.networks.clients')}</th>
+                    <th className="pb-2">{t('routerDetail.networks.traffic')}</th>
+                  </tr>
+                </thead>
+                <tbody>
+                  {networks.map((n) => {
+                    const knownClients = n.vlan ? clients.filter((c) => c.vlan === n.vlan).length : undefined
+                    const hasRate = n.rxBps !== undefined || n.txBps !== undefined
+                    return (
+                      <tr key={n.name} className="border-b border-border/30 last:border-0" data-vlan-id={n.vlan || undefined}>
+                        <td className="py-2 pr-4">
+                          <span className="flex items-center gap-1.5 font-semibold text-text-primary">
+                            <Network className="h-3.5 w-3.5 text-text-muted" strokeWidth={1.75} />
+                            {n.name}
+                          </span>
+                          {n.vlan ? (
+                            <span className="ml-[22px] font-mono text-[10px] text-text-muted">
+                              {t('routerDetail.networks.vlan', { id: n.vlan })}
+                            </span>
+                          ) : null}
+                        </td>
+                        <td className="py-2 pr-4 font-mono text-mono-sm text-text-secondary">{n.device ?? '-'}</td>
+                        <td className="py-2 pr-4 font-mono text-mono-sm text-text-secondary">{n.subnet ?? '-'}</td>
+                        <td className="py-2 pr-4 font-mono text-mono-sm text-text-secondary">
+                          {n.ports && n.ports.length > 0 ? n.ports.join(' ') : '-'}
+                        </td>
+                        <td className="py-2 pr-4" title={t('routerDetail.networks.clientsTip')}>
+                          {knownClients !== undefined ? (
+                            <span className="font-mono text-mono-sm text-text-primary">{knownClients}</span>
+                          ) : (
+                            <span className="text-text-muted">-</span>
+                          )}
+                        </td>
+                        <td className="py-2" title={hasRate ? undefined : t('routerDetail.networks.noCounters')}>
+                          {hasRate ? (
+                            <span className="whitespace-nowrap font-mono text-mono-sm text-text-secondary">
+                              ↓{fmtBps(n.rxBps)} ↑{fmtBps(n.txBps)}
+                            </span>
+                          ) : (
+                            <span className="text-text-muted">-</span>
+                          )}
+                        </td>
+                      </tr>
+                    )
+                  })}
+                </tbody>
+              </table>
+            </div>
+          </motion.div>
+        )}
+      </AnimatePresence>
+    </section>
+  )
+}

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

@@ -15,6 +15,7 @@
  */
 import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
 import type {
+  NetworkInfo,
   AdGuardStats,
   AgentInfo,
   AlertCategory,
@@ -99,6 +100,8 @@ export interface RouterDetailData {
   wireguard?: WireGuardStats
   /** VLANs del bridge (issue #315). Ausente si el router no tiene bridge vlan filtering. */
   vlans?: VlanPort[]
+  /** #1889: redes lógicas de OpenWrt (UCI) con su device, subred y tráfico. */
+  networks?: NetworkInfo[]
   /** Las varias conexiones a internet del router, si reporta más de una.
    *  Solo lectura: las gestiona el panel del propio router. */
   multiWan?: MultiWanInfo

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

@@ -711,3 +711,16 @@ export interface ReanchorResponse {
   daemon: 'none' | 'dawn' | 'usteer' | 'both'
   recommendations: ReanchorRecommendation[]
 }
+
+/** #1889: una red lógica de OpenWrt tal como la declara UCI, con su device,
+ *  subred, VLAN, miembros y el tráfico del device (ausente sin contadores). */
+export interface NetworkInfo {
+  name: string
+  device?: string
+  proto?: string
+  subnet?: string
+  vlan?: number
+  ports?: string[]
+  rxBps?: number
+  txBps?: number
+}

+ 6 - 0
app/src/pages/RouterDetail.tsx

@@ -20,6 +20,7 @@ import { RouterPerformance } from '@/components/routers/RouterPerformance'
 import { MultiWanPanel } from '@/components/routers/MultiWanPanel'
 import { WanLatency } from '@/components/routers/WanLatency'
 import { VlanPanel } from '@/components/routers/VlanPanel'
+import { NetworksPanel } from '@/components/routers/NetworksPanel'
 import { WireGuardPanel } from '@/components/routers/WireGuardPanel'
 
 /** Página `/routers/:id` — plantilla de detalle (router-detail.md) */
@@ -283,6 +284,11 @@ export default function RouterDetail() {
         />
       )}
 
+      {/* #1889: la unidad como redes de OpenWrt, no solo como chasis */}
+      {detail?.networks && detail.networks.length > 0 && (
+        <NetworksPanel networks={detail.networks} clients={detail.clients ?? []} />
+      )}
+
       {/* VLANs del bridge (issue #315, read-only) */}
       {detail?.vlans && detail.vlans.length > 0 && (
         <VlanPanel vlans={detail.vlans} />

+ 7 - 1
server-go/internal/adapters/agent.go

@@ -942,6 +942,12 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 	} else if cached != nil {
 		out.vlans = cached.vlans
 	}
+	// #1889: las redes UCI viajan en el mismo payload que las VLANs.
+	if len(p.Data.Networks) > 0 {
+		out.networks = p.Data.Networks
+	} else if cached != nil {
+		out.networks = cached.networks
+	}
 	if dh := p.Data.DHCP; dh != nil && len(dh.Reservations) > 0 {
 		out.reservations = dh.Reservations
 	}
@@ -1102,7 +1108,7 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		lldpSnap = cached.lldp // conserva la última sección buena (#489)
 	}
 	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: out.ports, radios: out.radios,
-		wireless: out.wireless, fdb: out.fdb, fdbVlans: out.fdbVlans, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
+		wireless: out.wireless, fdb: out.fdb, fdbVlans: out.fdbVlans, networks: out.networks, wirelessSide: out.wirelessSide, luci: out.luci, system: sysSnap, systemKind: sysSnapKind, lldp: lldpSnap,
 		clientBw: out.clientBw, vlans: out.vlans, multiWan: out.multiWan}
 	l.mu.Unlock()
 

+ 39 - 3
server-go/internal/adapters/live.go

@@ -159,6 +159,8 @@ type routerPolled struct {
 	// qué VLAN vive el cliente: solo este dato lo dice. Vacío = sin dato (el
 	// bridge no tiene VLAN filtering, o la sonda es por SSH y no lo reporta).
 	fdbVlans map[string]int
+	// networks: redes logicas declaradas en UCI (#1889).
+	networks []probe.UciNetwork
 	// wirelessSide: MACs que el bridge del router aprende en sus propios
 	// puertos de radio (wl0.1, wlan0…) pero que la tabla de estaciones no
 	// lista (MACs rotadas que siguen emitiendo, backhaul 4-address). El
@@ -225,6 +227,8 @@ type extrasSnapshot struct {
 	// fdbVlans: MAC → VLAN del FDB (#1757). Mismo anti-parpadeo que fdb: solo
 	// nace del payload del agente y una sonda SSH exitosa lo limpia.
 	fdbVlans map[string]int
+	// networks: última lista buena de redes UCI (#1889).
+	networks []probe.UciNetwork
 	// wirelessSide: último hint bueno de MACs detrás de radios propias
 	// (ver routerPolled.wirelessSide). Mismo anti-parpadeo que fdb.
 	wirelessSide map[string]string
@@ -1347,8 +1351,13 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	if vlans := client.GetBridgeVlans(); vlans != nil {
 		vlansGood = vlans
 	}
+	// #1889: la misma configuracion UCI dice las redes logicas de la unidad.
+	networksGood := cached.networks
+	if nets := client.GetNetworks(); nets != nil {
+		networksGood = nets
+	}
 	l.mu.Lock()
-	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, fdbVlans: fdbVlansGood, luci: luciGood, vlans: vlansGood}
+	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, fdbVlans: fdbVlansGood, luci: luciGood, vlans: vlansGood, networks: networksGood}
 	l.mu.Unlock()
 
 	// Uso de RAM: #513. Si el agente reporta memory.used (procesos) lo
@@ -1400,7 +1409,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, fdbVlans: fdbVlansGood, wirelessSide: wsGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
-		luci: luciGood, wanInfo: wanInfo, vlans: vlansGood,
+		luci: luciGood, wanInfo: wanInfo, vlans: vlansGood, networks: networksGood,
 		polledAt: l.now().UnixMilli(),
 	}, nil
 }
@@ -4778,6 +4787,10 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	if p != nil && len(p.vlans) > 0 {
 		vlans = vlanPortsWithNames(p.vlans, p.luci)
 	}
+	var networks []NetworkInfo
+	if p != nil && len(p.networks) > 0 {
+		networks = networkInfos(p.networks, p.ports)
+	}
 	var multiWan *MultiWanInfo
 	if p != nil {
 		multiWan = p.multiWan
@@ -4785,7 +4798,7 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	detail := &RouterDetail{
 		Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
 		Series:  PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
-		Clients: clients, Extras: extras, Vlans: vlans, MultiWan: multiWan,
+		Clients: clients, Extras: extras, Vlans: vlans, Networks: networks, MultiWan: multiWan,
 	}
 	// #930: contadores de salud SNMP del router (solo si se sondea por SNMP).
 	if cfg.SnmpEnabled {
@@ -6149,3 +6162,26 @@ func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
 	}
 	return port
 }
+
+// networkInfos convierte la configuracion UCI en la vista de redes (#1889).
+// El trafico es el del DEVICE de la red (br-iot), que ya llega como puerto
+// virtual con rates: una bridge suma lo de sus puertos y eso no es lo que el
+// operador lee en su panel. Sin contadores la fila simplemente no lo muestra.
+func networkInfos(nets []probe.UciNetwork, ports []EthPort) []NetworkInfo {
+	byIface := map[string]EthPort{}
+	for _, pt := range ports {
+		if pt.Iface != "" {
+			byIface[pt.Iface] = pt
+		}
+	}
+	out := make([]NetworkInfo, 0, len(nets))
+	for _, n := range nets {
+		ni := NetworkInfo{Name: n.Name, Device: n.Device, Proto: n.Proto, Subnet: n.Subnet, Vlan: n.Vlan, Ports: n.Ports}
+		if pt, ok := byIface[n.Device]; ok {
+			ni.RxBps = pt.RxBps
+			ni.TxBps = pt.TxBps
+		}
+		out = append(out, ni)
+	}
+	return out
+}

+ 41 - 0
server-go/internal/adapters/networks_1889_test.go

@@ -0,0 +1,41 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// #1889: la vista de redes lee el trafico del device de cada red, no el de sus
+// puertos, y una red sin contadores se queda sin cifra en vez de inventarla.
+func TestNetworkInfosTraficoDelDevice(t *testing.T) {
+	nets := []probe.UciNetwork{
+		{Name: "IOT", Device: "br-iot", Proto: "static", Subnet: "192.168.111.1/24", Vlan: 999, Ports: []string{"eth0.999"}},
+		{Name: "Guest", Device: "br_switch.777", Proto: "none", Vlan: 777},
+	}
+	ports := []EthPort{
+		{ID: "if-br-iot", Iface: "br-iot", RxBps: 1200, TxBps: 3400},
+		{ID: "lan1", Iface: "lan1", RxBps: 99999, TxBps: 99999},
+	}
+	out := networkInfos(nets, ports)
+	if len(out) != 2 {
+		t.Fatalf("redes = %d", len(out))
+	}
+	iot := out[0]
+	if iot.Name != "IOT" || iot.Vlan != 999 || iot.Subnet != "192.168.111.1/24" {
+		t.Fatalf("IOT = %+v", iot)
+	}
+	if iot.RxBps != 1200 || iot.TxBps != 3400 {
+		t.Fatalf("trafico de IOT = %v/%v, quiero el de br-iot", iot.RxBps, iot.TxBps)
+	}
+	if len(iot.Ports) != 1 || iot.Ports[0] != "eth0.999" {
+		t.Fatalf("miembros de IOT = %v", iot.Ports)
+	}
+	guest := out[1]
+	if guest.RxBps != 0 || guest.TxBps != 0 {
+		t.Fatalf("Guest sin contadores = %v/%v", guest.RxBps, guest.TxBps)
+	}
+	if guest.Vlan != 777 || guest.Proto != "none" {
+		t.Fatalf("Guest = %+v", guest)
+	}
+}

+ 16 - 0
server-go/internal/adapters/openwrt.go

@@ -714,3 +714,19 @@ func (c *OpenWrtClient) GetArp() (arp map[string]string, stale map[string]bool,
 	}
 	return probe.ParseArp(out), nil, probe.ParseArpDevs(out)
 }
+
+// GetNetworks: redes logicas que la unidad declara en UCI (#1889). Es la
+// misma lectura que alimenta las VLANs, asi que una unidad por SSH tambien
+// tiene la vista de redes; lo que no tiene son los contadores por interfaz.
+// nil si no hay datos, para que el anti-parpadeo conserve la ultima lista.
+func (c *OpenWrtClient) GetNetworks() []probe.UciNetwork {
+	out, err := c.pool.Run(c.Host, probe.CmdUciBridgeVlan, 0)
+	if err != nil {
+		return nil
+	}
+	nets := probe.ParseUciNetworks(out)
+	if len(nets) == 0 {
+		return nil
+	}
+	return nets
+}

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

@@ -729,6 +729,9 @@ type RouterDetail struct {
 	// Vlans: VLANs del bridge (issue #315). nil = sin datos (demo/routers
 	// sin bridge vlan filtering); slice vacio = sondeo sin VLANs.
 	Vlans []VlanPort `json:"vlans,omitempty"`
+	// Networks (#1889): las redes logicas de OpenWrt tal como las declara UCI,
+	// con su device, subred, VLAN, miembros y el trafico del device.
+	Networks []NetworkInfo `json:"networks,omitempty"`
 	// MultiWan: the router's internet connections and which one carries
 	// traffic — a read-only mirror of what its own panel manages. nil =
 	// the router never reported any; an empty uplink list = it reported
@@ -1151,3 +1154,17 @@ type Snapshotter interface {
 	// Close libera recursos (conexiones SSH, clientes HTTP).
 	Close() error
 }
+
+// NetworkInfo (#1889): una red logica de OpenWrt, la unidad en la que el
+// operador piensa cuando mira su router. El trafico es el del device de la
+// red; ausente cuando la unidad no reporta contadores.
+type NetworkInfo struct {
+	Name   string   `json:"name"`
+	Device string   `json:"device,omitempty"`
+	Proto  string   `json:"proto,omitempty"`
+	Subnet string   `json:"subnet,omitempty"`
+	Vlan   int      `json:"vlan,omitempty"`
+	Ports  []string `json:"ports,omitempty"`
+	RxBps  float64  `json:"rxBps,omitempty"`
+	TxBps  float64  `json:"txBps,omitempty"`
+}