Selaa lähdekoodia

fix: restore tree after #1176 squash carried a stale worktree (#1178)

Urgent repair: the #1176 squash carried a 107-file stale-worktree diff that reverted the MQTT v0.9.11 bump (#1155, the #1153 storm fix), the ndt7 module entry (breaking the build) and the #1173 race test fixes. This restores the 829fcf9 tree plus exactly the intended Rack.tsx change (19 lines, the rack fixes of #1176). go build green, adapters suite green.
Nacho 2 kuukautta sitten
vanhempi
sitoutus
348fdc981e
100 muutettua tiedostoa jossa 6270 lisäystä ja 1083 poistoa
  1. 15 0
      .gitignore
  2. 3 0
      .goreleaser.yaml
  3. 62 0
      CHANGELOG.md
  4. 37 2
      README.es.md
  5. 36 2
      README.md
  6. 1 1
      agent/VERSION
  7. 11 0
      agent/probe/local.go
  8. 16 0
      agent/probe/payload.go
  9. 86 0
      agent/probe/probe.go
  10. 122 0
      agent/probe/probe_test.go
  11. 1 1
      app/index.html
  12. 179 2
      app/package-lock.json
  13. 2 1
      app/package.json
  14. 230 38
      app/public/locales/en/translation.json
  15. 230 38
      app/public/locales/es/translation.json
  16. 10 0
      app/src/App.tsx
  17. 150 8
      app/src/components/DeviceEditSheet.tsx
  18. 1 0
      app/src/components/HealthRing.tsx
  19. 4 0
      app/src/components/InfoTip.tsx
  20. 11 9
      app/src/components/Layout.tsx
  21. 5 5
      app/src/components/UpdateDialog.tsx
  22. 4 0
      app/src/components/routers/AdGuardPanel.tsx
  23. 2 1
      app/src/components/routers/AgentBadge.tsx
  24. 2 1
      app/src/components/routers/AgentsSection.tsx
  25. 19 8
      app/src/components/routers/FleetCard.tsx
  26. 1 1
      app/src/components/routers/FleetTable.tsx
  27. 73 6
      app/src/components/routers/PortPanel.tsx
  28. 17 5
      app/src/components/routers/RouterDetailHeader.tsx
  29. 33 14
      app/src/components/routers/RouterInfo.tsx
  30. 131 44
      app/src/components/routers/WanLatency.tsx
  31. 10 2
      app/src/components/routers/routerExtras.ts
  32. 1 1
      app/src/components/topology/TopologyMap.tsx
  33. 29 2
      app/src/components/topology/model.ts
  34. 10 2
      app/src/components/ui/dialog.tsx
  35. 41 6
      app/src/data/DataProvider.tsx
  36. 9 2
      app/src/data/types.ts
  37. 24 20
      app/src/hooks/useIntegrations.ts
  38. 8 3
      app/src/hooks/useServicesVisibility.ts
  39. 2 1
      app/src/i18n.ts
  40. 11 0
      app/src/main.tsx
  41. 72 4
      app/src/pages/Alerts.tsx
  42. 789 251
      app/src/pages/ChannelPlan.tsx
  43. 94 13
      app/src/pages/Devices.tsx
  44. 34 2
      app/src/pages/FirmwareUpgrades.tsx
  45. 124 17
      app/src/pages/Roaming.tsx
  46. 4 3
      app/src/pages/RouterDetail.tsx
  47. 455 142
      app/src/pages/Settings.tsx
  48. 6 59
      app/src/sections/WanTraffic.tsx
  49. 1 0
      app/vite.config.ts
  50. 38 0
      server-go/cmd/netpulse/main.go
  51. 13 1
      server-go/go.mod
  52. 193 4
      server-go/go.sum
  53. 54 0
      server-go/internal/adapters/adapters_test.go
  54. 50 0
      server-go/internal/adapters/agent.go
  55. 1 1
      server-go/internal/adapters/demo.go
  56. 97 13
      server-go/internal/adapters/device_seen.go
  57. 67 0
      server-go/internal/adapters/device_seen_test.go
  58. 450 178
      server-go/internal/adapters/live.go
  59. 47 0
      server-go/internal/adapters/live_wanstats_test.go
  60. 52 1
      server-go/internal/adapters/proxmox.go
  61. 59 0
      server-go/internal/adapters/proxmox_test.go
  62. 41 0
      server-go/internal/adapters/snmp_live.go
  63. 71 5
      server-go/internal/adapters/topo_semantics.go
  64. 110 8
      server-go/internal/adapters/topo_semantics_test.go
  65. 1 1
      server-go/internal/adapters/topology_lldp_test.go
  66. 36 2
      server-go/internal/adapters/types.go
  67. 65 5
      server-go/internal/alerts/alerts.go
  68. 146 0
      server-go/internal/alerts/alerts_test.go
  69. 201 34
      server-go/internal/channelplan/store.go
  70. 270 0
      server-go/internal/channelplan/store_test.go
  71. 16 0
      server-go/internal/config/config.go
  72. 93 0
      server-go/internal/db/db.go
  73. 31 5
      server-go/internal/httpapi/config.go
  74. 41 0
      server-go/internal/httpapi/config_test.go
  75. 43 8
      server-go/internal/httpapi/data.go
  76. 26 0
      server-go/internal/httpapi/device_overrides.go
  77. 79 0
      server-go/internal/httpapi/device_overrides_test.go
  78. 11 10
      server-go/internal/httpapi/firmware_test.go
  79. 4 2
      server-go/internal/httpapi/rtlconsole.go
  80. 45 2
      server-go/internal/httpapi/server.go
  81. 23 8
      server-go/internal/httpapi/settings.go
  82. 6 1
      server-go/internal/httpapi/speedtest_api_test.go
  83. 23 6
      server-go/internal/httpapi/thresholds_settings.go
  84. 10 1
      server-go/internal/httpapi/wifi_channelplan.go
  85. 36 5
      server-go/internal/mqttpub/manager.go
  86. 33 10
      server-go/internal/mqttpub/mqttpub.go
  87. 37 0
      server-go/internal/mqttpub/mqttpub_test.go
  88. 4 0
      server-go/internal/ntfy/ntfy.go
  89. 58 21
      server-go/internal/roamevents/collector.go
  90. 80 7
      server-go/internal/roamevents/collector_test.go
  91. 51 6
      server-go/internal/routerstore/routerstore.go
  92. 42 4
      server-go/internal/snmp/ifTable.go
  93. 7 0
      server-go/internal/snmp/oids.go
  94. 42 0
      server-go/internal/snmp/snmp_test.go
  95. 2 1
      server-go/internal/speedtest/http_runner.go
  96. 3 3
      server-go/internal/speedtest/http_runner_test.go
  97. 137 11
      server-go/internal/speedtest/scheduler.go
  98. 1 1
      server-go/internal/speedtest/scheduler744_test.go
  99. 2 1
      server-go/internal/speedtest/speedtest_test.go
  100. 4 0
      server-go/internal/telegram/telegram.go

+ 15 - 0
.gitignore

@@ -9,6 +9,7 @@ app/node_modules
 
 # Backend: datos y secretos
 server/data/
+server-go/data/
 server/.env
 legacy/server-node/data/
 legacy/server-node/.env
@@ -43,3 +44,17 @@ server-go/internal/agentbin/agents/netpulse-agent-*
 # Rutas prerenderizadas por idioma (generadas, ver web/build-langs.mjs)
 web/langs/
 web/node_modules/
+
+plans
+docs/premortem
+
+# Instancia local de pruebas (worktrees dev; #931 arrastró una llave privada
+# generada por la instancia a un commit: gitleaks la cazó en el PR #1117)
+local-data/
+local-server.log
+netpulse-local
+jar.txt
+
+# Binarios de build locales (go build -o en raíz)
+/netpulse
+/netpulse-*

+ 3 - 0
.goreleaser.yaml

@@ -82,6 +82,7 @@ archives:
       {{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}
     files:
       - LICENSE
+      - THIRD_PARTY.md
       - src: server-go/.env.example
         dst: .env.example
 
@@ -92,6 +93,7 @@ archives:
       {{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}
     files:
       - LICENSE
+      - THIRD_PARTY.md
 
   - id: netpulse-agent
     ids: [netpulse-agent]
@@ -100,6 +102,7 @@ archives:
       {{ .Binary }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}
     files:
       - LICENSE
+      - THIRD_PARTY.md
       - src: agent/deploy/netpulse-agent.init
         dst: netpulse-agent.init
 

+ 62 - 0
CHANGELOG.md

@@ -5,6 +5,68 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
+## [2.31.1] - 2026-10-03
+
+### Fixed
+
+- **Alertas que reaparecen leídas tras un reinicio (#1094)**: una alerta ya leída en una sesión anterior (p. ej. "Agent outdated") se mostraba leída al re-emitirse justo tras arrancar el server; ahora un episodio nuevo tras reinicio vuelve a no-leída (los refreshes de un episodio en curso, como port flapping, conservan su estado).
+- **"First seen"/"Last seen" siempre con guion (#1095)**: la marca de visto solo se escribía desde el resumen; la lista de dispositivos que consume la UI ahora también la persiste (write-through).
+- **Eventos de roaming desordenados dentro del mismo segundo (#1097)**: los logs de OpenWrt no llevan millis; el desempate ahora usa el orden de inserción (id), que reproduce el orden del log. Nuevos filtros por cliente y por AP en la vista de eventos.
+- **Tarjeta "Edit client" (#1096)**: Guardar/Cancelar junto a los campos que editan (nombre, tipo, icono) y título renombrado de "dispositivo" a "cliente".
+- **Tooltips en los botones web/SSH de la unidad (#1098)**: muestran la URL y el comando exactos antes de pulsar.
+- **Agente 3.0.8**: una unidad sin clientes asociados en ese momento descartaba toda su sección wireless (radios, scans, BSSIDs propios); radios o BSSIDs propios ya bastan para reportarla.
+
+## [2.31.0] - 2026-10-03
+
+### Added
+
+- **Análisis de canales: de labs a primera clase (#1070, #1076, #1079, #1080, #1082, #1084)** - la página "Canales" es ahora un analizador de espectro WiFi completo y de solo lectura (nunca escribe en los routers): cascada por radio con campanas sobre un eje de frecuencia real, zonas DFS sombreadas con leyenda, franja continua de ocupación, tira de puntuación de TODOS los canales (13 en 2.4 GHz, todos los bloques a su ancho en 5 GHz, DFS etiquetados) agrupada por congestión, tabla ordenable con aislamiento cruzado en el gráfico y selector de flota sin unidades sin WiFi. Sin insignia de labs ni toggle.
+- **Motor de congestión inteligente (#1080, #1082)**: las redes propias nunca congestian un canal (detección por prefijo MAC, transitividad de SSID, datos dawn/usteer y los nuevos BSSIDs propios del agente); las vecinas se ponderan en dominio de potencia (un AP a -50 dBm pesa ~3000x uno a -85); el veredicto de congestión del canal actual es absoluto (umbrales sobre el score), no relativo al resto de la banda. Solo sugiere: recomienda canal y estima la reducción de ruido; aplicarlo sigue en manos del usuario.
+- **Agente 3.0.7 (#1087)**: reporta sus propios BSSIDs (`iw dev`, cubre MACs aleatorizadas y guests fuera de dawn/usteer) y lee el ancho de canal anunciado (HT/VHT operation) de cada vecina, persistido en `wifi_scans.width_mhz`; el espectro dibuja cada red a su ancho real en vez de los 20 MHz estimados.
+
+### Fixed
+
+- La notificación push de "Agent outdated" llevaba la hora estática 16:00:00 (epoch en la zona del servidor) al dispararse tras un reinicio: la rama de inserción de `EmitOrUpdate` notificaba sin el default de timestamp (#1074).
+- El análisis de canales mostraba "este equipo no reporta radios WiFi" cuando el payload del agente estaba momentáneamente fuera de la ventana de frescura; ahora cae al último payload conocido para esa vista de solo lectura (#1080).
+- La tarjeta de resumen proponía un bloque DFS como "mejor canal" al empatar a 100 en la normalización; ahora promociona siempre el canal que recomienda el motor (#1082).
+- El título del documento ("Tu red, de un vistazo") era español fijo en index.html; ahora sigue el idioma de la interfaz.
+
+### Community
+
+- Abiertas las GitHub Discussions del proyecto: sugerencias, preguntas y votos de ideas en https://github.com/gnacho/netpulse/discussions
+
+## [2.30.0] - 2026-10-02
+
+### Added
+
+- **Soporte RouterOS (MikroTik) de primera clase (#969, gracias @samex)**: nuevo tipo de router en la flota, sondeado desde el servidor por la API REST nativa de RouterOS 7+ (vitals reales: CPU/RAM/uptime, métricas WAN, comprobación de actualizaciones), con cliente del API binario (8728) escrito a mano para instalaciones con `www` cerrado: cero dependencias nuevas, login moderno y solo lectura. Contraseña solo en el servidor (`json:"-"`), TLS autofirmado opt-in, y agente `routeros-pusher` opcional.
+- **M-Lab NDT como proveedor de speedtest por defecto (#1037, idea de @crowedavid)**: red de medición neutra y sin ánimo de lucro, con política de datos abierta: mejor privacidad que Ookla o Cloudflare. Las instalaciones con proveedor guardado lo conservan. Nuevo modo de planificación "auto" que ejecuta el test a la hora de menos tráfico según el histórico propio de la red (#1066).
+- **Anclaje de uplinks de flota por evidencia FDB (#1047, #1051, #1060)**: cada unidad cuelga de su padre real (el switch donde su MAC bridge se aprendió, con etiqueta de puerto); si el puerto tiene un círculo de switch (inferido o gestionado), el uplink sale del círculo: gateway → (switch) → AP. Ya no depende de que las unidades aparezcan como devices.
+- **Equipo aguas arriba del gateway bajo el nodo Internet (#1042)**: cuando la IP de un cliente coincide con la puerta de enlace WAN (módem/ONT del ISP), se dibuja colgando de la nube, junto a la línea WAN, en vez de como cliente LAN.
+- **Granularidad horaria y diaria en Informes (#1032, #1033)**: el selector ofrece Horario (buckets por hora) y Diario; el endpoint conserva semanal/mensual para API/CSV.
+- **Retención del registro de alertas y "Vaciar registro" (#1034)**: "Marcar todo como leído" ya no borra del log (solo del read-set); vaciar es una acción aparte, con confirmación, y `alerts.retentionDays` (default 30, poda horaria y de arranque sin reinicio).
+
+### Fixed
+
+- El feed de roaming mostraba solo Disconnect en APs con wpad-mbedtls (OpenWrt 25.12.x), que no emite AP-STA-* (#1038).
+- Pantalla en blanco al cambiar el rango de Informes (#1029).
+- La tarjeta de edición de flota guardaba y cerraba al elegir el tipo; ahora hay etiquetas visibles, firmware target solo para OpenWrt/GL.iNet y sondeo SNMP disponible en el alta (#1026).
+- La tabla de enlaces siempre nombraba al gateway como padre de los uplinks aunque el mapa los dibujara desde un círculo de switch (#1063).
+- Literales en español filtrándose a UIs en inglés en las tarjetas de puertos; los pares inferidos llevan icono de red (#1039, #1040).
+- El matching LLDP exigía igualdad exacta de nombre: "sw1" (chasis) no casaba con "sw1.lan" (flota) y el uplink caía al gateway (#1041).
+- La integración Proxmox duplicaba un switch inferido entre el switch gestionado y los hosts; el inventario PVE (ground truth) lo absorbe (#1053).
+- La segunda instancia Proxmox con id vacío o duplicado pisaba la primera en silencio; el diálogo lo rechaza (#1057).
+- Previsualizaciones al pasar el cursor mientras se edita el layout de topología (#1045), tooltips que saltaban solos al abrir diálogos y marco de foco en la (x) (#1064, #1068), anillo de foco también al hover (#1069), y los diálogos de config cierran al guardar (#1065).
+- El historial de tráfico de un router desbordaba la tarjeta con muchos puertos: selector en desplegable con filtro All/Active/Inactive (#1035).
+
+### Changed
+
+- Las alertas se componen en inglés nativo y se traducen al idioma del cliente (#1014); las notas de release se muestran en el idioma del cliente (#1011).
+- Terminología consolidada: flota/unidad y clientes (#1025, #1027), botón "Detectar" de Proxmox recuperado (#967).
+- Actualización completa de dependencias (#1020 tramos 1 y 2, #1022, #1028).
+
+Gracias a @crowedavid por los reportes que formaron la mayor parte de esta release, a @samex por la integración RouterOS, y a @gnulan, @borky y todos los que reportan y discuten ideas.
+
 ## [2.28.43] - 2026-10-01
 
 ### Added

+ 37 - 2
README.es.md

@@ -85,7 +85,8 @@ en vivo contra tu plan contratado, feed de alertas, estadísticas de AdGuard
 Home y peers WireGuard en la misma pantalla (es la captura de arriba).
 
 **Un mapa de topología que se dibuja solo.** Inferido en vivo del FDB del
-bridge (y de LLDP donde está disponible): clientes cableados e inalámbricos
+bridge (y de LLDP donde está disponible, con LLDP-MIB en los switches
+gestionados por SNMP): clientes cableados e inalámbricos
 bajo el router y el puerto por los que hablan de verdad, switches
 gestionados e inferidos, hosts de Proxmox con sus VMs anidadas y túneles
 WireGuard trazados del peer a Internet. Los dispositivos callados conservan
@@ -116,7 +117,8 @@ y entérate cuando aparece algo nuevo.
 **Salud por router, de un vistazo.** Modelo, firmware, CPU, memoria,
 temperatura, uptime y tráfico en vivo de cada router, con historial por
 puerto y desglose de clientes por banda. Los switches gestionados sondeados
-por SNMP también son ciudadanos de primera.
+por SNMP también son ciudadanos de primera, y cualquier unidad se puede
+pausar sin borrarla: sin sondeo ni alertas, con su histórico intacto.
 
 <p align="center">
   <picture>
@@ -134,6 +136,17 @@ por SNMP también son ciudadanos de primera.
   más bloqueados.
 - **Wi-Fi y roaming**: matriz de señal por AP, estado 802.11r, utilización
   por canal, eventos de roaming persistentes.
+- **Analizador de canales WiFi**: un espectro real por radio, cada red dibujada
+  sobre el eje de frecuencias con puntuación de congestión por canal. Lee el
+  aire y aconseja; nunca escribe en tus routers.
+- **Actualizaciones de firmware de la flota**: actualiza dispositivos OpenWrt
+  desde la UI, solo OpenWrt vanilla (lista filtrada, con nota explicativa).
+- **Rack físico (preview en Labs)**: dibuja tu rack de 19", coloca tu hardware
+  y deja que NetPulse proponga el cableado desde la topología detectada.
+  Apagado por defecto.
+- **Asistente IA (MCP)**: un servidor MCP integrado de solo lectura que tu
+  asistente consulta con un token de API (ver
+  [Asistentes de IA](#asistentes-de-ia-mcp)).
 - **Alertas que te encuentran**: temperatura, dispositivo nuevo, firmware
   disponible, WAN caída, problemas de agente; feed en la campana más canales
   de aviso (Web Push nativo, ntfy, Telegram y webhook saliente). Los canales
@@ -294,6 +307,28 @@ OpenWrt deberían funcionar, pero el tuyo sería el primero en contarlo.
 - **[Discusiones](https://github.com/gnacho/netpulse/discussions)**:
   preguntas, ideas y hablar del futuro.
 
+## Asistentes de IA (MCP)
+
+NetPulse lleva un servidor [MCP](https://modelcontextprotocol.io) embebido
+(streamable-HTTP) para que los asistentes de IA puedan consultar tu instancia
+con herramientas de solo lectura: estado de la flota, salud por router,
+dispositivos conocidos, peers WireGuard, estadísticas de AdGuard Home, el
+grafo de topología detectado y las alertas activas. Nada más: sin cambios de
+configuración ni reinicios.
+
+Es experimental y vive bajo el flag de Labs en Ajustes. Está **desactivado por defecto**. Para activarlo:
+
+```bash
+NETPULSE_MCP_ENABLED=1
+```
+
+Después crea un token de API en Ajustes > Tokens de API y apunta tu cliente
+MCP a `http://<host-de-netpulse>:<puerto>/mcp` con ese token como Bearer. El
+endpoint solo acepta tokens de API (nunca la cookie de sesión), lleva rate
+limit y cada llamada a tool queda registrada en el log de auditoría. Mantén
+el puerto en tu LAN o detrás de un firewall: quien tenga el token puede leer
+el estado completo de tu red.
+
 ## Desarrollo
 
 ```bash

+ 36 - 2
README.md

@@ -83,7 +83,8 @@ contracted plan, alert feed, AdGuard Home stats and WireGuard peers on the
 same screen (that's the screenshot above).
 
 **A topology map that draws itself.** Inferred live from the bridge FDB (and
-LLDP where available): wired and wireless clients under the router and port
+LLDP where available, including LLDP-MIB on SNMP-managed switches): wired and
+wireless clients under the router and port
 they actually talk through, managed and inferred switches, Proxmox hosts with
 their VMs nested, and WireGuard tunnels drawn from peer to Internet. Quiet
 devices keep their place; nothing jumps around on refresh. Drag nodes to
@@ -112,7 +113,9 @@ new shows up.
 
 **Per-router health at a glance.** Model, firmware, CPU, memory, temperature,
 uptime and live traffic for each router, with port-level history and per-band
-client splits. SNMP-polled managed switches are first-class citizens too.
+client splits. SNMP-polled managed switches are first-class citizens too, and
+any unit can be paused without removing it: no polling, no alerts, history
+kept.
 
 <p align="center">
   <picture>
@@ -128,6 +131,16 @@ client splits. SNMP-polled managed switches are first-class citizens too.
 - **AdGuard Home**: query stats, blocked share, top blocked domains.
 - **Wi-Fi and roaming**: signal matrix per AP, 802.11r status, channel
   utilization, persistent roaming events.
+- **Wi-Fi channel analyzer**: a real spectrum per radio, every network drawn on
+  the frequency axis with a congestion score for every channel. It reads the
+  air and advises; it never writes to your routers.
+- **Fleet firmware upgrades**: upgrade OpenWrt devices from the UI, vanilla
+  OpenWrt only (device list filtered, with an explanatory note).
+- **Physical rack (Labs preview)**: draw your 19" rack, place your hardware and
+  let NetPulse propose the cabling from the detected topology. Off by default.
+- **AI assistant (MCP)**: an embedded read-only MCP server your assistant can
+  query with an API token (see
+  [AI assistants](#ai-assistants-mcp)).
 - **Alerts that find you**: temperature, new device, firmware available, WAN
   down, agent issues; bell feed plus notification channels (native Web Push,
   ntfy, Telegram and outgoing webhook). Notification channels only carry
@@ -284,6 +297,27 @@ first to tell.
 - **[Discussions](https://github.com/gnacho/netpulse/discussions)**: questions,
   ideas and shape-the-future talk.
 
+## AI assistants (MCP)
+
+NetPulse ships an embedded [MCP](https://modelcontextprotocol.io) server
+(streamable-HTTP) so AI assistants can query your instance with read-only
+tools: fleet status, per-router health, known devices, WireGuard peers,
+AdGuard Home stats, the detected topology graph and active alerts. Nothing
+else: no configuration changes, no restarts.
+
+It is experimental and lives under the Labs flag in Settings. It is **disabled by default**. To enable it:
+
+```bash
+NETPULSE_MCP_ENABLED=1
+```
+
+Then create an API token in Settings > API tokens and point your MCP client
+at `http://<your-netpulse-host>:<port>/mcp` with that token as the Bearer
+token. The endpoint only accepts API tokens (never the session cookie), is
+rate limited, and every tool call is logged for audit. Keep the port on your
+LAN or behind a firewall: anyone with the token can read your whole network
+state.
+
 ## Development
 
 ```bash

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.5
+3.0.8

+ 11 - 0
agent/probe/local.go

@@ -417,6 +417,10 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 				wd.Scans = ParseScan(out)
 			}
 		}
+		// BSSIDs propios (#1087): `iw dev` sin scan, barato y estable.
+		if out := p.runBest(ctx, CmdIwDev, 5*time.Second); out != "" {
+			wd.OwnBssids = ParseIwDev(out)
+		}
 	} else {
 		p.radiosMu.Lock()
 		cached := p.radiosCache
@@ -429,6 +433,13 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 		}
 	}
 
+	// #1092: `any` lo marcaban solo los CLIENTES: una unidad sin clientes
+	// asociados en ese momento descartaba TODA la sección wireless (radios,
+	// scans, BSSIDs propios) y el server la veía como "sin WiFi". Que haya
+	// radios o BSSIDs propios también prueba presencia wireless.
+	if !any && (len(wd.Radios) > 0 || len(wd.OwnBssids) > 0) {
+		any = true
+	}
 	if !any {
 		return nil
 	}

+ 16 - 0
agent/probe/payload.go

@@ -113,6 +113,18 @@ type WirelessData struct {
 	// Scans: redes vecinas vistas por cada interfaz WiFi (Fase 18/#452).
 	// nil/ausente = el scan no se pudo realizar en este push.
 	Scans []ScanResult `json:"scans,omitempty"`
+	// OwnBssids: BSSIDs de las interfaces AP de ESTE equipo (#1087), de
+	// `iw dev`. El server los usa de semilla exacta para no contar las
+	// propias redes como vecinas (casos con MAC aleatorizada o guest cuya
+	// MAC no casa con routers.mac). nil con agentes antiguos.
+	OwnBssids []OwnBSSID `json:"ownBssids,omitempty"`
+}
+
+// OwnBSSID: una interfaz AP local con su BSSID y SSID (#1087).
+type OwnBSSID struct {
+	Iface  string `json:"iface"`
+	BSSID  string `json:"bssid"` // MAC en mayúsculas
+	SSID   string `json:"ssid"`  // puede estar vacío
 }
 
 // ScanResult es un AP vecino detectado por un scan pasivo.
@@ -123,6 +135,10 @@ type ScanResult struct {
 	Channel int    `json:"channel"` // canal numérico
 	Freq    int    `json:"freq"`    // frecuencia en MHz
 	Signal  int    `json:"signal"`  // dBm (negativo)
+	// WidthMhz: ancho de canal anunciado (HT/VHT operation del scan, #1087).
+	// 0 con agentes antiguos o BSS sin esos bloques: la UI usa 20 MHz de
+	// fallback en ese caso.
+	WidthMhz int `json:"widthMhz,omitempty"`
 }
 
 // DHCPData: leases ipv4 (mac en mayúsculas) + clientes GL.iNet.

+ 86 - 0
agent/probe/probe.go

@@ -84,6 +84,10 @@ const (
 	// emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
 	// Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
 	CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
+	// CmdIwDev (#1087): `iw dev` a secas, sin scan. Lista las interfaces con
+	// su MAC y SSID: fuente de los BSSIDs propios para el análisis de
+	// canales. Barato (no saca la radio del canal).
+	CmdIwDev = "iw dev 2>/dev/null"
 	// 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="`
@@ -1492,10 +1496,21 @@ func ParseScan(out string) []ScanResult {
 	var res []ScanResult
 	iface := ""
 	var current *ScanResult
+	// Estado del bloque HT/VHT en curso para el ancho de canal (#1087).
+	section := ""
+	ht40, vhtWidth := false, 0
 	flush := func() {
 		if current != nil && current.BSSID != "" && current.Freq > 0 {
 			current.Channel = FreqToChannel(current.Freq)
 			if current.Channel > 0 {
+				switch {
+				case vhtWidth > 0:
+					current.WidthMhz = vhtWidth
+				case ht40:
+					current.WidthMhz = 40
+				default:
+					current.WidthMhz = 20
+				}
 				res = append(res, *current)
 			}
 		}
@@ -1516,11 +1531,43 @@ func ParseScan(out string) []ScanResult {
 			}
 			bssid := strings.ToUpper(strings.Split(fields[1], "(")[0])
 			current = &ScanResult{Iface: iface, BSSID: bssid}
+			section, ht40, vhtWidth = "", false, 0
 			continue
 		}
 		if current == nil {
 			continue
 		}
+		// Ancho de canal anunciado por el vecino (#1087): HT operation da
+		// el salto de 40 MHz; VHT operation el de 80/160.
+		switch {
+		case strings.HasPrefix(line, "HT operation:"):
+			section = "ht"
+			continue
+		case strings.HasPrefix(line, "VHT operation:"):
+			section = "vht"
+			continue
+		case strings.HasPrefix(line, "HE operation:") || strings.HasPrefix(line, "EHT operation:"):
+			section = ""
+			continue
+		}
+		if section == "ht" && strings.Contains(line, "secondary channel offset:") {
+			ht40 = !strings.Contains(line, "no secondary")
+			continue
+		}
+		if section == "vht" && strings.Contains(line, "channel width:") {
+			// "* channel width: 1 (80 MHz)": 1 = 80 MHz, 2 = 160 MHz.
+			re := vhtWidthRe.FindStringSubmatch(line)
+			if re != nil {
+				n, _ := strconv.Atoi(re[1])
+				switch n {
+				case 1:
+					vhtWidth = 80
+				case 2:
+					vhtWidth = 160
+				}
+			}
+			continue
+		}
 		if strings.HasPrefix(line, "freq:") {
 			// iw imprime la frecuencia como float ("freq: 5260.0"): Atoi
 			// fallaba en silencio, Freq quedaba 0 y el flush descartaba TODOS
@@ -1544,6 +1591,45 @@ func ParseScan(out string) []ScanResult {
 	return res
 }
 
+var vhtWidthRe = regexp.MustCompile(`channel width:\s*(\d)\s*\(`)
+
+// ParseIwDev parsea la salida de CmdIwDev (`iw dev`) y devuelve las
+// interfaces AP de ESTE equipo con su BSSID y SSID (#1087). Los bloques
+// "Interface <name>" traen addr, ssid y type; solo type AP interesa (los
+// STA/clientes managed no son red propia).
+func ParseIwDev(out string) []OwnBSSID {
+	var res []OwnBSSID
+	iface, addr, ssid, ifType := "", "", "", ""
+	flush := func() {
+		if iface != "" && addr != "" && ifType == "AP" {
+			res = append(res, OwnBSSID{Iface: iface, BSSID: strings.ToUpper(addr), SSID: ssid})
+		}
+	}
+	for _, raw := range strings.Split(out, "\n") {
+		line := strings.TrimSpace(raw)
+		fields := strings.Fields(line)
+		if len(fields) >= 2 && fields[0] == "Interface" {
+			flush()
+			iface, addr, ssid, ifType = fields[1], "", "", ""
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "addr" {
+			addr = fields[1]
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "ssid" {
+			ssid = strings.TrimSpace(strings.TrimPrefix(line, "ssid"))
+			continue
+		}
+		if len(fields) >= 2 && fields[0] == "type" {
+			ifType = fields[1]
+			continue
+		}
+	}
+	flush()
+	return res
+}
+
 // FreqToChannel convierte frecuencia (MHz) a número de canal 802.11.
 func FreqToChannel(freq int) int {
 	switch {

+ 122 - 0
agent/probe/probe_test.go

@@ -465,6 +465,40 @@ func TestParseFdbDenylistPuertos(t *testing.T) {
 // Prober local con runner fake
 // ---------------------------------------------------------------------------
 
+// TestProberWirelessWithoutClients (#1092): una unidad SIN clientes
+// asociados conserva la sección wireless (radios + BSSIDs propios); antes
+// el flag de presencia solo consideraba clientes y el server la veía como
+// "sin WiFi" (encontrado en un AP lab de NetGrip).
+func TestProberWirelessWithoutClients(t *testing.T) {
+	run := fakeRunner{outs: map[string]string{
+		CmdUbusSystemInfo:  `{"uptime":90061,"load":[0.1,0.2,0.3],"memory":{"total":256000000,"free":100000000,"buffered":0,"available":128000000}}`,
+		CmdUbusSystemBoard: `{"model":"GL.iNet Lab","hostname":"lab","release":{"version":"25.12","description":"OpenWrt 25.12"}}`,
+		CmdProcStat:        "cpu  4705 356 584 3699 23 0 23 0 0 0\n",
+		CmdTemp:            "43500\n",
+		CmdNetDev:          "  eth0: 1000000 0 0 0 0 0 0 0 500000 0\n",
+		CmdBridgeMAC:       "94:83:c4:00:00:09\n",
+		// Sin clientes: ningún comando de assoclist/ubus hostapd.
+		CmdRadios:   "2.4|6|HT20|20|0\n",
+		CmdDhcpFile: "1700000000 ec:71:db:44:12:8a 192.168.8.71 movil *\n",
+		CmdBridgeFDB: "==PORTS==\n0x1 lan1\n==MACS==\n1 ec:71:db:44:12:8a\n",
+		CmdPortStates: "lan1 up 1000\nwan down -1\n",
+		CmdUbusWireless: `{"radio0":{"up":true,"interfaces":[{"ifname":"wlan0","config":{"mode":"ap"}}]}}`,
+		CmdIwDev: "phy#0\n\tInterface wlan0\n\t\taddr 62:e5:56:b6:94:bd\n\t\tssid temiscira\n\t\ttype AP\n",
+	}}
+	p := NewProber(run, Options{GwPingTarget: "192.168.8.1", ScanInterval: ScanDisabled})
+
+	pl := p.Build(context.Background(), "lab", "3.0.7")
+	if pl.Data.Wireless == nil {
+		t.Fatal("sin clientes la sección wireless no debe descartarse (#1092)")
+	}
+	if len(pl.Data.Wireless.OwnBssids) != 1 || pl.Data.Wireless.OwnBssids[0].SSID != "temiscira" {
+		t.Fatalf("ownBssids perdidos: %+v", pl.Data.Wireless.OwnBssids)
+	}
+	if len(pl.Data.Wireless.Radios) != 1 {
+		t.Fatalf("radios perdidas: %+v", pl.Data.Wireless.Radios)
+	}
+}
+
 type fakeRunner struct{ outs map[string]string }
 
 func (f fakeRunner) Run(_ context.Context, cmd string, _ time.Duration) (string, error) {
@@ -936,6 +970,94 @@ func TestParseUsteer(t *testing.T) {
 }
 
 // TestParseScanExtraeVecinos (#452): parsea la salida de `iw dev` scan.
+func TestParseScanWidthMhz(t *testing.T) {
+	// Bloques HT/VHT reales de `iw dev wlan0 scan` (OpenWrt).
+	out := `==IFACE==wlan0
+BSS 11:22:33:44:55:66(on wlan0)
+	freq: 2437
+	signal: -55.00 dBm
+	SSID: ochenta
+	HT operation:
+		 * primary channel: 6
+		 * secondary channel offset: below
+	VHT operation:
+		 * channel width: 1 (80 MHz)
+BSS aa:bb:cc:dd:ee:ff(on wlan0)
+	freq: 2462
+	signal: -70.00 dBm
+	SSID: cuarenta
+	HT operation:
+		 * primary channel: 11
+		 * secondary channel offset: above
+BSS 22:33:44:55:66:77(on wlan0)
+	freq: 2412
+	signal: -80.00 dBm
+	SSID: veinte
+	HT operation:
+		 * primary channel: 1
+		 * secondary channel offset: no secondary
+BSS 33:44:55:66:77:88(on wlan0)
+	freq: 5500
+	signal: -60.00 dBm
+	SSID: ciento60
+	HT operation:
+		 * primary channel: 100
+		 * secondary channel offset: below
+	VHT operation:
+		 * channel width: 2 (160 MHz)
+`
+	got := ParseScan(out)
+	widths := map[string]int{}
+	for _, s := range got {
+		widths[s.SSID] = s.WidthMhz
+	}
+	if widths["ochenta"] != 80 || widths["cuarenta"] != 40 || widths["veinte"] != 20 || widths["ciento60"] != 160 {
+		t.Fatalf("anchos inesperados: %+v de %+v", widths, got)
+	}
+}
+
+func TestParseIwDev(t *testing.T) {
+	out := `phy#0
+	Interface wlan0
+		ifindex 12
+		wdev 0x200000000
+		addr 62:e5:56:b6:94:bd
+		ssid temiscira
+		type AP
+		channel 6 (2437 MHz), width: 80 MHz, center1: 2437 MHz
+		txpower 20.00 dBm
+	Interface wlan0-1
+		ifindex 13
+		wdev 0x200000001
+		addr 6a:e5:56:b6:94:bd
+		ssid temiscira-guest
+		type AP
+		channel 6 (2437 MHz), width: 20 MHz, center1: 2437 MHz
+	Interface wlan1
+		ifindex 14
+		wdev 0x200000002
+		addr 62:e5:56:b6:94:be
+		ssid temiscira
+		type AP
+		channel 36 (5180 MHz), width: 80 MHz, center1: 5210 MHz
+phy#1
+	Interface uap0
+		ifindex 20
+		addr 62:e5:56:b6:94:bf
+		type managed
+`
+	got := ParseIwDev(out)
+	if len(got) != 3 {
+		t.Fatalf("esperaba 3 APs (uap0 managed fuera): %+v", got)
+	}
+	if got[0].BSSID != "62:E5:56:B6:94:BD" || got[0].SSID != "temiscira" || got[0].Iface != "wlan0" {
+		t.Fatalf("bloque 0 mal parseado: %+v", got[0])
+	}
+	if got[1].SSID != "temiscira-guest" {
+		t.Fatalf("guest sin capturar: %+v", got[1])
+	}
+}
+
 func TestParseScanExtraeVecinos(t *testing.T) {
 	out := `==IFACE==wlan0
 BSS 00:11:22:33:44:55(on wlan0)

+ 1 - 1
app/index.html

@@ -17,7 +17,7 @@
       href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap"
       rel="stylesheet"
     />
-    <title>NetPulse - Tu red, de un vistazo</title>
+    <title>NetPulse</title>
     <link rel="stylesheet" href="/src/splash.css" />
     <script src="/boot.js"></script>
   </head>

+ 179 - 2
app/package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "netpulse",
-  "version": "2.28.43",
+  "version": "2.31.1",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "netpulse",
-      "version": "2.28.43",
+      "version": "2.31.1",
       "dependencies": {
         "@hookform/resolvers": "^5.9.1",
         "@radix-ui/react-accordion": "^1.2.12",
@@ -35,6 +35,7 @@
         "@radix-ui/react-toggle": "^1.1.10",
         "@radix-ui/react-toggle-group": "^1.1.11",
         "@radix-ui/react-tooltip": "^1.2.8",
+        "@xyflow/react": "^12.12.0",
         "class-variance-authority": "^0.7.1",
         "clsx": "^2.1.1",
         "cmdk": "^1.1.1",
@@ -4500,6 +4501,15 @@
       "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
       "license": "MIT"
     },
+    "node_modules/@types/d3-drag": {
+      "version": "3.0.7",
+      "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
+      "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-selection": "*"
+      }
+    },
     "node_modules/@types/d3-ease": {
       "version": "3.0.2",
       "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
@@ -4530,6 +4540,12 @@
         "@types/d3-time": "*"
       }
     },
+    "node_modules/@types/d3-selection": {
+      "version": "3.0.12",
+      "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.12.tgz",
+      "integrity": "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==",
+      "license": "MIT"
+    },
     "node_modules/@types/d3-shape": {
       "version": "3.1.8",
       "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
@@ -4551,6 +4567,25 @@
       "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
       "license": "MIT"
     },
+    "node_modules/@types/d3-transition": {
+      "version": "3.0.9",
+      "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
+      "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-selection": "*"
+      }
+    },
+    "node_modules/@types/d3-zoom": {
+      "version": "3.0.9",
+      "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.9.tgz",
+      "integrity": "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-interpolate": "*",
+        "@types/d3-selection": "*"
+      }
+    },
     "node_modules/@types/esrecurse": {
       "version": "4.3.1",
       "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@@ -5283,6 +5318,48 @@
         }
       }
     },
+    "node_modules/@xyflow/react": {
+      "version": "12.12.0",
+      "resolved": "https://registry.npmjs.org/@xyflow/react/-/react-12.12.0.tgz",
+      "integrity": "sha512-74oXI0Rgm1Eu33cHQAd74J6oVgCH9mbFyTVQbsGgp2kmWwh0HdtBr2VP04z8mbPD+M/xO69nqG5dDEt7/EN2rQ==",
+      "license": "MIT",
+      "dependencies": {
+        "@xyflow/system": "0.0.83",
+        "classcat": "^5.0.3",
+        "zustand": "^4.4.0"
+      },
+      "peerDependencies": {
+        "@types/react": ">=17",
+        "@types/react-dom": ">=17",
+        "react": ">=17",
+        "react-dom": ">=17"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        },
+        "@types/react-dom": {
+          "optional": true
+        }
+      }
+    },
+    "node_modules/@xyflow/system": {
+      "version": "0.0.83",
+      "resolved": "https://registry.npmjs.org/@xyflow/system/-/system-0.0.83.tgz",
+      "integrity": "sha512-a//eDjez3WZF47aaPTfVUDD0OINOq+WVwBZCRTqG+m0a5euX8EwlJ4jMY1Wxz0Ocj4xOeekJ70V22Pq0ll8RJw==",
+      "license": "MIT",
+      "dependencies": {
+        "@types/d3-drag": "^3.0.7",
+        "@types/d3-interpolate": "^3.0.4",
+        "@types/d3-selection": "^3.0.10",
+        "@types/d3-transition": "^3.0.8",
+        "@types/d3-zoom": "^3.0.8",
+        "d3-drag": "^3.0.0",
+        "d3-interpolate": "^3.0.1",
+        "d3-selection": "^3.0.0",
+        "d3-zoom": "^3.0.0"
+      }
+    },
     "node_modules/acorn": {
       "version": "8.18.0",
       "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
@@ -5656,6 +5733,12 @@
         "url": "https://polar.sh/cva"
       }
     },
+    "node_modules/classcat": {
+      "version": "5.0.5",
+      "resolved": "https://registry.npmjs.org/classcat/-/classcat-5.0.5.tgz",
+      "integrity": "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==",
+      "license": "MIT"
+    },
     "node_modules/clsx": {
       "version": "2.1.1",
       "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -5766,6 +5849,28 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-dispatch": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
+      "integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=12"
+      }
+    },
+    "node_modules/d3-drag": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
+      "integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-dispatch": "1 - 3",
+        "d3-selection": "3"
+      },
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/d3-ease": {
       "version": "3.0.1",
       "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
@@ -5821,6 +5926,15 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-selection": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
+      "integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
+      "license": "ISC",
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/d3-shape": {
       "version": "3.2.0",
       "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
@@ -5866,6 +5980,41 @@
         "node": ">=12"
       }
     },
+    "node_modules/d3-transition": {
+      "version": "3.0.1",
+      "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
+      "integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-color": "1 - 3",
+        "d3-dispatch": "1 - 3",
+        "d3-ease": "1 - 3",
+        "d3-interpolate": "1 - 3",
+        "d3-timer": "1 - 3"
+      },
+      "engines": {
+        "node": ">=12"
+      },
+      "peerDependencies": {
+        "d3-selection": "2 - 3"
+      }
+    },
+    "node_modules/d3-zoom": {
+      "version": "3.0.0",
+      "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
+      "integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
+      "license": "ISC",
+      "dependencies": {
+        "d3-dispatch": "1 - 3",
+        "d3-drag": "2 - 3",
+        "d3-interpolate": "1 - 3",
+        "d3-selection": "2 - 3",
+        "d3-transition": "2 - 3"
+      },
+      "engines": {
+        "node": ">=12"
+      }
+    },
     "node_modules/data-view-buffer": {
       "version": "1.0.2",
       "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
@@ -10555,6 +10704,34 @@
       "peerDependencies": {
         "zod": "^3.25.0 || ^4.0.0"
       }
+    },
+    "node_modules/zustand": {
+      "version": "4.5.7",
+      "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
+      "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
+      "license": "MIT",
+      "dependencies": {
+        "use-sync-external-store": "^1.2.2"
+      },
+      "engines": {
+        "node": ">=12.7.0"
+      },
+      "peerDependencies": {
+        "@types/react": ">=16.8",
+        "immer": ">=9.0.6",
+        "react": ">=16.8"
+      },
+      "peerDependenciesMeta": {
+        "@types/react": {
+          "optional": true
+        },
+        "immer": {
+          "optional": true
+        },
+        "react": {
+          "optional": true
+        }
+      }
     }
   }
 }

+ 2 - 1
app/package.json

@@ -1,7 +1,7 @@
 {
   "name": "netpulse",
   "private": true,
-  "version": "2.28.43",
+  "version": "2.31.1",
   "type": "module",
   "scripts": {
     "dev": "vite",
@@ -37,6 +37,7 @@
     "@radix-ui/react-toggle": "^1.1.10",
     "@radix-ui/react-toggle-group": "^1.1.11",
     "@radix-ui/react-tooltip": "^1.2.8",
+    "@xyflow/react": "^12.12.0",
     "class-variance-authority": "^0.7.1",
     "clsx": "^2.1.1",
     "cmdk": "^1.1.1",

+ 230 - 38
app/public/locales/en/translation.json

@@ -18,6 +18,10 @@
     "filterBySeverity": "Filter by severity",
     "loadingOld": "Loading older alerts…",
     "markAllRead": "Mark all as read",
+    "clearLog": "Clear log",
+    "clearLogTitle": "Clear the alert log?",
+    "clearLogDesc": "All alert log entries will be deleted from the server and the history view. This cannot be undone. To just clean the view, use \"Unread only\" or mark all as read.",
+    "clearLogConfirm": "Clear log",
     "moreActions": "More actions",
     "noMoreEvents": "No more alerts",
     "onlyUnread": "Unread only",
@@ -332,7 +336,8 @@
     "status": {
       "online": "Online",
       "warn": "Warning",
-      "offline": "Offline"
+      "offline": "Offline",
+      "paused": "Paused"
     },
     "temperature": "Temperature",
     "today": "today",
@@ -349,7 +354,8 @@
     "save": "Save",
     "never": "never",
     "notFound": "Page not found",
-    "tunnelIp": "Tunnel IP"
+    "tunnelIp": "Tunnel IP",
+    "roleExternal": "External"
   },
   "devices": {
     "badges": {
@@ -414,7 +420,7 @@
     "leaseMinutes": "{{minutes}}min",
     "leaseUnlimited": "unlimited",
     "edit": {
-      "title": "Edit device",
+      "title": "Edit client",
       "action": "Edit",
       "name": "Name",
       "nameHint": "Empty = automatic name (DHCP hostname)",
@@ -428,6 +434,15 @@
       "banTitle": "Block bands",
       "banHint": "Coming soon: block this device from 2.4/5/6 GHz networks.",
       "demoNotice": "Demo mode: changes are only saved in this browser.",
+      "linkedMacs": "Linked MACs",
+      "linkPlaceholder": "Link another client…",
+      "link": "Link",
+      "unlink": "Unlink",
+      "dangerZone": "Danger zone",
+      "delete": "Delete client",
+      "deleteTitle": "Delete this client?",
+      "deleteDesc": "Removes the client from the saved list. If the device is seen on the network again it will be re-discovered.",
+      "deleteConfirmDesc": "{{name}} will be removed from the saved clients list. If it shows up on the network again it will be re-discovered.",
       "reserveTitle": "Reserve IP",
       "reserveHint": "No DHCP reservation on gateway.",
       "reservedAs": "Reserved as {{ip}}",
@@ -448,6 +463,12 @@
       "planRun": "Run and apply",
       "planNone": "Nothing to apply"
     },
+    "suggestions": {
+      "title": "Possible duplicate clients",
+      "desc": "These clients share hostname and IP and are never seen at the same time: they may be one device with multiple MACs. Link them to show a single row.",
+      "link": "Link",
+      "dismiss": "Dismiss"
+    },
     "new": "New",
     "onlyOnline": "Only online",
     "onlineAll": "All",
@@ -615,7 +636,8 @@
     "orchestration": "Orchestration",
     "channelPlan": "Channels",
     "firmwareUpgrades": "Firmware upgrades",
-    "help": "Help"
+    "help": "Help",
+    "rack": "Rack"
   },
   "roaming": {
     "subtitle": "Roaming and WiFi mesh status",
@@ -625,7 +647,7 @@
     "empty": "No router has usteer enabled. Install it on OpenWrt to see the roaming mesh.",
     "tabMatrix": "Matrix",
     "tab11r": "802.11r",
-    "tabSurvey": "Channel analysis",
+    "tabSurvey": "Current channels",
     "tabEvents": "Events",
     "comingSoon": "Coming soon",
     "matrix": {
@@ -716,7 +738,11 @@
       "connected": "Connected",
       "disconnected": "Disconnected",
       "dawn": "DAWN",
-      "other": "Other"
+      "other": "Other",
+      "filterAp": "AP",
+      "filterApAll": "All APs",
+      "filterClient": "Client",
+      "filterClientAll": "All clients"
     },
     "tabsLabel": "Roaming views",
     "daemon": {
@@ -803,6 +829,7 @@
     },
     "latency": {
       "24h": "Latency 24 h",
+      "noData": "No probe data yet: it needs the fleet agent or SSH on the unit.",
       "aria": "Latency {{ms}} ms {{caption}}",
       "toHost": "to {{host}}"
     },
@@ -864,7 +891,13 @@
       "detailRouterLinkLldp": "link between routers · LLDP",
       "detailApWifi": "WiFi client behind",
       "detailMac": "MAC {{mac}}",
-      "inferredSwitch": "Switch"
+      "inferredSwitch": "Switch",
+      "virtualGroup": "Virtual interfaces ({{count}})",
+      "fam_lag": "LAG",
+      "fam_vlan": "VLAN",
+      "fam_bridge": "Bridge",
+      "fam_tunnel": "Tunnel",
+      "fam_virtual": "Virtual"
     },
     "radios": {
       "channel": "Channel",
@@ -1334,6 +1367,9 @@
       "unitsTitle": "Measurement units",
       "tempUnit": "Temperature",
       "limitHistory": "Limit history",
+      "alertRetention": "Alert log retention",
+      "alertRetentionCaption": "Entries older than this many days are pruned",
+      "alertRetentionHint": "Days the server keeps each alert log entry (pruned hourly, in addition to the 500-entry cap). 0 keeps them with no time limit.",
       "limitHistoryCaption": "Prunes old presence and roaming events",
       "limitHistoryHint": "When on, the server prunes events older than the configured retention every hour. When off, retention is unlimited (the history grows unpruned). The roaming ingest interval is independent and always applies.",
       "limitHistoryDialog": "History limits",
@@ -1489,7 +1525,14 @@
       "tempThresholdHint": "High-temperature alert threshold. Empty = 65 °C by default. A router that runs hotter can raise its own without hiding issues in cooler ones.",
       "openWrtBadge": "OpenWrt",
       "consolePolling": "Console polling",
-      "consolePollingHint": "The server logs into the switch web UI to read firmware, uptime and MAC. The firmware console allows a single session: every poll kicks whoever is logged in. Disable it if it kicks you out (with beacon v1.3+ the data arrives via UDP anyway)."
+      "consolePollingHint": "The server logs into the switch web UI to read firmware, uptime and MAC. The firmware console allows a single session: every poll kicks whoever is logged in. Disable it if it kicks you out (with beacon v1.3+ the data arrives via UDP anyway).",
+      "routerosUser": "RouterOS user",
+      "routerosPassword": "RouterOS password",
+      "routerosPasswordPlaceholder": "Leave blank to keep current",
+      "routerosInsecure": "Accept self-signed TLS certificate",
+      "disabled": "Paused",
+      "disabledHint": "Not polled, no alerts; history is kept. The Paused badge marks it in the fleet and it drops out of dropdowns.",
+      "disabledBadge": "Paused"
     },
     "overrides": {
       "title": "Topology — manual tagging",
@@ -1540,13 +1583,11 @@
       "dismiss": "Dismiss",
       "deleteTitle": "Revoke device token",
       "deleteDesc": "The token for “{{slug}}” will be revoked. The scraper will stop sending data until you regenerate the token.",
-      "canales": "Channels",
-      "canalesCaption": "WiFi channel planner (LABS)",
-      "actualizaciones": "Firmware upgrades",
-      "actualizacionesCaption": "Firmware upgrades (LABS)",
       "regenToken": "Regenerate token",
       "regenTokenCaption": "Rotate external agent token (LABS)",
-      "badge": "LABS"
+      "badge": "LABS",
+      "rack": "Rack canvas",
+      "rackCaption": "Draw your rack and detect cables. Off by default; do not use in production."
     },
     "saved": "Preferences saved",
     "services": {
@@ -1559,9 +1600,11 @@
       "labsCaption": "In development. They write to your routers",
       "orchestrationHint": "Manage routers from the UI (AdGuard, guest Wi-Fi, DDNS…)",
       "networkGroup": "Network services",
+      "firmwareUpgradesCaption": "Show or hide the firmware upgrades page",
       "integrationsGroup": "Integrations",
       "proxmoxCaption": "Cluster inventory (hypervisors and CTs)",
       "mqttCaption": "Fleet state published to the MQTT broker",
+      "mcpCaption": "Read-only queries for AI assistants (labs)",
       "configure": "Configure {{name}}"
     },
     "session": {
@@ -1658,7 +1701,7 @@
       "caption": "Real periodic measurement from the server",
       "enabled": "Periodic test enabled",
       "provider": "Test provider",
-      "providerHint": "Measurement method. Speedtest.net uses the Ookla server network; Cloudflare measures over HTTP against speed.cloudflare.com; LibreSpeed uses your own or a public instance (you need its URL); Custom measures against the URL you provide (it must accept GET for download and POST for upload). Try another one if the default result does not match your line.",
+      "providerHint": "Measurement method. Speedtest.net uses the Ookla server network; Cloudflare measures over HTTP against speed.cloudflare.com; LibreSpeed uses your own or a public instance (you need its URL); Custom measures against the URL you provide (it must accept GET for download and POST for upload). Try another one if the default result does not match your line. M-Lab NDT measures against the consortium public servers (nearest one auto-detected).",
       "providerOokla": "Speedtest.net (Ookla)",
       "providerCloudflare": "Cloudflare",
       "providerLibrespeed": "LibreSpeed",
@@ -1686,6 +1729,7 @@
       "lastResult": "Last test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "Not available in this mode",
       "kindInterval": "Every N hours",
+      "kindAuto": "Automatic (quietest hour)",
       "kindWeekly": "Weekly (day and time)",
       "kindMonthly": "Monthly (day and time)",
       "everyLabel": "Every:",
@@ -1704,7 +1748,9 @@
       "originManual": "Manual",
       "colServer": "Server",
       "noRecent": "No tests recorded yet",
-      "recentHide": "Hide"
+      "recentHide": "Hide",
+      "providerNdt": "M-Lab NDT",
+      "ndtPlaceholder": "Optional: M-Lab server FQDN (empty = auto-detect)"
     },
     "proxmox": {
       "title": "Proxmox VE",
@@ -1723,6 +1769,8 @@
       "add": "Add instance",
       "delete": "Remove",
       "instanceName": "Name (e.g. Home)",
+      "idDuplicate": "An instance with that id already exists.",
+      "idRequired": "Enter an id for the new instance.",
       "instanceId": "Identifier (slug, not editable later)",
       "test": "Test",
       "testOk": "Connected: Proxmox {{version}} · {{nodes}} node(s), {{vms}} VM(s), {{cts}} CT(s)",
@@ -1780,6 +1828,17 @@
       "urgentOnly": "Urgent alerts only",
       "urgentOnlyHint": "On: the channel receives only urgent alerts (recommended, the usual behavior). Turn it off to receive everything that shows in the feed according to the level chosen in Alerts."
     },
+    "mcp": {
+      "title": "MCP — AI assistants",
+      "description": "Exposes an MCP server (streamable-HTTP) at /mcp so AI assistants can query your instance with read-only tools: fleet status, per-router health, devices, WireGuard, AdGuard, topology and alerts. No configuration changes, no restarts.",
+      "enabled": "Endpoint /mcp active",
+      "lockedHint": "The /mcp endpoint is not enabled on this server: add NETPULSE_MCP_ENABLED=1 to its environment (e.g. the .env next to the binary) and restart the service.",
+      "endpoint": "Endpoint",
+      "endpointHint": "Only accepts API tokens as Bearer (never the session cookie), is rate limited, and every call lands in the audit log. Keep it on your LAN or behind a firewall.",
+      "copy": "Copy endpoint",
+      "tokensTitle": "API tokens",
+      "tokensHint": "These tokens are the only credential for the /mcp endpoint: create one per assistant or integration and revoke it when no longer needed."
+    },
     "mqtt": {
       "title": "MQTT / Home Assistant",
       "description": "Publishes the fleet state to an MQTT broker for Home Assistant (automatic discovery) and pushes the configuration to NetGrip routers.",
@@ -1954,33 +2013,89 @@
     "exit": "Exit demo"
   },
   "channelPlan": {
-    "title": "WiFi channel plan",
-    "subtitle": "Channel recommendations from neighbor scans.",
-    "router": "Router",
+    "title": "Channel analysis",
+    "subtitle": "Spectrum occupancy seen by each radio with a channel suggestion. Informational only: nothing is applied.",
+    "router": "Fleet",
     "band": "Band",
-    "currentChannel": "Current channel",
-    "recommendedChannel": "Recommended channel",
-    "neighbors": "Neighbor APs",
-    "noScans": "No recent scans for this router. Routers running NetGrip (gateway, APs managed by its panel) do not scan neighbors; routers with the NetPulse agent do. Pick another router from the list (e.g. rt2 or rt4) to see its plan.",
-    "noRadios": "This router does not report WiFi radios.",
-    "apply": "Apply channel",
-    "gateway": " (Gateway)",
+    "currentChannel": "Channel",
+    "channelWord": "Channel {{ch}}",
     "signal": "Signal",
     "score": "Score",
-    "updateAgent": "Update the router's agent to apply channels.",
-    "applyingState": "Applying…",
-    "appliedState": "Channel applied",
-    "failedState": "Could not apply",
-    "revertTo": "Back to {{ch}}",
-    "timeout": "No response from the plan (timeout)",
-    "applyConfirmTitle": "Change the {{band}} channel",
-    "applyConfirmBody": "The {{band}} channel will move from {{from}} to {{to}}. That router's network restarts for a few seconds and its WiFi clients will reconnect. The change is recorded as a plan and you can go back to the previous channel with one click.",
-    "applyConfirmAction": "Apply",
-    "scanInfo": "Scans from the last 24 hours"
+    "scanInfo": "scans from the last 24 h",
+    "refresh": "Refresh",
+    "lastRefresh": "updated {{time}}",
+    "lastScan": "last scan {{time}}",
+    "suggested": "Suggested",
+    "tagCurrent": "Current",
+    "tagBest": "Best",
+    "tagDfs": "DFS",
+    "tActual": "CURRENT",
+    "ownNetwork": "Your network",
+    "hidden": "Hidden",
+    "noScans": "No recent scans for this router. Routers running NetGrip (gateway and managed APs) do not scan neighbors; routers with the NetPulse agent do. Try rt2 or rt4.",
+    "noRadios": "This router does not report WiFi radios.",
+    "noBandScans": "This radio sees no networks on this band.",
+    "noNeighborsBlock": "No neighbor networks in the whole block.",
+    "neighborsBlock": "{{count}} neighbor networks · strongest at {{dbm}} dBm.",
+    "alreadyOptimal": "Already the one you use.",
+    "betterThanCurrent": "Better than your current channel ({{score}}/100).",
+    "applyHint": "Suggestion: apply it from your router's settings.",
+    "summarySuggested": "Best suggested channel",
+    "summaryCurrent": "Your current channel",
+    "summaryNetworks": "Networks detected",
+    "neighborsInBlock": "{{count}} networks in your block",
+    "noOverlap": "No neighbor network overlaps you.",
+    "yours": "{{own}} yours · {{neighbors}} neighbors",
+    "strongestNeighbor": "Strongest neighbor: {{ssid}} ({{dbm}} dBm, channel {{ch}})",
+    "viewFrom": "Seen from {{name}} ·",
+    "chartTitle": "Channel spectrum · {{band}}",
+    "chartSub": "Each bell is a network: position = channel, width = bandwidth, height = signal",
+    "netsCount": "{{n}} networks",
+    "heatTitle": "Occupancy per channel",
+    "heatNote": "neighbors drawn at 20 MHz (width unknown)",
+    "heatClean": "Clean",
+    "heatBusy": "Busy",
+    "scoresTitle": "Channel score",
+    "scoresBlocks": "{{w}} MHz blocks",
+    "scoresChannels": "20 MHz channels",
+    "scoresFoot": "The score weighs each neighbor's power and overlap. Your own networks do not count against.",
+    "whyAlone": "No interference",
+    "whyNeighbors": "{{n}} networks · max {{dbm}} dBm",
+    "tableSub": "{{n}} networks · click a column to sort · click a row to highlight",
+    "colWidth": "Width",
+    "gateway": " (Gateway)",
+    "congestion": {
+      "low": "Low congestion",
+      "moderate": "Moderate congestion",
+      "high": "High congestion"
+    },
+    "quality": {
+      "excellent": "Excellent",
+      "good": "Good",
+      "weak": "Weak",
+      "veryWeak": "Very weak"
+    },
+    "sortable": "sort",
+    "sortAsc": "ascending order, click to reverse",
+    "sortDesc": "descending order, click to reverse",
+    "tier": {
+      "optimal": "Optimal",
+      "moderate": "Moderate",
+      "busy": "Busy"
+    },
+    "hideAll": "Hide all",
+    "showAll": "Show all",
+    "onlyMine": "Only mine",
+    "legendDfs": "DFS range (radar)",
+    "legendSuggested": "Suggested block",
+    "legendCurrent": "Your channel",
+    "heatNoteKnown": "real widths from each neighbor HT/VHT advertisements"
   },
   "firmwareUpgrades": {
     "title": "Firmware upgrades",
     "subtitle": "Schedule OpenWrt firmware upgrades and track progress per router.",
+    "disabledTitle": "Firmware upgrades is hidden",
+    "disabledText": "Turn it on in Settings > Services to manage firmware upgrades from here.",
     "currentVersion": "Current version",
     "targetVersion": "Target version",
     "model": "Model / target",
@@ -2073,7 +2188,8 @@
     "consoleReboot": "router is rebooting; waiting for it to come back (up to 15 min)",
     "successTitle": "Upgrade completed!",
     "successBody": "The router is now on {{to}} in {{dur}} s: it rebooted and came back on its own, packages up to date. If you excluded a stack package, check its service is still running.",
-    "successDismiss": "Got it"
+    "successDismiss": "Got it",
+    "compatibleNote": "Only vanilla OpenWrt devices are shown; GL.iNet updates via its own channel."
   },
   "orchestration": {
     "title": "Orchestration",
@@ -2356,7 +2472,7 @@
         "subtitle": "Pick the WiFi channel with the least interference",
         "intro": "The page collects the passive neighbour scans pushed by the agents and scores each channel; the recommendation balances your current channel against the candidates.",
         "steps": [
-          "Open ⟦Channel plan⟧ in the menu (marked as labs).",
+          "Open ⟦Channels⟧ in the menu.",
           "Pick the router: each radio shows its current channel, the neighbours it hears and the score of every candidate channel.",
           "The highlighted recommendation is the channel with the least overlap; compare it with the current channel before touching anything."
         ],
@@ -2391,5 +2507,81 @@
   "announcement": {
     "link": "See more",
     "dismiss": "Dismiss announcement"
+  },
+  "app": {
+    "title": "NetPulse - Your network at a glance"
+  },
+  "rack": {
+    "title": "Rack",
+    "subtitle": "Your physical hardware, placed and patched.",
+    "addRack": "Add rack",
+    "deleteRack": "Delete rack",
+    "deleteRackConfirm": "Delete this rack and everything mounted on it?",
+    "rackDeleted": "Rack deleted",
+    "save": "Save",
+    "saving": "Saving…",
+    "saved": "Rack saved",
+    "saveFailed": "Could not save",
+    "unsaved": "unsaved changes",
+    "patch": "Patch",
+    "visibility": "Cables",
+    "visibilityHover": "On hover",
+    "visibilityAlways": "Always",
+    "visibilityHidden": "Hidden",
+    "noSpace": "No free slot fits it",
+    "patchBusy": "That port already has all its cables",
+    "cableDeleted": "Cable unplugged",
+    "drafting": "From {{port}}: pick the target port (Esc cancels)",
+    "empty": "No racks yet",
+    "emptyHint": "Create a rack first",
+    "pickHint": "Drag onto a rack (or click) to mount into the active rack (the cyan one). Then drag to adjust the slot.",
+    "pickFleet": "Routers",
+    "pickDevice": "Devices",
+    "pickAccessory": "Accessories",
+    "plates": {
+      "server-1u": "1U server",
+      "server-2u": "2U server",
+      "switch": "Switch",
+      "router": "Router",
+      "nas-tower": "NAS tower",
+      "patch-panel-1u": "24-port patch panel",
+      "pdu-1u": "PDU",
+      "ups-4u": "4U UPS",
+      "shelf-1u": "Shelf",
+      "blank-1u": "1U blank",
+      "blank-half-1u": "Half-U blank",
+      "patch-panel-12p": "12-port patch panel",
+      "patch-panel-48p": "48-port patch panel"
+    },
+    "createTitle": "New rack",
+    "createName": "Name",
+    "createU": "Height (U)",
+    "createSubmit": "Create",
+    "createCancel": "Cancel",
+    "deleteTitle": "Delete rack?",
+    "deleteDesc": "This will delete «{{name}}» along with everything mounted on it. This cannot be undone.",
+    "deleteConfirm": "Delete",
+    "deleteCancel": "Cancel",
+    "unmounted": "Device unmounted from the rack",
+    "editRack": "Edit rack",
+    "editTitle": "Edit rack",
+    "editSubmit": "Save changes",
+    "rackUpdated": "Rack updated",
+    "createLocation": "Location",
+    "locationPlaceholder": "e.g. Office, Living room, Garage…",
+    "import": "Import links",
+    "importResult": "Import: {{created}} created · {{skipped}} skipped · {{noFree}} no free port",
+    "askTitle": "Place “{{name}}”",
+    "askTitlePatch": "Place patch panel",
+    "askHeight": "Height (U)",
+    "askPorts": "Ports",
+    "askPlace": "Place",
+    "dropNoRack": "Drop it inside a rack",
+    "portCount": "detected ports",
+    "importNeedsSave": "Save the rack changes before importing links",
+    "betaTitle": "Preview: much work remains",
+    "betaText": "This view is under active development and not fully reliable yet. Do not use it in production; feedback is welcome.",
+    "disabledTitle": "Rack canvas is disabled",
+    "disabledText": "It is a development view (labs). Enable it in Settings → Labs → Rack canvas to try it."
   }
-}
+}

+ 230 - 38
app/public/locales/es/translation.json

@@ -18,6 +18,10 @@
     "filterBySeverity": "Filtrar por severidad",
     "loadingOld": "Cargando alertas antiguas…",
     "markAllRead": "Marcar todo como leído",
+    "clearLog": "Vaciar registro",
+    "clearLogTitle": "¿Vaciar el registro de alertas?",
+    "clearLogDesc": "Se borrarán todas las entradas del registro de alertas, en servidor e historial. No se puede deshacer. Si solo quieres limpiar la vista, usa \"Solo no leídas\" o marca todo como leído.",
+    "clearLogConfirm": "Vaciar registro",
     "moreActions": "Más acciones",
     "noMoreEvents": "No hay más alertas",
     "onlyUnread": "Solo no leídas",
@@ -332,7 +336,8 @@
     "status": {
       "online": "Online",
       "warn": "Atención",
-      "offline": "Offline"
+      "offline": "Offline",
+      "paused": "Pausada"
     },
     "temperature": "Temperatura",
     "today": "hoy",
@@ -349,7 +354,8 @@
     "save": "Guardar",
     "never": "nunca",
     "notFound": "Página no encontrada",
-    "tunnelIp": "IP túnel"
+    "tunnelIp": "IP túnel",
+    "roleExternal": "Externo"
   },
   "devices": {
     "badges": {
@@ -414,7 +420,7 @@
     "leaseMinutes": "{{minutes}}min",
     "leaseUnlimited": "ilimitado",
     "edit": {
-      "title": "Editar dispositivo",
+      "title": "Editar cliente",
       "action": "Editar",
       "name": "Nombre",
       "nameHint": "Vacío = nombre automático (hostname DHCP)",
@@ -428,6 +434,15 @@
       "banTitle": "Bloquear bandas",
       "banHint": "Próximamente: impedir que se conecte a redes 2.4/5/6 GHz.",
       "demoNotice": "En modo demo los cambios solo se guardan en este navegador.",
+      "linkedMacs": "MACs enlazadas",
+      "linkPlaceholder": "Enlazar otro cliente…",
+      "link": "Enlazar",
+      "unlink": "Desenlazar",
+      "dangerZone": "Zona de riesgo",
+      "delete": "Borrar cliente",
+      "deleteTitle": "¿Borrar este cliente?",
+      "deleteDesc": "Quita el cliente de la lista guardada. Si el dispositivo vuelve a verse en la red se redescubre solo.",
+      "deleteConfirmDesc": "{{name}} se quitará de la lista de clientes guardados. Si vuelve a verse en la red se redescubre solo.",
       "reserveTitle": "Reservar IP",
       "reserveHint": "Sin reserva DHCP en la puerta de enlace.",
       "reservedAs": "Reservado como {{ip}}",
@@ -448,6 +463,12 @@
       "planRun": "Ejecutar y aplicar",
       "planNone": "Sin cambios que aplicar"
     },
+    "suggestions": {
+      "title": "Posibles clientes duplicados",
+      "desc": "Estos clientes comparten hostname e IP y nunca se ven a la vez: pueden ser un dispositivo con varias MACs. Enlázalos para que salgan en una sola fila.",
+      "link": "Enlazar",
+      "dismiss": "Descartar"
+    },
     "new": "Nuevo",
     "onlyOnline": "Solo online",
     "onlineAll": "Todos",
@@ -615,7 +636,8 @@
     "orchestration": "Orquestación",
     "channelPlan": "Canales",
     "firmwareUpgrades": "Actualizaciones",
-    "help": "Ayuda"
+    "help": "Ayuda",
+    "rack": "Rack"
   },
   "roaming": {
     "subtitle": "Estado de la itinerancia WiFi y la malla WiFi",
@@ -625,7 +647,7 @@
     "empty": "Ningún router tiene usteer activo. Instálalo en OpenWrt para ver la malla de itinerancia.",
     "tabMatrix": "Matriz",
     "tab11r": "802.11r",
-    "tabSurvey": "Análisis de canales",
+    "tabSurvey": "Canales actuales",
     "tabEvents": "Eventos",
     "comingSoon": "Próximamente",
     "matrix": {
@@ -716,7 +738,11 @@
       "connected": "Conectado",
       "disconnected": "Desconectado",
       "dawn": "DAWN",
-      "other": "Otro"
+      "other": "Otro",
+      "filterAp": "AP",
+      "filterApAll": "Todos los APs",
+      "filterClient": "Cliente",
+      "filterClientAll": "Todos los clientes"
     },
     "tabsLabel": "Vistas de itinerancia",
     "daemon": {
@@ -803,6 +829,7 @@
     },
     "latency": {
       "24h": "Latencia 24 h",
+      "noData": "Sin datos de la sonda aún: hace falta el agente de flota o SSH en la unidad.",
       "aria": "Latencia {{ms}} ms {{caption}}",
       "toHost": "a {{host}}"
     },
@@ -864,7 +891,13 @@
       "detailRouterLinkLldp": "enlace entre routers · LLDP",
       "detailApWifi": "cliente WiFi detrás",
       "detailMac": "MAC {{mac}}",
-      "inferredSwitch": "Switch"
+      "inferredSwitch": "Switch",
+      "virtualGroup": "Interfaces virtuales ({{count}})",
+      "fam_lag": "LAG",
+      "fam_vlan": "VLAN",
+      "fam_bridge": "Bridge",
+      "fam_tunnel": "Túnel",
+      "fam_virtual": "Virtual"
     },
     "radios": {
       "channel": "Canal",
@@ -1334,6 +1367,9 @@
       "unitsTitle": "Unidades de medida",
       "tempUnit": "Temperatura",
       "limitHistory": "Limitar historial",
+      "alertRetention": "Retención del registro de alertas",
+      "alertRetentionCaption": "Se podan las entradas más antiguas que este número de días",
+      "alertRetentionHint": "Días que conserva el servidor cada entrada del registro de alertas (se poda cada hora, además de la cota de 500 entradas). 0 conserva sin límite temporal.",
       "limitHistoryCaption": "Poda los eventos antiguos de presencia e itinerancia",
       "limitHistoryHint": "Activado, el servidor poda cada hora los eventos más viejos que la retención configurada. Desactivado, la retención es ilimitada (el historial crece sin poda). El intervalo de ingesta de itinerancia es independiente y siempre aplica.",
       "limitHistoryDialog": "Límites del historial",
@@ -1489,7 +1525,14 @@
       "tempThresholdHint": "Umbral de alerta por temperatura alta. Vacío = 65 °C por defecto. Un router que corre más caliente puede subir el suyo sin ocultar problemas en los más frescos.",
       "openWrtBadge": "OpenWrt",
       "consolePolling": "Sondeo por consola",
-      "consolePollingHint": "El server entra en la web del switch para leer firmware, uptime y MAC. La consola del firmware admite una sola sesión: cada sondeo cierra la sesión de cualquiera que esté dentro. Desactívalo si te echa de la web (con el beacon v1.3+ los datos llegan igual por UDP)."
+      "consolePollingHint": "El server entra en la web del switch para leer firmware, uptime y MAC. La consola del firmware admite una sola sesión: cada sondeo cierra la sesión de cualquiera que esté dentro. Desactívalo si te echa de la web (con el beacon v1.3+ los datos llegan igual por UDP).",
+      "routerosUser": "Usuario RouterOS",
+      "routerosPassword": "Contraseña RouterOS",
+      "routerosPasswordPlaceholder": "Déjalo en blanco para conservar la actual",
+      "routerosInsecure": "Aceptar certificado TLS autofirmado",
+      "disabled": "Pausada",
+      "disabledHint": "No se sondea ni alerta; conserva el histórico. La insignia Pausada la distingue en la flota y queda fuera de los desplegables.",
+      "disabledBadge": "Pausada"
     },
     "overrides": {
       "title": "Topología — etiquetado manual",
@@ -1540,13 +1583,11 @@
       "dismiss": "Cerrar",
       "deleteTitle": "Revocar token del dispositivo",
       "deleteDesc": "Se revocará el token de \"{{slug}}\". El scraper dejará de poder enviar datos hasta que regeneres el token.",
-      "canales": "Canales",
-      "canalesCaption": "Planificador de canales WiFi (LABS)",
-      "actualizaciones": "Actualizaciones",
-      "actualizacionesCaption": "Actualizaciones de firmware (LABS)",
       "regenToken": "Regenerar token",
       "regenTokenCaption": "Rotación del token de agentes externos (LABS)",
-      "badge": "LABS"
+      "badge": "LABS",
+      "rack": "Rack canvas",
+      "rackCaption": "Dibuja tu rack y detecta los cables. Desactivado por defecto; no usar en producción."
     },
     "saved": "Preferencias guardadas",
     "services": {
@@ -1559,9 +1600,11 @@
       "labsCaption": "En desarrollo. Escriben en los routers",
       "orchestrationHint": "Permite gestionar routers desde la interfaz (AdGuard, WiFi invitados, DDNS…)",
       "networkGroup": "Servicios de red",
+      "firmwareUpgradesCaption": "Muestra u oculta la página de actualizaciones de firmware",
       "integrationsGroup": "Integraciones",
       "proxmoxCaption": "Inventario del cluster (hipervisores y CTs)",
       "mqttCaption": "Publicación del estado en el broker MQTT",
+      "mcpCaption": "Consultas de solo lectura para asistentes de IA (labs)",
       "configure": "Configurar {{name}}"
     },
     "session": {
@@ -1658,7 +1701,7 @@
       "caption": "Medición periódica real desde el servidor",
       "enabled": "Test periódico activado",
       "provider": "Proveedor del test",
-      "providerHint": "Método de medición. Speedtest.net usa la red de servidores de Ookla; Cloudflare mide contra speed.cloudflare.com por HTTP; LibreSpeed usa una instancia propia o pública (necesitas su URL); Personalizado mide contra la URL que indiques (debe aceptar GET para bajada y POST para subida). Prueba otro si el resultado por defecto no se parece a tu línea.",
+      "providerHint": "Método de medición. Speedtest.net usa la red de servidores de Ookla; Cloudflare mide contra speed.cloudflare.com por HTTP; LibreSpeed usa una instancia propia o pública (necesitas su URL); Personalizado mide contra la URL que indiques (debe aceptar GET para bajada y POST para subida). Prueba otro si el resultado por defecto no se parece a tu línea. M-Lab NDT mide contra los servidores públicos del consorcio (autodetección del más cercano).",
       "providerOokla": "Speedtest.net (Ookla)",
       "providerCloudflare": "Cloudflare",
       "providerLibrespeed": "LibreSpeed",
@@ -1686,6 +1729,7 @@
       "lastResult": "Último test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "No disponible en este modo",
       "kindInterval": "Cada N horas",
+      "kindAuto": "Automático (hora de menos tráfico)",
       "kindWeekly": "Semanal (día y hora)",
       "kindMonthly": "Mensual (día y hora)",
       "everyLabel": "Cada:",
@@ -1704,7 +1748,9 @@
       "originManual": "Manual",
       "colServer": "Servidor",
       "noRecent": "Aún no hay tests registrados",
-      "recentHide": "Ocultar"
+      "recentHide": "Ocultar",
+      "providerNdt": "M-Lab NDT",
+      "ndtPlaceholder": "Opcional: FQDN de un servidor M-Lab (vacío = autodetectar)"
     },
     "proxmox": {
       "title": "Proxmox VE",
@@ -1723,6 +1769,8 @@
       "add": "Añadir instancia",
       "delete": "Quitar",
       "instanceName": "Nombre (p. ej. Casa)",
+      "idDuplicate": "Ya existe una instancia con ese identificador.",
+      "idRequired": "Pon un identificador para la instancia nueva.",
       "instanceId": "Identificador (slug, no editable luego)",
       "test": "Probar",
       "testOk": "Conectado: Proxmox {{version}} · {{nodes}} nodo(s), {{vms}} VM(s), {{cts}} CT(s)",
@@ -1780,6 +1828,17 @@
       "urgentOnly": "Solo alertas urgentes",
       "urgentOnlyHint": "Activado: el canal recibe solo las alertas urgentes (recomendado, el comportamiento habitual). Desactívalo para que llegue todo lo que aparece en el feed según el nivel elegido en Alertas."
     },
+    "mcp": {
+      "title": "MCP — asistentes de IA",
+      "description": "Expone un servidor MCP (streamable-HTTP) en /mcp para que los asistentes de IA consulten tu instancia con herramientas de solo lectura: estado de la flota, salud por router, dispositivos, WireGuard, AdGuard, topología y alertas. Sin cambios de configuración ni reinicios.",
+      "enabled": "Endpoint /mcp activo",
+      "lockedHint": "El endpoint /mcp no está habilitado en este servidor: añade NETPULSE_MCP_ENABLED=1 a su entorno (p. ej. en el .env junto al binario) y reinicia el servicio.",
+      "endpoint": "Endpoint",
+      "endpointHint": "Solo acepta tokens de API como Bearer (nunca la cookie de sesión), lleva rate limit y cada llamada queda en el log de auditoría. Mantenlo en tu LAN o detrás de un firewall.",
+      "copy": "Copiar endpoint",
+      "tokensTitle": "Tokens de API",
+      "tokensHint": "Estos tokens son la única credencial del endpoint /mcp: crea uno por asistente o integración y revócalo cuando deje de usarse."
+    },
     "mqtt": {
       "title": "MQTT / Home Assistant",
       "description": "Publica el estado de la flota en un broker MQTT para Home Assistant (descubrimiento automático) y propaga la configuración a los routers NetGrip.",
@@ -1954,33 +2013,89 @@
     "exit": "Salir del demo"
   },
   "channelPlan": {
-    "title": "Plan de canales WiFi",
-    "subtitle": "Recomendaciones de canal a partir de scans de vecinos.",
-    "router": "Equipo",
+    "title": "Análisis de canales",
+    "subtitle": "Ocupación del espectro vista por cada radio con sugerencia de canal. Solo informativo: no se aplican cambios.",
+    "router": "Flota",
     "band": "Banda",
-    "currentChannel": "Canal actual",
-    "recommendedChannel": "Canal recomendado",
-    "neighbors": "APs vecinos",
-    "noScans": "Sin escaneos recientes para este router. Los routers que corren NetGrip (la puerta de enlace, los APs gestionados por su panel) no escanean vecinos; los que llevan el agente NetPulse sí. Selecciona otro router de la lista (p. ej. rt2 o rt4) para ver su plan.",
-    "noRadios": "Este equipo no reporta radios WiFi.",
-    "apply": "Aplicar canal",
-    "gateway": " (Puerta de enlace)",
+    "currentChannel": "Canal",
+    "channelWord": "Canal {{ch}}",
     "signal": "Señal",
     "score": "Puntuación",
-    "updateAgent": "Actualiza el agente del router para poder aplicar el canal.",
-    "applyingState": "Aplicando…",
-    "appliedState": "Canal aplicado",
-    "failedState": "No se pudo aplicar",
-    "revertTo": "Volver al {{ch}}",
-    "timeout": "Sin respuesta del plan (tiempo agotado)",
-    "applyConfirmTitle": "Cambiar el canal de {{band}}",
-    "applyConfirmBody": "El canal de {{band}} pasará de {{from}} a {{to}}. La red de ese router se reiniciará unos segundos y sus clientes WiFi se reconectarán. El cambio queda registrado como plan y podrás volver al canal anterior con un clic.",
-    "applyConfirmAction": "Aplicar",
-    "scanInfo": "Scans de las últimas 24 h"
+    "scanInfo": "scans de las últimas 24 h",
+    "refresh": "Actualizar",
+    "lastRefresh": "actualizado {{time}}",
+    "lastScan": "último scan {{time}}",
+    "suggested": "Sugerido",
+    "tagCurrent": "Actual",
+    "tagBest": "Mejor",
+    "tagDfs": "DFS",
+    "tActual": "ACTUAL",
+    "ownNetwork": "Tu red",
+    "hidden": "Oculta",
+    "noScans": "Sin escaneos recientes para este equipo. Los que corren NetGrip (puerta de enlace y APs gestionados) no escanean vecinos; los que llevan agente NetPulse sí. Prueba con rt2 o rt4.",
+    "noRadios": "Este equipo no reporta radios WiFi.",
+    "noBandScans": "Esta radio no ve redes en esta banda.",
+    "noNeighborsBlock": "Sin redes vecinas en todo el bloque.",
+    "neighborsBlock": "{{count}} redes vecinas · la más fuerte a {{dbm}} dBm.",
+    "alreadyOptimal": "Es el que ya estás usando.",
+    "betterThanCurrent": "Mejor que tu canal actual ({{score}}/100).",
+    "applyHint": "Sugerencia: aplícalo desde la configuración de tu router.",
+    "summarySuggested": "Mejor canal sugerido",
+    "summaryCurrent": "Tu canal actual",
+    "summaryNetworks": "Redes detectadas",
+    "neighborsInBlock": "{{count}} redes en tu bloque",
+    "noOverlap": "Ninguna red vecina te solapa.",
+    "yours": "{{own}} tuyas · {{neighbors}} vecinas",
+    "strongestNeighbor": "Vecina más fuerte: {{ssid}} ({{dbm}} dBm, canal {{ch}})",
+    "viewFrom": "Vista desde {{name}} ·",
+    "chartTitle": "Espectro de canales · {{band}}",
+    "chartSub": "Cada campana es una red: posición = canal, anchura = ancho de banda, altura = señal",
+    "netsCount": "{{n}} redes",
+    "heatTitle": "Ocupación por canal",
+    "heatNote": "los vecinos se dibujan a 20 MHz (ancho desconocido)",
+    "heatClean": "Limpio",
+    "heatBusy": "Saturado",
+    "scoresTitle": "Puntuación por canal",
+    "scoresBlocks": "Bloques de {{w}} MHz",
+    "scoresChannels": "Canales de 20 MHz",
+    "scoresFoot": "La puntuación pondera potencia y solapamiento de cada vecina. Tus propias redes no penalizan.",
+    "whyAlone": "Sin interferencias",
+    "whyNeighbors": "{{n}} redes · máx {{dbm}} dBm",
+    "tableSub": "{{n}} redes · clic en columna para ordenar · clic en fila para resaltar",
+    "colWidth": "Ancho",
+    "gateway": " (Puerta de enlace)",
+    "congestion": {
+      "low": "Congestión baja",
+      "moderate": "Congestión moderada",
+      "high": "Congestión alta"
+    },
+    "quality": {
+      "excellent": "Excelente",
+      "good": "Buena",
+      "weak": "Floja",
+      "veryWeak": "Muy floja"
+    },
+    "sortable": "ordenar",
+    "sortAsc": "orden ascendente, clic para invertir",
+    "sortDesc": "orden descendente, clic para invertir",
+    "tier": {
+      "optimal": "Óptimos",
+      "moderate": "Moderados",
+      "busy": "Saturados"
+    },
+    "hideAll": "Ocultar todas",
+    "showAll": "Mostrar todas",
+    "onlyMine": "Solo mías",
+    "legendDfs": "Zona DFS (radar)",
+    "legendSuggested": "Bloque sugerido",
+    "legendCurrent": "Tu canal",
+    "heatNoteKnown": "anchos reales de los anuncios HT/VHT de cada vecina"
   },
   "firmwareUpgrades": {
     "title": "Actualizaciones de firmware",
     "subtitle": "Programa actualizaciones de firmware OpenWrt y sigue el progreso por equipo.",
+    "disabledTitle": "Actualizaciones de firmware está oculto",
+    "disabledText": "Actívalo en Ajustes > Servicios para gestionar las actualizaciones desde aquí.",
     "currentVersion": "Versión actual",
     "targetVersion": "Versión objetivo",
     "model": "Modelo / target",
@@ -2073,7 +2188,8 @@
     "consoleReboot": "el router se está reiniciando; esperando a que vuelva (hasta 15 min)",
     "successTitle": "¡Actualización completada!",
     "successBody": "El router quedó en {{to}} en {{dur}} s: reinició y volvió solo, con los paquetes al día. Si excluiste algún paquete del stack, comprueba que su servicio sigue activo.",
-    "successDismiss": "Entendido"
+    "successDismiss": "Entendido",
+    "compatibleNote": "Solo se muestran dispositivos con OpenWrt; los GL.iNet se actualizan por su propia vía."
   },
   "orchestration": {
     "title": "Orquestación",
@@ -2356,7 +2472,7 @@
         "subtitle": "Elegir canal WiFi con la menor interferencia",
         "intro": "La página recoge los escaneos pasivos de vecinos que mandan los agentes y puntúa cada canal; la recomendación es el mejor balance entre tu canal actual y los candidatos.",
         "steps": [
-          "Abre ⟦Plan de canales⟧ en el menú (marcado como labs).",
+          "Abre ⟦Canales⟧ en el menú.",
           "Elige el router: verás cada radio con su canal actual, los vecinos que se oyen y la puntuación de cada canal candidato.",
           "La recomendación destacada es el canal con menos solapamiento; compárala con el canal actual antes de tocar nada."
         ],
@@ -2391,5 +2507,81 @@
   "announcement": {
     "link": "Ver más",
     "dismiss": "Descartar aviso"
+  },
+  "app": {
+    "title": "NetPulse - Tu red, de un vistazo"
+  },
+  "rack": {
+    "title": "Rack",
+    "subtitle": "Tu hardware físico, colocado y cableado.",
+    "addRack": "Añadir rack",
+    "deleteRack": "Eliminar rack",
+    "deleteRackConfirm": "¿Eliminar el rack y todo lo que tiene montado?",
+    "rackDeleted": "Rack eliminado",
+    "save": "Guardar",
+    "saving": "Guardando…",
+    "saved": "Rack guardado",
+    "saveFailed": "No se pudo guardar",
+    "unsaved": "cambios sin guardar",
+    "patch": "Cablear",
+    "visibility": "Cables",
+    "visibilityHover": "Al pasar",
+    "visibilityAlways": "Siempre",
+    "visibilityHidden": "Ocultos",
+    "noSpace": "No cabe en ningún hueco libre del rack",
+    "patchBusy": "Ese puerto ya tiene todos sus cables",
+    "cableDeleted": "Cable desconectado",
+    "drafting": "Desde {{port}}: elige el puerto de destino (Esc cancela)",
+    "empty": "Todavía no hay ningún rack",
+    "emptyHint": "Crea primero un rack",
+    "pickHint": "Arrastra al rack (o haz clic) para montar en el rack activo (el resaltado en cyan). Luego arrastra para ajustar el hueco.",
+    "pickFleet": "Routers",
+    "pickDevice": "Dispositivos",
+    "pickAccessory": "Accesorios",
+    "plates": {
+      "server-1u": "Servidor 1U",
+      "server-2u": "Servidor 2U",
+      "switch": "Switch",
+      "router": "Router",
+      "nas-tower": "NAS torre",
+      "patch-panel-1u": "Patch panel 24p",
+      "pdu-1u": "PDU",
+      "ups-4u": "SAI 4U",
+      "shelf-1u": "Bandeja",
+      "blank-1u": "Tapeta 1U",
+      "blank-half-1u": "Tapeta 1/2U",
+      "patch-panel-12p": "Patch panel 12p",
+      "patch-panel-48p": "Patch panel 48p"
+    },
+    "createTitle": "Nuevo rack",
+    "createName": "Nombre",
+    "createU": "Altura (U)",
+    "createSubmit": "Crear",
+    "createCancel": "Cancelar",
+    "deleteTitle": "¿Eliminar rack?",
+    "deleteDesc": "Se eliminará «{{name}}» con todo lo que tiene montado. No se puede deshacer.",
+    "deleteConfirm": "Eliminar",
+    "deleteCancel": "Cancelar",
+    "unmounted": "Equipo desmontado del rack",
+    "editRack": "Editar rack",
+    "editTitle": "Editar rack",
+    "editSubmit": "Guardar cambios",
+    "rackUpdated": "Rack actualizado",
+    "createLocation": "Ubicación",
+    "locationPlaceholder": "p. ej. Despacho, Salón, Garaje…",
+    "import": "Importar enlaces",
+    "importResult": "Importación: {{created}} creados · {{skipped}} saltados · {{noFree}} sin puerto libre",
+    "askTitle": "Colocar «{{name}}»",
+    "askTitlePatch": "Colocar patch panel",
+    "askHeight": "Altura (U)",
+    "askPorts": "Puertos",
+    "askPlace": "Colocar",
+    "dropNoRack": "Suéltalo dentro de un rack",
+    "portCount": "bocas detectadas",
+    "importNeedsSave": "Guarda los cambios del rack antes de importar enlaces",
+    "betaTitle": "Vista previa: queda mucho trabajo por hacer",
+    "betaText": "Esta vista está en desarrollo activo y todavía no es fiable al 100%. No la utilices todavía en producción; esperamos tus comentarios.",
+    "disabledTitle": "Rack canvas está desactivado",
+    "disabledText": "Es una vista en desarrollo (labs). Actívala en Ajustes → Labs → Rack canvas si quieres probarla."
   }
-}
+}

+ 10 - 0
app/src/App.tsx

@@ -1,3 +1,4 @@
+import { useEffect } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Route, Routes } from 'react-router'
 import { Navigate } from 'react-router'
@@ -14,6 +15,7 @@ import Alerts from '@/pages/Alerts'
 import Roaming from '@/pages/Roaming'
 import ChannelPlan from '@/pages/ChannelPlan'
 import Reports from '@/pages/Reports'
+import Rack from '@/pages/Rack'
 import Orchestration from '@/pages/Orchestration'
 import FirmwareUpgrades from '@/pages/FirmwareUpgrades'
 import Settings from '@/pages/Settings'
@@ -26,6 +28,13 @@ import Placeholder from '@/pages/Placeholder'
  * La ruta `/login` queda FUERA del Layout y del gate.
  */
 export default function App() {
+  // El título del documento sigue el idioma (antes era ES fijo en
+  // index.html, que no se traduce).
+  const { t, i18n } = useTranslation()
+  useEffect(() => {
+    document.title = t('app.title')
+  }, [t, i18n.language])
+
   return (
     <Routes>
       <Route path="/login" element={<Login />} />
@@ -46,6 +55,7 @@ export default function App() {
         <Route path="agents" element={<Navigate to="/routers" replace />} />
         <Route path="devices" element={<Devices />} />
         <Route path="topology" element={<Topology />} />
+        <Route path="rack" element={<Rack />} />
         <Route path="alerts" element={<Alerts />} />
         <Route path="roaming" element={<Roaming />} />
         <Route path="wifi/channel-plan" element={<ChannelPlan />} />

+ 150 - 8
app/src/components/DeviceEditSheet.tsx

@@ -17,6 +17,7 @@ import {
   SheetHeader,
   SheetTitle,
 } from '@/components/ui/sheet'
+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
 import { cn, fetchJson } from '@/lib/utils'
 import type { ClientDevice } from '@/pages/devices-data'
 
@@ -34,6 +35,12 @@ export interface DeviceEditSheetProps {
   onClose: () => void
   /** Patch absoluto: '' en un campo = volver al valor automático (#797). */
   onSave: (device: ClientDevice, patch: { icon: string; name: string; type: string }) => void
+  /** #1145: tras borrar el cliente del registro (el padre cierra y refresca). */
+  onDeleted?: () => void
+  /** #1151: resto de clientes (para el selector de enlace). */
+  clients?: ClientDevice[]
+  /** #1151: tras enlazar/desenlazar (el padre cierra y refresca). */
+  onLinkChanged?: () => void
 }
 
 // #797: tipos válidos del clasificador (paridad con adapters.ValidDeviceTypes
@@ -50,9 +57,52 @@ export function DeviceEditSheet({
   saving,
   onClose,
   onSave,
+  onDeleted,
+  clients,
+  onLinkChanged,
 }: DeviceEditSheetProps) {
   const { t } = useTranslation()
+  const [deleteOpen, setDeleteOpen] = useState(false)
+  const [deleting, setDeleting] = useState(false)
+  const [linkTarget, setLinkTarget] = useState('')
+  const [linkBusy, setLinkBusy] = useState(false)
   const [icon, setIcon] = useState(device?.iconOverride ?? '')
+
+  const otherClients = (clients ?? []).filter(
+    (c) => c.mac && c.mac !== device?.mac && c.mac !== device?.id && !(device?.aliasMacs ?? []).includes(c.mac),
+  )
+
+  const linkClient = async () => {
+    if (!linkTarget || !device?.mac) return
+    setLinkBusy(true)
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(linkTarget)}/link`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ target: device.mac }),
+      })
+      onLinkChanged?.()
+      onClose()
+    } catch {
+      // fallo silencioso: el botón vuelve a habilitarse
+    } finally {
+      setLinkBusy(false)
+    }
+  }
+
+  const unlinkAlias = async (alias: string) => {
+    if (!alias) return
+    setLinkBusy(true)
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(alias)}/link`, { method: 'DELETE' })
+      onLinkChanged?.()
+      onClose()
+    } catch {
+      // fallo silencioso
+    } finally {
+      setLinkBusy(false)
+    }
+  }
   const [name, setName] = useState(device?.nameOverride ?? '')
   const [devType, setDevType] = useState(device?.typeOverride ?? '')
   const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false })
@@ -220,6 +270,18 @@ export function DeviceEditSheet({
               </div>
             </div>
 
+            {/* #1096: Save/Cancel junto a la zona que editan (nombre, tipo,
+                icono); abajo quedaban lejos, tras Reserva/Bloqueo, que son
+                acciones independientes con sus propios botones. */}
+            <div className="flex gap-3">
+              <Button variant="outline" className="flex-1" onClick={onClose} disabled={saving}>
+                {t('common.cancel')}
+              </Button>
+              <Button className="flex-1" onClick={handleSave} disabled={saving}>
+                {saving ? t('common.loading') : t('devices.edit.save')}
+              </Button>
+            </div>
+
             {/* Detalles de red */}
             <div className="grid grid-cols-2 gap-3 rounded-xl border border-border bg-elevated/40 p-3 text-sm">
               <div>
@@ -454,22 +516,102 @@ export function DeviceEditSheet({
               </div>
             )}
 
+            {/* #1151: MACs enlazadas (mismo dispositivo, varias MACs) */}
+            {!isDemo && device?.mac && (
+              <div className="rounded-xl border border-border bg-elevated/40 p-3">
+                <div className="text-label uppercase tracking-wide text-text-muted">{t('devices.edit.linkedMacs')}</div>
+                {(device.aliasMacs?.length ?? 0) > 0 && (
+                  <ul className="mb-2 mt-1.5 space-y-1">
+                    {device.aliasMacs.map((alias) => (
+                      <li key={alias} className="flex items-center justify-between gap-2 rounded-lg bg-canvas/60 px-2 py-1.5">
+                        <span className="font-mono text-mono-sm text-text-primary">{alias}</span>
+                        <button
+                          type="button"
+                          disabled={linkBusy}
+                          onClick={() => void unlinkAlias(alias)}
+                          className="rounded-md px-2 py-0.5 text-caption text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+                        >
+                          {t('devices.edit.unlink')}
+                        </button>
+                      </li>
+                    ))}
+                  </ul>
+                )}
+                {otherClients.length > 0 && (
+                  <div className="mt-2 flex items-center gap-2">
+                    <Select value={linkTarget} onValueChange={setLinkTarget}>
+                      <SelectTrigger className="h-9 flex-1">
+                        <SelectValue placeholder={t('devices.edit.linkPlaceholder')} />
+                      </SelectTrigger>
+                      <SelectContent>
+                        {otherClients.map((c) => (
+                          <SelectItem key={c.mac} value={c.mac ?? ''}>
+                            {c.name || c.mac}
+                          </SelectItem>
+                        ))}
+                      </SelectContent>
+                    </Select>
+                    <Button size="sm" variant="outline" disabled={!linkTarget || linkBusy} onClick={() => void linkClient()}>
+                      {linkBusy ? t('common.loading') : t('devices.edit.link')}
+                    </Button>
+                  </div>
+                )}
+              </div>
+            )}
+
             {isDemo && (
               <p className="rounded-lg border border-warn/30 bg-warn/10 p-3 text-caption text-warn">
                 {t('devices.edit.demoNotice')}
               </p>
             )}
 
-            <div className="mt-auto flex gap-3 pt-2">
-              <Button variant="outline" className="flex-1" onClick={onClose} disabled={saving}>
-                {t('common.cancel')}
-              </Button>
-              <Button className="flex-1" onClick={handleSave} disabled={saving}>
-                {saving ? t('common.loading') : t('devices.edit.save')}
-              </Button>
-            </div>
+            {/* #1145: borrado del cliente del registro. Un cliente borrado
+                solo reaparece si se le vuelve a ver en vivo. */}
+            {!isDemo && device?.mac && (
+              <div className="rounded-xl border border-danger/30 bg-danger/5 p-3">
+                <div className="text-label uppercase tracking-wide text-danger">{t('devices.edit.dangerZone')}</div>
+                <p className="mb-2 mt-1 text-caption text-text-muted">{t('devices.edit.deleteDesc')}</p>
+                <Button variant="destructive" size="sm" onClick={() => setDeleteOpen(true)} disabled={deleting}>
+                  {t('devices.edit.delete')}
+                </Button>
+              </div>
+            )}
+
           </div>
         )}
+        <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
+          <AlertDialogContent>
+            <AlertDialogHeader>
+              <AlertDialogTitle>{t('devices.edit.deleteTitle')}</AlertDialogTitle>
+              <AlertDialogDescription>
+                {t('devices.edit.deleteConfirmDesc', { name: device?.name || device?.mac || '' })}
+              </AlertDialogDescription>
+            </AlertDialogHeader>
+            <AlertDialogFooter>
+              <AlertDialogCancel disabled={deleting}>{t('common.cancel')}</AlertDialogCancel>
+              <AlertDialogAction
+                disabled={deleting}
+                onClick={async (e) => {
+                  e.preventDefault()
+                  if (!device?.mac) return
+                  setDeleting(true)
+                  try {
+                    await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}`, { method: 'DELETE' })
+                    setDeleteOpen(false)
+                    onDeleted?.()
+                    onClose()
+                  } catch {
+                    // el fallo deja la hoja abierta; el botón vuelve a habilitarse
+                  } finally {
+                    setDeleting(false)
+                  }
+                }}
+              >
+                {deleting ? t('common.loading') : t('devices.edit.delete')}
+              </AlertDialogAction>
+            </AlertDialogFooter>
+          </AlertDialogContent>
+        </AlertDialog>
       </SheetContent>
     </Sheet>
   )

+ 1 - 0
app/src/components/HealthRing.tsx

@@ -8,6 +8,7 @@ export const STATUS_COLORS: Record<Status, string> = {
   online: '#34D399',
   warn: '#FBBF24',
   offline: '#F87171',
+  paused: '#6B7280',
 }
 
 interface HealthRingProps {

+ 4 - 0
app/src/components/InfoTip.tsx

@@ -11,6 +11,10 @@ export function InfoTip({ text }: { text: string }) {
       <TooltipTrigger asChild>
         <button
           type="button"
+          // #1064: sin tabIndex={-1}, el diálogo que lo contiene focaliza este
+          // botón al abrir (es el primer enfocable) y el tooltip salta solo.
+          // El texto sigue en aria-label para lectores de pantalla.
+          tabIndex={-1}
           aria-label={text}
           className="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-text-muted transition-colors hover:text-accent"
         >

+ 11 - 9
app/src/components/Layout.tsx

@@ -23,8 +23,7 @@ import {
   Settings,
   Waypoints,
   Wifi,
-  Wrench,
-} from 'lucide-react'
+  Wrench, RadioTower, Server } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { DashboardProvider, useDashboard } from '@/hooks/useDashboard'
@@ -59,9 +58,10 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/routers', labelKey: 'nav.routers', icon: RouterIcon },
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
+  { to: '/rack', labelKey: 'nav.rack', icon: Server, badge: 'labs' },
   { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
-  { to: '/wifi/channel-plan', labelKey: 'nav.channelPlan', icon: Wifi, badge: 'labs' },
-  { to: '/firmware-upgrades', labelKey: 'nav.firmwareUpgrades', icon: Cpu, badge: 'labs', adminOnly: true },
+  { to: '/wifi/channel-plan', labelKey: 'nav.channelPlan', icon: RadioTower },
+  { to: '/firmware-upgrades', labelKey: 'nav.firmwareUpgrades', icon: Cpu, adminOnly: true },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
   { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true, badge: 'labs' },
@@ -196,8 +196,9 @@ function LiveDot() {
 // ---------------------------------------------------------------------------
 
 /** Items de nav visibles según el overview. /roaming solo si hay usteer.
- *  La visibilidad de funcionalidades Labs (canales, actualizaciones) se
- *  controla desde la tarjeta Servicios en Ajustes (useServicesVisibility). */
+ *  La visibilidad de funcionalidades Labs (rack) se controla desde la
+ *  tarjeta Servicios en Ajustes (useServicesVisibility); actualizaciones de
+ *  firmware tiene toggle propio (#1146). */
 function useVisibleNavItems(): NavItem[] {
   const { usteer, orchestration } = useNetPulse()
   const [services] = useServicesVisibility()
@@ -212,10 +213,11 @@ function useVisibleNavItems(): NavItem[] {
           (it.to !== '/orchestration' || (labsOn && !!orchestration)) &&
           // Funcionalidades Labs controladas por cada toggle (rediseño v3):
           // solo se muestran en el nav si Labs está activo y su toggle encendido.
-          (it.to !== '/wifi/channel-plan' || (labsOn && services.canales)) &&
-          (it.to !== '/firmware-upgrades' || (labsOn && services.actualizaciones)),
+          // Firmware upgrades (#1146): visibilidad propia, ya no es Labs.
+          (it.to !== '/firmware-upgrades' || services.actualizaciones) &&
+          (it.to !== '/rack' || (labsOn && services.rack)),
       ),
-    [usteerAvailable, orchestration, labsOn, services.canales, services.actualizaciones],
+    [usteerAvailable, orchestration, labsOn, services.rack, services.actualizaciones],
   )
 }
 

+ 5 - 5
app/src/components/UpdateDialog.tsx

@@ -340,7 +340,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
 
   return (
     <Dialog open={open} onOpenChange={(o) => !busy && onOpenChange(o)}>
-      <DialogContent className="max-w-2xl">
+      <DialogContent className="max-w-2xl md:flex md:flex-col md:w-[800px] md:h-[600px] md:max-w-[calc(100vw-2rem)] md:max-h-[calc(100vh-2rem)]">
         <DialogHeader>
           <DialogTitle className="flex items-center gap-2">
             <DownloadCloud className="h-5 w-5 text-accent" strokeWidth={1.75} aria-hidden="true" />
@@ -350,7 +350,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
         </DialogHeader>
 
         {phase === 'confirm' && (
-          <div className="flex flex-col gap-4">
+          <div className="flex flex-col gap-4 md:flex-1 md:min-h-0">
             {/* Tarjeta de versión destacada (estilo Pulse) */}
             <div className="flex flex-col gap-1.5">
               <p className="text-xs font-semibold uppercase tracking-wider text-text-muted">
@@ -390,7 +390,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
                 <p className="text-xs font-semibold uppercase tracking-wider text-text-muted">
                   {t('update.dialog.changelogTitle')}
                 </p>
-                <div className="max-h-44 overflow-y-auto rounded-xl border border-border bg-surface px-3.5 py-2.5">
+                <div className="max-h-44 overflow-y-auto rounded-xl border border-border bg-surface px-3.5 py-2.5 md:max-h-none md:flex-1 md:min-h-0">
                   <ul className="flex flex-col gap-1">
                     {status!.commits!.map((c) => (
                       <li
@@ -421,7 +421,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
                 <p className="text-xs font-semibold uppercase tracking-wider text-text-muted">
                   {t('update.dialog.changelogTitle')}
                 </p>
-                <div className="max-h-44 overflow-y-auto rounded-xl border border-border bg-surface px-3.5 py-2.5">
+                <div className="max-h-44 overflow-y-auto rounded-xl border border-border bg-surface px-3.5 py-2.5 md:max-h-none md:flex-1 md:min-h-0">
                   <ul className="flex flex-col gap-1">
                     {changelogLines.map((l, i) => (
                         <li key={i} className="flex items-start gap-2 text-caption leading-snug text-text-secondary">
@@ -483,7 +483,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
               />
               <span>{t('update.dialog.ack')}</span>
             </label>
-            <DialogFooter className="border-t border-border pt-4">
+            <DialogFooter className="border-t border-border pt-4 md:mt-auto">
               <Button variant="outline" onClick={() => onOpenChange(false)}>
                 {t('update.dialog.cancel')}
               </Button>

+ 4 - 0
app/src/components/routers/AdGuardPanel.tsx

@@ -69,6 +69,10 @@ export function AdGuardPanel() {
     { label: t('home.services.avgDns'), value: adguard.dnsLatencyMs, unit: 'ms' },
   ] as const
 
+  // #1136: sin AdGuard configurado el panel no aplica: el estado caía en el
+  // fallback "inactivo" y la tarjeta se colgaba en el detalle de cada router.
+  if (!adguard.host) return null
+
   // Sin acceso a la API (GL.iNet exige sesión): estado honesto, sin números
   if (adguard.status !== 'active') {
     return (

+ 2 - 1
app/src/components/routers/AgentBadge.tsx

@@ -18,7 +18,8 @@ interface AgentBadgeProps {
 }
 
 function isOpenWrtDevice(t?: string): boolean {
-  return t === undefined || t === '' || t === 'glinet' || t === 'openwrt'
+  if (!t) return true
+  return t === 'glinet' || t === 'openwrt'
 }
 
 /**

+ 2 - 1
app/src/components/routers/AgentsSection.tsx

@@ -27,7 +27,8 @@ import { cn, copyToClipboard } from '@/lib/utils'
  */
 
 function isOpenWrtType(t: string | undefined): boolean {
-  return t === undefined || t === '' || t === 'glinet' || t === 'openwrt'
+  if (!t) return true
+  return t === 'glinet' || t === 'openwrt'
 }
 
 // copyText: alias del helper compartido con fallback para orígenes no

+ 19 - 8
app/src/components/routers/FleetCard.tsx

@@ -81,7 +81,7 @@ function TrafficTooltip({
 /** FleetCard grande de /routers (routers.md §②) */
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
   const { t } = useTranslation()
-  const { isDemo, serverUptimeSec } = useNetPulse()
+  const { isDemo, serverUptimeSec, adguard } = useNetPulse()
   const [tempUnit] = useTempUnit()
   const agent = useAgentFor(router.id)
   // #887: período de gracia post-arranque del server. Justo tras un reinicio
@@ -92,7 +92,7 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
   const inStartupGrace = (serverUptimeSec ?? Number.MAX_SAFE_INTEGER) < STARTUP_GRACE_SEC
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
-  const isOpenWrt = router.type === undefined || router.type === '' || router.type === 'glinet' || router.type === 'openwrt'
+  const isOpenWrt = !router.type || router.type === 'glinet' || router.type === 'openwrt'
   const agentDown = isOpenWrt && agent !== undefined && !agent.fresh
   const agentMissing = isOpenWrt && agent === undefined && router.agentOnly
   const reduce = useReducedMotion()
@@ -189,12 +189,23 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
                 <AgentBadge agent={agent} agentOnly={router.agentOnly} deviceType={router.type} />
               </div>
               <div className="truncate text-caption text-text-muted">
-                {isPrimary ? router.model : `OpenWrt · ${router.modelShort}`}
+                {router.type === 'routeros'
+                  ? (router.model || 'RouterOS')
+                  : router.type === 'managed-switch'
+                    ? (router.model || 'Switch')
+                    : isPrimary
+                      ? router.model
+                      : `OpenWrt · ${router.modelShort}`}
               </div>
-              {isPrimary && (
+              {isPrimary && router.type !== 'routeros' && router.type !== 'managed-switch' && (
                 <div className="mt-1.5 inline-flex items-center gap-1.5 rounded-full bg-elevated px-2 py-0.5">
-                  <span className="h-1.5 w-1.5 rounded-full bg-ok" />
-                  <span className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary">AdGuard</span>
+                  {/* #1136: el punto AdGuard solo con AdGuard configurado. */}
+                  {adguard.host && (
+                    <>
+                      <span className="h-1.5 w-1.5 rounded-full bg-ok" />
+                      <span className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary">AdGuard</span>
+                    </>
+                  )}
                   <span className="h-1.5 w-1.5 rounded-full bg-tunnel" />
                   <span className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary">WireGuard</span>
                 </div>
@@ -217,9 +228,9 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
               />
             </motion.div>
             <StatusPill
-              tone={router.status === 'online' ? 'ok' : router.status === 'warn' ? 'warn' : 'danger'}
+              tone={router.status === 'online' ? 'ok' : router.status === 'warn' ? 'warn' : router.status === 'paused' ? 'muted' : 'danger'}
               label={t(`common.status.${router.status}`)}
-              pulse={router.status !== 'online'}
+              pulse={router.status !== 'online' && router.status !== 'paused'}
             />
           </div>
         </div>

+ 1 - 1
app/src/components/routers/FleetTable.tsx

@@ -15,7 +15,7 @@ import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 
-const STATUS_ORDER: Record<Router['status'], number> = { online: 0, warn: 1, offline: 2 }
+const STATUS_ORDER: Record<Router['status'], number> = { online: 0, warn: 1, offline: 2, paused: 3 }
 
 type SortKey = 'name' | 'status' | 'cpu' | 'ram' | 'temp' | 'clients' | 'traffic' | 'uptime'
 

+ 73 - 6
app/src/components/routers/PortPanel.tsx

@@ -1,4 +1,5 @@
 import { motion, useReducedMotion } from 'framer-motion'
+import { useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import type { Router } from '@/data/mock'
@@ -7,7 +8,7 @@ import { SectionHeader } from '@/components/SectionHeader'
 import { getRouterExtras, portPeerDetail, portPeerLabel } from '@/components/routers/routerExtras'
 import type { EthPort, RouterExtras, SfpInfo } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
-import { Activity, Network } from 'lucide-react'
+import { Activity, ChevronDown, ChevronRight, Network } from 'lucide-react'
 import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
 import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
@@ -159,7 +160,7 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
         side="top"
         align="center"
         sideOffset={6}
-        className="w-56 border border-border-strong bg-elevated text-text-primary shadow-xl"
+        className="w-max min-w-56 max-w-[24rem] border border-border-strong bg-elevated text-text-primary shadow-xl"
       >
         {!port.up ? (
           <span className="text-caption text-text-muted">{t('routerDetail.ports.freeLabel', { label: port.label })}</span>
@@ -206,7 +207,7 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
                 )}
               </div>
             ) : (
-              (port.deviceMac || port.deviceCount) && (
+              (port.deviceMac || port.deviceCount || port.detail) && (
                 <div className="mt-2 grid grid-cols-2 gap-1.5">
                   {port.deviceMac && <MiniStat label="MAC" value={port.deviceMac} />}
                   {(port.detail || port.deviceCount) && <MiniStat label={t('routerDetail.ports.deviceDetail')} value={portPeerDetail(port)} />}
@@ -275,18 +276,32 @@ function SfpDetail({ sfp }: { sfp: SfpInfo }) {
   )
 }
 
-/** MiniStat: celda de dato del tooltip (mismo patrón que la topología). */
+/** MiniStat: celda de dato del tooltip (mismo patrón que la topología).
+ *  #1149: el valor hace wrap (break-words) en vez de truncar: lo único que
+ *  importa (IP, MAC, detalle) no se recorta por la derecha; el tooltip ya
+ *  crece con el contenido hasta max-w y aquí cae a una segunda línea. */
 function MiniStat({ label, value }: { label: string; value: string }) {
   return (
     <div className="rounded-lg bg-canvas/60 px-2 py-1.5">
       <div className="text-caption uppercase tracking-[0.06em] text-text-muted">{label}</div>
-      <div className="truncate font-mono text-mono-sm text-text-primary" title={value}>
+      <div className="break-words font-mono text-mono-sm text-text-primary" title={value}>
         {value}
       </div>
     </div>
   )
 }
 
+// FAMILY_LABEL_KEY (#1125): familia ifType (IANA) -> clave i18n de la
+// etiqueta del grupo de interfaces virtuales. Cerrado: el server solo emite
+// estas cinco ("lag"|"vlan"|"bridge"|"tunnel"|"virtual").
+const FAMILY_LABEL_KEY: Record<string, string> = {
+  lag: 'routerDetail.ports.fam_lag',
+  vlan: 'routerDetail.ports.fam_vlan',
+  bridge: 'routerDetail.ports.fam_bridge',
+  tunnel: 'routerDetail.ports.fam_tunnel',
+  virtual: 'routerDetail.ports.fam_virtual',
+}
+
 export function PortPanel({ router, extras, className, snmpStats }: {
   router: Router
   extras?: RouterExtras
@@ -296,7 +311,18 @@ export function PortPanel({ router, extras, className, snmpStats }: {
   const { t } = useTranslation()
   const { isDemo, wan } = useNetPulse()
   const ex = extras ?? (isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS)
-  const ports = ex.ethPorts
+  // #1125: las interfaces no físicas (LAG/VLAN/bridge/túnel/virtual) ya no se
+  // descartan (#1115): se listan en la sección colapsada de abajo. El chasis
+  // y el contador usados/total solo cuentan bocas físicas.
+  const ports = ex.ethPorts.filter((p) => !p.family)
+  const virtualPorts = ex.ethPorts.filter((p) => p.family)
+  const [virtualOpen, setVirtualOpen] = useState(() => localStorage.getItem('np-ports-virtual-open') === '1')
+  const toggleVirtual = () =>
+    setVirtualOpen((v) => {
+      const next = !v
+      localStorage.setItem('np-ports-virtual-open', next ? '1' : '0')
+      return next
+    })
   const used = ports.filter((p) => p.up).length
   const wirelessUplink = ex.backhaul?.kind === 'wireless'
 
@@ -358,6 +384,47 @@ export function PortPanel({ router, extras, className, snmpStats }: {
           </span>
         )}
       </div>
+
+      {/* #1125: las interfaces no físicas (LAG/VLAN/bridge/túnel) se listan
+          aquí, agrupadas y colapsadas por defecto, en vez de desaparecer de
+          la tarjeta (#1115): nada se oculta y el chasis queda limpio. El
+          estado plegado se recuerda. */}
+      {virtualPorts.length > 0 && (
+        <div className="mt-4 rounded-xl border border-border/70 bg-elevated/40">
+          <button
+            type="button"
+            onClick={toggleVirtual}
+            aria-expanded={virtualOpen}
+            className="flex w-full cursor-pointer items-center gap-2 px-4 py-2.5 text-caption font-medium text-text-secondary transition-colors hover:text-text-primary"
+          >
+            {virtualOpen ? (
+              <ChevronDown className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            ) : (
+              <ChevronRight className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            )}
+            {t('routerDetail.ports.virtualGroup', { count: virtualPorts.length })}
+          </button>
+          {virtualOpen && (
+            <ul className="border-t border-border/60 px-4 py-2">
+              {virtualPorts.map((p) => (
+                <li key={p.id} className="flex items-center gap-3 py-1.5 text-caption">
+                  <span className="inline-flex w-16 shrink-0 justify-center rounded border border-border px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wide text-text-muted">
+                    {t(FAMILY_LABEL_KEY[p.family ?? ''] ?? 'routerDetail.ports.fam_virtual', { defaultValue: p.family })}
+                  </span>
+                  <span className="truncate font-mono text-mono-sm text-text-primary">{p.label}</span>
+                  <span className="ml-auto inline-flex shrink-0 items-center gap-2">
+                    {p.speed && <span className="text-text-muted">{p.speed}</span>}
+                    <span
+                      className={p.up ? 'h-1.5 w-1.5 rounded-full bg-ok' : 'h-1.5 w-1.5 rounded-full bg-border-strong/50'}
+                      title={p.up ? t('routerDetail.ports.inUse') : t('routerDetail.ports.free')}
+                    />
+                  </span>
+                </li>
+              ))}
+            </ul>
+          )}
+        </div>
+      )}
     </section>
   )
 }

+ 17 - 5
app/src/components/routers/RouterDetailHeader.tsx

@@ -4,6 +4,7 @@ import { motion, useReducedMotion } from 'framer-motion'
 import { useTranslation } from 'react-i18next'
 import { roleLabel } from '@/i18n'
 import type { Router } from '@/data/mock'
+import { useNetPulse } from '@/data/DataProvider'
 import { HealthRing } from '@/components/HealthRing'
 import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
@@ -18,19 +19,24 @@ export function RouterDetailHeader({ router }: { router: Router }) {
   const reduce = useReducedMotion()
   const isGateway = router.roleBadge === 'Principal'
   const agent = useAgentFor(router.id)
+  // #1136: el chip AdGuard solo tiene sentido con AdGuard configurado; sin
+  // host era un adorno fijo en la cabecera del gateway.
+  const { adguard } = useNetPulse()
   const pills = [
     { label: roleLabel(router.roleBadge), tone: 'accent' as const, pulse: false },
     {
       label: t(`common.status.${router.status}`),
-      tone: (router.status === 'online' ? 'ok' : router.status === 'warn' ? 'warn' : 'danger') as 'ok' | 'warn' | 'danger',
-      pulse: router.status !== 'online',
+      tone: (router.status === 'online' ? 'ok' : router.status === 'warn' ? 'warn' : router.status === 'paused' ? 'muted' : 'danger') as 'ok' | 'warn' | 'danger' | 'muted',
+      pulse: router.status !== 'online' && router.status !== 'paused',
     },
-    ...(isGateway
+    ...(isGateway && adguard.host
       ? [
           { label: 'AdGuard', tone: 'ok' as const, pulse: false },
           { label: 'WireGuard', tone: 'tunnel' as const, pulse: false },
         ]
-      : []),
+      : isGateway
+        ? [{ label: 'WireGuard', tone: 'tunnel' as const, pulse: false }]
+        : []),
   ]
 
   return (
@@ -67,7 +73,13 @@ export function RouterDetailHeader({ router }: { router: Router }) {
           <div className="min-w-0">
             <h1 className="font-display text-h1 text-text-primary">{router.name}</h1>
             <p className="text-caption text-text-muted">
-              {isGateway ? router.model : `OpenWrt · ${router.modelShort}`}
+              {router.type === 'routeros'
+                ? (router.model || 'RouterOS')
+                : router.type === 'managed-switch'
+                  ? (router.model || 'Switch')
+                  : isGateway
+                    ? router.model
+                    : `OpenWrt · ${router.modelShort}`}
             </p>
             <div className="mt-2 flex flex-wrap items-center gap-1.5">
               {pills.map((p, i) => (

+ 33 - 14
app/src/components/routers/RouterInfo.tsx

@@ -54,7 +54,7 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
     // aparecer en ningún sitio de la web; la fila ID lo hace visible.
     { label: 'ID', node: router.id },
     { label: 'IP LAN', node: router.ip },
-    { label: 'MAC', node: ex.mac },
+    { label: 'MAC', node: ex.mac && ex.mac !== '—' ? ex.mac : (router.mac || '—') },
     {
       label: 'Firmware',
       node: (
@@ -64,14 +64,14 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
           {router.firmwareTarget && (
             <span className="text-text-muted">{t('routerDetail.info.firmwareTarget', { target: router.firmwareTarget })}</span>
           )}
-          {router.firmwareOutdated ? (
+          {ex.firmwareAvailable ? (
+            <span title={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })}>
+              <StatusPill tone="warn" label={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })} />
+            </span>
+          ) : router.firmwareOutdated ? (
             <StatusPill tone="warn" label={t('routers.firmwareOutdated')} />
           ) : ex.firmwareUpdated ? (
             <StatusPill tone="ok" label={t('routerDetail.info.updated')} />
-          ) : ex.firmwareAvailable ? (
-            <span title={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })}>
-              <StatusPill tone="warn" label={ex.firmwareAvailable} />
-            </span>
           ) : null}
         </span>
       ),
@@ -81,7 +81,17 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
     { label: t('routerDetail.info.timezone'), node: ex.timezone ?? '—' },
     {
       label: t('routerDetail.info.access'),
-      node: (
+      node: router.type === 'routeros' ? (
+        <span className="inline-flex items-center gap-1.5">
+          <Terminal className="h-3.5 w-3.5 text-text-muted" strokeWidth={1.75} />
+          RouterOS API
+          <span className="rounded-full bg-accent/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">8728</span>
+        </span>
+      ) : router.type === 'managed-switch' || router.type === 'external' ? (
+        <span className="inline-flex items-center gap-1.5">
+          SNMP / API
+        </span>
+      ) : (
         <span className="inline-flex items-center gap-1.5">
           <Terminal className="h-3.5 w-3.5 text-text-muted" strokeWidth={1.75} />
           SSH
@@ -110,10 +120,14 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
       <div className="mt-3 flex flex-wrap gap-2 border-t border-border pt-3.5">
         {/* #442: "Abrir WebUI" genérico: LuCI en OpenWrt, web del fabricante
             en switches gestionados/beacon (ninguno de los dos es "LuCI"). */}
+        {/* #1098: el title expone la URL exacta (http plano a la IP); con
+            HTTPS/LE u otro puerto el botón puede no servir y el usuario debe
+            poder verlo ANTES de pulsar. */}
         <a
           href={`http://${router.ip}`}
           target="_blank"
           rel="noreferrer"
+          title={`http://${router.ip}`}
           className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
         >
           <ExternalLink className="h-3.5 w-3.5" strokeWidth={1.75} />
@@ -131,13 +145,18 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
             {t('routerDetail.info.openNetgrip')}
           </a>
         )}
-        <button
-          onClick={copySsh}
-          className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
-        >
-          <Terminal className="h-3.5 w-3.5" strokeWidth={1.75} />
-          {t('routerDetail.info.copySsh')}
-        </button>
+        {/* #1098: mismo criterio que el botón web: mostrar el comando
+            exacto que se va a copiar. */}
+        {router.type !== 'routeros' && router.type !== 'managed-switch' && router.type !== 'external' && (
+          <button
+            onClick={copySsh}
+            title={`ssh root@${router.ip}`}
+            className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+          >
+            <Terminal className="h-3.5 w-3.5" strokeWidth={1.75} />
+            {t('routerDetail.info.copySsh')}
+          </button>
+        )}
       </div>
 
       {/* Toast "Comando copiado" */}

+ 131 - 44
app/src/components/routers/WanLatency.tsx

@@ -1,7 +1,7 @@
 import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis } from 'recharts'
 import { motion, useReducedMotion } from 'framer-motion'
 import { useTranslation } from 'react-i18next'
-import { Activity, Loader2 } from 'lucide-react'
+import { Activity, ChevronDown, ChevronUp, Loader2 } from 'lucide-react'
 import { useCallback, useEffect, useState } from 'react'
 import { fmtBytes, fmtEs } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
@@ -9,7 +9,7 @@ import { SectionHeader } from '@/components/SectionHeader'
 import { Sparkline } from '@/components/Sparkline'
 import { LatencyGauge } from '@/components/routers/LatencyGauge'
 import { relTimeFromTs } from '@/i18n'
-import { WAN_LATENCY_24H, WAN_LATENCY_STATS } from '@/components/routers/routerExtras'
+import type { RouterExtras } from '@/components/routers/routerExtras'
 
 function WanTooltip({
   active,
@@ -36,13 +36,29 @@ function WanTooltip({
   )
 }
 
-/** ④ WAN & Latencia del gateway (router-detail.md §④) — split 7/5. */
-export function WanLatency() {
+/** ④ WAN & Latencia del gateway (router-detail.md §④) — split 7/5.
+ *  #1148: el spark de latencia y sus stats salen de la serie REAL 24h
+ *  (extras.gatewayLatencySpark, AVG horario de metrics.latency_ms); sin
+ *  sonda/historial se pinta "sin datos" en vez de ceros ni mocks. */
+export function WanLatency({ extras }: { extras?: RouterExtras }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const { traffic: trafficByRange, wan } = useNetPulse()
   const data = trafficByRange['24h']
 
+  // Serie real 24h; stats derivadas. Sin muestras (sonda sin datos, unidad
+  // nueva) todo cae a undefined y la tarjeta muestra su estado vacío.
+  const spark = extras?.gatewayLatencySpark ?? []
+  const hasLatency = spark.length > 0
+  const avgMs = hasLatency ? spark.reduce((a, b) => a + b, 0) / spark.length : undefined
+  const jitterMs = hasLatency
+    ? spark.slice(1).reduce((acc, v, i) => acc + Math.abs(v - spark[i]), 0) / (spark.length - 1)
+    : undefined
+  // La pérdida solo es significativa si la sonda corre (latencia > 0).
+  const hasProbe = wan.latencyMs > 0
+  const lossPct = hasProbe ? wan.lossPct : undefined
+  const fmtMs = (v?: number) => (v === undefined ? '—' : `${fmtEs(v, v < 10 ? 1 : 0)} ms`)
+
   const WAN_METRICS = [
     { label: t('routerDetail.wan.publicIp'), value: wan.publicIp },
     { label: 'ISP', value: `${wan.isp} · ${t('routerDetail.wan.fiber', { plan: wan.plan.replace(' Mbps', '') })}` },
@@ -102,16 +118,33 @@ export function WanLatency() {
       <section className="flex flex-col rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-5">
         <SectionHeader title={t('home.latency')} />
         <div className="mt-4 flex flex-1 flex-col items-center justify-center gap-4">
-          <LatencyGauge valueMs={wan.latencyMs} caption={t('routerDetail.latency.toHost', { host: '1.1.1.1' })} />
+          {hasProbe ? (
+            <LatencyGauge valueMs={wan.latencyMs} caption={t('routerDetail.latency.toHost', { host: '1.1.1.1' })} />
+          ) : (
+            <div
+              className="flex h-[160px] w-[160px] flex-col items-center justify-center rounded-full border-2 border-dashed border-border"
+              role="img"
+              aria-label={t('routerDetail.latency.noData')}
+            >
+              <span className="font-mono text-3xl font-semibold text-text-muted">—</span>
+              <span className="text-caption font-medium uppercase tracking-[0.06em] text-text-muted">ms</span>
+            </div>
+          )}
           <div className="w-full">
             <div className="mb-1 text-[10px] font-medium uppercase tracking-[0.06em] text-text-muted">{t('routerDetail.latency.24h')}</div>
-            <Sparkline data={WAN_LATENCY_24H} width={560} height={48} color="#34D399" area className="w-full" />
+            {hasLatency ? (
+              <Sparkline data={spark} width={560} height={48} color="#34D399" area className="w-full" />
+            ) : (
+              <div className="flex h-12 items-center justify-center text-caption text-text-muted">
+                {t('routerDetail.latency.noData')}
+              </div>
+            )}
           </div>
           <div className="grid w-full grid-cols-3 gap-3 border-t border-border pt-3.5">
             {[
-              [t('home.traffic.average'), `${WAN_LATENCY_STATS.avgMs} ms`],
-              ['Jitter', `${fmtEs(WAN_LATENCY_STATS.jitterMs, 1)} ms`],
-              [t('home.traffic.loss'), `${WAN_LATENCY_STATS.lossPct} %`],
+              [t('home.traffic.average'), fmtMs(avgMs)],
+              ['Jitter', fmtMs(jitterMs)],
+              [t('home.traffic.loss'), lossPct === undefined ? '—' : `${fmtEs(lossPct, 1)} %`],
             ].map(([k, v]) => (
               <div key={k} className="text-center">
                 <div className="text-label uppercase text-text-muted">{k}</div>
@@ -138,6 +171,8 @@ type SpeedtestItem = {
   upMbps: number
   pingMs?: number
   serverName?: string
+  /** manual | auto (#744), para el desplegable de recientes (#1092). */
+  origin?: string
 }
 
 /** Punto de la serie del histórico de speedtests (etiqueta ya formateada). */
@@ -148,38 +183,11 @@ function toPoints(items: SpeedtestItem[]): SpeedtestPoint[] {
   return items.map((it) => ({ t: fmt.format(new Date(it.ts)), down: it.downMbps, up: it.upMbps }))
 }
 
-/** Hook ligero del histórico de speedtests (overview #982): la serie y el
- *  último test real (para la línea de valores), sin estado de ejecución ni
- *  botón. Carga única al montar. */
-export function useSpeedtestHistory(hours = 168): { points: SpeedtestPoint[]; last: SpeedtestItem | null } {
-  const [points, setPoints] = useState<SpeedtestPoint[]>([])
-  const [last, setLast] = useState<SpeedtestItem | null>(null)
-  useEffect(() => {
-    let cancelled = false
-    void (async () => {
-      try {
-        const res = await fetch(`/api/speedtest/history?hours=${hours}`)
-        if (!res.ok || cancelled) return
-        const h = await res.json()
-        if (cancelled) return
-        const items: SpeedtestItem[] = h.items ?? []
-        setPoints(toPoints(items))
-        setLast(items.length ? items[items.length - 1]! : null)
-      } catch {
-        // Sin red / sesión caducada: no se pinta nada.
-      }
-    })()
-    return () => {
-      cancelled = true
-    }
-  }, [hours])
-  return { points, last }
-}
-
 /** Gráfica del histórico de velocidad medida: SOLO la serie, sin botón de
- *  ejecutar test ni línea de valores. La reutilizan SpeedtestStrip (detalle
- *  del gateway) y el overview dentro de WanTraffic (#982). Lleva sus propios
- *  gradientes (antes dependía de los ids del chart WAN del detalle). */
+ *  ejecutar test ni línea de valores. La reutiliza SpeedtestStrip, que vive
+ *  en el overview (restaurado en #1092) y vivió en el detalle del gateway.
+ *  Lleva sus propios gradientes (antes dependía de los ids del chart WAN del
+ *  detalle). */
 export function SpeedtestHistoryChart({ points, height = 64 }: { points: SpeedtestPoint[]; height?: number }) {
   const { t } = useTranslation()
   if (points.length <= 1) return null
@@ -220,6 +228,7 @@ function useSpeedtestState() {
   const [lastError, setLastError] = useState<string | null>(null)
   const [last, setLast] = useState<SpeedtestItem | null>(null)
   const [points, setPoints] = useState<SpeedtestPoint[]>([])
+  const [items, setItems] = useState<SpeedtestItem[]>([])
   const [starting, setStarting] = useState(false)
 
   const load = useCallback(async () => {
@@ -236,7 +245,11 @@ function useSpeedtestState() {
       }
       if (hRes.ok) {
         const h = await hRes.json()
-        setPoints(toPoints(h.items ?? []))
+        const list: SpeedtestItem[] = h.items ?? []
+        setPoints(toPoints(list))
+        // Recientes para el desplegable (#1092): los 10 últimos, más nuevo
+        // arriba. Los mismos datos que ya trae el histórico.
+        setItems([...list].slice(-10).reverse())
       }
     } catch {
       // Sin red / sesión caducada: se conserva el último estado pintado.
@@ -267,12 +280,13 @@ function useSpeedtestState() {
     }
   }, [])
 
-  return { running, lastError, last, points, starting, run, reload: load }
+  return { running, lastError, last, points, items, starting, run, reload: load }
 }
 
 export function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
-  const { t } = useTranslation()
-  const { running, lastError, last, points, starting, run } = useSpeedtestState()
+  const { t, i18n } = useTranslation()
+  const { running, lastError, last, points, items, starting, run } = useSpeedtestState()
+  const [recentOpen, setRecentOpen] = useState(false)
 
   const busy = running || starting
   // El API serializa ts como ISO 8601; relTimeFromTs espera unix SEGUNDOS
@@ -280,6 +294,12 @@ export function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
   const when = last ? (relTimeFromTs(Math.floor(new Date(last.ts).getTime() / 1000)) ?? '') : ''
   const planPct =
     contractDown && contractDown > 0 && last ? Math.round((last.downMbps / contractDown) * 100) : null
+  const recentFmt = new Intl.DateTimeFormat(i18n.language?.startsWith('en') ? 'en-GB' : 'es-ES', {
+    day: 'numeric',
+    month: 'short',
+    hour: '2-digit',
+    minute: '2-digit',
+  })
 
   return (
     <div className="mt-4 border-t border-border pt-4" aria-label={t('routerDetail.wan.speedtestTitle')}>
@@ -347,6 +367,73 @@ export function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
           {lastError === 'unavailable' ? t('settings.speedtest.unavailable') : t('routerDetail.wan.speedtestEmpty')}
         </p>
       )}
+
+      {/* Tests recientes (#1092): desplegable compacto con los 10 últimos
+          resultados (origen, bajada/subida, ping y servidor). Los datos ya
+          los trae /api/speedtest/history. */}
+      {items.length > 0 && (
+        <div className="mt-1">
+          <button
+            type="button"
+            onClick={() => setRecentOpen((v) => !v)}
+            aria-expanded={recentOpen}
+            className="inline-flex cursor-pointer items-center gap-1 text-caption text-accent hover:underline"
+          >
+            {recentOpen ? (
+              <ChevronUp className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            ) : (
+              <ChevronDown className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+            )}
+            {recentOpen ? t('settings.speedtest.recentHide') : t('settings.speedtest.recentShow')}
+          </button>
+          {recentOpen && (
+            <div className="mt-1.5 overflow-x-auto">
+              <table className="w-full text-caption">
+                <thead>
+                  <tr className="text-left text-text-muted">
+                    <th className="py-1 pr-3 font-medium">{t('settings.speedtest.colWhen')}</th>
+                    <th className="py-1 pr-3 font-medium">{t('settings.speedtest.colOrigin')}</th>
+                    <th className="py-1 pr-3 font-medium">↓</th>
+                    <th className="py-1 pr-3 font-medium">↑</th>
+                    <th className="py-1 pr-3 font-medium">ping</th>
+                    <th className="py-1 font-medium">{t('settings.speedtest.colServer')}</th>
+                  </tr>
+                </thead>
+                <tbody className="font-mono text-text-secondary">
+                  {items.map((it, idx) => (
+                    <tr key={`${it.ts}-${idx}`} className="border-t border-border/60">
+                      <td className="py-1.5 pr-3">
+                        {(() => {
+                          try {
+                            return recentFmt.format(new Date(it.ts))
+                          } catch {
+                            return it.ts
+                          }
+                        })()}
+                      </td>
+                      <td className="py-1.5 pr-3">
+                        <span
+                          className={`rounded-full border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${
+                            it.origin === 'manual'
+                              ? 'border-accent/40 bg-accent/10 text-accent'
+                              : 'border-border bg-surface text-text-muted'
+                          }`}
+                        >
+                          {it.origin === 'manual' ? t('settings.speedtest.originManual') : t('settings.speedtest.originAuto')}
+                        </span>
+                      </td>
+                      <td className="py-1.5 pr-3 text-accent">{fmtEs(it.downMbps, 1)}</td>
+                      <td className="py-1.5 pr-3 text-tunnel">{fmtEs(it.upMbps, 1)}</td>
+                      <td className="py-1.5 pr-3">{it.pingMs !== undefined ? `${fmtEs(it.pingMs, 0)} ms` : '-'}</td>
+                      <td className="py-1.5">{it.serverName ?? '-'}</td>
+                    </tr>
+                  ))}
+                </tbody>
+              </table>
+            </div>
+          )}
+        </div>
+      )}
     </div>
   )
 }

+ 10 - 2
app/src/components/routers/routerExtras.ts

@@ -70,6 +70,10 @@ export interface EthPort {
   up: boolean
   speed?: string // "2.5 Gbps" | "1 Gbps"
   iface?: string // interfaz física (/proc/net/dev), si difiere del id
+  /** #1125: familia para interfaces NO físicas ("lag"|"vlan"|"bridge"|
+   * "tunnel"|"virtual"); ausente = boca física. La tarjeta las agrupa en
+   * la sección colapsada en vez de ocultarlas (#1115). */
+  family?: string
   rxBytes?: number // contadores acumulados de la boca (#305)
   txBytes?: number
   rxErrors?: number
@@ -121,9 +125,13 @@ export function portPeerDetail(port: EthPort): string {
   }
   switch (port.peerKind) {
     case 'router-link':
-      return i18n.t('routerDetail.ports.detailRouterLink')
     case 'router-link-lldp':
-      return i18n.t('routerDetail.ports.detailRouterLinkLldp')
+      // #1150: la mgmt-ip del vecino LLDP viaja en detail y es más útil
+      // que la plantilla; sin dato LLDP se queda la plantilla traducida.
+      return (
+        port.detail ||
+        i18n.t(port.peerKind === 'router-link' ? 'routerDetail.ports.detailRouterLink' : 'routerDetail.ports.detailRouterLinkLldp')
+      )
     case 'ap-wifi':
       return i18n.t('routerDetail.ports.detailApWifi')
     case 'mac':

+ 1 - 1
app/src/components/topology/TopologyMap.tsx

@@ -210,7 +210,7 @@ function TooltipCard({
           <div className="mt-2 grid grid-cols-2 gap-1.5">
             <MiniStat label={t('routerDetail.wan.publicIp')} value={wan.publicIp} />
             <MiniStat label={t('topology.plan')} value={wan.plan} />
-            <MiniStat label={t('home.latency')} value={`${wan.latencyMs} ms`} />
+            <MiniStat label={t('home.latency')} value={wan.latencyMs > 0 ? `${Math.round(wan.latencyMs)} ms` : '—'} />
             <MiniStat label={t('home.traffic.loss')} value={`${wan.lossPct} %`} />
           </div>
         </div>

+ 29 - 2
app/src/components/topology/model.ts

@@ -1427,7 +1427,13 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
           const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
           // #1047: el padre lo decide la semántica (FDB del switch cuando no
           // hay LLDP); solo se cae al gateway si el server no lo resolvió.
-          const from = routerById.get(sl.from) ?? gatewayNode ?? null
+          // #1060: el padre puede ser un distnode (círculo inferido/gestionado):
+          // el uplink sale del círculo, no del router.
+          const from =
+            routerById.get(sl.from) ??
+            distNodes.find((n) => n.id === sl.from) ??
+            gatewayNode ??
+            null
           const d = from ? curve(from, node) : ''
           return {
             id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
@@ -1550,6 +1556,27 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     return mbps >= 1000 ? `${(mbps / 1000).toFixed(mbps % 1000 === 0 ? 0 : 1)} Gbps` : `${mbps} Mbps`
   }
   const backhauls: BackhaulRow[] = []
+  // #1063: la columna A de un uplink debe nombrar al padre REAL que dice la
+  // semántica server-side (sem.links kind 'uplink': from = id de router o de
+  // distnode, p. ej. el padre aprendido por FDB #1047/#1060), no siempre el
+  // gateway. Sin semántica o sin match → gateway (comportamiento de siempre,
+  // demo incluido).
+  const uplinkFromByNodeId = new Map<string, string>()
+  if (sem) {
+    for (const sl of sem.links) {
+      if (sl.kind === 'uplink') uplinkFromByNodeId.set(sl.to, sl.from)
+    }
+  }
+  const uplinkParentName = (nodeId: string): string => {
+    const fromId = uplinkFromByNodeId.get(nodeId)
+    if (fromId) {
+      const rn = routerById.get(fromId)
+      if (rn) return rn.router.name
+      const dn = distById.get(fromId) ?? distNodes.find((n) => n.id === fromId)?.node
+      if (dn) return dn.name ?? dn.ip ?? dn.id
+    }
+    return gatewayNode?.router.name ?? ''
+  }
   if (gatewayNode) {
     backhauls.push({
       id: 'wan', a: gatewayNode.router.name, b: 'Internet', kind: 'wan',
@@ -1561,7 +1588,7 @@ 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: gatewayNode?.router.name ?? '', b: node.router.name, kind: 'uplink',
+      id: `uplink-${node.id}`, a: uplinkParentName(node.id), b: node.router.name, kind: 'uplink',
       type: isWifi ? 'topology.links.wifiUplink' : 'common.cable',
       // 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

+ 10 - 2
app/src/components/ui/dialog.tsx

@@ -36,7 +36,7 @@ function DialogOverlay({
     <DialogPrimitive.Overlay
       data-slot="dialog-overlay"
       className={cn(
-        "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+        "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 backdrop-blur-md",
         className
       )}
       {...props}
@@ -57,6 +57,14 @@ function DialogContent({
       <DialogOverlay />
       <DialogPrimitive.Content
         data-slot="dialog-content"
+        // #1064: el autofocus inicial de Radix cae en la (x) y la pinta con el
+        // anillo de foco al abrir; lo dirigimos al propio panel (tabIndex -1)
+        // para que no parpadee el marco en el botón de cerrar.
+        onOpenAutoFocus={(e) => {
+          e.preventDefault()
+          ;(e.currentTarget as HTMLElement | null)?.focus?.()
+        }}
+        tabIndex={-1}
         className={cn(
           "bg-surface data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
           className
@@ -67,7 +75,7 @@ function DialogContent({
         {showCloseButton && (
           <DialogPrimitive.Close
             data-slot="dialog-close"
-            className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
+            className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 hover:ring-2 hover:ring-ring hover:ring-offset-2 hover:outline-hidden focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
           >
             <XIcon />
             <span className="sr-only">Close</span>

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

@@ -180,7 +180,12 @@ export interface NetPulseApi extends NetPulseData {
   setAlertConfig: (category: AlertCategory, level: AlertConfigLevel) => Promise<boolean>
   /** Read state en SERVIDOR (live): POST /api/alerts/read. Demo: estado local. Optimista. */
   markAlertsRead: (ids: string[]) => void
-  /** #971: VACÍA el feed - POST /api/alerts/clear (live). Demo: estado local. Optimista. */
+  /** Marca leídas TODAS las alertas actuales sin borrarlas (#1034): el feed
+   * las conserva como leídas; en live POST /api/alerts/read-all. Demo:
+   * estado local. Optimista. */
+  markAllAlertsRead: () => void
+  /** Acción destructiva "Vaciar registro" (#1034) - POST /api/alerts/clear
+   * (live): borra el log del servidor. Demo: estado local. Optimista. */
   clearAllAlerts: () => void
   /** POST /api/alerts/silence (live): silencia alertas con la misma dedup key. */
   silenceAlert: (id: string, duration: '1h' | '24h' | 'forever') => void
@@ -935,10 +940,39 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
-  // #971: "Marcar todo como leído" VACÍA el feed - las alertas visibles se
-  // descartan (dismiss en servidor: borradas de alert_log + conjunto dismissed,
-  // no reaparecen tras F5) - no solo se marcan. Una alerta viva (volátil con
-  // la condición aún activa, p.ej. agent-down) puede volver al re-evaluarse.
+  /** #1034: marca leídas todas las alertas actuales SIN borrarlas del log:
+   * solo toca el read state (feed conservado, "Solo no leídas" es lo que
+   * limpia la vista). Optimista; en live además POST /api/alerts/read-all. */
+  const markAllAlertsRead = useCallback(() => {
+    setBundle((prev) => ({
+      ...prev,
+      alerts: prev.alerts.map((a) => ({ ...a, read: true })),
+      unreadAlerts: modeRef.current === 'live' ? prev.unreadAlerts : 0,
+    }))
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/read-all', { method: 'POST' })
+        if (res.status === 401) redirectLogin()
+        // #891: igual que en markAlertsRead — re-aplica el leído por si un
+        // snapshot pre-POST pisó el estado optimista mientras el POST volaba.
+        if (res.ok) {
+          setBundle((prev) => ({
+            ...prev,
+            alerts: prev.alerts.map((a) => ({ ...a, read: true })),
+          }))
+        }
+      } catch {
+        /* el próximo snapshot/SSE resincroniza el read state */
+      }
+    })()
+  }, [])
+
+  // #1034: "Vaciar registro" BORRA el feed (dismiss en servidor: alert_log +
+  // conjunto dismissed, no reaparecen tras F5). Es la acción destructiva; el
+  // botón "Marcar todo como leído" ya no toca este endpoint (marca leídas
+  // todas sin borrar). Una alerta viva (volátil con la condición aún activa,
+  // p.ej. agent-down) puede volver al re-evaluarse.
   const clearAllAlerts = useCallback(() => {
     setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
     if (modeRef.current !== 'live') return
@@ -1259,6 +1293,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       alertsConfig,
       setAlertConfig,
       markAlertsRead,
+      markAllAlertsRead,
       clearAllAlerts,
       silenceAlert,
       dismissAlert,
@@ -1269,7 +1304,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       uninstallAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, clearAllAlerts, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

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

@@ -9,7 +9,7 @@
 // Tipos base
 // ---------------------------------------------------------------------------
 
-export type Status = 'online' | 'warn' | 'offline'
+export type Status = 'online' | 'warn' | 'offline' | 'paused'
 export type TimeRange = '1h' | '24h' | '7d' | '30d'
 
 export interface Router {
@@ -22,7 +22,7 @@ export interface Router {
   modelShort: string
   role: string
   /** Pill de rol: "Principal" | "AP" | "SW" */
-  roleBadge: 'Principal' | 'AP' | 'SW'
+  roleBadge: 'Principal' | 'AP' | 'SW' | 'EXT'
   ip: string
   /** MAC del bridge br-lan (live) */
   mac?: string
@@ -34,6 +34,8 @@ export interface Router {
   firmwareOutdated?: boolean
   /** Router configurado para funcionar solo con agente (sin SSH). */
   agentOnly?: boolean
+  /** #1085: unidad pausada (no se sondea ni alerta; insignia "paused"). */
+  disabled?: boolean
   /** Tipo de dispositivo: "glinet"|"openwrt"|"managed-switch"|"external". */
   type?: string
   status: Status
@@ -253,6 +255,11 @@ export interface Device {
    */
   firstSeenMs?: number
   lastSeenMs?: number
+  /**
+   * #1151: MACs enlazadas a este cliente (mismo dispositivo con varias
+   * MACs, p. ej. una por SSID). Solo viaja en la entrada canónica.
+   */
+  aliasMacs?: string[]
 }
 
 /**

+ 24 - 20
app/src/hooks/useIntegrations.ts

@@ -11,16 +11,32 @@ export interface IntegrationsState {
   telegram: boolean
   proxmox: boolean
   mqtt: boolean
+  mcp: boolean
 }
 
-const DEFAULTS: IntegrationsState = { ntfy: true, telegram: true, proxmox: true, mqtt: false }
+const DEFAULTS: IntegrationsState = { ntfy: true, telegram: true, proxmox: true, mqtt: false, mcp: false }
+
+// parseIntegrations: mapea la view del servidor (#968 + MCP #1114). mcp solo
+// es true si el despliegue lo habilitó por env (mcpLocked=false) y el toggle
+// está activo; mcpLocked=true (sin env) lo muestra apagado y bloqueado.
+function parseIntegrations(d: Record<string, unknown>): IntegrationsState {
+  return {
+    ntfy: d.ntfy !== false,
+    telegram: d.telegram !== false,
+    proxmox: d.proxmox !== false,
+    mqtt: d.mqtt === true,
+    mcp: d.mcp === true,
+  }
+}
 
 export function useIntegrations(enabled = true): {
   integrations: IntegrationsState
   loaded: boolean
+  mcpLocked: boolean
   setIntegration: (k: keyof IntegrationsState, v: boolean) => void
 } {
   const [integrations, setIntegrations] = useState<IntegrationsState>(DEFAULTS)
+  const [mcpLocked, setMcpLocked] = useState(true)
   const [loaded, setLoaded] = useState(false)
 
   useEffect(() => {
@@ -30,12 +46,8 @@ export function useIntegrations(enabled = true): {
       .then((r) => (r.ok ? r.json() : null))
       .then((d) => {
         if (!alive || !d) return
-        setIntegrations({
-          ntfy: d.ntfy !== false,
-          telegram: d.telegram !== false,
-          proxmox: d.proxmox !== false,
-          mqtt: d.mqtt === true,
-        })
+        setIntegrations(parseIntegrations(d))
+        setMcpLocked(d.mcpLocked === true)
         setLoaded(true)
       })
       .catch(() => undefined)
@@ -59,12 +71,8 @@ export function useIntegrations(enabled = true): {
       })
       .then((d) => {
         if (d) {
-          setIntegrations({
-            ntfy: d.ntfy !== false,
-            telegram: d.telegram !== false,
-            proxmox: d.proxmox !== false,
-            mqtt: d.mqtt === true,
-          })
+          setIntegrations(parseIntegrations(d))
+          setMcpLocked(d.mcpLocked === true)
         }
       })
       .catch(() => {
@@ -73,17 +81,13 @@ export function useIntegrations(enabled = true): {
           .then((r) => (r.ok ? r.json() : null))
           .then((d) => {
             if (d) {
-              setIntegrations({
-                ntfy: d.ntfy !== false,
-                telegram: d.telegram !== false,
-                proxmox: d.proxmox !== false,
-                mqtt: d.mqtt === true,
-              })
+              setIntegrations(parseIntegrations(d))
+              setMcpLocked(d.mcpLocked === true)
             }
           })
           .catch(() => undefined)
       })
   }, [])
 
-  return { integrations, loaded, setIntegration }
+  return { integrations, loaded, mcpLocked, setIntegration }
 }

+ 8 - 3
app/src/hooks/useServicesVisibility.ts

@@ -12,8 +12,11 @@ export interface ServicesVisibility {
   labs: boolean
   /** Funcionalidades individuales de Labs (rediseño v3): cada una se
    *  activa/desactiva por separado y controla su entrada en el nav/sidebar. */
-  canales: boolean
+  /** Actualizaciones de firmware: visibilidad propia de la página (#1146),
+   *  ya no es Labs: el admin la muestra u oculta desde Servicios. */
   actualizaciones: boolean
+  /** Rack canvas (labs): desactivado por defecto hasta madurar. */
+  rack: boolean
 }
 
 const KEY = 'netpulse-services'
@@ -22,10 +25,12 @@ const DEFAULTS: ServicesVisibility = {
   wireguard: true,
   openvpn: false,
   labs: false,
-  // Por defecto, al activar Labs se muestran las 3 funcionalidades activas;
+  // Por defecto, al activar Labs se muestran las funcionalidades activas;
   // el admin las puede desactivar individualmente.
-  canales: true,
+  // Actualizaciones visible por defecto (salió de Labs en #1121).
   actualizaciones: true,
+  // Rack (labs) nace DESACTIVADO: vista en desarrollo.
+  rack: false,
 }
 
 export function getServicesVisibility(): ServicesVisibility {

+ 2 - 1
app/src/i18n.ts

@@ -163,10 +163,11 @@ export function manufacturerLabel(manufacturer: string): string {
   return manufacturer
 }
 
-/** Rol canónico del dataset ("Principal" | "AP") → idioma activo */
+/** Rol canónico del dataset ("Principal" | "AP" | "SW" | "EXT") → idioma activo */
 export function roleLabel(role: string): string {
   if (role === 'Principal') return i18n.t('common.rolePrimary')
   if (role === 'AP') return i18n.t('common.roleAP')
+  if (role === 'EXT') return i18n.t('common.roleExternal')
   return role
 }
 

+ 11 - 0
app/src/main.tsx

@@ -1,3 +1,14 @@
+// Cuando el service worker instala una versión nueva y toma el control,
+// recargamos la pestaña UNA vez: sin esto, tras cada despliegue el usuario
+// quedaba en la app vieja hasta hacer dos recargas manuales.
+let swReloaded = false
+if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.addEventListener('controllerchange', () => {
+    if (swReloaded) return
+    swReloaded = true
+    window.location.reload()
+  })
+}
 import { createRoot } from 'react-dom/client'
 import { BrowserRouter } from 'react-router'
 import './index.css'

+ 72 - 4
app/src/pages/Alerts.tsx

@@ -24,6 +24,7 @@ import {
   Signal,
   Smartphone,
   Tablet,
+  Trash2,
   Users,
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
@@ -41,6 +42,16 @@ import {
   DropdownMenuItem,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
 import { buildAlertFeed, buildLiveFeed, DAY_ORDER } from '@/data/alertFeed'
 import type { FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
 import { useNetPulse } from '@/data/DataProvider'
@@ -479,6 +490,7 @@ export default function Alerts() {
     alertsConfig,
     setAlertConfig,
     markAlertsRead,
+    markAllAlertsRead,
     clearAllAlerts,
     silenceAlert,
     dismissAlert,
@@ -495,7 +507,14 @@ export default function Alerts() {
   const [cats, setCats] = useState<ReadonlySet<AlertCategory>>(new Set())
   const [searchParams] = useSearchParams()
   const navigate = useNavigate()
-  const [onlyUnread, setOnlyUnread] = useState(() => searchParams.get('unread') === '1')
+  // Persistencia de la opción de vista: sobrevive a recargas y sesiones.
+  // Sin preferencia guardada (instalación nueva) arranca en "solo no
+  // leídas"; ?unread=1 en la URL fuerza el estado.
+  const [onlyUnread, setOnlyUnread] = useState(() => {
+    if (searchParams.get('unread') === '1') return true
+    const stored = localStorage.getItem('netpulse-alerts-onlyUnread')
+    return stored === null ? true : stored === '1'
+  })
   const [expandedId, setExpandedId] = useState<string | null>(null)
   const [burst, setBurst] = useState(0)
   const [configOpen, setConfigOpen] = useState(false)
@@ -509,9 +528,18 @@ export default function Alerts() {
   const isRead = (ev: FeedEvent) => ev.read
   const unread = unreadAlerts
 
+  const [confirmClear, setConfirmClear] = useState(false)
+
   const markAllRead = () => {
-    // #971: "Marcar todo como leído" VACÍA el feed (dismiss de las visibles
-    // en servidor), no solo marca. El botón conserva su texto original.
+    // #1034: "Marcar todo como leído" SOLO marca leídas las alertas visibles;
+    // el feed se conserva (las entradas quedan como leídas) y la acción de
+    // vaciado destructiva vive en el botón "Vaciar registro".
+    markAllAlertsRead()
+    setBurst((b) => b + 1)
+  }
+
+  const clearLog = () => {
+    setConfirmClear(false)
     clearAllAlerts()
     setBurst((b) => b + 1)
   }
@@ -665,6 +693,15 @@ export default function Alerts() {
             </motion.span>
             {t('alerts.markAllRead')}
           </button>
+          <button
+            type="button"
+            onClick={() => setConfirmClear(true)}
+            disabled={alertFeed.length === 0}
+            className="inline-flex h-9 items-center gap-2 rounded-lg border border-danger/30 bg-danger/10 px-3 text-xs font-medium text-danger transition-colors duration-150 hover:bg-danger/15 disabled:cursor-not-allowed disabled:opacity-40"
+          >
+            <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+            {t('alerts.clearLog')}
+          </button>
         </div>
         <div className="md:hidden">
           <DropdownMenu>
@@ -693,6 +730,14 @@ export default function Alerts() {
                 <CheckCheck className="h-4 w-4" strokeWidth={1.75} />
                 {t('alerts.markAllRead')}
               </DropdownMenuItem>
+              <DropdownMenuItem
+                disabled={alertFeed.length === 0}
+                onSelect={() => setConfirmClear(true)}
+                className="gap-2 text-danger focus:bg-hover"
+              >
+                <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+                {t('alerts.clearLog')}
+              </DropdownMenuItem>
             </DropdownMenuContent>
           </DropdownMenu>
         </div>
@@ -869,7 +914,10 @@ export default function Alerts() {
           type="button"
           role="switch"
           aria-checked={onlyUnread}
-          onClick={() => setOnlyUnread((v) => !v)}
+          onClick={() => setOnlyUnread((v) => {
+            localStorage.setItem('netpulse-alerts-onlyUnread', v ? '0' : '1')
+            return !v
+          })}
           className={cn(
             'inline-flex h-8 items-center gap-2 rounded-full border px-3 text-xs font-medium transition-colors duration-150',
             onlyUnread
@@ -963,6 +1011,26 @@ export default function Alerts() {
           )}
         </div>
       )}
+
+      {/* #1034: confirmación de la acción destructiva "Vaciar registro".
+          Marcar todo como leído ya no toca el log. */}
+      <AlertDialog open={confirmClear} onOpenChange={setConfirmClear}>
+        <AlertDialogContent>
+          <AlertDialogHeader>
+            <AlertDialogTitle>{t('alerts.clearLogTitle')}</AlertDialogTitle>
+            <AlertDialogDescription>{t('alerts.clearLogDesc')}</AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>{t('settings.users.cancel')}</AlertDialogCancel>
+            <AlertDialogAction
+              onClick={clearLog}
+              className="bg-danger text-danger-foreground hover:bg-danger/90"
+            >
+              {t('alerts.clearLogConfirm')}
+            </AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
     </div>
   )
 }

+ 789 - 251
app/src/pages/ChannelPlan.tsx

@@ -1,19 +1,26 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNetPulse } from '@/data/DataProvider'
-import { Signal, Radio as RadioIcon, AlertCircle, CheckCircle2, Loader2 } from 'lucide-react'
+import { AlertCircle, ArrowDown, ArrowUp, ArrowUpDown, RefreshCw, Router, Sparkles } from 'lucide-react'
 import { cn } from '@/lib/utils'
+import { ssidColor } from '@/lib/ssidColor'
 import { Button } from '@/components/ui/button'
 import {
-  AlertDialog,
-  AlertDialogAction,
-  AlertDialogCancel,
-  AlertDialogContent,
-  AlertDialogDescription,
-  AlertDialogFooter,
-  AlertDialogHeader,
-  AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
+  DropdownMenu,
+  DropdownMenuContent,
+  DropdownMenuLabel,
+  DropdownMenuRadioGroup,
+  DropdownMenuRadioItem,
+  DropdownMenuSeparator,
+  DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
+import {
+  ChannelSpectrum,
+  channelFreq,
+  isDfsChannel,
+  themeColor,
+  type SpectrumNet,
+} from '@/components/channels/ChannelSpectrum'
 
 interface Scan {
   iface: string
@@ -22,7 +29,19 @@ interface Scan {
   channel: number
   freq: number
   signal: number
+  widthMhz?: number
   routerId: string
+  ts?: number
+  own?: boolean
+}
+
+interface Score {
+  channel: number
+  score: number
+  neighbors: number
+  strongest: number // dBm de la vecina más fuerte considerada
+  dfs: boolean
+  recommendable: boolean
 }
 
 interface RadioRec {
@@ -34,6 +53,7 @@ interface RadioRec {
   recommended: number
   currentScore: number
   bestScore: number
+  scores?: Score[]
 }
 
 interface ChannelPlanData {
@@ -42,13 +62,6 @@ interface ChannelPlanData {
   scans: Scan[]
 }
 
-interface RadioApplyState {
-  busy: boolean
-  status?: 'applied' | 'failed'
-  error?: string
-  prevChannel?: number
-}
-
 function bandFromFreq(freq: number): string {
   if (freq >= 2412 && freq <= 2484) return '2.4 GHz'
   if (freq >= 5180 && freq <= 5885) return '5 GHz'
@@ -56,128 +69,330 @@ function bandFromFreq(freq: number): string {
   return `${freq} MHz`
 }
 
+// Señal → nivel (4 barras) y calidad, como el channel analysis de LuCI.
+function signalLevel(signal: number): 1 | 2 | 3 | 4 {
+  if (signal >= -50) return 4
+  if (signal >= -65) return 3
+  if (signal >= -78) return 2
+  return 1
+}
+
+function SignalBars({ signal, own }: { signal: number; own?: boolean }) {
+  const lvl = signalLevel(signal)
+  const colorCls = own ? 'bg-accent' : lvl >= 3 ? 'bg-ok' : lvl === 2 ? 'bg-warn' : 'bg-danger'
+  const heights = [4, 7, 10, 13]
+  return (
+    <span className="inline-flex h-[14px] items-end gap-[2px]" aria-hidden>
+      {heights.map((h, i) => (
+        <span
+          key={i}
+          className={cn('w-[3.5px] rounded-[1.5px]', i < lvl ? colorCls : 'bg-border')}
+          style={{ height: h }}
+        />
+      ))}
+    </span>
+  )
+}
+
+// Anillo de puntuación (SVG): pct alto = canal limpio.
+function ScoreRing({ pct }: { pct: number }) {
+  const color = pct >= 80 ? themeColor('--ok') : pct >= 55 ? themeColor('--warn') : themeColor('--danger')
+  return (
+    <div className="relative h-[52px] w-[52px] shrink-0" aria-hidden>
+      <svg width="52" height="52" className="-rotate-90">
+        <circle cx="26" cy="26" r="21" fill="none" stroke={themeColor('--border')} strokeWidth="6" />
+        <circle
+          cx="26"
+          cy="26"
+          r="21"
+          fill="none"
+          stroke={color}
+          strokeWidth="6"
+          strokeLinecap="round"
+          strokeDasharray={`${(pct / 100) * 131.9} 131.9`}
+        />
+      </svg>
+      <span className="absolute inset-0 grid place-items-center text-[13px] font-extrabold text-text-primary">{pct}</span>
+    </div>
+  )
+}
+
+
+// FleetMenuTrigger (#1070): selector de unidad de flota NO nativo, con el
+// mismo look que los filtros desplegables de Clientes (Devices.tsx #989).
+// forwardRef + spread OBLIGATORIOS (#1006): DropdownMenuTrigger asChild
+// inyecta el ref y los handlers; sin ellos el menú no abre.
+const FleetMenuTrigger = forwardRef<
+  HTMLButtonElement,
+  React.ComponentPropsWithoutRef<'button'> & { label: string; value: string }
+>(function FleetMenuTrigger({ label, value, className, ...props }, ref) {
+  return (
+    <button
+      ref={ref}
+      className={cn(
+        'inline-flex h-8 items-center gap-1.5 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary',
+        className,
+      )}
+      {...props}
+    >
+      <Router className="h-3.5 w-3.5" strokeWidth={1.75} />
+      {label}
+      <span className="font-semibold text-text-primary">{value}</span>
+    </button>
+  )
+})
+
 export default function ChannelPlan() {
-  const { t } = useTranslation()
+  const { t, i18n } = useTranslation()
   const { routers } = useNetPulse()
   const [routerId, setRouterId] = useState('')
   const [data, setData] = useState<ChannelPlanData | null>(null)
   const [loading, setLoading] = useState(false)
   const [error, setError] = useState('')
-  const [applyState, setApplyState] = useState<Record<string, RadioApplyState>>({})
-  const [confirmTarget, setConfirmTarget] = useState<RadioRec | null>(null)
+  const [activeRadio, setActiveRadio] = useState('')
+  const [hidden, setHidden] = useState<Set<string>>(new Set())
+  const [selected, setSelected] = useState<string | null>(null)
+  const [hover, setHover] = useState<{ net: SpectrumNet; x: number; y: number } | null>(null)
+  const [sort, setSort] = useState<{ key: 'signal' | 'ssid' | 'channel'; dir: 'asc' | 'desc' } | null>(null)
+  const [focus, setFocus] = useState<number | null>(null)
+  const [onlyMine, setOnlyMine] = useState(false)
+  const [lastRefresh, setLastRefresh] = useState<number>(0)
   const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null)
 
   const sortedRouters = useMemo(() => {
-    return [...routers].sort((a, b) => (a.roleBadge === 'Principal' ? -1 : 1) || a.name.localeCompare(b.name))
+    // #1147: en el análisis de canales solo tienen sentido los AP. Los
+    // switches (gestionados o externos SNMP) fuera salvo que presenten bandas
+    // WiFi reales (un AP externo sin agente se queda); routers/APs siempre.
+    // Las pausadas (#1085) también fuera: no aportan canales.
+    return [...routers]
+      .filter((r) => {
+        if (r.disabled) return false
+        const b = r.bandSplit
+        const hasWifi = !!b && b.band24 + b.band5 + b.band6 > 0
+        if (r.type === 'managed-switch' || r.type === 'external') return hasWifi
+        return true
+      })
+      .sort((a, b) => (a.roleBadge === 'Principal' ? -1 : 1) || a.name.localeCompare(b.name))
   }, [routers])
 
   useEffect(() => {
-    if (!routerId && sortedRouters.length > 0) {
+    // Selecciona la primera unidad si no hay selección o si la actual queda
+    // fuera del picker (p. ej. unidad recién filtrada por no tener WiFi).
+    if (sortedRouters.length > 0 && !sortedRouters.some((r) => r.id === routerId)) {
       setRouterId(sortedRouters[0]!.id)
     }
   }, [sortedRouters, routerId])
 
-  const loadPlan = useCallback((rid: string) => {
-    setLoading(true)
-    setError('')
+  const loadPlan = useCallback((rid: string, silent = false) => {
+    if (!silent) {
+      setLoading(true)
+      setError('')
+    }
     fetch(`/api/wifi/channel-plan?routerId=${encodeURIComponent(rid)}`)
       .then(async (res) => {
         if (!res.ok) throw new Error(await res.text())
         return res.json()
       })
-      .then((d) => setData({ ...d, radios: d.radios ?? [], scans: d.scans ?? [] }))
-      .catch((e) => setError(String(e)))
-      .finally(() => setLoading(false))
+      .then((d) => {
+        setData({ ...d, radios: d.radios ?? [], scans: d.scans ?? [] })
+        setLastRefresh(Date.now())
+      })
+      .catch((e) => {
+        if (!silent) setError(String(e))
+      })
+      .finally(() => {
+        if (!silent) setLoading(false)
+      })
   }, [])
 
   useEffect(() => {
     if (!routerId) return
+    setActiveRadio('')
+    setHidden(new Set())
+    setSelected(null)
     loadPlan(routerId)
+    if (pollTimer.current) clearInterval(pollTimer.current)
+    // Refresco silencioso: los agentes escanean solos; la página sigue el
+    // último scan sin recargar a mano.
+    pollTimer.current = setInterval(() => loadPlan(routerId, true), 60000)
+    return () => {
+      if (pollTimer.current) clearInterval(pollTimer.current)
+    }
   }, [routerId, loadPlan])
 
+  const radioKey = (r: RadioRec) => `${r.section || r.iface}-${r.name}-${r.channel}`
+  const radios: RadioRec[] = data?.radios ?? []
+  const active: RadioRec | undefined = radios.find((r) => radioKey(r) === activeRadio) ?? radios[0]
+  const routerName = sortedRouters.find((r) => r.id === routerId)?.name ?? routerId
+
+  // Vecinos de la radio activa: por banda; si el iface del radio casa con
+  // iface de scan, se estrece a lo visto por esa interfaz (dos radios en la
+  // misma banda no se mezclan).
+  const bandScans = useMemo(() => {
+    if (!data || !active) return []
+    const inBand = data.scans.filter((s) => bandFromFreq(s.freq) === active.name)
+    const ifaceHits = active.iface ? inBand.filter((s) => s.iface === active.iface) : []
+    return ifaceHits.length > 0 ? ifaceHits : inBand
+  }, [data, active])
+
+  // Redes para el espectro: la propia del radio va al final para pintarse
+  // encima de las campanas vecinas que se solapen.
+  const nets = useMemo<SpectrumNet[]>(() => {
+    if (!active) return []
+    const own: SpectrumNet = {
+      key: 'own',
+      ssid: t('channelPlan.ownNetwork'),
+      bssid: '',
+      channel: active.channel,
+      freq: channelFreq(active.name, active.channel),
+      signal: -25,
+      widthMhz: active.widthMhz > 0 ? active.widthMhz : 20,
+      own: true,
+      color: themeColor('--accent'),
+    }
+    const neighbors: SpectrumNet[] = bandScans.map((s) => ({
+      key: s.bssid + s.channel,
+      ssid: s.ssid || t('channelPlan.hidden'),
+      bssid: s.bssid,
+      channel: s.channel,
+      freq: s.freq,
+      signal: s.signal,
+      // Ancho real del anuncio HT/VHT del vecino (#1087); 20 MHz de
+      // fallback cuando el agente viejo/no lo trae.
+      widthMhz: s.widthMhz && s.widthMhz > 0 ? s.widthMhz : 20,
+      own: s.own ?? false,
+      color: s.own ? themeColor('--accent') : ssidColor(s.ssid || s.bssid),
+    }))
+    return [...neighbors, own]
+  }, [active, bandScans, t])
+
+  const allKeys = useMemo(() => new Set(nets.map((n) => n.key)), [nets])
+  const nonOwnKeys = useMemo(() => new Set(nets.filter((n) => !n.own).map((n) => n.key)), [nets])
+
+  // "Solo mías": oculta las vecinas mientras el toggle esté activo.
   useEffect(() => {
-    return () => {
-      if (pollTimer.current) clearInterval(pollTimer.current)
+    if (onlyMine) setHidden(new Set(nonOwnKeys))
+  }, [onlyMine, nonOwnKeys])
+
+  // Puntuación normalizada (0-100) de cada canal/bloque de la banda: 100 =
+  // el más limpio. Incluye DFS informativos (#1076); el sugerido es el mejor
+  // recomendable.
+  const scored = useMemo(() => {
+    if (!active?.scores || active.scores.length === 0) return []
+    const raw = active.scores.map((c) => c.score)
+    if (active.currentScore > 0 && active.currentScore < 900000) raw.push(active.currentScore)
+    const worst = Math.max(...raw)
+    const best = Math.min(...raw)
+    const pctOf = (score: number) => (worst <= best ? 100 : Math.round((100 * (worst - score)) / (worst - best)))
+    return active.scores
+      .map((c) => ({
+        ...c,
+        pct: pctOf(c.score),
+        isCurrent: c.channel === active.channel,
+        isBest: c.channel === active.recommended && c.channel !== active.channel,
+      }))
+      .sort((a, b) => b.pct - a.pct || a.channel - b.channel)
+  }, [active])
+
+  // Grupos por congestión para la tira de puntuación (#1076).
+  const tiers = useMemo(() => {
+    const t: { key: string; items: typeof scored }[] = [
+      { key: 'optimal', items: [] },
+      { key: 'moderate', items: [] },
+      { key: 'busy', items: [] },
+    ]
+    for (const s of scored) {
+      (s.pct >= 80 ? t[0]! : s.pct >= 55 ? t[1]! : t[2]!).items.push(s)
     }
-  }, [])
+    return t.filter((g) => g.items.length > 0)
+  }, [scored])
 
-  const radioKey = (r: RadioRec) => r.section || r.name
-
-  const applyChannel = useCallback(
-    (r: RadioRec, target: number, prevChannel: number) => {
-      const key = radioKey(r)
-      setApplyState((s) => ({ ...s, [key]: { busy: true } }))
-      const ops = [
-        {
-          kind: 'uci_set',
-          args: { config: 'wireless', section: r.section, option: 'channel', value: String(target) },
-          desc: `channel ${r.section} -> ${target}`,
-        },
-        { kind: 'uci_commit', args: { config: 'wireless' }, desc: 'commit wireless' },
-        { kind: 'service', args: { name: 'network', action: 'restart' }, desc: 'reload network' },
-      ]
-      const fail = (err: string) => {
-        if (pollTimer.current) clearInterval(pollTimer.current)
-        pollTimer.current = null
-        setApplyState((s) => ({ ...s, [key]: { busy: false, status: 'failed', error: err } }))
-      }
-      fetch('/api/plans', {
-        method: 'POST',
-        headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({ routerId, resource: 'wireless', diff: ops }),
-      })
-        .then(async (res) => {
-          if (!res.ok) throw new Error(await res.text())
-          return res.json()
-        })
-        .then((plan) =>
-          fetch(`/api/plans/${plan.id}/apply`, { method: 'POST' }).then(async (res) => {
-            if (!res.ok) throw new Error(await res.text())
-          }).then(() => plan),
-        )
-        .then((plan) => {
-          let ticks = 0
-          pollTimer.current = setInterval(() => {
-            ticks++
-            if (ticks > 60) return fail(t('channelPlan.timeout'))
-            fetch(`/api/plans/${plan.id}`)
-              .then(async (res) => {
-                if (!res.ok) throw new Error(await res.text())
-                return res.json()
-              })
-              .then((p: { status?: string; result?: { error?: string } }) => {
-                if (p.status === 'applied') {
-                  if (pollTimer.current) clearInterval(pollTimer.current)
-                  pollTimer.current = null
-                  setApplyState((s) => ({ ...s, [key]: { busy: false, status: 'applied', prevChannel } }))
-                  loadPlan(routerId)
-                } else if (p.status === 'failed' || p.status === 'rolled_back') {
-                  fail(p.result?.error || t('channelPlan.failedState'))
-                }
-              })
-              .catch((e) => fail(String(e)))
-          }, 3000)
-        })
-        .catch((e) => fail(String(e)))
-    },
-    [routerId, loadPlan, t],
-  )
+  const currentScoreValid = !!active && active.currentScore > 0 && active.currentScore < 900000
+  const currentPct = useMemo(() => {
+    if (!active) return 0
+    if (scored.length > 0) {
+      const cur = scored.find((s) => s.isCurrent)
+      if (cur) return cur.pct
+      const best = scored.reduce((a, b) => (b.pct > a.pct ? b : a))
+      return best.pct
+    }
+    return 0
+  }, [active, scored])
 
-  const onConfirmApply = () => {
-    if (!confirmTarget) return
-    const r = confirmTarget
-    setConfirmTarget(null)
-    if (r.recommended > 0 && r.recommended !== r.channel) {
-      applyChannel(r, r.recommended, r.channel)
+  // Mejor candidato = el RECOMENDADO por el motor (nunca un bloque DFS o no
+  // ortodoxo que empate a 100 en la normalización relativa, #1082).
+  const bestCand = useMemo(() => {
+    if (scored.length === 0) return null
+    if (active && active.recommended > 0) {
+      const rec = scored.find((s) => s.channel === active.recommended)
+      if (rec) return rec
     }
-  }
+    const recs = scored.filter((s) => s.recommendable)
+    return (recs.length > 0 ? recs : scored)[0]!
+  }, [scored, active])
+  const suggested = active && active.recommended > 0 && active.recommended !== active.channel ? active.recommended : 0
+  const ownCount = bandScans.filter((s) => s.own).length
+  const neighborCount = bandScans.length - ownCount
+  const strongestNeighbor = useMemo(() => {
+    const ns = bandScans.filter((s) => !s.own)
+    if (ns.length === 0) return null
+    return ns.reduce((a, b) => (b.signal > a.signal ? b : a))
+  }, [bandScans])
+  const lastScanAt = useMemo(() => {
+    const tss = bandScans.map((s) => s.ts ?? 0).filter((v) => v > 0)
+    if (tss.length === 0) return 0
+    return Math.max(...tss)
+  }, [bandScans])
+  // Congestión ABSOLUTA del canal actual (#1082): el verdict no depende de
+  // lo malo que sea el resto de la banda. Referencias del score (potencia
+  // x1000): 1 vecina a -60 ≈ 1000; a -50 ≈ 10000. Dos -72 ≈ 126 → baja.
+  const congestionAbs = useMemo(() => {
+    if (!active || !currentScoreValid) return null
+    const s = active.currentScore
+    return s < 500 ? 'low' : s < 5000 ? 'moderate' : 'high'
+  }, [active, currentScoreValid])
 
-  const onRevert = (r: RadioRec) => {
-    const key = radioKey(r)
-    const prev = applyState[key]?.prevChannel
-    if (!prev) return
-    applyChannel(r, prev, r.channel)
-  }
+  // Limpieza ABSOLUTA del anillo (misma escala que el chip): decaimiento
+  // logarítmico sobre el score de potencia, no el peor-vs-mejor de la banda.
+  const ringPct = useMemo(() => {
+    if (!active || !currentScoreValid) return currentPct
+    const clean = Math.round(100 - Math.min(100, (100 * Math.log10(active.currentScore + 1)) / 4))
+    return Math.max(0, clean)
+  }, [active, currentScoreValid, currentPct])
+
+  // Ordenación de la tabla: por defecto propias primero y luego señal desc;
+  // al elegir columna se ordena puro asc/desc (la alterna al repetir clic).
+  const toggleSort = (key: 'signal' | 'ssid' | 'channel') =>
+    setSort((prev) => (prev && prev.key === key ? { key, dir: prev.dir === 'asc' ? 'desc' : 'asc' } : { key, dir: key === 'signal' ? 'desc' : 'asc' }))
+
+  const sortedScans = useMemo(() => {
+    const arr = bandScans.slice()
+    if (!sort) return arr.sort((a, b) => Number(b.own ?? false) - Number(a.own ?? false) || b.signal - a.signal)
+    const dir = sort.dir === 'asc' ? 1 : -1
+    return arr.sort((a, b) => {
+      if (sort.key === 'signal') return (a.signal - b.signal) * dir
+      if (sort.key === 'channel') return (a.channel - b.channel) * dir
+      return (a.ssid || a.bssid).localeCompare(b.ssid || b.bssid, undefined, { sensitivity: 'base' }) * dir
+    })
+  }, [bandScans, sort])
+
+  const SortHeader = ({ id, label }: { id: 'signal' | 'ssid' | 'channel'; label: string }) => (
+    <button
+      onClick={() => toggleSort(id)}
+      aria-label={`${label}: ${sort?.key === id ? (sort.dir === 'asc' ? t('channelPlan.sortAsc') : t('channelPlan.sortDesc')) : t('channelPlan.sortable')}`}
+      className={cn('inline-flex items-center gap-1 uppercase tracking-wide transition-colors hover:text-text-primary', sort?.key === id ? 'text-accent' : '')}
+    >
+      {label}
+      {sort?.key !== id ? (
+        <ArrowUpDown className="h-3 w-3 opacity-50" strokeWidth={2} />
+      ) : sort.dir === 'asc' ? (
+        <ArrowUp className="h-3 w-3" strokeWidth={2} />
+      ) : (
+        <ArrowDown className="h-3 w-3" strokeWidth={2} />
+      )}
+    </button>
+  )
+  const currentDfs = active ? isDfsChannel(active.name, active.channel) : false
 
   return (
     <div className="space-y-4 md:space-y-5">
@@ -186,25 +401,73 @@ export default function ChannelPlan() {
         <p className="mt-0.5 text-sm text-text-secondary">{t('channelPlan.subtitle')}</p>
       </header>
 
-      <div className="rounded-2xl border border-border bg-surface p-5">
-        <label className="flex flex-col gap-1">
-          <span className="text-caption font-medium text-text-secondary">{t('channelPlan.router')}</span>
-          <select
-            value={routerId}
-            onChange={(e) => {
-              setApplyState({})
-              setRouterId(e.target.value)
-            }}
-            className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
-          >
-            {sortedRouters.map((r) => (
-              <option key={r.id} value={r.id}>
-                {r.name}
-                {r.roleBadge === 'Principal' ? ` ${t('channelPlan.gateway')}` : ''}
-              </option>
-            ))}
-          </select>
-        </label>
+      {/* Barra de contexto: equipo + pestañas de radio + acciones */}
+      <div className="flex flex-wrap items-center gap-3 rounded-2xl border border-border bg-surface p-4">
+        <DropdownMenu>
+          <DropdownMenuTrigger asChild>
+            <FleetMenuTrigger label={t('channelPlan.router')} value={routerName} />
+          </DropdownMenuTrigger>
+          <DropdownMenuContent align="start" className="w-56">
+            <DropdownMenuLabel>{t('channelPlan.router')}</DropdownMenuLabel>
+            <DropdownMenuSeparator />
+            <DropdownMenuRadioGroup value={routerId} onValueChange={setRouterId}>
+              {sortedRouters.map((r) => (
+                <DropdownMenuRadioItem key={r.id} value={r.id}>
+                  <span className="flex-1">
+                    {r.name}
+                    {r.roleBadge === 'Principal' ? ` ${t('channelPlan.gateway')}` : ''}
+                  </span>
+                </DropdownMenuRadioItem>
+              ))}
+            </DropdownMenuRadioGroup>
+          </DropdownMenuContent>
+        </DropdownMenu>
+
+        {radios.length > 1 && (
+          <div className="inline-flex items-center gap-0.5 rounded-xl bg-canvas p-1" role="tablist" aria-label={t('channelPlan.band')}>
+            {radios.map((r) => {
+              const key = radioKey(r)
+              const isActive = active !== undefined && radioKey(active) === key
+              return (
+                <button
+                  key={key}
+                  role="tab"
+                  aria-selected={isActive}
+                  onClick={() => {
+                    setActiveRadio(key)
+                    setHidden(new Set())
+                    setSelected(null)
+                    setFocus(null)
+                  }}
+                  className={cn(
+                    'rounded-lg px-3.5 py-1.5 text-[13px] font-semibold transition-all',
+                    isActive ? 'bg-surface text-accent shadow-sm' : 'text-text-muted hover:text-text-secondary',
+                  )}
+                >
+                  {r.name}
+                  <span className="ml-1.5 font-mono text-caption text-text-muted">ch {r.channel}</span>
+                </button>
+              )
+            })}
+          </div>
+        )}
+
+        <div className="ml-auto flex items-center gap-3">
+          <span className="text-caption text-text-muted">
+            {lastScanAt > 0
+              ? t('channelPlan.lastScan', {
+                  time: new Date(lastScanAt * 1000).toLocaleTimeString(i18n.language, { hour: '2-digit', minute: '2-digit' }),
+                })
+              : lastRefresh > 0 &&
+                t('channelPlan.lastRefresh', {
+                  time: new Date(lastRefresh).toLocaleTimeString(i18n.language, { hour: '2-digit', minute: '2-digit' }),
+                })}
+          </span>
+          <Button size="sm" variant="outline" disabled={!routerId || loading} onClick={() => loadPlan(routerId)}>
+            <RefreshCw className={cn('mr-1.5 h-3.5 w-3.5', loading && 'animate-spin')} strokeWidth={1.75} />
+            {t('channelPlan.refresh')}
+          </Button>
+        </div>
       </div>
 
       {error && (
@@ -214,152 +477,427 @@ export default function ChannelPlan() {
         </div>
       )}
 
-      {loading && (
+      {loading && !data && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-text-secondary">
           {t('common.loading')}
         </div>
       )}
 
-      {!loading && data && (
+      {!loading && data && radios.length === 0 && (
+        <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-text-secondary">
+          {t('channelPlan.noRadios')}
+        </div>
+      )}
+
+      {!loading && data && active && (
         <>
-          {data.radios.length === 0 ? (
-            <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-text-secondary">
-              {t('channelPlan.noRadios')}
+          {/* Resumen: sugerido / actual / redes detectadas */}
+          <div className="grid gap-3 lg:grid-cols-3">
+            <div className="relative overflow-hidden rounded-2xl border border-border bg-surface p-5">
+              {bestCand && (
+                <span className="absolute right-4 top-4 inline-flex items-center gap-1.5 rounded-full border border-ok/30 bg-ok/10 px-2.5 py-1 text-caption font-bold text-ok">
+                  <Sparkles className="h-3 w-3" strokeWidth={2} />
+                  {bestCand.pct}/100
+                </span>
+              )}
+              <div className="text-label uppercase text-text-muted">{t('channelPlan.summarySuggested')}</div>
+              {bestCand ? (
+                <>
+                  <div className="mt-1 flex items-baseline gap-2">
+                    <span className="font-display text-[30px] font-extrabold tracking-tight text-text-primary">
+                      {active.name === '2.4 GHz' || active.name === '6 GHz'
+                        ? t('channelPlan.channelWord', { ch: bestCand.channel })
+                        : bestCand.channel}
+                    </span>
+                    <span className="text-[13px] font-semibold text-text-secondary">
+                      {active.widthMhz > 0 ? `${active.widthMhz} MHz` : '20 MHz'}
+                    </span>
+                  </div>
+                  <p className="mt-1 text-xs leading-relaxed text-text-secondary">
+                    {bestCand.neighbors === 0
+                      ? t('channelPlan.noNeighborsBlock')
+                      : t('channelPlan.neighborsBlock', { count: bestCand.neighbors, dbm: bestCand.strongest })}
+                    {bestCand.channel === active.channel || bestCand.pct === currentPct
+                      ? ` ${t('channelPlan.alreadyOptimal')}`
+                      : ` ${t('channelPlan.betterThanCurrent', { score: ringPct })}`}
+                  </p>
+                  <p className="mt-1.5 text-xs text-text-muted">{t('channelPlan.applyHint')}</p>
+                </>
+              ) : (
+                <p className="mt-2 text-sm text-text-secondary">{t('channelPlan.noBandScans')}</p>
+              )}
             </div>
-          ) : (
-            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
-              {data.radios.map((r, idx) => {
-                const key = radioKey(r)
-                const st: RadioApplyState = applyState[key] ?? { busy: false }
-                const canApply = !!r.section && r.recommended > 0 && r.recommended !== r.channel && !st.busy
-                const showScore = r.bestScore > 0 && r.currentScore > 0 && r.currentScore < 900000
-                return (
-                  <div
-                    key={idx}
-                    className={cn(
-                      'rounded-2xl border border-border bg-surface p-5',
-                      r.recommended !== r.channel && r.recommended > 0 && 'border-accent/40',
+
+            <div className="rounded-2xl border border-border bg-surface p-5">
+              <div className="text-label uppercase text-text-muted">{t('channelPlan.summaryCurrent')}</div>
+              <div className="mt-2 flex items-center gap-3.5">
+                <ScoreRing pct={ringPct} />
+                <div>
+                  <div className="text-[15px] font-bold text-text-primary">
+                    {active.name === '2.4 GHz' || active.name === '6 GHz'
+                      ? t('channelPlan.channelWord', { ch: active.channel })
+                      : active.channel}
+                    {active.widthMhz > 0 && <span className="ml-1 text-caption font-normal text-text-muted">{active.widthMhz} MHz</span>}
+                  </div>
+                  <div className="mt-1 flex items-center gap-1.5">
+                    {congestionAbs && (
+                      <span
+                        className={cn(
+                          'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-caption font-semibold',
+                          congestionAbs === 'low' && 'bg-ok/10 text-ok',
+                          congestionAbs === 'moderate' && 'bg-warn/10 text-warn',
+                          congestionAbs === 'high' && 'bg-danger/10 text-danger',
+                        )}
+                      >
+                        {t(`channelPlan.congestion.${congestionAbs}`)}
+                      </span>
                     )}
-                  >
-                    <div className="mb-3 flex items-center justify-between gap-2">
-                      <div className="flex items-center gap-2">
-                        <RadioIcon className="h-4 w-4 text-accent" strokeWidth={1.75} />
-                        <h3 className="text-sm font-semibold text-text-primary">{r.name}</h3>
-                      </div>
-                      {showScore && (
-                        <span className="text-caption text-text-muted">
-                          {t('channelPlan.score')}: {r.currentScore} → {r.bestScore}
-                        </span>
+                    {currentDfs && (
+                      <span className="rounded-full bg-elevated px-2 py-0.5 text-caption font-semibold text-text-muted">
+                        {t('channelPlan.tagDfs')}
+                      </span>
+                    )}
+                  </div>
+                </div>
+              </div>
+              <p className="mt-2 text-xs text-text-secondary">
+                {(() => {
+                  const cur = scored.find((s) => s.isCurrent)
+                  if (cur) {
+                    return cur.neighbors === 0 ? t('channelPlan.noOverlap') : t('channelPlan.neighborsInBlock', { count: cur.neighbors })
+                  }
+                  return currentScoreValid ? t('channelPlan.noOverlap') : t('channelPlan.noBandScans')
+                })()}
+              </p>
+            </div>
+
+            <div className="rounded-2xl border border-border bg-surface p-5">
+              <div className="text-label uppercase text-text-muted">{t('channelPlan.summaryNetworks')}</div>
+              <div className="mt-1 flex items-baseline gap-2">
+                <span className="font-display text-[30px] font-extrabold tracking-tight text-text-primary">{bandScans.length}</span>
+                <span className="text-[13px] font-semibold text-text-secondary">
+                  {t('channelPlan.yours', { own: ownCount, neighbors: neighborCount })}
+                </span>
+              </div>
+              <p className="mt-1 text-xs leading-relaxed text-text-secondary">
+                {strongestNeighbor
+                  ? t('channelPlan.strongestNeighbor', {
+                      ssid: strongestNeighbor.ssid || t('channelPlan.hidden'),
+                      dbm: strongestNeighbor.signal,
+                      ch: strongestNeighbor.channel,
+                    })
+                  : t('channelPlan.noNeighborsBlock')}
+              </p>
+              <p className="mt-1.5 text-xs text-text-muted">
+                {t('channelPlan.viewFrom', { name: routerName })} · {t('channelPlan.scanInfo')}
+              </p>
+            </div>
+          </div>
+
+          {/* Espectro a todo lo ancho (#1076); la puntuación baja a una
+              tira debajo, agrupada por congestión. Espectro, tira y leyenda
+              se muestran SIEMPRE (#1077): en una banda sin vecinos la
+              puntuación es justo lo más útil (todo limpio, elige canal). */}
+          <div>
+            <div className="rounded-2xl border border-border bg-surface">
+                  <div className="flex items-start justify-between gap-3 px-5 pt-4">
+                    <div>
+                      <h2 className="text-sm font-bold text-text-primary">{t('channelPlan.chartTitle', { band: active.name })}</h2>
+                      <p className="mt-0.5 text-caption text-text-muted">{t('channelPlan.chartSub')}</p>
+                    </div>
+                    <div className="ml-auto flex flex-wrap items-center gap-x-4 gap-y-1 text-caption text-text-muted">
+                      <span className="inline-flex items-center gap-1.5">
+                        <span className="inline-block h-2.5 w-4 rounded-sm" style={{ backgroundColor: 'rgba(167,139,250,0.2)' }} />
+                        {t('channelPlan.legendDfs')}
+                      </span>
+                      <span className="inline-flex items-center gap-1.5">
+                        <span className="inline-block h-2.5 w-4 rounded-sm" style={{ backgroundColor: 'rgba(52,211,153,0.2)' }} />
+                        {t('channelPlan.legendSuggested')}
+                      </span>
+                      <span className="inline-flex items-center gap-1.5">
+                        <span className="inline-block h-0 w-4 border-t-2 border-dashed border-accent" />
+                        {t('channelPlan.legendCurrent')}
+                      </span>
+                      {bandScans.length === 0 && (
+                        <span className="rounded-lg bg-warn/10 px-2.5 py-1 text-caption text-warn">{t('channelPlan.noBandScans')}</span>
                       )}
                     </div>
-                    <div className="grid grid-cols-2 gap-4">
-                      <div>
-                        <div className="text-caption text-text-muted">{t('channelPlan.currentChannel')}</div>
-                        <div className="text-2xl font-bold text-text-primary">{r.channel}</div>
-                      </div>
-                      <div>
-                        <div className="text-caption text-text-muted">{t('channelPlan.recommendedChannel')}</div>
-                        <div className={cn('text-2xl font-bold', r.recommended === r.channel ? 'text-text-primary' : 'text-accent')}>
-                          {r.recommended > 0 ? r.recommended : '-'}
+                    <span className="rounded-full bg-elevated px-2.5 py-1 text-caption font-semibold text-text-secondary">
+                      {t('channelPlan.netsCount', { n: nets.length })}
+                    </span>
+                  </div>
+
+                  <div className="relative px-3 pt-2">
+                    <ChannelSpectrum
+                      band={active.name}
+                      nets={nets}
+                      suggested={suggested}
+                      widthMhz={active.widthMhz}
+                      hidden={hidden}
+                      selected={selected}
+                      focus={focus}
+                      onHover={(net, x, y) => setHover(net ? { net, x, y } : null)}
+                      tSuggest={t('channelPlan.suggested')}
+                      tDfs={t('channelPlan.tagDfs')}
+                      tActual={t('channelPlan.tActual')}
+                      tDbm="dBm"
+                    />
+                    {hover && (
+                      <div
+                        className="pointer-events-none absolute z-10 -translate-x-1/2 whitespace-nowrap rounded-[10px] bg-elevated px-3 py-2 text-xs shadow-lg"
+                        style={{ left: Math.max(Math.min(hover.x, 320), 90), top: Math.max(hover.y - 12, 30) }}
+                      >
+                        <div className="flex items-center gap-2 font-bold text-text-primary">
+                          <span className="inline-block h-2 w-2 rounded-[3px]" style={{ backgroundColor: hover.net.color }} />
+                          {hover.net.ssid}
+                        </div>
+                        <div className="mt-0.5 text-text-secondary">
+                          {t('channelPlan.channelWord', { ch: hover.net.channel })}
+                          {hover.net.key === 'own' && hover.net.widthMhz > 0 ? ` · ${hover.net.widthMhz} MHz` : ''} · {hover.net.signal} dBm
                         </div>
+                        {hover.net.bssid && <div className="font-mono text-caption text-text-muted">{hover.net.bssid}</div>}
                       </div>
+                    )}
+                  </div>
+
+                  <div className="px-5 pb-3 pt-1">
+                    <div className="mb-1.5 flex items-center gap-2">
+                      <span className="text-label uppercase text-text-muted">{t('channelPlan.heatTitle')}</span>
+                      <span className="ml-auto text-caption font-normal normal-case tracking-normal text-text-muted">
+                        {bandScans.some((s) => !s.own && !(s.widthMhz && s.widthMhz > 0))
+                          ? t('channelPlan.heatNote')
+                          : t('channelPlan.heatNoteKnown')}
+                      </span>
                     </div>
-                    <div className="mt-4 flex flex-wrap items-center gap-2">
-                      {canApply ? (
-                        <Button size="sm" onClick={() => setConfirmTarget(r)}>
-                          {t('channelPlan.apply')}
-                        </Button>
-                      ) : r.recommended > 0 && r.recommended !== r.channel && !r.section ? (
-                        <span className="text-caption text-text-muted">{t('channelPlan.updateAgent')}</span>
-                      ) : null}
-                      {st.busy && (
-                        <span className="inline-flex items-center gap-1.5 text-caption text-text-secondary">
-                          <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
-                          {t('channelPlan.applyingState')}
-                        </span>
-                      )}
-                      {st.status === 'applied' && st.prevChannel && (
-                        <>
-                          <span className="inline-flex items-center gap-1.5 text-caption text-emerald-600 dark:text-emerald-400">
-                            <CheckCircle2 className="h-3.5 w-3.5" strokeWidth={1.75} />
-                            {t('channelPlan.appliedState')}
-                          </span>
-                          <Button size="sm" variant="outline" disabled={st.busy} onClick={() => onRevert(r)}>
-                            {t('channelPlan.revertTo', { ch: st.prevChannel })}
-                          </Button>
-                        </>
-                      )}
-                      {st.status === 'failed' && (
-                        <span className="inline-flex items-center gap-1.5 text-caption text-rose-600 dark:text-rose-400">
-                          <AlertCircle className="h-3.5 w-3.5" strokeWidth={1.75} />
-                          {t('channelPlan.failedState')}
-                          {st.error ? `: ${st.error}` : ''}
+                    <div className="flex justify-between text-[10.5px] text-text-muted">
+                      <span>{t('channelPlan.heatClean')}</span>
+                      <span>{t('channelPlan.heatBusy')}</span>
+                    </div>
+                  </div>
+
+                  {/* Puntuación por canal: tira a todo lo ancho agrupada por
+                      congestión; clic enfoca el bloque en el espectro (#1076) */}
+                  <div className="border-t border-border px-5 py-3">
+                    <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+                      <h2 className="text-sm font-bold text-text-primary">{t('channelPlan.scoresTitle')}</h2>
+                      <span className="text-caption text-text-muted">
+                        {active.name === '5 GHz'
+                          ? t('channelPlan.scoresBlocks', { w: active.widthMhz > 0 ? active.widthMhz : 80 })
+                          : t('channelPlan.scoresChannels')}
+                        {' · '}
+                        {t('channelPlan.scoresFoot')}
+                      </span>
+                    </div>
+                    {tiers.map((g) => (
+                      <div key={g.key} className="mt-2 flex flex-wrap items-center gap-1.5">
+                        <span
+                          className={cn(
+                            'w-24 shrink-0 text-[11px] font-bold uppercase tracking-wide',
+                            g.key === 'optimal' ? 'text-ok' : g.key === 'moderate' ? 'text-warn' : 'text-danger',
+                          )}
+                        >
+                          {t(`channelPlan.tier.${g.key}`)}
                         </span>
+                        {g.items.map((s) => (
+                          <button
+                            key={s.channel}
+                            onClick={() => setFocus(focus === s.channel ? null : s.channel)}
+                            title={
+                              s.neighbors === 0
+                                ? t('channelPlan.whyAlone')
+                                : t('channelPlan.whyNeighbors', { n: s.neighbors, dbm: s.strongest })
+                            }
+                            className={cn(
+                              'inline-flex items-center gap-1.5 rounded-lg border px-2 py-1 text-xs transition-colors',
+                              focus === s.channel
+                                ? 'border-accent/60 bg-accent/10'
+                                : s.isCurrent
+                                  ? 'border-accent/40 bg-accent/5'
+                                  : s.isBest
+                                    ? 'border-ok/40 bg-ok/5'
+                                    : 'border-border hover:border-border-strong',
+                              !s.recommendable && 'opacity-70',
+                            )}
+                          >
+                            <span className="font-mono font-bold text-text-primary">{s.channel}</span>
+                            {s.isCurrent && (
+                              <span className="rounded bg-accent/15 px-1 py-px text-[9px] font-bold uppercase text-accent">
+                                {t('channelPlan.tagCurrent')}
+                              </span>
+                            )}
+                            {s.isBest && (
+                              <span className="rounded bg-ok/15 px-1 py-px text-[9px] font-bold uppercase text-ok">
+                                ★ {t('channelPlan.tagBest')}
+                              </span>
+                            )}
+                            {s.dfs && (
+                              <span className="rounded bg-elevated px-1 py-px text-[9px] font-bold uppercase text-text-muted">
+                                {t('channelPlan.tagDfs')}
+                              </span>
+                            )}
+                            <span
+                              className={cn(
+                                'font-mono font-bold',
+                                s.pct >= 80 ? 'text-ok' : s.pct >= 55 ? 'text-warn' : 'text-danger',
+                              )}
+                            >
+                              {s.pct}
+                            </span>
+                          </button>
+                        ))}
+                      </div>
+                    ))}
+                    {scored.length === 0 && <p className="mt-1 text-caption text-text-muted">{t('channelPlan.noBandScans')}</p>}
+                  </div>
+
+                  {/* Leyenda interactiva */}
+                  <div className="flex flex-wrap gap-1.5 border-t border-border px-5 py-3">
+                    <button
+                      onClick={() => {
+                        setOnlyMine(false)
+                        setHidden(new Set(allKeys))
+                      }}
+                      className="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-text-secondary transition-colors hover:border-border-strong hover:text-text-primary"
+                    >
+                      {t('channelPlan.hideAll')}
+                    </button>
+                    <button
+                      onClick={() => {
+                        setOnlyMine(false)
+                        setHidden(new Set())
+                      }}
+                      className="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-text-secondary transition-colors hover:border-border-strong hover:text-text-primary"
+                    >
+                      {t('channelPlan.showAll')}
+                    </button>
+                    <button
+                      onClick={() => setOnlyMine((v) => !v)}
+                      className={cn(
+                        'inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold transition-colors',
+                        onlyMine ? 'border-accent/50 bg-accent/10 text-accent' : 'border-border text-text-secondary hover:border-border-strong hover:text-text-primary',
                       )}
-                    </div>
+                    >
+                      {t('channelPlan.onlyMine')}
+                    </button>
+                    {nets.map((n) => (
+                      <button
+                        key={n.key}
+                        onClick={() =>
+                          setHidden((prev) => {
+                            const next = new Set(prev)
+                            if (next.has(n.key)) next.delete(n.key)
+                            else next.add(n.key)
+                            return next
+                          })
+                        }
+                        className={cn(
+                          'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold transition-opacity',
+                          n.own
+                            ? 'border-accent/40 bg-accent/10 text-accent'
+                            : 'border-border text-text-secondary hover:border-border-strong',
+                          hidden.has(n.key) && 'opacity-40',
+                        )}
+                      >
+                        <span className="inline-block h-2 w-2 rounded-[3px]" style={{ backgroundColor: n.color }} />
+                        {n.ssid}
+                        <span className="font-mono text-caption font-normal text-text-muted">ch {n.channel}</span>
+                      </button>
+                    ))}
                   </div>
-                )
-              })}
-            </div>
-          )}
-
-          <div className="rounded-2xl border border-border bg-surface p-5">
-            <h2 className="mb-3 text-sm font-semibold text-text-primary">{t('channelPlan.neighbors')}</h2>
-            {data.scans.length === 0 ? (
-              <div className="py-4 text-sm text-text-secondary">{t('channelPlan.noScans')}</div>
-            ) : (
-              <div className="overflow-x-auto">
-                <table className="w-full text-sm">
-                  <thead className="border-b border-border text-left text-caption text-text-muted">
-                    <tr>
-                      <th className="py-2 pr-4">SSID</th>
-                      <th className="py-2 pr-4">BSSID</th>
-                      <th className="py-2 pr-4">{t('channelPlan.band')}</th>
-                      <th className="py-2 pr-4">{t('channelPlan.currentChannel')}</th>
-                      <th className="py-2 pr-4">{t('channelPlan.signal')}</th>
-                    </tr>
-                  </thead>
-                  <tbody className="text-text-primary">
-                    {data.scans.map((s, idx) => (
-                      <tr key={idx} className="border-b border-border/50 last:border-0">
-                        <td className="py-2 pr-4 font-medium">{s.ssid || t('common.unknown')}</td>
-                        <td className="py-2 pr-4 font-mono text-text-secondary">{s.bssid}</td>
-                        <td className="py-2 pr-4">{bandFromFreq(s.freq)}</td>
-                        <td className="py-2 pr-4">{s.channel}</td>
-                        <td className="py-2 pr-4">
-                          <span className="inline-flex items-center gap-1">
-                            <Signal className="h-3.5 w-3.5" strokeWidth={1.75} />
-                            {s.signal} dBm
-                          </span>
-                        </td>
+                </div>
+              </div>
+
+              {/* Tabla de redes (solo si hay scans) */}
+              {bandScans.length > 0 && (
+              <div className="overflow-hidden rounded-2xl border border-border bg-surface">
+                <div className="px-5 pt-4">
+                  <h2 className="text-sm font-bold text-text-primary">{t('channelPlan.summaryNetworks')}</h2>
+                  <p className="mt-0.5 text-caption text-text-muted">{t('channelPlan.tableSub', { n: bandScans.length })}</p>
+                </div>
+                <div className="mt-2 overflow-x-auto">
+                  <table className="w-full border-collapse text-left text-sm">
+                    <thead>
+                      <tr className="text-label uppercase text-text-muted">
+                        <th className="px-5 py-2.5 font-medium">
+                          <SortHeader id="signal" label={t('channelPlan.signal')} />
+                        </th>
+                        <th className="px-3 py-2.5 font-medium">
+                          <SortHeader id="ssid" label="SSID" />
+                        </th>
+                        <th className="px-3 py-2.5 font-medium">
+                          <SortHeader id="channel" label={t('channelPlan.currentChannel')} />
+                        </th>
+                        <th className="px-3 py-2.5 font-medium">{t('channelPlan.colWidth')}</th>
+                        <th className="px-3 py-2.5 font-medium">BSSID</th>
                       </tr>
-                    ))}
-                  </tbody>
-                </table>
+                    </thead>
+                    <tbody>
+                      {sortedScans.map((s) => {
+                          const lvl = signalLevel(s.signal)
+                          const color = s.own ? themeColor('--accent') : ssidColor(s.ssid || s.bssid)
+                          const key = s.bssid + s.channel
+                          return (
+                            <tr
+                              key={key}
+                              onClick={() => setSelected(selected === key ? null : key)}
+                              className={cn(
+                                'cursor-pointer border-t border-border/60 transition-colors hover:bg-hover',
+                                selected === key && 'bg-accent/5',
+                              )}
+                            >
+                              <td className="px-5 py-2.5">
+                                <span className="inline-flex items-center gap-2 tabular-nums">
+                                  <SignalBars signal={s.signal} own={s.own} />
+                                  <b className="text-text-primary">{s.signal}</b>
+                                  <small className="text-caption text-text-muted">
+                                    dBm · {t(`channelPlan.quality.${lvl === 4 ? 'excellent' : lvl === 3 ? 'good' : lvl === 2 ? 'weak' : 'veryWeak'}`)}
+                                  </small>
+                                </span>
+                              </td>
+                              <td className="px-3 py-2.5">
+                                <span className="flex items-center gap-2.5">
+                                  <span className="inline-block h-2.5 w-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: color }} />
+                                  <span>
+                                    <span className="font-semibold text-text-primary">
+                                      {s.ssid || <em className="font-normal text-text-muted">{t('channelPlan.hidden')}</em>}
+                                    </span>
+                                    {s.own && (
+                                      <span className="ml-2 rounded-md bg-accent/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-accent">
+                                        {t('channelPlan.ownNetwork')}
+                                      </span>
+                                    )}
+                                  </span>
+                                </span>
+                              </td>
+                              <td className="px-3 py-2.5 font-mono font-bold text-text-primary">{s.channel}</td>
+                              <td className="px-3 py-2.5">
+                                {s.own ? (
+                                  active.widthMhz > 0 ? (
+                                    <span className="rounded-md bg-elevated px-2 py-0.5 text-[11px] font-bold text-text-secondary">
+                                      {active.widthMhz} MHz
+                                    </span>
+                                  ) : (
+                                    <span className="text-text-muted">—</span>
+                                  )
+                                ) : s.widthMhz && s.widthMhz > 0 ? (
+                                  <span className="rounded-md bg-elevated px-2 py-0.5 text-[11px] font-bold text-text-secondary">
+                                    {s.widthMhz} MHz
+                                  </span>
+                                ) : (
+                                  <span className="text-text-muted">—</span>
+                                )}
+                              </td>
+                              <td className="px-3 py-2.5 font-mono text-caption text-text-muted">{s.bssid}</td>
+                            </tr>
+                          )
+                        })}
+                    </tbody>
+                  </table>
+                </div>
               </div>
-            )}
-          </div>
+              )}
         </>
       )}
-
-      <AlertDialog open={!!confirmTarget} onOpenChange={(open) => !open && setConfirmTarget(null)}>
-        <AlertDialogContent className="max-w-lg">
-          <AlertDialogHeader>
-            <AlertDialogTitle>{t('channelPlan.applyConfirmTitle', { band: confirmTarget?.name ?? '' })}</AlertDialogTitle>
-            <AlertDialogDescription>
-              {t('channelPlan.applyConfirmBody', {
-                band: confirmTarget?.name ?? '',
-                from: confirmTarget?.channel ?? 0,
-                to: confirmTarget?.recommended ?? 0,
-              })}
-            </AlertDialogDescription>
-          </AlertDialogHeader>
-          <AlertDialogFooter>
-            <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
-            <AlertDialogAction onClick={onConfirmApply}>{t('channelPlan.applyConfirmAction')}</AlertDialogAction>
-          </AlertDialogFooter>
-        </AlertDialogContent>
-      </AlertDialog>
     </div>
   )
 }

+ 94 - 13
app/src/pages/Devices.tsx

@@ -341,7 +341,7 @@ function StatsStrip({
 }) {
   const { t } = useTranslation()
   const { refreshKey } = useDashboard()
-  const { deviceTotals } = useNetPulse()
+  const { deviceTotals, adguard } = useNetPulse()
   const reduce = useReducedMotion()
   const newThisWeekDevices = allDevices.filter((d) => d.isNew)
   // #1003: el umbral de señal débil es el ajuste global (/api/settings/thresholds),
@@ -483,9 +483,13 @@ function StatsStrip({
       ),
     },
   ]
+  // #1136: sin AdGuard configurado (host vacío) la tarjeta de cobertura no
+  // aplica: en live el flag por cliente nunca se rellena y la tarjeta
+  // mostraba "0/N protegidos" permanentemente.
+  const visibleCards = adguard.host ? cards : cards.filter((c) => c.key !== 'adguard')
   return (
     <div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
-      {cards.map((c, i) => (
+      {visibleCards.map((c, i) => (
         <motion.div
           key={c.key}
           initial={reduce ? false : { opacity: 0, y: 16 }}
@@ -816,6 +820,8 @@ function DeviceDetail({
   onEdit: () => void
 }) {
   const { t } = useTranslation()
+  const { adguard } = useNetPulse()
+  const hasAdGuard = Boolean(adguard.host)
   return (
     <div className="grid grid-cols-2 gap-x-4 gap-y-4 px-4 py-4 md:grid-cols-3 md:px-5">
       <DetailItem label="MAC" mono>
@@ -823,21 +829,25 @@ function DeviceDetail({
       </DetailItem>
       <DetailItem label={t('devices.detail.dhcpLease')}>{dhcpLease(device.dhcpLease)}</DetailItem>
       <DetailItem label={t('devices.detail.firstSeen')}>{fmtSeenAgo(device.firstSeenMs)}</DetailItem>
-      <DetailItem label={t('devices.detail.lastSeen')}>{fmtSeenAgo(device.lastSeenMs)}</DetailItem>
-      <DetailItem label={t('devices.detail.manufacturer')}>{manufacturerLabel(device.manufacturer)}</DetailItem>
+      {/* #1131: hostname junto a MAC (izquierda) y los "seen" juntos a la
+          derecha: intercambio de posiciones con lastSeen. */}
       <DetailItem label="Hostname" mono>
         {device.hostname}
       </DetailItem>
-      <div className="min-w-0">
-        <div className="text-label uppercase text-text-muted">AdGuard</div>
-        <div className="mt-1.5">
-          {device.adguard ? (
-            <StatusPill tone="ok" label={t('devices.detail.protected')} />
-          ) : (
-            <StatusPill tone="muted" label={t('devices.detail.unfiltered')} />
-          )}
+      <DetailItem label={t('devices.detail.manufacturer')}>{manufacturerLabel(device.manufacturer)}</DetailItem>
+      <DetailItem label={t('devices.detail.lastSeen')}>{fmtSeenAgo(device.lastSeenMs)}</DetailItem>
+      {hasAdGuard && (
+        <div className="min-w-0">
+          <div className="text-label uppercase text-text-muted">AdGuard</div>
+          <div className="mt-1.5">
+            {device.adguard ? (
+              <StatusPill tone="ok" label={t('devices.detail.protected')} />
+            ) : (
+              <StatusPill tone="muted" label={t('devices.detail.unfiltered')} />
+            )}
+          </div>
         </div>
-      </div>
+      )}
       <ConnectedToItem device={device} />
       {infra && (
         <DetailItem label={t('devices.detail.infra')}>
@@ -1341,6 +1351,37 @@ export default function Devices() {
   const navigate = useNavigate()
   const reduce = useReducedMotion()
   const { devices, deviceTotals, isDemo, routers, distributionNodes, refresh } = useNetPulse()
+  const { refreshKey } = useDashboard()
+  // #1151: candidatos a "mismo dispositivo con varias MACs" que el server
+  // detecta (hostname+IP compartidos, nunca simultáneos). Enlazar es manual.
+  const [linkSuggestions, setLinkSuggestions] = useState<[string, string][]>([])
+  const [dismissedLinks, setDismissedLinks] = useState<Set<string>>(new Set())
+  useEffect(() => {
+    if (isDemo) return
+    let alive = true
+    void fetchJson<{ linkSuggestions?: [string, string][] }>('/api/devices?page=1&pageSize=1')
+      .then((r) => {
+        if (alive && r.ok && Array.isArray(r.data?.linkSuggestions)) setLinkSuggestions(r.data.linkSuggestions)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [refreshKey, isDemo])
+
+  const linkPair = async (a: string, b: string) => {
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(b)}/link`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ target: a }),
+      })
+      setLinkSuggestions((p) => p.filter(([x, y]) => !(x === a && y === b) && !(x === b && y === a)))
+      refresh()
+    } catch {
+      // fallo silencioso: la sugerencia sigue para reintentar
+    }
+  }
   const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string }>>(() => {
     try {
       const raw = localStorage.getItem('netpulse-device-overrides')
@@ -1791,6 +1832,43 @@ export default function Devices() {
       {/* ② Stats strip */}
       <StatsStrip allDevices={allDevices} onlyUnprotected={onlyUnprotected} onToggleUnprotected={toggleUnprotected} />
 
+      {/* #1151: sugerencias de enlace (mismo dispositivo, varias MACs) */}
+      {linkSuggestions.filter(([a, b]) => !dismissedLinks.has(a + b)).length > 0 && (
+        <div className="mb-4 rounded-2xl border border-accent/30 bg-accent/5 p-4">
+          <div className="text-label uppercase tracking-[0.06em] text-accent">{t('devices.suggestions.title')}</div>
+          <p className="mb-2 mt-1 text-caption text-text-muted">{t('devices.suggestions.desc')}</p>
+          <ul className="space-y-1.5">
+            {linkSuggestions
+              .filter(([a, b]) => !dismissedLinks.has(a + b))
+              .map(([a, b]) => {
+                const na = allDevices.find((d) => d.mac === a)?.name ?? a
+                const nb = allDevices.find((d) => d.mac === b)?.name ?? b
+                return (
+                  <li key={a + b} className="flex flex-wrap items-center gap-2 text-sm">
+                    <span className="font-medium text-text-primary">{na}</span>
+                    <span className="text-text-muted">·</span>
+                    <span className="font-medium text-text-primary">{nb}</span>
+                    <button
+                      type="button"
+                      onClick={() => void linkPair(a, b)}
+                      className="rounded-lg border border-accent/40 px-2.5 py-1 text-caption font-medium text-accent transition-colors hover:bg-accent/10"
+                    >
+                      {t('devices.suggestions.link')}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => setDismissedLinks((p) => new Set(p).add(a + b))}
+                      className="rounded-lg px-2.5 py-1 text-caption text-text-muted transition-colors hover:text-text-primary"
+                    >
+                      {t('devices.suggestions.dismiss')}
+                    </button>
+                  </li>
+                )
+              })}
+          </ul>
+        </div>
+      )}
+
       {/* ③ Filter bar */}
       <FilterBar
         routerIds={routerIds}
@@ -1935,6 +2013,9 @@ export default function Devices() {
         saving={savingOverride}
         onClose={() => setEditingId(null)}
         onSave={handleEditSave}
+        onDeleted={() => setEditingId(null)}
+        clients={allDevices}
+        onLinkChanged={() => setEditingId(null)}
       />
 
       <OnboardingIntake

+ 34 - 2
app/src/pages/FirmwareUpgrades.tsx

@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
+import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import { AlertCircle, CalendarClock, Cpu, PartyPopper, Radar, RefreshCw, Rocket, ShieldCheck, Terminal, TriangleAlert, Download } from 'lucide-react'
 import { cn } from '@/lib/utils'
 import { relTimeFromTs } from '@/i18n'
@@ -122,6 +123,8 @@ export default function FirmwareUpgrades() {
   const { t, i18n } = useTranslation()
   const auth = useAuth()
   const { routers } = useNetPulse()
+  // #1146: la visibilidad de la página la controla el toggle de Servicios.
+  const [services] = useServicesVisibility()
   const isAdmin = auth?.role === 'admin'
 
   const [items, setItems] = useState<FirmwareItem[]>([])
@@ -158,6 +161,15 @@ export default function FirmwareUpgrades() {
     return [...routers].sort((a, b) => (a.roleBadge === 'Principal' ? -1 : 1) || a.name.localeCompare(b.name))
   }, [routers])
 
+  // Solo dispositivos con OpenWrt vanilla: son los únicos actualizables
+  // desde aquí (los GL.iNet se actualizan por su propia vía; SNMP y
+  // externos quedan fuera de esta página y se gestionan donde corresponde).
+  const compatibleItems = useMemo(() => {
+    const compatIds = new Set(sortedRouters.filter((r) => !r.type || r.type === 'openwrt').map((r) => r.id))
+    return items.filter((it) => compatIds.has(it.routerId) || !sortedRouters.some((r) => r.id === it.routerId))
+  }, [items, sortedRouters])
+  const hiddenCount = items.length - compatibleItems.length
+
   const fetchItems = async () => {
     setLoading(true)
     setError('')
@@ -505,6 +517,19 @@ export default function FirmwareUpgrades() {
     ? sortedRouters.find((r) => r.id === scheduleItem.routerId)?.name ?? scheduleItem.name
     : ''
 
+  // Oculta con el toggle de Servicios: aviso en vez de contenido (patrón rack).
+  if (!services.actualizaciones) {
+    return (
+      <div className="flex h-full flex-col">
+        <div className="mx-auto my-auto max-w-md rounded-xl border border-border bg-surface p-6 text-center">
+          <TriangleAlert size={24} className="mx-auto mb-2 text-warn" aria-hidden />
+          <p className="text-sm font-semibold text-text-primary">{t('firmwareUpgrades.disabledTitle')}</p>
+          <p className="mt-1 text-[13px] text-text-secondary">{t('firmwareUpgrades.disabledText')}</p>
+        </div>
+      </div>
+    )
+  }
+
   return (
     <div className="space-y-4 md:space-y-5">
       <header className="flex items-start justify-between gap-4">
@@ -538,12 +563,19 @@ export default function FirmwareUpgrades() {
 
       {items.length === 0 && !loading && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-text-secondary">
-          {t('firmwareUpgrades.empty')}
+          <p>{t('firmwareUpgrades.empty')}</p>
+          {items.length > 0 && <p className="mt-1 text-xs text-text-muted">{t('firmwareUpgrades.compatibleNote', { count: items.length })}</p>}
         </div>
       )}
 
+      {hiddenCount > 0 && (
+        <p className="mb-3 text-[12px] text-text-muted" data-testid="fw-compat-note">
+          {t('firmwareUpgrades.compatibleNote', { count: hiddenCount })}
+        </p>
+      )}
+
       <div className="grid gap-4">
-        {items.map((item) => {
+        {compatibleItems.map((item) => {
           const e = edits[item.routerId] ?? {}
           const active = upgradeActive(item)
           const scheduled = scheduledPending(item)

+ 124 - 17
app/src/pages/Roaming.tsx

@@ -3,10 +3,19 @@ import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
-import { AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CheckCircle2, GitFork, History, RefreshCw, Wifi, X, XCircle } from 'lucide-react'
+import { AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CheckCircle2, Filter, GitFork, History, RefreshCw, Wifi, X, XCircle } from 'lucide-react'
 import { cn, fetchJson } from '@/lib/utils'
+import { ssidColor } from '@/lib/ssidColor'
 import { useNetPulse, redirectLogin } from '@/data/DataProvider'
 import { useWeakSignalDbm } from '@/hooks/useWeakSignalDbm'
+import {
+  DropdownMenu,
+  DropdownMenuCheckboxItem,
+  DropdownMenuContent,
+  DropdownMenuLabel,
+  DropdownMenuSeparator,
+  DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu'
 import ReanchorPanel from './ReanchorPanel'
 
 // ---------------------------------------------------------------------------
@@ -190,6 +199,10 @@ export default function Roaming() {
   const [eventsError, setEventsError] = useState(false)
   const [eventsNoApi, setEventsNoApi] = useState(false)
   const [eventsTypeFilter, setEventsTypeFilter] = useState<'all' | 'connected' | 'disconnected' | 'dawn_decision'>('all')
+  // #1127: filtros AP/cliente multi-select (string[] = IDs/MACs seleccionados;
+  // vacío = todos). El fetch las serializa separadas por comas.
+  const [eventsRouterFilter, setEventsRouterFilter] = useState<string[]>([])
+  const [eventsMacFilter, setEventsMacFilter] = useState<string[]>([])
   // #907: retención y cadencia efectivas, devueltas como meta por la API, para
   // que la cabecera de la tabla describa los valores reales en vez de texto
   // hardcodeado. null = aún no cargada (o servidor antiguo).
@@ -322,7 +335,10 @@ export default function Roaming() {
     setEventsLoading(true)
     setEventsError(false)
     setEventsNoApi(false)
-    const result = await fetchJson<{ events: RoamEvent[]; retentionDays?: number; collectIntervalSec?: number }>('/api/roam-events?limit=100', { signal: ac.signal })
+    const params = new URLSearchParams({ limit: '100' })
+    if (eventsRouterFilter.length) params.set('router', eventsRouterFilter.join(','))
+    if (eventsMacFilter.length) params.set('mac', eventsMacFilter.join(','))
+    const result = await fetchJson<{ events: RoamEvent[]; retentionDays?: number; collectIntervalSec?: number }>(`/api/roam-events?${params.toString()}`, { signal: ac.signal })
     if (ac.signal.aborted) return
     if (result.ok) {
       setEvents(result.data.events ?? [])
@@ -357,7 +373,7 @@ export default function Roaming() {
       window.clearInterval(id)
       eventsAc.current?.abort()
     }
-  }, [tab])
+  }, [tab, eventsRouterFilter, eventsMacFilter])
 
   // Expulsar a un cliente de su AP actual para forzar la reconexión
   // (usteering manual cuando usteer no cambia al cliente).
@@ -621,7 +637,7 @@ export default function Roaming() {
 
       {tab === 'events' && (
         <div role="tabpanel" id="panel-events" aria-labelledby="tab-events" tabIndex={0}>
-          <EventsPanel events={events} loading={eventsLoading} error={eventsError} noApi={eventsNoApi} typeFilter={eventsTypeFilter} setTypeFilter={setEventsTypeFilter} nameByMac={nameByMac} hasDawn={dawnDeprecated === true} meta={eventsMeta} />
+          <EventsPanel events={events} loading={eventsLoading} error={eventsError} noApi={eventsNoApi} typeFilter={eventsTypeFilter} setTypeFilter={setEventsTypeFilter} routerFilter={eventsRouterFilter} setRouterFilter={setEventsRouterFilter} macFilter={eventsMacFilter} setMacFilter={setEventsMacFilter} nameByMac={nameByMac} hasDawn={dawnDeprecated === true} meta={eventsMeta} />
         </div>
       )}
 
@@ -1112,19 +1128,8 @@ function signalDot(signal: number): string {
   return 'bg-danger'
 }
 
-// ssidColor (#542): color pastel determinista por SSID (hash), como el canal
-// analysis del LuCI: cada red vecina su color para reconocerla en la cascada.
-const SSID_PALETTE = [
-  '#c084fc', '#f472b6', '#34d399', '#60a5fa', '#fbbf24',
-  '#f87171', '#2dd4bf', '#a78bfa', '#facc15', '#fb923c',
-]
-function ssidColor(s: string): string {
-  let h = 0
-  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0
-  return SSID_PALETTE[h % SSID_PALETTE.length] ?? '#a78bfa'
-}
-
-// bandOfFreq: 2.4 / 5 / 6 GHz a partir de la frecuencia del canal.
+// ssidColor vive en @/lib/ssidColor (compartido con el informe de canales
+// #1070). bandOfFreq: 2.4 / 5 / 6 GHz a partir de la frecuencia del canal.
 function bandOfFreq(freq: number): string {
   if (freq >= 2412 && freq <= 2484) return '2.4 GHz'
   if (freq >= 5180 && freq <= 5885) return '5 GHz'
@@ -1504,6 +1509,67 @@ function formatEventTime(tsMs: number): string {
   return `${dd}/${mo} ${hh}:${mm}`
 }
 
+// EventsFilterMenu (#1127): desplegable multi-select para los filtros de la
+// vista de eventos (AP y cliente). Mismo patrón visual que los filtros de
+// la página Clients (#989): botón con icono + etiqueta + contador, items
+// con checkbox; vacío = todos.
+function EventsFilterMenu({
+  label,
+  allLabel,
+  options,
+  selected,
+  onToggle,
+  onClear,
+}: {
+  label: string
+  allLabel: string
+  options: { value: string; label: string }[]
+  selected: string[]
+  onToggle: (value: string) => void
+  onClear: () => void
+}) {
+  return (
+    <DropdownMenu>
+      <DropdownMenuTrigger asChild>
+        <button
+          type="button"
+          aria-label={label}
+          className={cn(
+            'inline-flex h-8 items-center gap-1.5 rounded-lg border px-3 text-caption font-medium transition-colors',
+            selected.length > 0
+              ? 'border-accent/50 bg-accent-soft text-accent'
+              : 'border-border bg-elevated text-text-secondary hover:bg-hover hover:text-text-primary',
+          )}
+        >
+          <Filter className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden />
+          <span className="max-w-32 truncate">{label}</span>
+          {selected.length > 0 && (
+            <span className="rounded-full bg-accent/20 px-1.5 py-0.5 text-[10px] font-semibold">{selected.length}</span>
+          )}
+        </button>
+      </DropdownMenuTrigger>
+      <DropdownMenuContent align="start" className="max-h-72 min-w-44 overflow-y-auto">
+        <DropdownMenuLabel>{allLabel}</DropdownMenuLabel>
+        <DropdownMenuSeparator />
+        {options.length === 0 && <DropdownMenuLabel className="font-normal text-text-muted">-</DropdownMenuLabel>}
+        {options.map((o) => (
+          <DropdownMenuCheckboxItem key={o.value} checked={selected.includes(o.value)} onCheckedChange={() => onToggle(o.value)}>
+            <span className="max-w-48 truncate">{o.label}</span>
+          </DropdownMenuCheckboxItem>
+        ))}
+        {selected.length > 0 && (
+          <>
+            <DropdownMenuSeparator />
+            <DropdownMenuCheckboxItem checked onCheckedChange={onClear} className="text-text-muted">
+              {allLabel}
+            </DropdownMenuCheckboxItem>
+          </>
+        )}
+      </DropdownMenuContent>
+    </DropdownMenu>
+  )
+}
+
 function EventsPanel({
   events,
   loading,
@@ -1511,6 +1577,10 @@ function EventsPanel({
   noApi,
   typeFilter,
   setTypeFilter,
+  routerFilter,
+  setRouterFilter,
+  macFilter,
+  setMacFilter,
   nameByMac,
   hasDawn,
   meta,
@@ -1521,10 +1591,17 @@ function EventsPanel({
   noApi: boolean
   typeFilter: EventTypeFilter
   setTypeFilter: (t: EventTypeFilter) => void
+  /** #1097/#1127: filtros multi-select por AP (router) y por cliente (MAC);
+   *  string[] vacío = todos. */
+  routerFilter: string[]
+  setRouterFilter: (v: string[]) => void
+  macFilter: string[]
+  setMacFilter: (v: string[]) => void
   nameByMac: Map<string, string>
   hasDawn: boolean
   meta: { retentionDays: number; collectIntervalSec: number } | null
 }) {
+  const { routers, devices } = useNetPulse()
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const initial = reduce ? false : { opacity: 0, y: 12 }
@@ -1597,6 +1674,36 @@ function EventsPanel({
               </button>
             ))}
           </div>
+          {/* #1097/#1127: seguir clientes entre APs o acotar a APs concretos.
+              Multi-select (OR dentro del filtro, AND entre filtros); las
+              opciones de AP se recortan a la flota con bandas WiFi (los
+              switches SNMP no son AP). */}
+          <EventsFilterMenu
+            label={t('roaming.events.filterAp')}
+            allLabel={t('roaming.events.filterApAll')}
+            options={routers
+              .filter((r) => {
+                if (r.disabled) return false // #1085: la unidad pausada no se ofrece
+                const b = r.bandSplit
+                return !b || b.band24 + b.band5 + b.band6 > 0
+              })
+              .map((r) => ({ value: r.id, label: r.name }))}
+            selected={routerFilter}
+            onToggle={(v) =>
+              setRouterFilter(routerFilter.includes(v) ? routerFilter.filter((x) => x !== v) : [...routerFilter, v])
+            }
+            onClear={() => setRouterFilter([])}
+          />
+          <EventsFilterMenu
+            label={t('roaming.events.filterClient')}
+            allLabel={t('roaming.events.filterClientAll')}
+            options={devices
+              .filter((d) => d.band !== 'cable' && d.mac)
+              .map((d) => ({ value: d.mac, label: d.name }))}
+            selected={macFilter}
+            onToggle={(v) => setMacFilter(macFilter.includes(v) ? macFilter.filter((x) => x !== v) : [...macFilter, v])}
+            onClear={() => setMacFilter([])}
+          />
         </div>
       </div>
 

+ 4 - 3
app/src/pages/RouterDetail.tsx

@@ -195,7 +195,7 @@ export default function RouterDetail() {
       </div>
 
       {/* ④ WAN & Latencia (gateway) / Backhaul (APs) */}
-      {isGateway ? <WanLatency /> : <BackhaulPanel router={router} extras={detail?.extras} />}
+      {isGateway ? <WanLatency extras={detail?.extras} /> : <BackhaulPanel router={router} extras={detail?.extras} />}
 
       {/* Las varias conexiones a internet, si el router reporta más de una.
           Va junto a la tarjeta de conexión porque explica la IP que muestra. */}
@@ -206,8 +206,9 @@ export default function RouterDetail() {
       {/* ⑤⑥ Servicios + Puertos (gateway) / Radios + Puertos (APs) */}
       {isGateway ? (
         <>
-          <AdGuardPanel />
-          <WireGuardPanel />
+          {/* AdGuard Home y WireGuard (vía ubus OpenWrt); no aplican a RouterOS. */}
+          {router.type !== 'routeros' && <AdGuardPanel />}
+          {router.type !== 'routeros' && <WireGuardPanel />}
           <PortPanel router={router} extras={detail?.extras} snmpStats={snmpStats} className="lg:col-span-12" />
         </>
       ) : (

+ 455 - 142
app/src/pages/Settings.tsx

@@ -39,6 +39,7 @@ import {
    Star,
    Sun,
    Trash2,
+   TriangleAlert,
    UserCog,
    Users,
    Volume2,
@@ -333,8 +334,7 @@ function Confetti({ burstKey, reduce }: { burstKey: number; reduce: boolean }) {
         s: 4 + Math.random() * 4,
         d: Math.random() * 0.15,
       })),
-    // eslint-disable-next-line react-hooks/exhaustive-deps
-    [burstKey],
+      [burstKey],
   )
   if (!burstKey || reduce) return null
   return (
@@ -357,7 +357,7 @@ function Confetti({ burstKey, reduce }: { burstKey: number; reduce: boolean }) {
 // Gestión de routers (modo live): CRUD contra /api/config/routers
 // ---------------------------------------------------------------------------
 
-type RouterType = 'glinet' | 'openwrt' | 'managed-switch' | 'external'
+type RouterType = 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'
 
 interface ConfigRouter {
   id: string
@@ -366,6 +366,7 @@ interface ConfigRouter {
   type: RouterType
   is_gateway: boolean
   agent_only: boolean
+  disabled: boolean
   firmware_target: string
   snmp_enabled: boolean
   snmp_community: string
@@ -374,6 +375,11 @@ interface ConfigRouter {
   ssh_port?: number
   temp_threshold?: number | null
   console_polling?: boolean
+  // RouterOS: routeros_user viaja tal cual; routeros_password NUNCA se
+  // devuelve (json:"-" en el server, igual que la clave SSH) — dejar el
+  // campo en blanco en el form de edición conserva la password existente.
+  routeros_user?: string
+  routeros_insecure?: boolean
 }
 
 interface DiscoverCandidate {
@@ -417,6 +423,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editType, setEditType] = useState<RouterType>('openwrt')
   const [editGateway, setEditGateway] = useState(false)
   const [editAgentOnly, setEditAgentOnly] = useState(false)
+  const [editDisabled, setEditDisabled] = useState(false)
   const [editFirmwareTarget, setEditFirmwareTarget] = useState('')
   const [editSnmpEnabled, setEditSnmpEnabled] = useState(false)
   const [editConsolePolling, setEditConsolePolling] = useState(true)
@@ -425,6 +432,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editSnmpPollInterval, setEditSnmpPollInterval] = useState(60)
   const [editSshPort, setEditSshPort] = useState(22)
   const [editTempThreshold, setEditTempThreshold] = useState('')
+  const [editRouterOSUser, setEditRouterOSUser] = useState('')
+  const [editRouterOSPassword, setEditRouterOSPassword] = useState('')
+  const [editRouterOSInsecure, setEditRouterOSInsecure] = useState(false)
   const [editSubmitting, setEditSubmitting] = useState(false)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [copied, setCopied] = useState(false)
@@ -610,6 +620,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditType(r.type)
     setEditGateway(r.is_gateway)
     setEditAgentOnly(r.agent_only)
+    setEditDisabled(r.disabled ?? false)
     setEditFirmwareTarget(r.firmware_target ?? '')
     setEditSnmpEnabled(r.snmp_enabled ?? false)
     setEditConsolePolling(r.console_polling ?? true)
@@ -618,6 +629,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditSnmpPollInterval(r.snmp_poll_interval ?? 60)
     setEditSshPort(r.ssh_port ?? 22)
     setEditTempThreshold(r.temp_threshold != null ? String(r.temp_threshold) : '')
+    setEditRouterOSUser(r.routeros_user ?? '')
+    setEditRouterOSPassword('') // blank = conservar la password existente
+    setEditRouterOSInsecure(r.routeros_insecure ?? false)
     setError(null)
   }
 
@@ -636,6 +650,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           type: editType,
           gateway: editGateway,
           agent_only: editAgentOnly,
+          disabled: editDisabled,
           firmware_target: editFirmwareTarget.trim(),
           snmp_enabled: editSnmpEnabled,
           snmp_community: editSnmpCommunity.trim() || undefined,
@@ -644,6 +659,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           ssh_port: editSshPort,
           temp_threshold: editTempThreshold.trim() === '' ? 0 : Number(editTempThreshold),
           console_polling: editConsolePolling,
+          routeros_user: editType === 'routeros' ? editRouterOSUser.trim() : undefined,
+          routeros_password: editRouterOSPassword || undefined,
+          routeros_insecure: editType === 'routeros' ? editRouterOSInsecure : undefined,
         }),
       })
       if (res.status === 409) {
@@ -763,7 +781,11 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   <td className="px-3.5 py-2.5 font-mono text-[12px] font-medium text-text-primary">{r.host}</td>
                   <td className="px-3.5 py-2.5 text-text-secondary">{r.name && r.name !== r.host ? r.name : '—'}</td>
                   <td className="px-3.5 py-2.5">
-                    {r.is_gateway ? (
+                    {r.disabled ? (
+                      <span className="rounded bg-elevated px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-warn ring-1 ring-inset ring-warn/40">
+                        {t('settings.routers.disabledBadge')}
+                      </span>
+                    ) : r.is_gateway ? (
                       <span className="rounded bg-accent-soft px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-accent">
                         {t('settings.routers.gatewayBadge')}
                       </span>
@@ -971,6 +993,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
             options={[
               { value: 'openwrt', label: 'OpenWrt' },
               { value: 'glinet', label: 'GL.iNet' },
+              { value: 'routeros', label: 'RouterOS' },
               { value: 'managed-switch', label: t('settings.routers.typeManaged') },
               { value: 'external', label: t('settings.routers.typeExternal') },
             ]}
@@ -1140,6 +1163,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   options={[
                     { value: 'openwrt', label: 'OpenWrt' },
                     { value: 'glinet', label: 'GL.iNet' },
+                    { value: 'routeros', label: 'RouterOS' },
                     { value: 'managed-switch', label: t('settings.routers.typeManaged') },
                     { value: 'external', label: t('settings.routers.typeExternal') },
                   ]}
@@ -1156,6 +1180,12 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   {t('settings.routers.agentOnly')}
                   <InfoTip text={t('settings.routers.agentOnlyHint')} />
                 </label>
+                {/* #1085: pausa la unidad sin borrarla ni perder histórico. */}
+                <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
+                  <Switch checked={editDisabled} onCheckedChange={setEditDisabled} />
+                  {t('settings.routers.disabled')}
+                  <InfoTip text={t('settings.routers.disabledHint')} />
+                </label>
                 {editType === 'managed-switch' && (
                   <label className="flex cursor-pointer items-start gap-2 text-sm text-text-secondary">
                     <Switch checked={editConsolePolling} onCheckedChange={setEditConsolePolling} className="mt-0.5" />
@@ -1240,6 +1270,44 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   )}
                 </div>
               )}
+              {editType === 'routeros' && (
+                <div className="space-y-2.5 rounded-lg border border-border bg-canvas/50 p-3">
+                  <div className="grid grid-cols-2 gap-2.5">
+                    <div>
+                      <label htmlFor="routeros-user" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                        {t('settings.routers.routerosUser')}
+                      </label>
+                      <input
+                        id="routeros-user"
+                        type="text"
+                        value={editRouterOSUser}
+                        onChange={(e) => setEditRouterOSUser(e.target.value)}
+                        placeholder="admin"
+                        aria-label={t('settings.routers.routerosUser')}
+                        className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                      />
+                    </div>
+                    <div>
+                      <label htmlFor="routeros-password" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                        {t('settings.routers.routerosPassword')}
+                      </label>
+                      <input
+                        id="routeros-password"
+                        type="password"
+                        value={editRouterOSPassword}
+                        onChange={(e) => setEditRouterOSPassword(e.target.value)}
+                        placeholder={t('settings.routers.routerosPasswordPlaceholder')}
+                        aria-label={t('settings.routers.routerosPassword')}
+                        className="w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                      />
+                    </div>
+                  </div>
+                  <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
+                    <Switch checked={editRouterOSInsecure} onCheckedChange={setEditRouterOSInsecure} />
+                    {t('settings.routers.routerosInsecure')}
+                  </label>
+                </div>
+              )}
               {error && <p className="text-caption text-danger">{error}</p>}
               <div className="flex items-center justify-between gap-2">
                 <button
@@ -1959,6 +2027,20 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const save = async (e: React.FormEvent) => {
     e.preventDefault()
     if (!editing || saving) return
+    // #1057: el PUT hace upsert por id y un id vacío se coerciona a
+    // "default" en el server (legado): sin esta guarda, añadir una segunda
+    // instancia dejando el id vacío (o duplicado) pisa la primera.
+    if (isNew) {
+      const newId = editing.id.trim()
+      if (newId === '') {
+        setError(t('settings.proxmox.idRequired'))
+        return
+      }
+      if (instances.some((i) => i.id === newId)) {
+        setError(t('settings.proxmox.idDuplicate'))
+        return
+      }
+    }
     setSaving(true)
     setError(null)
     try {
@@ -2599,6 +2681,72 @@ function LimitHistoryRow({ onSaved }: { onSaved: () => void }) {
   )
 }
 
+// #1034: retención del log de alertas en días (kv alerts.retentionDays, por
+// /api/settings/thresholds). 0 = poda temporal off (la cota de 500 filas
+// sigue aplicando). Efecto sin reinicio: la poda horaria y la de arranque le
+// releen el kv en cada pasada.
+function AlertRetentionRow({ onSaved }: { onSaved: () => void }) {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const [days, setDays] = useState<number | null>(null)
+
+  useEffect(() => {
+    if (isDemo) {
+      setDays(30)
+      return
+    }
+    let cancelled = false
+    fetch('/api/settings/thresholds')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((j) => {
+        if (!cancelled && j && typeof j.alertRetentionDays === 'number')
+          setDays(j.alertRetentionDays)
+      })
+      .catch(() => {})
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+
+  if (days === null) return null
+
+  const save = (raw: number) => {
+    if (!Number.isFinite(raw)) return
+    const v = Math.max(0, Math.min(365, Math.round(raw)))
+    setDays(v)
+    onSaved()
+    if (isDemo) return
+    void fetch('/api/settings/thresholds', {
+      method: 'PUT',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ alertRetentionDays: v }),
+    }).catch(() => {})
+  }
+
+  return (
+    <div className="flex flex-wrap items-center justify-between gap-3">
+      <div className="min-w-0">
+        <div className="flex items-center gap-1 text-sm font-medium text-text-primary">
+          {t('settings.data.alertRetention')}
+          <InfoTip text={t('settings.data.alertRetentionHint')} />
+        </div>
+        <div className="mt-0.5 text-caption text-text-muted">
+          {t('settings.data.alertRetentionCaption')}
+        </div>
+      </div>
+      <input
+        type="number"
+        min={0}
+        max={365}
+        value={days}
+        onChange={(e) => save(Number(e.target.value))}
+        aria-label={t('settings.data.alertRetention')}
+        className="w-24 rounded-lg border border-border bg-elevated px-3 py-2 text-right text-sm text-text-primary focus:border-accent focus:outline-none"
+      />
+    </div>
+  )
+}
+
 function BackupsPanel() {
   const { t, i18n } = useTranslation()
   const [cfg, setCfg] = useState<{ enabled: boolean; frequency_h: number; retention_days: number; last_run: string; time: string } | null>(null)
@@ -3052,12 +3200,17 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
   const [alertPct, setAlertPct] = useState(50)
   const [serverUrl, setServerUrl] = useState('')
   // Proveedor del test (#976): ookla/cloudflare/librespeed + custom (#1001,
-  // endpoint HTTP libre cuya URL completa escribe el usuario).
-  const [provider, setProvider] = useState<'ookla' | 'cloudflare' | 'librespeed' | 'custom'>('ookla')
-  const [scheduleKind, setScheduleKind] = useState<'interval' | 'weekly' | 'monthly'>('interval')
+  // endpoint HTTP libre cuya URL completa escribe el usuario) + ndt (#1037,
+  // M-Lab NDT con autodetección de servidor).
+  const [provider, setProvider] = useState<'ookla' | 'cloudflare' | 'librespeed' | 'custom' | 'ndt'>('ndt')
+  const [scheduleKind, setScheduleKind] = useState<'interval' | 'auto' | 'weekly' | 'monthly'>('interval')
   const [dayOfWeek, setDayOfWeek] = useState(1)
   const [dayOfMonth, setDayOfMonth] = useState(1)
-  const [schedTime, setSchedTime] = useState('01:00')
+  // Hora por defecto 03:00 (#1066): valle típico del tráfico residencial.
+  const [schedTime, setSchedTime] = useState('03:00')
+  // #1066: con kind "auto" la hora la elige el server (la de menos tráfico
+  // de su histórico) y la expone en /status: el UI la muestra solo lectura.
+  const [autoTime, setAutoTime] = useState('')
   const [busy, setBusy] = useState(false)
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState<string | null>(null)
@@ -3077,13 +3230,13 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
         if (typeof d.alertPct === 'number') setAlertPct(d.alertPct)
         if (typeof d.serverUrl === 'string') setServerUrl(d.serverUrl)
         // Proveedor del test (#976): ookla/cloudflare/librespeed/custom.
-        if (d.provider === 'ookla' || d.provider === 'cloudflare' || d.provider === 'librespeed' || d.provider === 'custom') {
+        if (d.provider === 'ookla' || d.provider === 'cloudflare' || d.provider === 'librespeed' || d.provider === 'custom' || d.provider === 'ndt') {
           setProvider(d.provider)
         }
         // Migración visual de los "semanal/mensual" históricos (#744):
         // 168h/720h sin scheduleKind pasan a weekly/monthly con día y hora.
         const kind = typeof d.scheduleKind === 'string' ? d.scheduleKind : ''
-        if (kind === 'weekly' || kind === 'monthly') {
+        if (kind === 'interval' || kind === 'auto' || kind === 'weekly' || kind === 'monthly') {
           setScheduleKind(kind)
         } else if (d.intervalHours === 168) {
           setScheduleKind('weekly')
@@ -3103,6 +3256,22 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     }
   }, [])
 
+  // #1066: la hora elegida por kind "auto" la calcula el server; se lee al
+  // abrir el diálogo y se refresca al cambiar a "auto".
+  useEffect(() => {
+    if (scheduleKind !== 'auto') return
+    let alive = true
+    void fetch('/api/speedtest/status')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (alive && d && typeof d.autoTime === 'string' && d.autoTime) setAutoTime(d.autoTime)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [scheduleKind, cfgOpen])
+
   const bodyJson = useCallback(
     () => ({
       enabled,
@@ -3113,7 +3282,8 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       scheduleKind,
       ...(scheduleKind === 'weekly' ? { dayOfWeek } : {}),
       ...(scheduleKind === 'monthly' ? { dayOfMonth } : {}),
-      ...(scheduleKind !== 'interval' ? { time: schedTime } : {}),
+      // "auto" no envía time: la hora la deriva el server del histórico.
+      ...(scheduleKind === 'weekly' || scheduleKind === 'monthly' ? { time: schedTime } : {}),
     }),
     [enabled, intervalHours, serverUrl, provider, alertPct, scheduleKind, dayOfWeek, dayOfMonth, schedTime],
   )
@@ -3160,7 +3330,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       setError(t('settings.speedtest.invalid'))
       return
     }
-    if (scheduleKind !== 'interval' && !/^\d{2}:\d{2}$/.test(schedTime)) {
+    if ((scheduleKind === 'weekly' || scheduleKind === 'monthly') && !/^\d{2}:\d{2}$/.test(schedTime)) {
       setError(t('settings.speedtest.invalidSchedule'))
       return
     }
@@ -3184,15 +3354,29 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       setSaved(true)
       window.setTimeout(() => setSaved(false), 2000)
       onSaved()
+      setCfgOpen(false) // #1065: guardar con éxito cierra el diálogo
     } finally {
       setBusy(false)
     }
   }, [serverUrl, provider, intervalHours, alertPct, scheduleKind, schedTime, bodyJson, onSaved, t])
 
+  // #1092: «Probar» debe funcionar también con el servidor vacío
+  // (auto-detect) en los proveedores que lo soportan (Ookla, NDT,
+  // Cloudflare). LibreSpeed y custom siguen exigiendo URL, igual que
+  // Guardar. Mismo criterio de validación que save().
+  const rawUrl = serverUrl.trim()
+  const urlFormatOk = rawUrl === '' || /^https?:\/\/.+\..+/.test(rawUrl)
+  const urlRequired = provider === 'librespeed' || provider === 'custom'
+  const canTest =
+    urlFormatOk &&
+    (rawUrl === ''
+      ? !urlRequired
+      : rawUrl !== 'https://speedtest.net' && rawUrl !== 'https://www.speedtest.net')
+
   // «Probar»: guarda la URL del servidor y lanza un test de velocidad
   // inmediato (usa esa URL en el backend).
   const testUrl = useCallback(async () => {
-    if (!serverUrl.trim()) return
+    if (!canTest) return
     setBusy(true)
     setError(null)
     try {
@@ -3219,7 +3403,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     } finally {
       setBusy(false)
     }
-  }, [serverUrl, bodyJson, onSaved, t])
+  }, [canTest, bodyJson, onSaved, t])
 
   // Etiqueta/placeholder del campo URL según proveedor (#976, #1001):
   // LibreSpeed = base de instancia; custom = endpoint libre; Ookla =
@@ -3235,7 +3419,9 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       ? t('settings.speedtest.librespeedPlaceholder')
       : provider === 'custom'
         ? t('settings.speedtest.customPlaceholder')
-        : t('settings.speedtest.serverPlaceholder')
+        : provider === 'ndt'
+          ? t('settings.speedtest.ndtPlaceholder')
+          : t('settings.speedtest.serverPlaceholder')
 
   return (
     <div className="space-y-3">
@@ -3277,7 +3463,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
         </span>
         <select
           value={provider}
-          onChange={(e) => setProvider(e.target.value as 'ookla' | 'cloudflare' | 'librespeed' | 'custom')}
+          onChange={(e) => setProvider(e.target.value as 'ookla' | 'cloudflare' | 'librespeed' | 'custom' | 'ndt')}
           disabled={disabled || loading}
           aria-label={t('settings.speedtest.provider')}
           className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
@@ -3286,6 +3472,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           <option value="cloudflare">{t('settings.speedtest.providerCloudflare')}</option>
           <option value="librespeed">{t('settings.speedtest.providerLibrespeed')}</option>
           <option value="custom">{t('settings.speedtest.providerCustom')}</option>
+          <option value="ndt">{t('settings.speedtest.providerNdt')}</option>
         </select>
       </label>
       <div className="grid grid-cols-2 gap-3">
@@ -3296,12 +3483,13 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           </span>
           <select
             value={scheduleKind}
-            onChange={(e) => setScheduleKind(e.target.value as 'interval' | 'weekly' | 'monthly')}
+            onChange={(e) => setScheduleKind(e.target.value as 'interval' | 'auto' | 'weekly' | 'monthly')}
             disabled={disabled || loading}
             aria-label={t('settings.speedtest.interval')}
             className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
           >
             <option value="interval">{t('settings.speedtest.kindInterval')}</option>
+            <option value="auto">{t('settings.speedtest.kindAuto')}</option>
             <option value="weekly">{t('settings.speedtest.kindWeekly')}</option>
             <option value="monthly">{t('settings.speedtest.kindMonthly')}</option>
           </select>
@@ -3321,6 +3509,19 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
               ))}
             </select>
           </label>
+        ) : scheduleKind === 'auto' ? (
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.timeLabel')}</span>
+            <input
+              type="time"
+              value={autoTime}
+              readOnly
+              disabled={disabled || loading}
+              aria-label={t('settings.speedtest.timeLabel')}
+              title={t('settings.speedtest.kindAuto')}
+              className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-muted focus:outline-none"
+            />
+          </label>
         ) : (
           <label className="block">
             <span className="text-label uppercase text-text-muted">{t('settings.speedtest.dayLabel')}</span>
@@ -3354,6 +3555,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       </div>
       {scheduleKind !== 'interval' && (
         <div className="flex flex-wrap items-end gap-3">
+          {(scheduleKind === 'weekly' || scheduleKind === 'monthly') && (
           <label className="block max-w-[220px]">
             <span className="text-label uppercase text-text-muted">{t('settings.speedtest.timeLabel')}</span>
             <input
@@ -3365,8 +3567,12 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
               className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
             />
           </label>
+          )}
           <label className="block max-w-[160px]">
-            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
+            <span className="flex items-center gap-1 text-label uppercase text-text-muted">
+              {t('settings.speedtest.alertPctLabel')}
+              <InfoTip text={t('settings.speedtest.alertPctHint')} />
+            </span>
             <input
               type="text"
               inputMode="numeric"
@@ -3381,7 +3587,10 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       )}
       {scheduleKind === 'interval' && (
         <label className="block max-w-[160px]">
-          <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
+          <span className="flex items-center gap-1 text-label uppercase text-text-muted">
+            {t('settings.speedtest.alertPctLabel')}
+            <InfoTip text={t('settings.speedtest.alertPctHint')} />
+          </span>
           <input
             type="text"
             inputMode="numeric"
@@ -3393,7 +3602,6 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           />
         </label>
       )}
-      <p className="text-caption text-text-muted">{t('settings.speedtest.alertPctHint')}</p>
       {/* URL del servidor/instancia/endpoint: no aplica a Cloudflare
           (endpoints fijos); opcional en Ookla, obligatoria en LibreSpeed
           (#976) y en custom (#1001, donde es la URL completa del endpoint
@@ -3427,19 +3635,22 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
             <span className="hidden sm:inline">{t('settings.speedtest.serverAuto')}</span>
           </button>
           )}
-          <button
-            type="button"
-            onClick={() => void testUrl()}
-            disabled={disabled || busy || loading || !serverUrl.trim()}
-            className="inline-flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-xl border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50"
-          >
-            <Gauge className="h-4 w-4" strokeWidth={1.75} />
-            {t('settings.speedtest.test')}
-          </button>
         </div>
       </div>
       )}
       <div className="flex flex-wrap items-center gap-3">
+        {/* #1092: «Probar» vive junto a Guardar (no en la fila de URL) para
+            existir también con Cloudflare, y se habilita con el servidor
+            vacío cuando el proveedor soporta auto-detect. */}
+        <button
+          type="button"
+          onClick={() => void testUrl()}
+          disabled={disabled || busy || loading || !canTest}
+          className="inline-flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-xl border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50"
+        >
+          <Gauge className="h-4 w-4" strokeWidth={1.75} />
+          {t('settings.speedtest.test')}
+        </button>
         <button
           type="button"
           onClick={() => void save()}
@@ -3612,7 +3823,7 @@ function SpeedtestRecent({ disabled = false }: { disabled?: boolean }) {
 
 // Clave de integración configurable desde la tarjeta (icono Settings2 que
 // abre el Dialog con su manager, #968).
-type IntegrationDialogKey = 'adguard' | 'proxmox' | 'ntfy' | 'telegram' | 'mqtt'
+type IntegrationDialogKey = 'adguard' | 'proxmox' | 'ntfy' | 'telegram' | 'mqtt' | 'mcp'
 
 // Los diálogos de configuración van GRANDES (#968, #977): el manager
 // (formularios, tablas) necesita el ancho casi completo. Wrapper compartido
@@ -3636,6 +3847,82 @@ function ConfigGear({ label, onClick, disabled = false }: { label: string; onCli
   )
 }
 
+// ---------------------------------------------------------------------------
+// Integración MCP (#1114): endpoint /mcp para asistentes de IA. El toggle es
+// el server-side settings.integrations.mcp (aplica sin reinicio); sin
+// NETPULSE_MCP_ENABLED=1 en el servidor el endpoint no existe y el toggle
+// queda bloqueado. Los tokens de API son la ÚNICA auth del endpoint: se
+// gestionan aquí mismo (crear/revocar).
+// ---------------------------------------------------------------------------
+function McpIntegration({ onToggle }: { onToggle: () => void }) {
+  const { t } = useTranslation()
+  const { integrations, setIntegration, mcpLocked } = useIntegrations()
+  const [copied, setCopied] = useState(false)
+  const endpoint = `${window.location.origin}/mcp`
+
+  return (
+    <div>
+      <div className="flex items-center gap-2">
+        <KeyRound className="h-4 w-4 text-accent" strokeWidth={1.75} />
+        <h3 className="text-sm font-semibold text-text-primary">{t('settings.mcp.title')}</h3>
+      </div>
+      <p className="mt-1 text-caption text-text-muted">{t('settings.mcp.description')}</p>
+
+      {mcpLocked ? (
+        <div className="mt-3 flex items-start gap-2 rounded-lg border border-warning/30 bg-warning/5 px-3 py-2 text-caption text-text-secondary">
+          <CircleAlert className="mt-0.5 h-4 w-4 shrink-0 text-warning" strokeWidth={1.75} />
+          <span>{t('settings.mcp.lockedHint')}</span>
+        </div>
+      ) : (
+        <div className="mt-2 divide-y divide-border/60">
+          <SwitchRow
+            label={t('settings.mcp.enabled')}
+            checked={integrations.mcp}
+            disabled={mcpLocked}
+            onCheckedChange={(v) => {
+              setIntegration('mcp', v)
+              onToggle()
+            }}
+          />
+        </div>
+      )}
+
+      <div className="mt-3">
+        <div className="text-label uppercase text-text-muted">{t('settings.mcp.endpoint')}</div>
+        <div className="mt-1 flex items-center gap-2">
+          <code className="min-w-0 flex-1 truncate rounded-lg bg-elevated px-3 py-2 text-caption text-text-primary">{endpoint}</code>
+          <button
+            type="button"
+            onClick={() => {
+              void copyToClipboard(endpoint).then(() => {
+                setCopied(true)
+                setTimeout(() => setCopied(false), 1500)
+              })
+            }}
+            aria-label={t('settings.mcp.copy')}
+            title={t('settings.mcp.copy')}
+            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+          >
+            {copied ? <Check className="h-4 w-4 text-accent" strokeWidth={1.75} /> : <Copy className="h-4 w-4" strokeWidth={1.75} />}
+          </button>
+        </div>
+        <p className="mt-1.5 flex items-start gap-1.5 text-caption text-text-muted">
+          <ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0" strokeWidth={1.75} />
+          {t('settings.mcp.endpointHint')}
+        </p>
+      </div>
+
+      <div className="mt-5 border-t border-border pt-4">
+        <div className="text-label uppercase text-text-muted">{t('settings.mcp.tokensTitle')}</div>
+        <p className="mt-1 text-caption text-text-muted">{t('settings.mcp.tokensHint')}</p>
+        <div className="mt-2">
+          <TokensManager />
+        </div>
+      </div>
+    </div>
+  )
+}
+
 function ServicesCard({
   reduce,
   onSaved,
@@ -3654,20 +3941,27 @@ function ServicesCard({
   const { t } = useTranslation()
   const [services, setService] = useServicesVisibility()
   // Toggles server-side de integraciones (#968): se leen del servidor al
-  // montar (coherencia entre navegadores) y se escriben al cambiar.
-  const { integrations, setIntegration } = useIntegrations(!disabled)
+  // montar (coherencia entre navegadores) y se escriben al cambiar. mcpLocked
+  // (#1114): sin NETPULSE_MCP_ENABLED=1 el endpoint /mcp no existe y el
+  // toggle queda bloqueado con una explicación.
+  const { integrations, setIntegration, mcpLocked } = useIntegrations(!disabled)
   const [dialog, setDialog] = useState<IntegrationDialogKey | null>(null)
   const networkRows: { key: keyof ServicesVisibility; label: string; caption: string; dialogKey?: IntegrationDialogKey }[] = [
     { key: 'adguard', label: 'AdGuard Home', caption: t('settings.services.adguardCaption'), dialogKey: 'adguard' },
     { key: 'wireguard', label: 'WireGuard', caption: t('settings.services.wireguardCaption') },
     { key: 'openvpn', label: 'OpenVPN', caption: t('settings.services.openvpnCaption') },
+    // #1146: visibilidad de la página de actualizaciones (ya no es Labs).
+    { key: 'actualizaciones', label: t('nav.firmwareUpgrades'), caption: t('settings.services.firmwareUpgradesCaption') },
   ]
   // #996: el grupo Integraciones se queda SOLO con MQTT y Proxmox (estado e
   // inventario); ntfy y Telegram son canales de aviso y viven en la tarjeta
-  // de Notificaciones.
-  const integrationRows: { key: keyof IntegrationsState; label: string; caption: string; dialogKey: IntegrationDialogKey }[] = [
+  // de Notificaciones. MCP (#1114) es LABS: fila con acento rojo (danger)
+  // visible solo con Labs activado; el endpoint no muere al ocultar Labs
+  // (misma semántica que orquestación: el opt-in persiste server-side).
+  const integrationRows: { key: keyof IntegrationsState; label: string; caption: string; dialogKey: IntegrationDialogKey; locked?: boolean; labs?: boolean; danger?: boolean }[] = [
     { key: 'proxmox', label: 'Proxmox VE', caption: t('settings.services.proxmoxCaption'), dialogKey: 'proxmox' },
     { key: 'mqtt', label: 'MQTT', caption: t('settings.services.mqttCaption'), dialogKey: 'mqtt' },
+    { key: 'mcp', label: 'MCP', caption: t('settings.services.mcpCaption'), dialogKey: 'mcp', locked: mcpLocked, labs: true, danger: true },
   ]
 
   // AdGuard (#813): el toggle de Servicios también controla el sondeo y la
@@ -3704,12 +3998,33 @@ function ServicesCard({
   )
 
   return (
-    <Card title={t('settings.services.title')} caption={t('settings.services.caption')} index={3} reduce={reduce}>
-      {/* Lista única: primero todos los servicios de red, luego todas las
-          integraciones (sin columnas). */}
+    <Card
+      title={t('settings.services.title')}
+      caption={t('settings.services.caption')}
+      index={3}
+      reduce={reduce}
+      headerSlot={
+        <div className="flex shrink-0 items-center gap-2">
+          <span className="text-label uppercase tracking-[0.06em] text-text-muted">{t('settings.labs.title')}</span>
+          <Switch
+            checked={services.labs}
+            onCheckedChange={(v) => {
+              setService('labs', v)
+              onSaved()
+            }}
+            disabled={disabled}
+            aria-label={t('settings.services.labs')}
+            className="data-[state=checked]:bg-danger"
+          />
+        </div>
+      }
+    >
+      {/* Servicios en dos columnas (Labs incluido) y debajo Integraciones,
+          también en dos columnas (#1146). Sin divide-y: en flujo de 2
+          columnas pinta líneas a mitad de fila. */}
       <div>
         <div className="pb-1 text-label uppercase text-text-muted">{t('settings.services.networkGroup')}</div>
-        <div className="divide-y divide-border/60">
+        <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
           {networkRows.map((row) => (
             <SwitchRow
               key={row.key}
@@ -3724,80 +4039,76 @@ function ServicesCard({
               }}
             />
           ))}
-          <SwitchRow
-            label={t('settings.services.labs')}
-            caption={t('settings.services.labsCaption')}
-            checked={services.labs}
-            disabled={disabled}
-            danger
-            onCheckedChange={(v) => {
-              setService('labs', v)
-              onSaved()
-            }}
-          />
         </div>
 
-        {/* Servicios de Labs (#1012): antes que las integraciones */}
-        {services.labs && (
-          <div className="mt-2 grid grid-cols-1 gap-x-6 gap-y-0 sm:grid-cols-2">
-            <div className="divide-y divide-border/60">
-              {/* Orquestación (opt-in del admin) */}
-              <SwitchRow
-                label={t('settings.admin.orchestration')}
-                caption={t('settings.services.orchestrationHint')}
-                checked={orchOn}
-                onCheckedChange={(v) => void toggleOrchestration(v)}
-                disabled={orchBusy || disabled}
-                danger
-              />
-              {/* Canales */}
-              <SwitchRow
-                label={t('settings.labs.canales')}
-                caption={t('settings.labs.canalesCaption')}
-                checked={services.canales}
-                disabled={disabled}
-                danger
-                onCheckedChange={(v) => {
-                  setService('canales', v)
-                  onSaved()
-                }}
-              />
-            </div>
-            <div className="divide-y divide-border/60">
-              {/* Actualizaciones */}
-              <SwitchRow
-                label={t('settings.labs.actualizaciones')}
-                caption={t('settings.labs.actualizacionesCaption')}
-                checked={services.actualizaciones}
-                disabled={disabled}
-                danger
-                onCheckedChange={(v) => {
-                  setService('actualizaciones', v)
-                  onSaved()
-                }}
-              />
-            </div>
-          </div>
-        )}
-
         <div className="pb-1 pt-4 text-label uppercase text-text-muted">{t('settings.services.integrationsGroup')}</div>
-        <div className="divide-y divide-border/60">
-          {integrationRows.map((row) => (
+        <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
+          {integrationRows.filter((row) => !row.labs).map((row) => (
             <SwitchRow
               key={row.key}
               label={row.label}
               caption={row.caption}
               checked={integrations[row.key]}
-              disabled={disabled}
+              disabled={disabled || row.locked}
+              danger={row.danger}
               trailing={gear(row.dialogKey, row.label)}
+              onCheckedChange={(v) => {
+                setIntegration(row.key, v)
+                onSaved()
+              }}
+            />
+          ))}
+        </div>
+      </div>
+
+      {/* Labs: subtarjeta con acento rojo (#1146) con TODAS las filas labs
+          (servicios e integraciones): orquestación, rack y MCP. Sin Labs
+          activo no se muestra nada de este bloque. */}
+      {services.labs && (
+        <div className="mt-4 rounded-xl border border-danger/30 bg-danger/5 p-4">
+          <div className="mb-1 flex items-center gap-1.5">
+            <TriangleAlert className="h-3.5 w-3.5 text-danger" aria-hidden />
+            <span className="text-label uppercase tracking-[0.06em] text-danger">{t('settings.labs.title')}</span>
+          </div>
+          <p className="mb-2 text-caption text-text-muted">{t('settings.services.labsCaption')}</p>
+          <div className="grid grid-cols-1 gap-x-6 sm:grid-cols-2">
+            <SwitchRow
+              label={t('settings.admin.orchestration')}
+              caption={t('settings.services.orchestrationHint')}
+              checked={orchOn}
+              onCheckedChange={(v) => void toggleOrchestration(v)}
+              disabled={orchBusy || disabled}
+              danger
+            />
+            <SwitchRow
+              label={t('settings.labs.rack')}
+              caption={t('settings.labs.rackCaption')}
+              checked={services.rack}
+              disabled={disabled}
+              danger
+              onCheckedChange={(v) => {
+                setService('rack', v)
+                onSaved()
+              }}
+            />
+            {integrationRows.filter((row) => row.labs).map((row) => (
+              <SwitchRow
+                key={row.key}
+                label={row.label}
+                caption={row.caption}
+                checked={integrations[row.key]}
+                disabled={disabled || row.locked}
+                danger={row.danger}
+                trailing={gear(row.dialogKey, row.label)}
                 onCheckedChange={(v) => {
                   setIntegration(row.key, v)
                   onSaved()
                 }}
               />
             ))}
+          </div>
         </div>
-      </div>
+      )}
 
       {/* Diálogos de configuración de integraciones (#968): los managers
           viven SOLO en diálogo (#977: las cards sueltas ya no están en el
@@ -3807,7 +4118,7 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.adguard.title')}</DialogTitle>
           </DialogHeader>
-          <AdGuardManager reduce={reduce} onSaved={onSaved} />
+          <AdGuardManager reduce={reduce} onSaved={() => { onSaved(); setDialog(null) }} />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'proxmox'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -3815,7 +4126,7 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.proxmox.title')}</DialogTitle>
           </DialogHeader>
-          <ProxmoxManager reduce={reduce} onSaved={onSaved} />
+          <ProxmoxManager reduce={reduce} onSaved={() => { onSaved(); setDialog(null) }} />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'mqtt'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -3823,7 +4134,15 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.mqtt.title')}</DialogTitle>
           </DialogHeader>
-          <MqttCard onSaved={onSaved} bare />
+          <MqttCard onSaved={() => { onSaved(); setDialog(null) }} bare />
+        </DialogContent>
+      </Dialog>
+      <Dialog open={dialog === 'mcp'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
+        <DialogContent className={integrationDialogCls} aria-describedby={undefined}>
+          <DialogHeader>
+            <DialogTitle className="sr-only">{t('settings.mcp.title')}</DialogTitle>
+          </DialogHeader>
+          <McpIntegration onToggle={() => onSaved()} />
         </DialogContent>
       </Dialog>
     </Card>
@@ -3865,42 +4184,40 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
     { key: 'telegram', label: 'Telegram', caption: t('settings.notif.telegramCaption') },
   ]
   return (
-    <div className="mt-4 border-t border-border pt-4">
-      <div className="divide-y divide-border/60">
-        {rows.map((row) => (
-          <SwitchRow
-            key={row.key}
-            label={row.label}
-            caption={row.caption}
-            checked={integrations[row.key]}
-            disabled={disabled}
-            trailing={
-              <span className="flex items-center gap-2.5">
-                {integrations[row.key] && configured && !configured[row.key] && (
-                  <button
-                    type="button"
-                    onClick={() => setDialog(row.key)}
-                    className="rounded-full bg-warn/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-warn transition-colors hover:bg-warn/20"
-                  >
-                    {t('settings.notif.notConfigured')}
-                  </button>
-                )}
-                <ConfigGear label={t('settings.services.configure', { name: row.label })} onClick={() => setDialog(row.key)} />
-              </span>
-            }
+    <div className="mt-4 grid grid-cols-1 gap-x-6 border-t border-border pt-4 sm:grid-cols-2">
+      {rows.map((row) => (
+        <SwitchRow
+          key={row.key}
+          label={row.label}
+          caption={row.caption}
+          checked={integrations[row.key]}
+          disabled={disabled}
+          trailing={
+            <span className="flex items-center gap-2.5">
+              {integrations[row.key] && configured && !configured[row.key] && (
+                <button
+                  type="button"
+                  onClick={() => setDialog(row.key)}
+                  className="rounded-full bg-warn/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-warn transition-colors hover:bg-warn/20"
+                >
+                  {t('settings.notif.notConfigured')}
+                </button>
+              )}
+              <ConfigGear label={t('settings.services.configure', { name: row.label })} onClick={() => setDialog(row.key)} />
+            </span>
+          }
             onCheckedChange={(v) => {
               setIntegration(row.key, v)
               onSaved()
             }}
           />
         ))}
-      </div>
       <Dialog open={dialog === 'ntfy'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
         <DialogContent className={integrationDialogCls} aria-describedby={undefined}>
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.ntfy.title')}</DialogTitle>
           </DialogHeader>
-          <NtfyCard onSaved={onSaved} bare />
+          <NtfyCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'telegram'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -3908,7 +4225,7 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.telegram.title')}</DialogTitle>
           </DialogHeader>
-          <TelegramCard onSaved={onSaved} bare />
+          <TelegramCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
     </div>
@@ -5371,6 +5688,7 @@ export default function Settings() {
                 {/* Limitar historial (#975): toggle maestro + diálogo con
                     retención de presencia (#771) e ingesta de itinerancia (#907) */}
                 <LimitHistoryRow onSaved={notify} />
+                <AlertRetentionRow onSaved={notify} />
               </div>
 
               {/* Sliders de umbrales */}
@@ -5669,30 +5987,25 @@ export default function Settings() {
                 de la sección. */}
             <NotifChannels onSaved={notify} disabled={isDemo} />
 
-            {/* Notificaciones push DENTRO de la misma card (#977): el texto
-                largo vive en el (i) del título de la subsección. */}
-            <div className="mt-4 border-t border-border pt-4">
-              <div className="mb-2 flex items-center gap-1.5">
-                <span className="text-sm font-medium text-text-primary">{t('settings.push.title')}</span>
-                <InfoTip text={t('settings.push.note')} />
+            {/* Push + idioma en una fila de dos columnas (#1146) */}
+            <div className="mt-4 grid grid-cols-1 gap-x-6 gap-y-4 border-t border-border pt-4 sm:grid-cols-2">
+              <div className="flex flex-col">
+                <div className="mb-2 flex items-center gap-1.5">
+                  <span className="text-sm font-medium text-text-primary">{t('settings.push.title')}</span>
+                  <InfoTip text={t('settings.push.note')} />
+                </div>
+                <PushNotificationsCard onSaved={notify} />
               </div>
-              <PushNotificationsCard onSaved={notify} />
-            </div>
-
-            {/* Idioma de las notificaciones (#889): movido a esta card
-                (#977). #998: una sola fila (título + (i) + select), sin el
-                label duplicado que decía lo mismo. */}
-            {!isDemo && (
-              <div className="mt-4 border-t border-border pt-4">
-                <div className="flex items-center justify-between gap-3">
+              {!isDemo && (
+                <div className="flex items-start justify-between gap-3">
                   <div className="flex items-center gap-1.5">
                     <span className="text-sm font-medium text-text-primary">{t('settings.alertsLang.title')}</span>
                     <InfoTip text={t('settings.alertsLang.description')} />
                   </div>
                   <AlertsLangControl onSaved={notify} />
                 </div>
-              </div>
-            )}
+              )}
+            </div>
           </Card>
         </div>
 

+ 6 - 59
app/src/sections/WanTraffic.tsx

@@ -1,17 +1,15 @@
 import { useEffect, useMemo, useState } from 'react'
 import { Area, AreaChart, CartesianGrid, ReferenceLine, ResponsiveContainer, Tooltip, XAxis } from 'recharts'
 import { motion } from 'framer-motion'
-import { Activity } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import type { TimeRange, TrafficPoint } from '@/data/mock'
 import { fmtBytes, fmtEs } from '@/data/mock'
-import { relTimeFromTs } from '@/i18n'
 import { useNetPulse } from '@/data/DataProvider'
 import { InfoTip } from '@/components/InfoTip'
 import { SectionHeader } from '@/components/SectionHeader'
 import { SegmentedControl, TIME_RANGE_OPTIONS } from '@/components/SegmentedControl'
 import { StatusPill } from '@/components/StatusPill'
-import { SpeedtestHistoryChart, useSpeedtestHistory } from '@/components/routers/WanLatency'
+import { SpeedtestStrip } from '@/components/routers/WanLatency'
 
 // ---------------------------------------------------------------------------
 // Tooltip custom (design.md §7): superficie elevated, valores mono con unidad
@@ -54,60 +52,6 @@ function makeLiveDot(dataLength: number, color: string) {
   }
 }
 
-/** Velocidad medida (#982): último test real (% del plan, bajada/subida,
- *  ping, antigüedad y servidor) + evolución del histórico (7 días). SIN
- *  botón de ejecutar test (ese vive en Ajustes y en el detalle del gateway).
- *  Vive dentro de Tráfico WAN porque mide la capacidad real de la misma WAN
- *  y así no se añade otra fila al overview. Oculta si no hay histórico. */
-function SpeedtestHistoryBlock({ contractDown }: { contractDown?: number }) {
-  const { t } = useTranslation()
-  const { points, last } = useSpeedtestHistory(168)
-  if (points.length <= 1) return null
-  // El API serializa ts como ISO 8601; relTimeFromTs espera unix SEGUNDOS.
-  const when = last ? (relTimeFromTs(Math.floor(new Date(last.ts).getTime() / 1000)) ?? '') : ''
-  const planPct =
-    contractDown && contractDown > 0 && last ? Math.round((last.downMbps / contractDown) * 100) : null
-  return (
-    <div className="mt-4 border-t border-border pt-4">
-      <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
-        <div className="flex items-center gap-1.5">
-          <Activity className="h-3.5 w-3.5 text-accent" aria-hidden />
-          <span className="text-label uppercase text-text-muted">{t('routerDetail.wan.speedtestTitle')}</span>
-          {planPct !== null && (
-            <span
-              className={`ml-1 rounded-full border px-2 py-0.5 font-mono text-[11px] ${
-                planPct >= 80
-                  ? 'border-ok/40 bg-ok/10 text-ok'
-                  : planPct >= 50
-                    ? 'border-warn/40 bg-warn/10 text-warn'
-                    : 'border-danger/40 bg-danger/10 text-danger'
-              }`}
-            >
-              {t('routerDetail.wan.planPct', { pct: planPct })}
-            </span>
-          )}
-        </div>
-        {last && (
-          <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 font-mono text-mono-sm text-text-primary">
-            <span>
-              <span className="text-accent">↓</span> {fmtEs(last.downMbps, 0)} Mbps
-            </span>
-            <span>
-              <span className="text-tunnel">↑</span> {fmtEs(last.upMbps, 0)} Mbps
-            </span>
-            {last.pingMs !== undefined && <span className="text-text-muted">{fmtEs(last.pingMs, 0)} ms</span>}
-            {when && <span className="text-text-muted">· {when}</span>}
-            {last.serverName && (
-              <span className="text-text-muted">· {t('routerDetail.wan.speedtestServer', { name: last.serverName })}</span>
-            )}
-          </div>
-        )}
-      </div>
-      <SpeedtestHistoryChart points={points} height={96} />
-    </div>
-  )
-}
-
 /** ② Tráfico WAN — área doble serie (home.md §②) */
 export function WanTraffic() {
   const { t } = useTranslation()
@@ -286,8 +230,11 @@ export function WanTraffic() {
         ))}
       </div>
 
-      {/* Velocidad medida (#982): gráfica del histórico de speedtests */}
-      <SpeedtestHistoryBlock contractDown={wan.contractDownMbps} />
+      {/* Velocidad medida (#511, #744): strip completo en el overview, bajo
+          las métricas peak/avg/total/loss. Quitado por estética en la dieta
+          de UI del 1-Oct y restaurado con el botón adhoc «Ejecutar test» y
+          el desplegable de tests recientes (#1092, crowedavid). */}
+      <SpeedtestStrip contractDown={wan.contractDownMbps} />
     </section>
   )
 }

+ 1 - 0
app/vite.config.ts

@@ -54,6 +54,7 @@ export default defineConfig({
         ],
       },
       injectManifest: {
+      maximumFileSizeToCacheInBytes: 3.5 * 1024 * 1024,
         // App-shell precache (mismo glob que con generateSW: 16 entradas);
         // el fallback de navegación vive ahora en src/sw.ts (NavigationRoute)
         globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],

+ 38 - 0
server-go/cmd/netpulse/main.go

@@ -45,6 +45,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
 	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/mcp"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/ntfy"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
@@ -278,6 +279,9 @@ func run() error {
 		}
 	}
 	agentReg := adapters.NewAgentRegistry(agentTTL)
+	// #1082: los agentes conocen sus propios BSSIDs (dawn/usteer local);
+	// el channel-plan los usa para no contar las propias como vecinas.
+	chPlan.SetOwnSeeds(agentReg.LocalBssids)
 	var adapter adapters.Snapshotter
 	var sshPool *adapters.SSHPool
 	var eventsCollector *roamevents.Collector
@@ -663,6 +667,10 @@ func run() error {
 	// conservar siempre). Sin esto ambas tablas crecen sin límite. El
 	// interruptor maestro history.limit_enabled (#975) desactiva la poda
 	// por completo (retención ilimitada).
+	// El mismo tick horario poda alert_log por antigüedad (#1034) según
+	// alerts.retentionDays (kv; 0 = poda temporal off, la cota de 500 filas
+	// sigue aplicando). Es independiente del interruptor maestro #975: el
+	// log de alertas tiene su propio ajuste.
 	presenceStop := make(chan struct{})
 	if !cfg.DemoMode {
 		go func() {
@@ -683,11 +691,21 @@ func run() error {
 					log.Printf("[netpulse] poda de presencia: %d eventos (> %d días)", n, retention)
 				}
 			}
+			pruneAlerts := func() {
+				if adapter == nil {
+					return
+				}
+				if n := adapter.AlertsEngine().PruneLogByRetention(); n > 0 {
+					log.Printf("[netpulse] poda del log de alertas: %d entradas por antigüedad", n)
+				}
+			}
 			prune() // primera pasada al arrancar
+			pruneAlerts()
 			for {
 				select {
 				case <-tick.C:
 					prune()
+					pruneAlerts()
 				case <-presenceStop:
 					return
 				}
@@ -697,6 +715,25 @@ func run() error {
 
 	mqttMgr := mqttpub.NewManager(mqttpub.LoadConfig(mqttpub.SQLKV{DB: dbHandle.DB}), httpapi.Version, p.LastOverview, cfg.DemoMode)
 
+	// MCP (#1114): servidor MCP embebido (streamable-HTTP en /mcp), solo si
+	// NETPULSE_MCP_ENABLED=1. Sin token store NO se monta: el endpoint solo
+	// existe con su auth Bearer (fail-closed, también en mcp.Handler).
+	var mcpSrv *mcp.Server
+	if cfg.MCPEnabled && tokenStore != nil {
+		var engine *alerts.Engine
+		if adapter != nil {
+			engine = adapter.AlertsEngine()
+		}
+		mcpSrv = mcp.New(mcp.Deps{
+			LastOverview: p.LastOverview,
+			Engine:       engine,
+			Version:      httpapi.Version,
+		})
+		log.Printf("[netpulse] MCP server activo en /mcp (streamable-HTTP, auth: API token Bearer, LAN-only)")
+	} else if cfg.MCPEnabled {
+		log.Printf("[netpulse] aviso: NETPULSE_MCP_ENABLED=1 pero no hay token store; MCP desactivado")
+	}
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:          cfg,
 		DB:              dbHandle,
@@ -723,6 +760,7 @@ func run() error {
 		Speedtest:       stScheduler,
 		AlertEmitter:    adapter.AlertsEngine(),
 		ChannelPlan:     chPlan,
+		MCP:             mcpSrv,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},

+ 13 - 1
server-go/go.mod

@@ -5,8 +5,10 @@ go 1.26
 require (
 	github.com/SherClockHolmes/webpush-go v1.4.0
 	github.com/gnacho/netpulse/agent v0.0.0
-	github.com/gonzalop/mq v0.9.10
+	github.com/gonzalop/mq v0.9.11
 	github.com/gosnmp/gosnmp v1.44.0
+	github.com/m-lab/ndt7-client-go v0.10.1
+	github.com/mark3labs/mcp-go v1.1.1
 	github.com/showwin/speedtest-go v1.8.3
 	golang.org/x/crypto v0.55.0
 	golang.org/x/net v0.58.0
@@ -19,12 +21,22 @@ require (
 replace github.com/gnacho/netpulse/agent => ../agent
 
 require (
+	github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de // indirect
 	github.com/dustin/go-humanize v1.0.1 // indirect
 	github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
+	github.com/google/jsonschema-go v0.4.2 // indirect
 	github.com/google/uuid v1.6.0 // indirect
+	github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
+	github.com/m-lab/go v0.1.76 // indirect
+	github.com/m-lab/locate v0.19.0 // indirect
+	github.com/m-lab/ndt-server v0.25.0 // indirect
+	github.com/m-lab/tcp-info v1.9.0 // indirect
 	github.com/mattn/go-isatty v0.0.24 // indirect
 	github.com/ncruces/go-strftime v1.0.0 // indirect
 	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+	github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
+	github.com/spf13/cast v1.7.1 // indirect
+	github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
 	golang.org/x/sys v0.47.0 // indirect
 	modernc.org/libc v1.74.4 // indirect
 	modernc.org/mathutil v1.7.1 // indirect

+ 193 - 4
server-go/go.sum

@@ -1,36 +1,203 @@
+cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
+cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
+cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
+cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
+cloud.google.com/go/auth v0.18.0 h1:wnqy5hrv7p3k7cShwAU/Br3nzod7fxoqG+k0VZ+/Pk0=
+cloud.google.com/go/auth v0.18.0/go.mod h1:wwkPM1AgE1f2u6dG443MiWoD8C3BtOywNsUMcUTVDRo=
+cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
+cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
+cloud.google.com/go/compute v1.53.0 h1:dILGanjePNsYfZVYYv6K0d4+IPnKX1gn84Fk8jDPNvs=
+cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
+cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
+cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc=
+cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU=
+cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE=
+cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI=
+cloud.google.com/go/storage v1.59.1 h1:DXAZLcTimtiXdGqDSnebROVPd9QvRsFVVlptz02Wk58=
+cloud.google.com/go/storage v1.59.1/go.mod h1:cMWbtM+anpC74gn6qjLh+exqYcfmB9Hqe5z6adx+CLI=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 h1:sBEjpZlNHzK1voKq9695PJSX2o5NEXl7/OL3coiIY0c=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.54.0 h1:lhhYARPUu3LmHysQ/igznQphfzynnqI3D75oUyw1HXk=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.54.0/go.mod h1:l9rva3ApbBpEJxSNYnwT9N4CDLrWgtq3u8736C5hyJw=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.54.0 h1:s0WlVbf9qpvkh1c/uDAPElam0WrL7fHRIidgZJ7UqZI=
+github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.54.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=
 github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s=
 github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/apex/log v1.9.0 h1:FHtw/xuaM8AgmvDDTI9fiwoAL25Sq2cxojnZICUU8l0=
+github.com/apex/log v1.9.0/go.mod h1:m82fZlWIuiWzWP04XCTXmnX0xRkYYbCdYn8jbJeLBEA=
+github.com/aptible/supercronic v0.2.41 h1:BkAZ0fJ+nd8P9M+yA4/YUM2DJi1txDQZBj7YlfIv9co=
+github.com/aptible/supercronic v0.2.41/go.mod h1:eCxg17hDIYvX98QoWMd0vaN+IlSuJkj+8vEmJWdbxS8=
+github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA=
+github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw=
+github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
+github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
+github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
+github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
 github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
 github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
+github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=
+github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
+github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
+github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
+github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
+github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
+github.com/gocarina/gocsv v0.0.0-20210408192840-02d7211d929d h1:r3mStZSyjKhEcgbJ5xtv7kT5PZw/tDiFBTMgQx2qsXE=
+github.com/gocarina/gocsv v0.0.0-20210408192840-02d7211d929d/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
 github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
 github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
 github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
-github.com/gonzalop/mq v0.9.10 h1:7uaSKq/m/n0ElV3SJtXQTZnI5HyHtgoNIL/ufsxFU+8=
-github.com/gonzalop/mq v0.9.10/go.mod h1:chaGtxnueekistsTKhDnLOoNdJPKEI6vadlUBRQS2ok=
+github.com/gomodule/redigo v1.9.3 h1:dNPSXeXv6HCq2jdyWfjgmhBdqnR6PRO3m/G05nvpPC8=
+github.com/gomodule/redigo v1.9.3/go.mod h1:KsU3hiK/Ay8U42qpaJk+kuNa3C+spxapWpM+ywhcgtw=
+github.com/gonzalop/mq v0.9.11 h1:cKdoCT3dgiz3kV53QKUDqtcdDHCpMHS8nXrxVhqt3gE=
+github.com/gonzalop/mq v0.9.11/go.mod h1:QVPtaf408IuhzPJO4w2Q0sjzM+nP6FWHyfyXUjvY/PQ=
 github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
+github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
 github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
+github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
+github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
 github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/googleapis/enterprise-certificate-proxy v0.3.11 h1:vAe81Msw+8tKUxi2Dqh/NZMz7475yUvmRIkXr4oN2ao=
+github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
+github.com/googleapis/gax-go/v2 v2.16.0 h1:iHbQmKLLZrexmb0OSsNGTeSTS0HO4YvFOG8g5E4Zd0Y=
+github.com/googleapis/gax-go/v2 v2.16.0/go.mod h1:o1vfQjjNZn4+dPnRdl/4ZD7S9414Y4xA+a/6Icj6l14=
+github.com/googleapis/google-cloud-go-testing v0.0.0-20210719221736-1c9a4c676720 h1:zC34cGQu69FG7qzJ3WiKW244WfhDC3xxYMeNOX2gtUQ=
+github.com/googleapis/google-cloud-go-testing v0.0.0-20210719221736-1c9a4c676720/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
+github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
+github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
+github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=
+github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
 github.com/gosnmp/gosnmp v1.44.0 h1:6SUNAJWjSu/j05rm+M1G39NoPW8jvShiFqYf6XNnM+k=
 github.com/gosnmp/gosnmp v1.44.0/go.mod h1:30xQDXCVXXehh/xwRd62+JwIizwc3HZaBi4F/Hv5/0o=
+github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
+github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
+github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
+github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
 github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
 github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
+github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
+github.com/justinas/alice v1.2.0 h1:+MHSA/vccVCF4Uq37S42jwlkvI2Xzl7zTPCN5BnZNVo=
+github.com/justinas/alice v1.2.0/go.mod h1:fN5HRH/reO/zrUflLfTN43t3vXvKzvZIENsNEe7i7qA=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/m-lab/access v0.0.13 h1:ZCtOEZp2qmcp0CFUBP21r42miNqqWu7gQVa8GxzASts=
+github.com/m-lab/access v0.0.13/go.mod h1:V3hWcsesp1kDgIRQOUXRU8uDTfUhYv/D0SJ4g3WOUS8=
+github.com/m-lab/go v0.1.76 h1:zdxI5k0AIZaf99Cyh7zjNyNBBZxTlhIJvWg7AX710bU=
+github.com/m-lab/go v0.1.76/go.mod h1:BirARfHWjjXHaCGNyWCm/CKW1OarjuEj8Yn6Z2rc0M4=
+github.com/m-lab/locate v0.19.0 h1:Ar2E537yUIcfGjK8XUQ0+L2GUYltrv6IhNNR6HkKJEQ=
+github.com/m-lab/locate v0.19.0/go.mod h1:hto2NaSThvaFrsi34k2g554z+wS3Q1QYM+YYo+ZnDv4=
+github.com/m-lab/ndt-server v0.25.0 h1:hhF7ezVInKUzZFlCmsQt763t5dF77Oqmdy8lSSY6JdI=
+github.com/m-lab/ndt-server v0.25.0/go.mod h1:KJJpSLcrRvLHsOJlBb/o4CCy+iYW/ddIrPQhivyelrY=
+github.com/m-lab/ndt7-client-go v0.10.1 h1:+BCtqsmONk8Sw1dvhOrCAUa5oBOrNobA1AB8FbPAejA=
+github.com/m-lab/ndt7-client-go v0.10.1/go.mod h1:UJ8E4LqWZmwwwrxMzsELZ7ojU6VK7gCluPMp7cUrfkA=
+github.com/m-lab/tcp-info v1.9.0 h1:kBpnOFzO7/InGekbtAp9HXsJCw7qHZ1bxhUnC7/n4fs=
+github.com/m-lab/tcp-info v1.9.0/go.mod h1:tNw76DkILOd0aFVg2kG3b+W+6aVdpNXg9HcYX45x/qE=
+github.com/m-lab/uuid v1.0.2 h1:rlkqHQ0fXnj4VtqWElJkc3KgCvOYf3SSZgRRxbycHN8=
+github.com/m-lab/uuid v1.0.2/go.mod h1:SAjW6jto9p0Ms5ZCaTCVe2GTu1pvctlr6W/TEMQ1/vg=
+github.com/m-lab/uuid-annotator v0.5.10 h1:ZojVfeiFDdhtN/GqqxxRtBPVxSY4Focf6YRr7Om9XgM=
+github.com/m-lab/uuid-annotator v0.5.10/go.mod h1:djp2929KpTtHEJMVubnjniks5sEMVtyvDaBKR+8QVqQ=
+github.com/mark3labs/mcp-go v1.1.1 h1:PMZjyayCF01Y4R2kQXgDtsmxVLOdq1Mol4CnzzTYSEo=
+github.com/mark3labs/mcp-go v1.1.1/go.mod h1:r2fW4o3wsoJ7IMsx1Wuq5xeP8PRGXPDfNveoGAYbb/s=
 github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
 github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
+github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
+github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=
+github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
+github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
 github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
 github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/oschwald/geoip2-golang v1.13.0 h1:Q44/Ldc703pasJeP5V9+aFSZFmBN7DKHbNsSFzQATJI=
+github.com/oschwald/geoip2-golang v1.13.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo=
+github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE=
+github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
+github.com/paulmach/orb v0.12.0 h1:z+zOwjmG3MyEEqzv92UN49Lg1JFYx0L9GpGKNVDKk1s=
+github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=
+github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
+github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
+github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
 github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
+github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
+github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
+github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
+github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
+github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
+github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
+github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
+github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
+github.com/scylladb/termtables v0.0.0-20191203121021-c4c0b6d42ff4/go.mod h1:C1a7PQSMz9NShzorzCiG2fk9+xuCgLkPeCvMHYR2OWg=
 github.com/showwin/speedtest-go v1.8.3 h1:x988hyZFsa5V1EEwox84niAji632uxBTk8Clsc1itF8=
 github.com/showwin/speedtest-go v1.8.3/go.mod h1:N4bn2lgNNWmfJyC1AIHD4T5wYhU+9D21OfacVhJsxiU=
+github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
+github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g=
+github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
+github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
+github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
+github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
 github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
+go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
+go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0 h1:RN3ifU8y4prNWeEnQp2kRRHz8UwonAEYZl8tUzHEXAk=
+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.64.0/go.mod h1:habDz3tEWiFANTo6oUE99EmaFUrCNYAAg3wiVmusm70=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0 h1:ssfIgGNANqpVFCndZvcuyKbl0g+UAVcbBcqGkG28H0Y=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.64.0/go.mod h1:GQ/474YrbE4Jx8gZ4q5I4hrhUzM6UPzyrqJYV2AqPoQ=
+go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
+go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
+go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=
+go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=
+go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=
+go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=
+go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
+go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
+go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=
+go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=
+go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
+go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
@@ -39,6 +206,8 @@ golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v
 golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
 golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
 golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
+golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU=
+golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU=
 golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
 golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
 golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
@@ -56,6 +225,8 @@ golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
 golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
 golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
 golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
+golang.org/x/oauth2 v0.34.0 h1:hqK/t4AKgbqWkdkcAeI8XLmbK+4m4G5YeQRrmiotGlw=
+golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
 golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
 golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -100,6 +271,8 @@ golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
 golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
 golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
 golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
+golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
 golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
 golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
 golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
@@ -109,6 +282,22 @@ golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxb
 golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
 golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
 golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/api v0.260.0 h1:XbNi5E6bOVEj/uLXQRlt6TKuEzMD7zvW/6tNwltE4P4=
+google.golang.org/api v0.260.0/go.mod h1:Shj1j0Phr/9sloYrKomICzdYgsSDImpTxME8rGLaZ/o=
+google.golang.org/genproto v0.0.0-20260114163908-3f89685c29c3 h1:rUamZFBwsWVWg4Yb7iTbwYp81XVHUvOXNdrFCoYRRNE=
+google.golang.org/genproto v0.0.0-20260114163908-3f89685c29c3/go.mod h1:wE6SUYr3iNtF/D0GxVAjT+0CbDFktQNssYs9PVptCt4=
+google.golang.org/genproto/googleapis/api v0.0.0-20260114163908-3f89685c29c3 h1:X9z6obt+cWRX8XjDVOn+SZWhWe5kZHm46TThU9j+jss=
+google.golang.org/genproto/googleapis/api v0.0.0-20260114163908-3f89685c29c3/go.mod h1:dd646eSK+Dk9kxVBl1nChEOhJPtMXriCcVb4x3o6J+E=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3 h1:C4WAdL+FbjnGlpp2S+HMVhBeCq2Lcib4xZqfPNF6OoQ=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260114163908-3f89685c29c3/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
+google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
+google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
+gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
+gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=

+ 54 - 0
server-go/internal/adapters/adapters_test.go

@@ -594,6 +594,60 @@ func TestDemoRouterLldpCanon(t *testing.T) {
 
 // --- Regresión single-flight GetOverview ---
 
+// TestDisabledUnitPaused (#1085): una unidad pausada no se sondea (sin
+// fallos, sin alerta de offline) y aparece en el overview con status
+// "paused" + Disabled. La unidad activa sin cliente, en cambio, acumula
+// fallo y alerta (control de que el sondeo sigue vivo para el resto).
+func TestDisabledUnitPaused(t *testing.T) {
+	eng := alerts.New(nil, nil)
+	l := &Live{
+		cfg:           &config.Config{},
+		engine:        eng,
+		routers:       []RouterConfig{{ID: "pausado", Host: "192.0.2.10", Type: "openwrt", Disabled: true}, {ID: "activo", Host: "192.0.2.20", Type: "openwrt"}},
+		lastGood:      map[string]*Router{},
+		lastStatus:    map[string]string{},
+		boardCache:    map[string]*BoardInfo{},
+		layoutCache:   map[string][]PortLayout{},
+		extrasCache:   map[string]*extrasSnapshot{},
+		lastPolled:    map[string]*routerPolled{},
+		failCount:     map[string]int{},
+		lastErr:       map[string]error{},
+		offlineOpen:   map[string]bool{},
+		wanDown:       map[string]int{},
+		onlineMacs:    map[string]bool{},
+		weakAlerted:   map[string]int64{},
+		backhaulCache: map[string]backhaulCacheEntry{},
+		lldpCache:     map[string]lldpCacheEntry{},
+	}
+
+	ov, err := l.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	byID := map[string]Router{}
+	for _, r := range ov.Routers {
+		byID[r.ID] = r
+	}
+	paused, ok := byID["pausado"]
+	if !ok {
+		t.Fatal("la unidad pausada no aparece en el overview")
+	}
+	if paused.Status != "paused" || !paused.Disabled {
+		t.Fatalf("status/disabled = %q/%v, esperaba paused/true", paused.Status, paused.Disabled)
+	}
+	if l.failCount["pausado"] != 0 {
+		t.Fatalf("la unidad pausada se sondeó (failCount %d)", l.failCount["pausado"])
+	}
+	for _, ev := range eng.List() {
+		if ev.RouterID == "pausado" {
+			t.Fatalf("alerta inesperada para la unidad pausada: %+v", ev)
+		}
+	}
+	if l.failCount["activo"] == 0 {
+		t.Fatal("la unidad activa debería haberse sondeado (y fallado sin cliente)")
+	}
+}
+
 func TestLiveGetOverviewConcurrent(t *testing.T) {
 	cfg := &config.Config{}
 	eng := alerts.New(nil, nil)

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

@@ -151,6 +151,56 @@ func (r *AgentRegistry) ExternalDownConfirm(slug string, base time.Duration) tim
 	return base
 }
 
+// LocalBssids devuelve los BSSID que los agentes reportan como propios
+// (AP local=true en sus datos dawn/usteer). El channel-plan los usa de
+// semilla exacta para la detección de redes propias (#1082): casos como el
+// guest de un GL.iNet, cuya MAC no comparte prefijo con routers.mac.
+func (r *AgentRegistry) LocalBssids() []string {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	seen := map[string]bool{}
+	var out []string
+	add := func(mac string) {
+		mac = strings.ToUpper(strings.TrimSpace(mac))
+		if mac == "" || seen[mac] {
+			return
+		}
+		seen[mac] = true
+		out = append(out, mac)
+	}
+	for _, st := range r.states {
+		if st.Payload == nil {
+			continue
+		}
+		// BSSIDs propios reportados por el agente (#1087): exactos, cubren
+		// MACs aleatorizadas y guests fuera de dawn/usteer.
+		if w := st.Payload.Data.Wireless; w != nil {
+			for _, ob := range w.OwnBssids {
+				add(ob.BSSID)
+			}
+		}
+		if st.Payload.Data.Dawn != nil {
+			for _, ssid := range st.Payload.Data.Dawn.SSIDs {
+				for _, ap := range ssid.APs {
+					if ap.Local {
+						add(ap.BSSID)
+					}
+				}
+			}
+		}
+		if st.Payload.Data.Usteer != nil {
+			for _, ssid := range st.Payload.Data.Usteer.SSIDs {
+				for _, ap := range ssid.APs {
+					if ap.Local {
+						add(ap.BSSID)
+					}
+				}
+			}
+		}
+	}
+	return out
+}
+
 // Fresh devuelve el último payload si está dentro de su ventana de
 // frescura (TTL base o 3x cadencia declarada, #288).
 func (r *AgentRegistry) Fresh(slug string) (*probe.Payload, bool) {

+ 1 - 1
server-go/internal/adapters/demo.go

@@ -225,7 +225,7 @@ func (d *Demo) buildOverview() *Overview {
 		Alerts:            d.alertsCopy(),
 		UnreadAlerts:      d.engine.UnreadCount(),
 		DistributionNodes: dists,
-		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists, ""), // SPEC-65 D65-3
+		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists, "", nil), // SPEC-65 D65-3
 		VM:                ViewModelVersion,                                    // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}

+ 97 - 13
server-go/internal/adapters/device_seen.go

@@ -14,11 +14,14 @@ import (
 // quedan ausentes, como hasta ahora.
 
 func normSeenMAC(mac string) string {
-	return strings.ToUpper(strings.TrimSpace(mac))
+	return strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(mac), "-", ":"))
 }
 
 // noteDevicesSeen upsert de las MACs online en device_seen (#954): alta con
 // first_seen=last_seen=now; las ya conocidas solo actualizan last_seen.
+// #1145: guarda también el último nombre conocido (hostname de lease o nombre
+// visible) para que un cliente que deje de verse conserve su nombre en la
+// lista (el nombre nuevo pisa al viejo solo si no es vacío).
 func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) {
 	if l.db == nil {
 		return
@@ -28,8 +31,10 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) {
 		return
 	}
 	defer tx.Rollback() //nolint:errcheck // no-op tras Commit
-	stmt, err := tx.Prepare(`INSERT INTO device_seen (mac, first_seen, last_seen) VALUES (?, ?, ?)
-		ON CONFLICT(mac) DO UPDATE SET last_seen = excluded.last_seen`)
+	stmt, err := tx.Prepare(`INSERT INTO device_seen (mac, first_seen, last_seen, name, ip) VALUES (?, ?, ?, ?, ?)
+		ON CONFLICT(mac) DO UPDATE SET last_seen = excluded.last_seen,
+			name = CASE WHEN excluded.name != '' THEN excluded.name ELSE device_seen.name END,
+			ip = CASE WHEN excluded.ip != '' THEN excluded.ip ELSE device_seen.ip END`)
 	if err != nil {
 		return
 	}
@@ -42,7 +47,11 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) {
 		if mac == "" {
 			continue
 		}
-		if _, err := stmt.Exec(mac, nowMs, nowMs); err != nil {
+		name := d.Hostname
+		if name == "" && d.Name != "" && !strings.EqualFold(d.Name, d.MAC) {
+			name = d.Name
+		}
+		if _, err := stmt.Exec(mac, nowMs, nowMs, name, d.IP); err != nil {
 			return
 		}
 	}
@@ -56,25 +65,100 @@ func (l *Live) applyDeviceSeen(devices []Device) {
 	if l.db == nil || len(devices) == 0 {
 		return
 	}
-	rows, err := l.db.DB.Query(`SELECT mac, first_seen, last_seen FROM device_seen`)
+	byMac, err := l.seenByMac()
 	if err != nil {
 		return
 	}
+	for i := range devices {
+		if s, ok := byMac[normSeenMAC(devices[i].MAC)]; ok {
+			devices[i].FirstSeenMs = s.first
+			devices[i].LastSeenMs = s.last
+		}
+	}
+}
+
+type seenRow struct {
+	first, last int64
+	name, ip    string
+}
+
+// seenByMac carga la tabla device_seen completa (una query, sin N+1).
+func (l *Live) seenByMac() (map[string]seenRow, error) {
+	rows, err := l.db.DB.Query(`SELECT mac, first_seen, last_seen, COALESCE(name, ''), COALESCE(ip, '') FROM device_seen`)
+	if err != nil {
+		return nil, err
+	}
 	defer rows.Close()
-	type seen struct{ first, last int64 }
-	byMac := map[string]seen{}
+	byMac := map[string]seenRow{}
 	for rows.Next() {
 		var mac string
-		var s seen
-		if err := rows.Scan(&mac, &s.first, &s.last); err != nil {
-			return
+		var s seenRow
+		if err := rows.Scan(&mac, &s.first, &s.last, &s.name, &s.ip); err != nil {
+			return nil, err
 		}
 		byMac[mac] = s
 	}
+	return byMac, nil
+}
+
+// ghostDevices: clientes del registro (device_seen) que ya no aparecen en
+// ninguna fuente viva (lease caducado, ARP limpiada, FDB envejecido) y por
+// tanto buildDevices no emite. Se listan como offline con su último nombre
+// y último seen: retención indefinida (#1145). El front los distingue por
+// Online=false y su LastSeenMs antiguo.
+func (l *Live) ghostDevices(devices []Device) []Device {
+	if l.db == nil {
+		return nil
+	}
+	live := make(map[string]bool, len(devices))
 	for i := range devices {
-		if s, ok := byMac[normSeenMAC(devices[i].MAC)]; ok {
-			devices[i].FirstSeenMs = s.first
-			devices[i].LastSeenMs = s.last
+		live[normSeenMAC(devices[i].MAC)] = true
+	}
+	// #1151: una alias enlazada no sale como fantasma propio - su canónico la
+	// representa en la lista (si el canónico no está en el registro, la alias
+	// se muestra tal cual para no perder al cliente).
+	links := l.deviceLinks()
+	byMac, err := l.seenByMac()
+	if err != nil {
+		return nil
+	}
+	// #1151: aliases registradas de cada canónico (para que la hoja las
+	// muestre y permita desenlazarlas).
+	revAlias := map[string][]string{}
+	for alias, canonical := range links {
+		if _, registered := byMac[canonical]; registered {
+			revAlias[canonical] = append(revAlias[canonical], alias)
+		}
+	}
+	var out []Device
+	for rawMac, s := range byMac {
+		mac := normSeenMAC(rawMac)
+		if live[mac] {
+			continue
+		}
+		if canonical, linked := links[mac]; linked {
+			if _, canonRegistered := byMac[canonical]; canonRegistered {
+				continue
+			}
+		}
+		d := Device{
+			ID:          strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
+			MAC:         mac,
+			Type:        "desconocido",
+			IP:          s.ip,
+			Online:      false,
+			Band:        "—",
+			FirstSeenMs: s.first,
+			LastSeenMs:  s.last,
+		}
+		if s.name != "" {
+			d.Hostname = s.name
+			d.Name = s.name
+		}
+		if aliases := revAlias[mac]; len(aliases) > 0 {
+			d.AliasMacs = aliases
 		}
+		out = append(out, d)
 	}
+	return out
 }

+ 67 - 0
server-go/internal/adapters/device_seen_test.go

@@ -40,3 +40,70 @@ func TestDeviceSeenNilDB(t *testing.T) {
 		t.Errorf("con db nil no se rellena: %+v", devs[0])
 	}
 }
+
+// #1145: los clientes del registro que ya no se ven en vivo salen como
+// offline (ghosts) conservando su último nombre y seen; los que siguen
+// vivos no se duplican.
+func TestGhostDevicesOfflineRetention(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	l.noteDevicesSeen([]Device{
+		{MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "iphone-peter"},
+		{MAC: "11:22:33:44:55:66", Online: true},
+	}, 1000)
+
+	// Solo uno sigue vivo: el otro sale como ghost con su nombre y seen.
+	ghosts := l.ghostDevices([]Device{{MAC: "11:22:33:44:55:66", Online: true}})
+	if len(ghosts) != 1 {
+		t.Fatalf("ghosts = %d, want 1", len(ghosts))
+	}
+	g := ghosts[0]
+	if g.MAC != "AA:BB:CC:DD:EE:FF" || g.Online {
+		t.Fatalf("ghost = %+v, want offline AA:BB:CC:DD:EE:FF", g)
+	}
+	if g.Hostname != "iphone-peter" {
+		t.Fatalf("hostname = %q, want iphone-peter", g.Hostname)
+	}
+	if g.FirstSeenMs != 1000 || g.LastSeenMs != 1000 {
+		t.Fatalf("seen = %d/%d, want 1000/1000", g.FirstSeenMs, g.LastSeenMs)
+	}
+
+	// Los dos vivos: ningún ghost.
+	if ghosts := l.ghostDevices([]Device{
+		{MAC: "11:22:33:44:55:66", Online: true},
+		{MAC: "AA:BB:CC:DD:EE:FF", Online: true},
+	}); len(ghosts) != 0 {
+		t.Fatalf("ghosts = %d, want 0", len(ghosts))
+	}
+}
+
+// #1145: la caché gl-clients de GL.iNet emite MACs con guiones; el pase de
+// normalización dedupe con la versión de dos puntos y enriquece la entrada.
+func TestNormalizeDevicesDashedMAC(t *testing.T) {
+	out := normalizeDevices([]Device{
+		{MAC: "AA-BB-CC-DD-EE-FF", Online: false, Hostname: "watch"},
+		{MAC: "aa:bb:cc:dd:ee:ff", Online: true, IP: "192.168.1.50"},
+	})
+	if len(out) != 1 {
+		t.Fatalf("devices = %d, want 1 (dedup por MAC normalizada)", len(out))
+	}
+	if out[0].MAC != "AA:BB:CC:DD:EE:FF" || !out[0].Online {
+		t.Fatalf("device = %+v, want online con MAC canonica", out[0])
+	}
+	if out[0].Hostname != "watch" || out[0].IP != "192.168.1.50" {
+		t.Fatalf("merge = %+v, want hostname+IP combinados", out[0])
+	}
+}
+
+// #1145: el nombre nuevo (lease) pisa al guardado solo si no es vacío.
+func TestNoteDevicesSeenKeepsLastName(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d}
+	l.noteDevicesSeen([]Device{{MAC: "aa:bb:cc:dd:ee:ff", Online: true, Hostname: "iphone"}}, 1000)
+	l.noteDevicesSeen([]Device{{MAC: "AA:BB:CC:DD:EE:FF", Online: true}}, 2000)
+
+	ghosts := l.ghostDevices(nil)
+	if len(ghosts) != 1 || ghosts[0].Hostname != "iphone" {
+		t.Fatalf("ghosts = %+v, want 1 con hostname iphone", ghosts)
+	}
+}

+ 450 - 178
server-go/internal/adapters/live.go

@@ -97,8 +97,10 @@ type routerPolled struct {
 	board     *BoardInfo
 	cpu       int
 	ram       int
-	temp      int
-	uptimeSec float64
+	temp              int
+	flash             string
+	firmwareAvailable string
+	uptimeSec         float64
 	net       *NetDevBps
 	leases    []DhcpLease
 	// glClients (GL.iNet): base de clientes del firmware, superset de las
@@ -255,6 +257,10 @@ type Live struct {
 	snmpPorts map[string]map[string]snmpPortSample
 	// snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
 	snmpLastPoll map[string]time.Time
+	// roNetPrev: última muestra de contadores rx/tx del interfaz WAN de un
+	// router RouterOS, para calcular bps por delta entre polls (igual que
+	// GetNetDev de OpenWrt sobre /proc/net/dev, routeros_api.go).
+	roNetPrev map[string]netByteSample
 	// snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
 	// para loguear solo cuando el resultado cambia.
 	snmpFdbCount map[string]int
@@ -413,6 +419,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		snmpLastPoll:         map[string]time.Time{},
+		roNetPrev:            map[string]netByteSample{},
 		snmpFdbCount:         map[string]int{},
 		snmpBrMac:            map[string]string{},
 		snmpPollStats:        map[string]*snmpPollStat{},
@@ -500,6 +507,22 @@ func (l *Live) loadRouterMacs() {
 // Mode: "live".
 func (l *Live) Mode() string { return "live" }
 
+// FleetFdbUplinks (rack canvas): evidencia FDB de uplinks entre miembros
+// de flota, para el auto-cableado del canvas. Usa el último sondeo.
+func (l *Live) FleetFdbUplinks() map[string]FdbUplink {
+	out := map[string]FdbUplink{}
+	brMacBy := map[string]string{}
+	for id, p := range l.lastPolled {
+		if p != nil && p.brMac != "" {
+			brMacBy[id] = p.brMac
+		}
+	}
+	for child, up := range fleetFdbEvidence(l.lastPolled) {
+		out[child] = FdbUplink{ChildID: child, ParentID: up.parent, Port: up.port}
+	}
+	return out
+}
+
 // Tick: no-op (el sondeo real ocurre en GetOverview, como el JS).
 func (l *Live) Tick(context.Context) error { return nil }
 
@@ -517,7 +540,9 @@ func (l *Live) SetRouters(list []RouterConfig) {
 	l.gatewayCfg = pickGateway(l.routers)
 	l.clients = map[string]*OpenWrtClient{}
 	for _, c := range l.routers {
-		if !c.AgentOnly {
+		// RouterOS no habla SSH/ubus: se sondea por su REST API (routeros_live.go),
+		// sin cliente SSH.
+		if !c.AgentOnly && c.Type != "routeros" {
 			l.clients[c.ID] = NewOpenWrtClient(c, l.pool, "root", "")
 		}
 	}
@@ -575,6 +600,11 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.snmpBrMac, id)
 		}
 	}
+	for id := range l.roNetPrev {
+		if !ids[id] {
+			delete(l.roNetPrev, id)
+		}
+	}
 	for id := range l.snmpLastMetricsTick {
 		if !ids[id] {
 			delete(l.snmpLastMetricsTick, id)
@@ -954,6 +984,9 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	if cfg.SnmpEnabled {
 		return l.pollRouterSNMP(cfg)
 	}
+	if cfg.Type == "routeros" {
+		return l.pollRouterROS(cfg)
+	}
 	l.mu.Lock()
 	client := l.clients[cfg.ID]
 	gw := l.gatewayCfg
@@ -1214,8 +1247,16 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	}
 	if isGw {
 		r.Role, r.RoleBadge = "Gateway principal", "Principal"
-	} else if p.cfg.AgentOnly {
+	} else if p.cfg.Type == "routeros" {
+		r.Role, r.RoleBadge = "Router", "Router"
+	} else if p.cfg.AgentOnly || p.cfg.Type == "managed-switch" || (p.cfg.Type == "external" && p.cfg.SnmpEnabled) {
+		// external sondeado por SNMP = switch en la práctica (#661); evita el
+		// fallback AP para los switches SNMP de crowedavid (#1137).
 		r.Role, r.RoleBadge = "Switch", "SW"
+	} else if p.cfg.Type == "external" {
+		// #1137: un external genérico NO es un AP; el fallback anterior le
+		// colgaba el chip AP cian en la tarjeta del detalle.
+		r.Role, r.RoleBadge = "External", "EXT"
 	} else {
 		r.Role, r.RoleBadge = "Punto de acceso", "AP"
 	}
@@ -1243,7 +1284,10 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.cfg.Type != "" {
 		r.Type = p.cfg.Type
 	}
-	if outdatedFw {
+	if p.firmwareAvailable != "" && r.FirmwareTarget == "" {
+		r.FirmwareTarget = p.firmwareAvailable
+	}
+	if outdatedFw || p.firmwareAvailable != "" {
 		r.FirmwareOutdated = true
 		// Alerta no urgente (category system); el engine aplica dedup 5 min.
 		l.engine.Emit(AlertEvent{
@@ -1293,6 +1337,20 @@ func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
 }
 
 // offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
+// pausedRouter (#1085): una unidad pausada no se sondea ni alerta. Se
+// muestra con la última snapshot conocida (o el esqueleto básico) y el
+// estado "paused", que la UI distingue con la insignia de pausada. Reutiliza
+// offlineRouter para el esqueleto y le pisa el estado: pausar no es estar
+// caído, y los flags de acceso/host key no aplican mientras no se sondea.
+func (l *Live) pausedRouter(cfg RouterConfig) Router {
+	r := l.offlineRouter(cfg)
+	r.Status = "paused"
+	r.AccessMissing = false
+	r.HostKeyChanged = false
+	r.Disabled = true
+	return r
+}
+
 // issue #257: si el último fallo fue de ACCESO (el router responde pero la
 // clave SSH no está autorizada), el estado es "unreachable" + accessMissing,
 // no un "offline" de apagado/inalcanzable (config issue, no power issue).
@@ -1306,8 +1364,13 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 		r = *prev
 	} else {
 		model := "OpenWrt"
-		if cfg.Type == "glinet" {
+		switch cfg.Type {
+		case "glinet":
 			model = "GL.iNet"
+		case "routeros":
+			model = "RouterOS"
+		case "managed-switch":
+			model = "Managed Switch"
 		}
 		name := cfg.Name
 		if name == "" {
@@ -1318,13 +1381,21 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 			IP: cfg.Host, Health: 0,
 			CPU: iptr(0), RAM: iptr(0), Temp: iptr(0),
 			Uptime: "—", Clients: 0, Sparkline: []float64{},
+			Type: cfg.Type,
 		}
 		if gw != nil && cfg.ID == gw.ID {
 			r.Role, r.RoleBadge = "Gateway principal", "Principal"
+		} else if cfg.Type == "routeros" {
+			r.Role, r.RoleBadge = "Router", "Router"
+		} else if cfg.Type == "managed-switch" || (cfg.Type == "external" && cfg.SnmpEnabled) {
+			r.Role, r.RoleBadge = "Switch", "SW"
+		} else if cfg.Type == "external" {
+			r.Role, r.RoleBadge = "External", "EXT"
 		} else {
 			r.Role, r.RoleBadge = "Punto de acceso", "AP"
 		}
 	}
+	r.Type = cfg.Type
 	r.Status = "offline"
 	if l.accessMissing(cfg.ID) {
 		r.Status = "unreachable"
@@ -1419,19 +1490,30 @@ func isHostKeyError(err error) bool {
 }
 
 // pollAll sondea todos los routers en paralelo (Promise.allSettled).
+// issue #1085: las unidades pausadas (disabled) NO se sondean; se limpian
+// sus contadores de fallo y sus alertas de offline abiertas, y quedan con
+// estado "paused" en el overview (ver pausedRouter).
 func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	l.mu.Lock()
 	routers := append([]RouterConfig(nil), l.routers...)
 	l.mu.Unlock()
 
+	active := make([]RouterConfig, 0, len(routers))
+	for _, cfg := range routers {
+		if cfg.Disabled {
+			continue
+		}
+		active = append(active, cfg)
+	}
+
 	type result struct {
 		cfg RouterConfig
 		p   *routerPolled
 		err error
 	}
-	results := make([]result, len(routers))
+	results := make([]result, len(active))
 	var wg sync.WaitGroup
-	for i, cfg := range routers {
+	for i, cfg := range active {
 		wg.Add(1)
 		go func(i int, cfg RouterConfig) {
 			defer wg.Done()
@@ -1444,6 +1526,18 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	polled := map[string]*routerPolled{}
 	l.mu.Lock()
 	defer l.mu.Unlock()
+	// #1085: una unidad pausada no se sondea: sus fallos en curso se anulan
+	// (al reanudar, el sondeo arranca limpio) y sus alertas de offline se
+	// resuelven: pausar no es estar caído.
+	for _, cfg := range routers {
+		if !cfg.Disabled {
+			continue
+		}
+		l.failCount[cfg.ID] = 0
+		delete(l.lastErr, cfg.ID)
+		delete(l.lastStatus, cfg.ID)
+		l.resolveOfflineAlerts(cfg.ID)
+	}
 	for _, res := range results {
 		if res.err == nil {
 			polled[res.cfg.ID] = res.p
@@ -2228,15 +2322,17 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
 func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	leasesByMac := map[string]DhcpLease{}
+	leaseRouter := map[string]string{}
 	arpByMac := map[string]string{}
 	glByMac := map[string]DhcpLease{}
-	for _, p := range polled {
+	for rID, p := range polled {
 		for mac, ip := range p.arp {
 			arpByMac[mac] = ip
 		}
 		for _, le := range p.leases {
 			if le.MAC != "" {
 				leasesByMac[le.MAC] = le
+				leaseRouter[le.MAC] = rID
 			}
 		}
 		// gl-clients: fallback de IP para MACs sin lease (dnsmasq sin ese
@@ -2428,9 +2524,6 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			if _, ok := seen[mac]; ok {
 				continue
 			}
-			if _, ok := leasesByMac[mac]; ok {
-				continue
-			}
 			if _, ok := known[mac]; ok {
 				continue
 			}
@@ -2562,11 +2655,17 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		// tiene idioma: "Desconocido" viajaba tal cual hasta la UI y salía en
 		// español en una interfaz en inglés. Quien pinta, traduce.
 		manufacturer := oui.Lookup(mac)
+		defaultRouterID := gwID
+		if defaultRouterID == "" {
+			if rID, ok := leaseRouter[mac]; ok {
+				defaultRouterID = rID
+			}
+		}
 		d := Device{
 			ID:  strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
 			MAC: mac, Manufacturer: manufacturer,
 			TrafficMbps: 0, Sparkline: []float64{},
-			RouterID: gwID, Band: "—",
+			RouterID: defaultRouterID, Band: "—",
 			Online: isSeen,
 		}
 		if hasLease {
@@ -2661,6 +2760,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			d.RouterID = k.routerID
 			d.Band = k.band
 			d.SignalDbm = k.signal
+		} else if rID, ok := leaseRouter[mac]; ok && d.RouterID == "" {
+			d.RouterID = rID
 		}
 		// #551: TrafficMbps del cliente desde el rate en memoria (nlbwmon u
 		// hostapd) sin consultar la store en cada rebuild. Solo online; los
@@ -2678,7 +2779,45 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	// topología → los chips saltaban de posición al refrescar. Ordenar por
 	// MAC hace el contrato determinista para el mismo set de dispositivos.
 	sort.Slice(devices, func(i, j int) bool { return devices[i].MAC < devices[j].MAC })
-	return devices
+	// #1151: canónicas + fusión de enlazadas (orden: normalizar -> fusionar).
+	return normalizeDevices(mergeLinkedDevices(devices, l.deviceLinks()))
+}
+
+// normalizeDevices: MACs a formato canónico (mayúsculas, ':') y dedup por
+// MAC. La caché gl-clients de GL.iNet emite MACs con guiones y entradas
+// caducadas: sin normalizar el mismo cliente puede aparecer duplicado
+// (#1145). Gana la entrada online; hostname/IP/fabricante de la descartada
+// enriquecen a la conservada.
+func normalizeDevices(devices []Device) []Device {
+	byMac := make(map[string]int, len(devices))
+	out := make([]Device, 0, len(devices))
+	for _, d := range devices {
+		mac := strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(d.MAC), "-", ":"))
+		d.MAC = mac
+		if i, ok := byMac[mac]; ok {
+			a, b := out[i], d
+			if b.Online && !a.Online {
+				a, b = b, a
+			}
+			if a.Hostname == "" {
+				a.Hostname = b.Hostname
+			}
+			if a.IP == "" {
+				a.IP = b.IP
+			}
+			if a.Manufacturer == "" {
+				a.Manufacturer = b.Manufacturer
+			}
+			if a.Name == "" {
+				a.Name = b.Name
+			}
+			out[i] = a
+			continue
+		}
+		byMac[mac] = len(out)
+		out = append(out, d)
+	}
+	return out
 }
 
 // emitTempAlert emite la alerta de temperatura alta UNA vez por proceso
@@ -2857,6 +2996,12 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	routerList := make([]Router, 0, len(routers))
 	for _, cfg := range routers {
 		p := polled[cfg.ID]
+		if cfg.Disabled {
+			// #1085: unidad pausada: última snapshot conocida (o el
+			// esqueleto) con estado "paused"; nunca offline ni alerta.
+			routerList = append(routerList, l.pausedRouter(cfg))
+			continue
+		}
 		if p == nil {
 			l.mu.Lock()
 			prev := l.lastGood[cfg.ID]
@@ -2941,6 +3086,14 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	l.trackDevicePresence(devices, time.Now().UnixMilli())
 	// #954: first/last seen persistente de TODOS los clientes online.
 	l.noteDevicesSeen(devices, time.Now().UnixMilli())
+	// #1095: el overview (snapshot SSE del que vive la tabla de clientes)
+	// escribía las marcas pero NUNCA las aplicaba: la UI en vivo mostraba
+	// "—" aunque la API REST las tuviera (sólo los detalles las aplicaban).
+	l.applyDeviceSeen(devices)
+	// #1145: retención indefinida - clientes del registro que ya no se ven
+	// en ninguna fuente viva salen como offline (con último nombre y seen).
+	// El overview es el snapshot SSE del que vive la tabla de clientes.
+	devices = append(devices, l.ghostDevices(devices)...)
 	// Clientes reales por router (atribución wireless/FDB, no leases)
 	countClientsPerRouter(routerList, devices)
 	// Sparkline de la tarjeta para fuentes sin throughput bps (switch beacon/
@@ -2993,6 +3146,10 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	if len(top) > 5 {
 		top = top[:5]
 	}
+	// #1051: evidencia FDB directa para anclar uplinks de flota sin depender
+	// de que la unidad aparezca como device (la MAC bridge de cada router
+	// aprendida en el FDB de otro miembro dice dónde cuelga).
+	fdbEvidence := fleetFdbEvidence(polled)
 	// El motor de alertas es el dueño de la lista y del read-state
 	// (SPEC-ALERTAS §3-4): UnreadAlerts = no leídas que pasaron config.
 	alertsCopy := l.engine.List()
@@ -3009,7 +3166,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
 		DistributionNodes: distNodes,
-		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway), // SPEC-65 D65-3 + #1042
+		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway, fdbEvidence), // SPEC-65 D65-3 + #1042/#1051
 		Devices:           devices,
 		Usteer:            &UsteerOverview{Available: usteerAvailable},
 		DawnDeprecated:    dawnDetected,
@@ -3094,6 +3251,10 @@ func (l *Live) GetRouters(context.Context) []Router {
 	out := make([]Router, 0, len(routers))
 	for _, cfg := range routers {
 		p := polled[cfg.ID]
+		if cfg.Disabled {
+			out = append(out, l.pausedRouter(cfg))
+			continue
+		}
 		if p == nil {
 			l.mu.Lock()
 			prev := l.lastGood[cfg.ID]
@@ -3148,6 +3309,7 @@ type liveExtras struct {
 	MAC                 string        `json:"mac"`
 	Firmware            string        `json:"firmware"`
 	FirmwareUpdated     bool          `json:"firmwareUpdated"`
+	FirmwareAvailable   string        `json:"firmwareAvailable,omitempty"`
 	LastReboot          string        `json:"lastReboot"`
 	Soc                 string        `json:"soc"`
 	Flash               string        `json:"flash"`
@@ -3244,171 +3406,25 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	if p != nil {
 		ports = p.ports
 	}
+	var depsLldp []LldpNeighbor
+	if p != nil {
+		depsLldp = p.lldp
+	}
+	deps := portEnrichDeps{
+		routerByMac: routerByMac,
+		leaseMap:    leaseMap,
+		aliasByMac:  aliasByMac,
+		wifiByMac:   wifiByMac,
+		portMacs:    portMacs,
+		lldp:        depsLldp,
+	}
 	enriched := make([]EthPort, 0, len(ports))
 	for _, port := range ports {
 		if !port.Up {
 			enriched = append(enriched, port)
 			continue
 		}
-		netdev := portNetdev(port)
-		all := portMacs[netdev]
-		// #1036: portMacs se construye iterando el FDB (mapa), así que el
-		// ORDEN de las MACs por boca cambia en cada tick. Con 2-3 MACs la
-		// heurística de "primera con hostname DHCP" elegía un dispositivo
-		// distinto por ciclo y la etiqueta del puerto flappeaba. Orden
-		// estable: la selección queda determinista entre polls.
-		sort.Strings(all)
-		// 1) ¿Otro router al otro lado? (uplink router↔router)
-		neighbor := ""
-		for _, mac := range all {
-			if _, ok := routerByMac[mac]; ok {
-				neighbor = mac
-				break
-			}
-		}
-		if neighbor != "" {
-			port.ConnectedTo = routerByMac[neighbor]
-			// El cliente traduce la plantilla según PeerKind (#1039).
-			port.PeerKind = "router-link"
-			// El vecino además se anuncia por LLDP → el frontend puede
-			// mostrar el sufijo "· LLDP" en la etiqueta del uplink (C2).
-			if nb := lldpNeighborOnPort(p.lldp, netdev); nb != nil {
-				port.PeerKind = "router-link-lldp"
-			}
-			enriched = append(enriched, port)
-			continue
-		}
-		// 1.5) Cliente WiFi detrás de un AP: la boca del switch lleva al AP
-		// (el cliente viaja por su radio). Atribuir la boca al AP y señalar
-		// el cliente como "detrás" (#291). Guard de longitud PRIMERO: una
-		// boca up sin MACs aprendidas llega con all vacío.
-		if len(all) > 0 {
-			if ap, isWifi := wifiByMac[all[0]]; isWifi && allWifiOfOneAP(all, wifiByMac) {
-				port.ConnectedTo = ap
-				port.DeviceMac = all[0]
-				// La pista "cliente WiFi detrás" la traduce el cliente
-				// según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
-				port.PeerKind = "ap-wifi"
-				enriched = append(enriched, port)
-				continue
-			}
-		}
-		// 2) Un solo dispositivo final
-		if len(all) == 1 {
-			mac := all[0]
-			lease, ok := leaseMap[mac]
-			// MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
-			// el equipo enchufado es el hypervisor; lo aprendido es una
-			// NIC virtual de una VM/CT (#291).
-			if isVirtualMAC(mac) {
-				port.ConnectedTo = "Hypervisor"
-				port.DeviceMac = mac
-				port.Detail = virtualDetail(mac, leaseMap, aliasByMac)
-				enriched = append(enriched, port)
-				continue
-			}
-			// Label curada que no coincide con el dispositivo resuelto:
-			// - si el dispositivo tiene nombre real (lease/alias), la label
-			//   nombra la infraestructura física y lo aprendido está DETRÁS
-			//   (p. ej. ngxpm detrás de citadel-02);
-			// - si el dispositivo no tiene nombre mejor que su MAC, la label
-			//   ES su nombre (bautizada a mano: "hikvision"), y la MAC queda
-			//   como detalle.
-			if isCuratedLabel(port) && !labelMatchesDevice(port.Label, mac, leaseMap, aliasByMac) {
-				name := deviceDisplayName(mac, leaseMap, aliasByMac)
-				port.DeviceMac = mac
-				if name != mac {
-					// El cliente compone "nombre · detrás de <label>" con
-					// su i18n (#1039); aquí viaja el nombre a pelo.
-					port.ConnectedTo = name
-					port.PeerKind = "curated"
-				} else {
-					port.ConnectedTo = port.Label
-					port.PeerKind = "mac"
-				}
-				if lease, ok := leaseMap[mac]; ok && lease.IP != "" {
-					port.Detail = lease.IP
-				}
-				enriched = append(enriched, port)
-				continue
-			}
-			switch {
-			case ok && lease.Hostname != "":
-				port.ConnectedTo = lease.Hostname
-			case ok && lease.IP != "":
-				port.ConnectedTo = lease.IP
-			case aliasByMac[mac] != "":
-				port.ConnectedTo = aliasByMac[mac]
-			default:
-				port.ConnectedTo = mac
-			}
-			port.DeviceMac = mac
-			if ok && lease.IP != "" {
-				port.Detail = lease.IP + " · full duplex"
-			}
-			enriched = append(enriched, port)
-			continue
-		}
-		// 3) Varios: el vecino es un switch/hub/hipervisor
-		if len(all) > 1 {
-			// Muchas MACs detrás de una boca = agregación (hipervisor Proxmox
-			// con CTs, switch tonto): nombrar UN CT al azar engaña (la MAC es
-			// virtual, no el equipo enchufado). La label curada del puerto ya
-			// identifica el físico; aquí se cuenta lo que hay detrás (#291).
-			if len(all) > 3 {
-				// deviceCount lo traduce la app; aquí NO se formatea texto (#1036).
-				port.DeviceCount = len(all)
-				enriched = append(enriched, port)
-				continue
-			}
-			// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
-			// es mejor pista que el hostname DHCP.
-			if nb := lldpNeighborOnPort(p.lldp, netdev); nb != nil && nb.displayName() != "" {
-				port.ConnectedTo = nb.displayName()
-				if nb.Mgmt != "" {
-					port.Detail = nb.Mgmt + " · LLDP"
-				} else {
-					port.Detail = "LLDP"
-				}
-				enriched = append(enriched, port)
-				continue
-			}
-			infraMac := ""
-			for _, mac := range all {
-				if le, ok := leaseMap[mac]; ok && le.Hostname != "" {
-					infraMac = mac
-					break
-				}
-			}
-			if infraMac == "" {
-				// Sin hostname DHCP: primer alias manual como pista (#291).
-				for _, mac := range all {
-					if aliasByMac[mac] != "" {
-						infraMac = mac
-						break
-					}
-				}
-			}
-			if infraMac != "" {
-				if lease, ok := leaseMap[infraMac]; ok && lease.Hostname != "" {
-					port.ConnectedTo = lease.Hostname
-					port.DeviceMac = infraMac
-					if lease.IP != "" {
-						port.Detail = lease.IP
-					}
-				} else if alias := aliasByMac[infraMac]; alias != "" {
-					port.ConnectedTo = alias
-					port.DeviceMac = infraMac
-				}
-			} else {
-				// Switch/bridge tonto inferido: sin lease ni alias que lo
-				// nombre. El cliente traduce la etiqueta (#1039/#1040).
-				port.PeerKind = "inferred-switch"
-			}
-			enriched = append(enriched, port)
-			continue
-		}
-		enriched = append(enriched, port)
+		enriched = append(enriched, enrichEthPort(port, portNetdev(port), deps))
 	}
 	// Per-port health score (issue #299): compute from recent series + flapping.
 	l.enrichPortHealth(id, enriched)
@@ -3445,7 +3461,7 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		MAC: "—", Firmware: "—", FirmwareUpdated: true, LastReboot: "—",
 		Soc: "—", Flash: "—", RamMb: 0,
 		BandSplit:           bandSplit,
-		GatewayLatencySpark: []float64{},
+		GatewayLatencySpark: l.latencySpark24h(id),
 		BackhaulSignal:      []float64{},
 		Radios:              radios,
 		Ports:               enriched,
@@ -3462,6 +3478,13 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 				extras.Soc = "—"
 			}
 		}
+		if p.firmwareAvailable != "" {
+			extras.FirmwareAvailable = p.firmwareAvailable
+			extras.FirmwareUpdated = false
+		}
+		if p.flash != "" {
+			extras.Flash = p.flash
+		}
 		if p.uptimeSec > 0 {
 			rb := time.Now().Add(-time.Duration(p.uptimeSec) * time.Second)
 			extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
@@ -3498,8 +3521,11 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		l.mu.Unlock()
 	}
 	if gw != nil && id == gw.ID {
-		detail.Adguard = l.pollAdGuard(ctx)
-		detail.Wireguard = l.pollWireGuard(clients)
+		// AdGuard Home y WireGuard (OpenWrt/GL.iNet ubus/SSH) no aplican a RouterOS.
+		if cfg.Type != "routeros" {
+			detail.Adguard = l.pollAdGuard(ctx)
+			detail.Wireguard = l.pollWireGuard(clients)
+		}
 	} else {
 		// Backhaul real del AP: boca que enlaza con otro router + latencia
 		var uplink *EthPort
@@ -3538,6 +3564,35 @@ func (l *Live) GetDevices(context.Context) []Device {
 	return l.attributedDevices()
 }
 
+// latencySpark24h: serie 24h de latencia de la unidad en buckets horarios
+// (AVG de latency_ms en la tabla metrics, solo muestras con sonda). #1148:
+// alimenta el spark real del detalle; vacía si no hay historial (sin sonda
+// o unidad recién añadida) para que el front pinte "sin datos" y no ceros.
+func (l *Live) latencySpark24h(routerID string) []float64 {
+	if l.db == nil || routerID == "" {
+		return []float64{}
+	}
+	rows, err := l.db.Query(
+		`SELECT (ts / 3600000) AS bucket, AVG(latency_ms) AS lat
+		 FROM metrics WHERE router_id = ? AND ts >= ? AND latency_ms IS NOT NULL
+		 GROUP BY bucket ORDER BY bucket`,
+		routerID, l.now().UnixMilli()-86400e3)
+	if err != nil {
+		return []float64{}
+	}
+	defer rows.Close()
+	out := []float64{}
+	for rows.Next() {
+		var bucket int64
+		var lat float64
+		if err := rows.Scan(&bucket, &lat); err != nil {
+			continue
+		}
+		out = append(out, lat)
+	}
+	return out
+}
+
 // 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
@@ -3559,8 +3614,17 @@ func (l *Live) attributedDevices() []Device {
 	// #561: sellado de infraestructura con el inventario PVE (si configurado).
 	// El detalle no consume distnodes, pero el sellado de devices sí corre.
 	l.sealProxmoxInfra(devices, nil)
-	// #954: first/last seen persistente (device_seen) en el payload final.
+	// #954 + #1095: first/last seen persistente (device_seen) en el payload
+	// final. La escritura vivía SOLO en buildOverview: si por lo que fuera
+	// esa lista no contenía un cliente (p. ej. flota agent-only), el visto
+	// nunca se persistía y aquí se mostraba "—" para siempre. Escribir también
+	// desde la lista que la UI realmente consume hace el write-through
+	// inevitable; el upsert es idempotente y barato.
+	l.noteDevicesSeen(devices, time.Now().UnixMilli())
 	l.applyDeviceSeen(devices)
+	// #1145: retención indefinida - clientes del registro que ya no se ven
+	// en ninguna fuente viva salen como offline con su último nombre y seen.
+	devices = append(devices, l.ghostDevices(devices)...)
 	return devices
 }
 
@@ -4449,3 +4513,211 @@ func deviceDisplayName(mac string, leases map[string]DhcpLease, aliases map[stri
 	}
 	return mac
 }
+
+
+// portEnrichDeps: mapas compartidos del enriquecimiento de bocas del
+// detalle (extraído de GetRouterDetail, #1150, para poder testearlo).
+type portEnrichDeps struct {
+	routerByMac map[string]string
+	leaseMap    map[string]DhcpLease
+	aliasByMac  map[string]string
+	wifiByMac   map[string]string
+	portMacs    map[string][]string
+	lldp        []LldpNeighbor
+}
+
+// enrichEthPort: enriquece UNA boca encendida con el par que tiene enfrente
+// (router-link, cliente WiFi detrás del AP, dispositivo único, agregación).
+// Mismo comportamiento que el bucle inline que sustituye (#1150).
+func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
+	all := d.portMacs[netdev]
+	// #1036: d.portMacs se construye iterando el FDB (mapa), así que el
+	// ORDEN de las MACs por boca cambia en cada tick. Con 2-3 MACs la
+	// heurística de "primera con hostname DHCP" elegía un dispositivo
+	// distinto por ciclo y la etiqueta del puerto flappeaba. Orden
+	// estable: la selección queda determinista entre polls.
+	sort.Strings(all)
+	// 1) ¿Otro router al otro lado? (uplink router↔router)
+	neighbor := ""
+	for _, mac := range all {
+		if _, ok := d.routerByMac[mac]; ok {
+			neighbor = mac
+			break
+		}
+	}
+	if neighbor != "" {
+		port.ConnectedTo = d.routerByMac[neighbor]
+		// El cliente traduce la plantilla según PeerKind (#1039).
+		port.PeerKind = "router-link"
+		// #1150: con switches encadenados la boca aprende las MACs de bridge
+		// de VARIAS unidades (el tráfico de sw2 atraviesa sw1) y la primera
+		// MAC ordenada puede nombrar al switch LEJANO. El LLDP anuncia al
+		// vecino DIRECTO de la boca: su chassis MAC (si es unidad conocida)
+		// o su sysName manda sobre la MAC ordenada, y la mgmt-ip va al
+		// detalle del hover.
+		if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
+			port.PeerKind = "router-link-lldp"
+			if nb.ChassisMac != "" {
+				// La MAC del vecino (su bridge) va al hover como en las bocas
+				// de dispositivo único (#1150).
+				port.DeviceMac = strings.ToUpper(nb.ChassisMac)
+				if name, ok := d.routerByMac[strings.ToUpper(nb.ChassisMac)]; ok {
+					port.ConnectedTo = name
+				} else if dn := nb.displayName(); dn != "" {
+					port.ConnectedTo = dn
+				}
+			} else if dn := nb.displayName(); dn != "" {
+				port.ConnectedTo = dn
+			}
+			if nb.Mgmt != "" {
+				port.Detail = nb.Mgmt + " · LLDP"
+			}
+		}
+		return port
+	}
+	// 1.5) Cliente WiFi detrás de un AP: la boca del switch lleva al AP
+	// (el cliente viaja por su radio). Atribuir la boca al AP y señalar
+	// el cliente como "detrás" (#291). Guard de longitud PRIMERO: una
+	// boca up sin MACs aprendidas llega con all vacío.
+	if len(all) > 0 {
+		if ap, isWifi := d.wifiByMac[all[0]]; isWifi && allWifiOfOneAP(all, d.wifiByMac) {
+			port.ConnectedTo = ap
+			port.DeviceMac = all[0]
+			// La pista "cliente WiFi detrás" la traduce el cliente
+			// según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
+			port.PeerKind = "ap-wifi"
+		return port
+		}
+	}
+	// 2) Un solo dispositivo final
+	if len(all) == 1 {
+		mac := all[0]
+		lease, ok := d.leaseMap[mac]
+		// #931: un vecino LLDP en esta boca es el propio equipo
+		// anunciándose; su sysName/mgmt-ip son mejor identificación que
+		// la MAC pelada cuando no hay hostname DHCP ni alias.
+		lldpName, lldpMgmt := "", ""
+		if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
+			lldpName = nb.displayName()
+			lldpMgmt = nb.Mgmt
+		}
+		// MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
+		// el equipo enchufado es el hypervisor; lo aprendido es una
+		// NIC virtual de una VM/CT (#291).
+		if isVirtualMAC(mac) {
+			port.ConnectedTo = "Hypervisor"
+			port.DeviceMac = mac
+			port.Detail = virtualDetail(mac, d.leaseMap, d.aliasByMac)
+		return port
+		}
+		// Label curada que no coincide con el dispositivo resuelto:
+		// - si el dispositivo tiene nombre real (lease/alias), la label
+		//   nombra la infraestructura física y lo aprendido está DETRÁS
+		//   (p. ej. ngxpm detrás de citadel-02);
+		// - si el dispositivo no tiene nombre mejor que su MAC, la label
+		//   ES su nombre (bautizada a mano: "hikvision"), y la MAC queda
+		//   como detalle.
+		if isCuratedLabel(port) && !labelMatchesDevice(port.Label, mac, d.leaseMap, d.aliasByMac) {
+			name := deviceDisplayName(mac, d.leaseMap, d.aliasByMac)
+			port.DeviceMac = mac
+			if name != mac {
+				// El cliente compone "nombre · detrás de <label>" con
+				// su i18n (#1039); aquí viaja el nombre a pelo.
+				port.ConnectedTo = name
+				port.PeerKind = "curated"
+			} else if lldpName != "" {
+				// #931: sin nombre mejor, el equipo se anuncia por LLDP.
+				port.ConnectedTo = lldpName
+				port.PeerKind = "mac"
+			} else {
+				port.ConnectedTo = port.Label
+				port.PeerKind = "mac"
+			}
+			if lease, ok := d.leaseMap[mac]; ok && lease.IP != "" {
+				port.Detail = lease.IP
+			} else if lldpMgmt != "" && lldpName != "" {
+				port.Detail = lldpMgmt + " · LLDP"
+			}
+		return port
+		}
+		switch {
+		case ok && lease.Hostname != "":
+			port.ConnectedTo = lease.Hostname
+		case ok && lease.IP != "":
+			port.ConnectedTo = lease.IP
+		case d.aliasByMac[mac] != "":
+			port.ConnectedTo = d.aliasByMac[mac]
+		case lldpName != "":
+			// #931: sin lease ni alias, el nombre anunciado por el
+			// propio equipo (LLDP sysName) es la mejor etiqueta.
+			port.ConnectedTo = lldpName
+			if lldpMgmt != "" {
+				port.Detail = lldpMgmt + " · LLDP"
+			}
+		default:
+			port.ConnectedTo = mac
+		}
+		port.DeviceMac = mac
+		if ok && lease.IP != "" {
+			port.Detail = lease.IP + " · full duplex"
+		}
+		return port
+	}
+	// 3) Varios: el vecino es un switch/hub/hipervisor
+	if len(all) > 1 {
+		// Muchas MACs detrás de una boca = agregación (hipervisor Proxmox
+		// con CTs, switch tonto): nombrar UN CT al azar engaña (la MAC es
+		// virtual, no el equipo enchufado). La label curada del puerto ya
+		// identifica el físico; aquí se cuenta lo que hay detrás (#291).
+		if len(all) > 3 {
+			// deviceCount lo traduce la app; aquí NO se formatea texto (#1036).
+			port.DeviceCount = len(all)
+		return port
+		}
+		// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
+		// es mejor pista que el hostname DHCP.
+		if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil && nb.displayName() != "" {
+			port.ConnectedTo = nb.displayName()
+			if nb.Mgmt != "" {
+				port.Detail = nb.Mgmt + " · LLDP"
+			} else {
+				port.Detail = "LLDP"
+			}
+		return port
+		}
+		infraMac := ""
+		for _, mac := range all {
+			if le, ok := d.leaseMap[mac]; ok && le.Hostname != "" {
+				infraMac = mac
+				break
+			}
+		}
+		if infraMac == "" {
+			// Sin hostname DHCP: primer alias manual como pista (#291).
+			for _, mac := range all {
+				if d.aliasByMac[mac] != "" {
+					infraMac = mac
+					break
+				}
+			}
+		}
+		if infraMac != "" {
+			if lease, ok := d.leaseMap[infraMac]; ok && lease.Hostname != "" {
+				port.ConnectedTo = lease.Hostname
+				port.DeviceMac = infraMac
+				if lease.IP != "" {
+					port.Detail = lease.IP
+				}
+			} else if alias := d.aliasByMac[infraMac]; alias != "" {
+				port.ConnectedTo = alias
+				port.DeviceMac = infraMac
+			}
+		} else {
+			// Switch/bridge tonto inferido: sin lease ni alias que lo
+			// nombre. El cliente traduce la etiqueta (#1039/#1040).
+			port.PeerKind = "inferred-switch"
+		}
+		return port
+	}
+	return port
+}

+ 47 - 0
server-go/internal/adapters/live_wanstats_test.go

@@ -94,3 +94,50 @@ func TestWanDayStatsSinBD(t *testing.T) {
 		t.Fatalf("sin BD debería devolver zeros/'—': %+v", res)
 	}
 }
+
+// latencySpark24h: solo muestras con sonda (latency_ms NOT NULL) dentro de
+// la ventana 24h, en orden (#1148).
+func TestLatencySpark24h(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := &Live{db: d, now: fixedNow}
+	now := fixedNow()
+
+	insertLatency := func(ts time.Time, lat *float64) {
+		t.Helper()
+		if lat != nil {
+			if _, err := d.Exec(
+				"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES ('gw', ?, 0,0,0, ?, 0, 0)",
+				ts.UnixMilli(), *lat); err != nil {
+				t.Fatalf("insert: %v", err)
+			}
+			return
+		}
+		// Muestra sin sonda (latency_ms NULL): no debe entrar en la serie.
+		if _, err := d.Exec(
+			"INSERT INTO metrics (router_id, ts, cpu, ram, temp, rx_bps, tx_bps) VALUES ('gw', ?, 0,0,0, 0, 0)",
+			ts.UnixMilli()); err != nil {
+			t.Fatalf("insert null: %v", err)
+		}
+	}
+	f := func(v float64) *float64 { return &v }
+
+	insertLatency(now.Add(-25*time.Hour), f(99)) // fuera de ventana
+	insertLatency(now.Add(-3*time.Hour), f(20))
+	insertLatency(now.Add(-2*time.Hour), f(12.5))
+	insertLatency(now.Add(-1*time.Hour), nil) // NULL: fuera
+	insertLatency(now.Add(-30*time.Minute), f(25))
+	// Otra unidad: no contamina.
+	if _, err := d.Exec(
+		"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES ('rt2', ?, 0,0,0, 77, 0, 0)",
+		now.Add(-2*time.Hour).UnixMilli()); err != nil {
+		t.Fatalf("insert rt2: %v", err)
+	}
+
+	got := l.latencySpark24h("gw")
+	if len(got) != 3 {
+		t.Fatalf("len=%d, want 3 muestras en ventana con sonda", len(got))
+	}
+	if got[0] != 20 || got[1] != 12.5 || got[2] != 25 {
+		t.Fatalf("serie = %v, want [20 12.5 25] en orden temporal", got)
+	}
+}

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

@@ -401,6 +401,50 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 			continue
 		}
 		n := inv.nodes[key]
+		host := &devices[idx]
+		// #1053: si L2 infirió un nodo "inferred" en el (router, puerto) del
+		// host y TODO lo colgado de él es el host o sus invitados, ese
+		// círculo es redundante con la ground truth PVE: se absorbe. El host
+		// pasa a colgar DIRECTAMENTE del router con su puerto (igual que el
+		// hipervisor del canon demo) y el distnode PVE que se crea abajo
+		// queda como agrupación de CTs, no como nodo dibujado extra.
+		guests := map[string]bool{id: true}
+		for i := range devices {
+			if devices[i].AttachTo == id {
+				guests[devices[i].ID] = true
+			}
+		}
+		absorbed := ""
+		for di := range dists {
+			dn := &dists[di]
+			if dn.Kind != "inferred" || dn.RouterID != host.RouterID ||
+				dn.Port == "" || host.Port == "" || dn.Port != host.Port {
+				continue
+			}
+			explained := true
+			for i := range devices {
+				if devices[i].AttachTo == dn.ID && !guests[devices[i].ID] {
+					explained = false
+					break
+				}
+			}
+			if !explained {
+				continue
+			}
+			absorbed = dn.ID
+			dn.Kind = "absorbed" // se filtra al salir del bucle
+			break
+		}
+		if absorbed != "" {
+			if host.AttachTo == absorbed {
+				host.AttachTo = ""
+			}
+			for i := range devices {
+				if devices[i].AttachTo == absorbed {
+					devices[i].AttachTo = id
+				}
+			}
+		}
 		dists = append(dists, DistributionNode{
 			ID: "dist-pve-" + n.Instance + "-" + n.Node, Kind: "hypervisor",
 			RouterID: devices[idx].RouterID, Port: devices[idx].Port, PortLabel: devices[idx].PortLabel,
@@ -408,7 +452,14 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 			Source: "proxmox", Instance: n.Instance,
 		})
 	}
-	return dists
+	// #1053: retirar los nodos inferred absorbidos por un host PVE.
+	kept := dists[:0]
+	for _, dn := range dists {
+		if dn.Kind != "absorbed" {
+			kept = append(kept, dn)
+		}
+	}
+	return kept
 }
 
 // looksLikeMACName: true si el nombre del device es una MAC (no tiene nombre

+ 59 - 0
server-go/internal/adapters/proxmox_test.go

@@ -568,3 +568,62 @@ func TestSealProxmoxTypesEveryGuest(t *testing.T) {
 		}
 	}
 }
+
+// TestPVEAbsorbeInferredDeHypervisor: cuando L2 infirió un nodo "inferred" en
+// el (router, puerto) del host PVE y todo lo colgado es el host o sus
+// invitados (#1053), el inferred se absorbe: el host pasa a colgar del router
+// con su puerto (como el canon) y solo queda el distnode PVE de agrupación.
+func TestPVEAbsorbeInferredDeHypervisor(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
+			"02:78:F4:02:8A:94": {Name: "ha", Node: "citadel-01", Type: "lxc", Instance: "default"},
+		},
+		nodes:   map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
+		nodeIPs: map[string][]string{"default|citadel-01": {"192.168.1.100"}},
+	}
+	devices := []Device{
+		{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "C8:FF:BF:0C:60:12", IP: "192.168.1.100",
+			RouterID: "switch16", Port: "lan5", AttachTo: "dist-switch16-lan5", Online: true},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", AttachTo: "dist-switch16-lan5"},
+		{ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "ha", AttachTo: "dist-switch16-lan5"},
+	}
+	dists := []DistributionNode{{ID: "dist-switch16-lan5", Kind: "inferred", RouterID: "switch16", Port: "lan5", MacCount: 3}}
+	out := applyPVEInfra(devices, dists, inv)
+	if len(out) != 1 || out[0].Kind != "hypervisor" || out[0].ID != "dist-pve-default-citadel-01" {
+		t.Fatalf("distnodes = %+v (want solo el distnode PVE)", out)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("host AttachTo=%q (want vacío: cuelga del router con su puerto)", devices[0].AttachTo)
+	}
+	if devices[1].AttachTo != devices[0].ID || devices[2].AttachTo != devices[0].ID {
+		t.Fatalf("CTs no re-anidados bajo el host: %+v", devices)
+	}
+}
+
+// TestPVENoAbsorbeInferredConDesconocidos: si en el puerto inferred hay algo
+// que NO es el host ni un invitado, el nodo inferred se conserva (hay
+// hardware real sin explicar detrás).
+func TestPVENoAbsorbeInferredConDesconocidos(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
+		},
+		nodes:   map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
+		nodeIPs: map[string][]string{"default|citadel-01": {"192.168.1.100"}},
+	}
+	devices := []Device{
+		{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "C8:FF:BF:0C:60:12", IP: "192.168.1.100",
+			RouterID: "switch16", Port: "lan5", AttachTo: "dist-switch16-lan5", Online: true},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", AttachTo: "dist-switch16-lan5"},
+		{ID: "a4-d5-c2-05-ef-66", MAC: "A4:D5:C2:05:EF:66", Name: "equipo-suelto", AttachTo: "dist-switch16-lan5"},
+	}
+	dists := []DistributionNode{{ID: "dist-switch16-lan5", Kind: "inferred", RouterID: "switch16", Port: "lan5", MacCount: 3}}
+	out := applyPVEInfra(devices, dists, inv)
+	if len(out) != 2 || out[0].ID != "dist-switch16-lan5" || out[0].Kind != "inferred" {
+		t.Fatalf("el inferred con desconocidos debe conservarse: %+v", out)
+	}
+	if devices[0].AttachTo != "dist-switch16-lan5" {
+		t.Fatalf("host AttachTo=%q (want sin cambios)", devices[0].AttachTo)
+	}
+}

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

@@ -99,6 +99,15 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		l.recordSnmpSuccess(cfg)
 	}
 
+	// #931: vecinos LLDP del switch vía LLDP-MIB (mismo contrato que la
+	// sonda lldpd de los routers, #300). Alimenta routerPolled.lldp y con
+	// ello la fase LLDP-first de la topología (inferLldpLinks). Un switch
+	// sin LLDP devuelve (nil, nil) sin ruido; el error solo se loguea.
+	lldpRem, lldpErr := npsnmp.PollLldpRemTable(session)
+	if lldpErr != nil {
+		log.Printf("[netpulse] SNMP LLDP %s: %v", cfg.LogLabel(), lldpErr)
+	}
+
 	portIdxToName := map[int]string{}
 	for _, p := range ports {
 		portIdxToName[p.Index] = p.DisplayName()
@@ -114,6 +123,7 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 			Up:      p.OperUp,
 			Speed:   p.SpeedString(),
 			Iface:   name,
+			Family:  p.Family,
 			RxBytes: p.RxBytes,
 			TxBytes: p.TxBytes,
 			RxErrs:  p.RxErrors,
@@ -178,6 +188,7 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		ports:     ethPorts,
 		fdb:       fdbMap,
 		brMac:     brMac,
+		lldp:      snmpLldpNeighbors(lldpRem, portIdxToName),
 		polledAt:  now.UnixMilli(),
 	}
 	l.mu.Lock()
@@ -404,6 +415,36 @@ func snmpFdbMap(fdb []npsnmp.FdbEntry, portIdxToName map[int]string) map[string]
 	return out
 }
 
+// snmpLldpNeighbors convierte los vecinos LLDP-MIB del switch al contrato
+// LldpNeighbor (#931). El puerto se nombra como en el FDB (DisplayName del
+// ifTable vía ifIndex; fallback al número de puerto de bridge, paridad con
+// snmpFdbMap #661) para que inferLldpLinks case el vecino con las MACs
+// aprendidas en esa boca.
+func snmpLldpNeighbors(rem []npsnmp.LldpRemEntry, portIdxToName map[int]string) []LldpNeighbor {
+	if len(rem) == 0 {
+		return nil
+	}
+	out := make([]LldpNeighbor, 0, len(rem))
+	for _, e := range rem {
+		port := portIdxToName[e.IfIndex]
+		if port == "" {
+			port = portIdxToName[e.LocalPortNum]
+		}
+		if port == "" {
+			port = fmt.Sprintf("port-%d", e.LocalPortNum)
+		}
+		out = append(out, LldpNeighbor{
+			Port:       port,
+			ChassisMac: e.ChassisMac,
+			Chassis:    e.Chassis,
+			Mgmt:       e.Mgmt,
+			Caps:       e.Caps,
+			PortDesc:   e.PortDesc,
+		})
+	}
+	return out
+}
+
 // snmpAggregateNet suma la tasa (bps) de todos los puertos para dar una
 // métrica agregada al switch SNMP (#661). Devuelve nil si todo está a 0
 // (primera muestra sin delta o sin tráfico).

+ 71 - 5
server-go/internal/adapters/topo_semantics.go

@@ -16,7 +16,10 @@
 //     generan enlace (la app los agrupa en su chip "+N" de peers).
 package adapters
 
-import "strings"
+import (
+	"sort"
+	"strings"
+)
 
 // Capacidad de los anillos canónicos de model.ts (GATEWAY_RINGS 8+12+16+24,
 // AP_RINGS 8+14+18): el límite de chips visibles por anillo que aplica la app.
@@ -34,7 +37,49 @@ const maxTopoPeerChips = 4
 
 // BuildTopoSemantics deriva enlaces, anillos y peers ocultos del mismo bundle
 // que hoy consume la app (routers, devices, wireguard, distributionNodes).
-func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode, wanGateway string) *TopoSemantics {
+// topoParent (#1047/#1051): padre de uplink de una unidad de flota derivado
+// de evidencia FDB (en qué equipo se aprendió su MAC y en qué puerto).
+type topoParent struct {
+	parent string
+	port   string
+}
+
+// fleetFdbEvidence (#1051): para cada router de la flota, ¿en qué OTRO miembro
+// se aprendió su MAC bridge y en qué puerto? Fuente directa del FDB de cada
+// poller, sin pasar por la atribución a devices (que no existe en redes donde
+// las unidades no aparecen como clientes). Orden determinista: ids ordenados,
+// primer padre candidato gana.
+func fleetFdbEvidence(polled map[string]*routerPolled) map[string]topoParent {
+	macs := map[string]string{} // MAC bridge (upper) → router propietario
+	ids := make([]string, 0, len(polled))
+	for id, p := range polled {
+		if p == nil || p.brMac == "" {
+			continue
+		}
+		macs[strings.ToUpper(p.brMac)] = id
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	out := map[string]topoParent{}
+	for _, sid := range ids {
+		p := polled[sid]
+		if p == nil {
+			continue
+		}
+		for mac, port := range p.fdb {
+			rid, ok := macs[strings.ToUpper(mac)]
+			if !ok || rid == sid {
+				continue
+			}
+			if _, seen := out[rid]; !seen {
+				out[rid] = topoParent{parent: sid, port: port}
+			}
+		}
+	}
+	return out
+}
+
+func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode, wanGateway string, fdbEvidence map[string]topoParent) *TopoSemantics {
 	sem := &TopoSemantics{Links: []TopoLink{}, Rings: map[string][]string{}}
 	if len(routers) == 0 {
 		return sem
@@ -90,13 +135,13 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 			routerMacs[strings.ToUpper(r.MAC)] = r.ID
 		}
 	}
-	uplinkEvidence := map[string]struct{ parent, port string }{}
+	uplinkEvidence := map[string]topoParent{}
 	filtered := online[:0]
 	for _, d := range online {
 		if rid, ok := routerMacs[strings.ToUpper(d.MAC)]; ok {
 			if rid != d.RouterID {
 				if _, seen := uplinkEvidence[rid]; !seen {
-					uplinkEvidence[rid] = struct{ parent, port string }{d.RouterID, d.Port}
+					uplinkEvidence[rid] = topoParent{parent: d.RouterID, port: d.Port}
 				}
 			}
 			continue
@@ -104,6 +149,14 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 		filtered = append(filtered, d)
 	}
 	online = filtered
+	// #1051: la evidencia FDB directa del poller cubre las redes donde las
+	// unidades de flota NO aparecen como devices; la atribución de device
+	// (attachTo/override) manda cuando existe.
+	for rid, ev := range fdbEvidence {
+		if _, ok := uplinkEvidence[rid]; !ok {
+			uplinkEvidence[rid] = ev
+		}
+	}
 	// #1042: el equipo aguas arriba del gateway (módem/ONT del ISP) se
 	// descubre por ARP como un cliente más, pero vive en el lado WAN: si su
 	// IP coincide con la puerta de enlace WAN se representa bajo el nodo
@@ -202,7 +255,20 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 				port = ev.port
 			}
 		}
-		sem.Links = append(sem.Links, TopoLink{From: parent, To: ap.ID, Kind: "uplink", Port: port})
+		// #1060: si el puerto de la evidencia tiene un distnode (inferred o
+		// managed) en ese router, el uplink sale del CÍRCULO, no del router:
+		// gateway -> (switch inferido, lan1) -> AP. Sin esto el enlace salta
+		// por encima del círculo y el cableado real no se reconoce.
+		from := parent
+		if port != "" {
+			for _, dn := range dists {
+				if dn.RouterID == parent && (dn.Kind == "inferred" || dn.Kind == "managed") && dn.Port == port {
+					from = dn.ID
+					break
+				}
+			}
+		}
+		sem.Links = append(sem.Links, TopoLink{From: from, To: ap.ID, Kind: "uplink", Port: port})
 	}
 	// router → distnode (solo inferred|managed son hubs propios en el mapa).
 	// En una cadena LLDP switch→switch (issue #300) el distnode cuelga de su

+ 110 - 8
server-go/internal/adapters/topo_semantics_test.go

@@ -23,7 +23,7 @@ import (
 //   - hiddenPeers ausente: todos los anillos bajo el límite de chips visibles
 //     de la app (gateway 13, AP 20)
 func TestTopoSemanticsGoldenCanon(t *testing.T) {
-	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
+	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "", nil)
 
 	wantLinks := []TopoLink{
 		{From: "internet", To: "flint2", Kind: "wan"},
@@ -109,7 +109,7 @@ func TestTopoSemanticsHiddenPeers(t *testing.T) {
 			RouterID: "ap", Band: "2.4 GHz", Online: true,
 		})
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	want := map[string]int{"gw": 2, "ap": 2} // 62-60 y 42-40
 	if !reflect.DeepEqual(sem.HiddenPeers, want) {
 		t.Fatalf("hiddenPeers: got %+v want %+v", sem.HiddenPeers, want)
@@ -133,7 +133,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 		t.Fatal("overview.Topology ausente en demo")
 	}
 	// Mismo resultado que el builder puro sobre el canon.
-	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
+	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "", nil)
 	if !reflect.DeepEqual(ov.Topology, want) {
 		t.Fatalf("overview.Topology != builder canon:\n got: %+v\nwant: %+v", ov.Topology, want)
 	}
@@ -141,7 +141,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 
 // Sin routers: semántica vacía pero no nil (la app cae a su cálculo propio).
 func TestTopoSemanticsSinRouters(t *testing.T) {
-	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil, "", nil)
 	if sem == nil || sem.Links == nil || sem.Rings == nil {
 		t.Fatalf("semántica vacía debe tener links/rings no-nil: %+v", sem)
 	}
@@ -161,7 +161,7 @@ func TestTopoSemanticsDeviceHubBajoDistnode(t *testing.T) {
 	}
 	routers := []Router{{ID: "gateway", Name: "gateway", RoleBadge: "Principal", Status: "online"}}
 	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred", RouterID: "gateway", Port: "lan1"}}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "", nil)
 
 	var toHost []TopoLink
 	for _, l := range sem.Links {
@@ -201,7 +201,7 @@ func TestTopoSemanticsWanPeer(t *testing.T) {
 		{ID: "modem", MAC: "AA:BB:CC:00:00:01", RouterID: "gw", Band: "cable", Online: true, IP: "100.64.0.1"},
 		{ID: "nas", MAC: "AA:BB:CC:00:00:02", RouterID: "gw", Band: "cable", Online: true, IP: "192.168.1.10"},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "100.64.0.1")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "100.64.0.1", nil)
 	if sem.WanPeer != "modem" {
 		t.Fatalf("WanPeer = %q, want modem", sem.WanPeer)
 	}
@@ -223,7 +223,7 @@ func TestTopoSemanticsWanPeer(t *testing.T) {
 		t.Fatal("falta el enlace internet→modem (wan-peer)")
 	}
 	// Sin gateway WAN no hay wan peer aunque haya dispositivos.
-	sem2 := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem2 := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	if sem2.WanPeer != "" {
 		t.Fatalf("WanPeer sin gateway WAN = %q, want vacío", sem2.WanPeer)
 	}
@@ -244,7 +244,7 @@ func TestTopoSemanticsFdbUplinkParent(t *testing.T) {
 		{ID: "dev-ap1", MAC: "AA:BB:CC:00:00:03", RouterID: "sw1", Band: "cable", Online: true, Port: "5"},
 		{ID: "nas", MAC: "AA:BB:CC:00:00:09", RouterID: "gw", Band: "cable", Online: true, Port: "2"},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", nil)
 	links := map[string]TopoLink{}
 	for _, l := range sem.Links {
 		if l.Kind == "uplink" {
@@ -266,3 +266,105 @@ func TestTopoSemanticsFdbUplinkParent(t *testing.T) {
 		}
 	}
 }
+
+// #1051: el anclaje FDB no debe depender de que las unidades de flota
+// aparezcan como devices: la evidencia directa del poller basta.
+func TestTopoSemanticsFdbEvidenceSinDevices(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "sw1", Name: "sw1", MAC: "AA:BB:CC:00:00:02"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	devices := []Device{
+		{ID: "nas", MAC: "AA:BB:CC:00:00:09", RouterID: "gw", Band: "cable", Online: true, Port: "2"},
+	}
+	ev := map[string]topoParent{
+		"sw1": {parent: "gw", port: "1"},
+		"ap1": {parent: "sw1", port: "5"},
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", ev)
+	links := map[string]TopoLink{}
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" {
+			links[l.To] = l
+		}
+	}
+	if got := links["ap1"]; got.From != "sw1" || got.Port != "5" {
+		t.Fatalf("uplink ap1: %+v, want from sw1 puerto 5", got)
+	}
+	if got := links["sw1"]; got.From != "gw" || got.Port != "1" {
+		t.Fatalf("uplink sw1: %+v, want from gw puerto 1", got)
+	}
+}
+
+// #1051: la evidencia de device (attachTo/atribución) manda sobre la FDB
+// directa cuando ambas existen.
+func TestTopoSemanticsDeviceEvidenceManda(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	devices := []Device{
+		{ID: "dev-ap1", MAC: "AA:BB:CC:00:00:03", RouterID: "gw", Band: "cable", Online: true, Port: "4"},
+	}
+	ev := map[string]topoParent{"ap1": {parent: "swX", port: "9"}}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "", ev)
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" && l.To == "ap1" {
+			if l.From != "gw" || l.Port != "4" {
+				t.Fatalf("la evidencia de device debe mandar: %+v", l)
+			}
+			return
+		}
+	}
+	t.Fatal("falta el uplink de ap1")
+}
+
+// #1051: fleetFdbEvidence deriva el padre del FDB crudo de cada poller.
+func TestFleetFdbEvidence(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"gw":  {brMac: "aa:bb:cc:00:00:01", fdb: map[string]string{"AA:BB:CC:00:00:02": "1"}},
+		"sw1": {brMac: "AA:BB:CC:00:00:02", fdb: map[string]string{"AA:BB:CC:00:00:03": "5"}},
+		"ap1": {brMac: "AA:BB:CC:00:00:03", fdb: map[string]string{}},
+	}
+	ev := fleetFdbEvidence(polled)
+	if got := ev["sw1"]; got.parent != "gw" || got.port != "1" {
+		t.Fatalf("sw1: %+v, want gw/1", got)
+	}
+	if got := ev["ap1"]; got.parent != "sw1" || got.port != "5" {
+		t.Fatalf("ap1: %+v, want sw1/5", got)
+	}
+	if _, ok := ev["gw"]; ok {
+		t.Fatal("gw no debe tener padre (cuelga de internet)")
+	}
+}
+
+// #1060: el uplink sale del distnode (círculo inferido/gestionado) cuando el
+// puerto de la evidencia coincide con su (router, puerto): gateway -> círculo
+// -> AP, sin saltarse el switch intermedio.
+func TestTopoSemanticsUplinkViaDistNode(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal", MAC: "AA:BB:CC:00:00:01"},
+		{ID: "ap1", Name: "ap1", MAC: "AA:BB:CC:00:00:03"},
+	}
+	devices := []Device{
+		{ID: "nas", MAC: "AA:BB:CC:00:00:09", RouterID: "gw", Band: "cable", Online: true, Port: "2"},
+	}
+	dists := []DistributionNode{
+		{ID: "dist-gw-lan1", RouterID: "gw", Kind: "inferred", Port: "lan1"},
+	}
+	ev := map[string]topoParent{"ap1": {parent: "gw", port: "lan1"}}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "", ev)
+	found := false
+	for _, l := range sem.Links {
+		if l.Kind == "uplink" && l.To == "ap1" {
+			found = true
+			if l.From != "dist-gw-lan1" {
+				t.Fatalf("uplink ap1: from = %q, want dist-gw-lan1 (%+v)", l.From, l)
+			}
+		}
+	}
+	if !found {
+		t.Fatal("falta el uplink de ap1")
+	}
+}

+ 1 - 1
server-go/internal/adapters/topology_lldp_test.go

@@ -225,7 +225,7 @@ func TestTopoSemanticsCadenaLldp(t *testing.T) {
 		{RouterID: "flint2", Band: "cable", Port: "lan3", ID: "pc1", MAC: "04:D4:C4:8B:30:A7", AttachTo: "dist-flint2-lan3", Online: true},
 		{RouterID: "swA", Band: "cable", Port: "ge5", ID: "pc2", MAC: "DC:A6:32:4F:77:02", AttachTo: "dist-swA-ge5", Online: true},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "", nil)
 
 	var gotDist []TopoLink
 	for _, l := range sem.Links {

+ 36 - 2
server-go/internal/adapters/types.go

@@ -161,12 +161,15 @@ type Router struct {
 	// (sin SSH). El frontend lo usa para marcar "agente no instalado" cuando
 	// no hay agente registrado (certeza: el router no es sondeable por SSH).
 	AgentOnly bool `json:"agentOnly,omitempty"`
+	// Disabled (issue #1085): unidad pausada (no se sondea ni alerta; el
+	// status llega como "paused" y la UI la excluye de los desplegables).
+	Disabled bool `json:"disabled,omitempty"`
 	// SelfExpose (#832): el equipo se expone ÉL MISMO a Home Assistant por
 	// MQTT (NetGrip con su MQTT activado). El publisher de flota NO crea
 	// dispositivo ni entidades por router en ese caso. Ausente = no se
 	// expone (lo hace NetPulse).
 	SelfExpose *bool `json:"selfExpose,omitempty"`
-	// Type: "glinet"|"openwrt"|"managed-switch"|"external". El frontend lo usa
+	// Type: "glinet"|"openwrt"|"routeros"|"managed-switch"|"external". El frontend lo usa
 	// para NO ofrecer reinstall/upgrade de agentes en dispositivos que no usan
 	// el agente nativo (scrapers de switches, etc.).
 	Type   string `json:"type,omitempty"`
@@ -295,6 +298,9 @@ type Device struct {
 	// server NO pre-formatea (lección #899).
 	FirstSeenMs  int64  `json:"firstSeenMs,omitempty"`
 	LastSeenMs   int64  `json:"lastSeenMs,omitempty"`
+	// AliasMacs: MACs enlazadas a este cliente (#1151, mismo dispositivo con
+	// varias MACs - p. ej. una por SSID). Solo viaja en el canónico.
+	AliasMacs []string `json:"aliasMacs,omitempty"`
 	Traffic24hRx string `json:"traffic24hRx,omitempty"`
 	Traffic24hTx string `json:"traffic24hTx,omitempty"`
 	Adguard      *bool  `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)
@@ -561,6 +567,10 @@ type EthPort struct {
 	Up          bool     `json:"up"`
 	Speed       string   `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
 	Iface       string   `json:"iface,omitempty"` // iface física (/proc/net/dev)
+	// #1125: familia para interfaces NO físicas ("lag"|"vlan"|"bridge"|
+	// "tunnel"|"virtual"); vacío/ausente = boca física. El frontend las
+	// agrupa en la sección colapsada de la tarjeta de puertos.
+	Family      string   `json:"family,omitempty"`
 	RxBytes     uint64   `json:"rxBytes,omitempty"`
 	TxBytes     uint64   `json:"txBytes,omitempty"`
 	RxErrs      uint64   `json:"rxErrors,omitempty"`
@@ -606,6 +616,20 @@ type Radio struct {
 // Radios: nil → null (demo sin radios), no-nil vacío → [] (live). Quirk SPEC.
 // Backhaul y Extras son `any`: la demo tiene objetos ricos canónicos
 // (routerExtras, dataset.js) y el live construye los suyos (SPEC §7.8).
+// FdbUplink: el router (hijo) se aprende en el puerto Port del router
+// ParentID. Evidencia directa del FDB de los pollers (#1051).
+type FdbUplink struct {
+	ChildID  string `json:"childId"`
+	ParentID string `json:"parentId"`
+	Port     string `json:"port"`
+}
+
+// FleetFdbProvider lo implementan los adapters capaces de exponer la
+// evidencia FDB de uplinks de flota (live).
+type FleetFdbProvider interface {
+	FleetFdbUplinks() map[string]FdbUplink
+}
+
 type RouterDetail struct {
 	Router   Router     `json:"router"`
 	Ports    []EthPort  `json:"ports"`
@@ -883,7 +907,7 @@ type RouterConfig struct {
 	ID        string `json:"id"`
 	Name      string `json:"name"`
 	Host      string `json:"host"`
-	Type      string `json:"type"` // "glinet"|"openwrt"
+	Type      string `json:"type"` // "glinet"|"openwrt"|"routeros"
 	IsGateway bool   `json:"is_gateway"`
 	AgentOnly bool   `json:"agent_only"`
 	CreatedAt int64  `json:"created_at"` // epoch ms
@@ -897,6 +921,10 @@ type RouterConfig struct {
 	SnmpCommunity    string `json:"snmp_community,omitempty"`
 	SnmpPort         int    `json:"snmp_port,omitempty"`
 	SnmpPollInterval int    `json:"snmp_poll_interval,omitempty"` // segundos; 0 → default 60
+	// Disabled (issue #1085): unidad pausada. No se sondea (SSH/SNMP/agente),
+	// no alerta y queda fuera de los desplegables de la UI; el histórico se
+	// conserva y la insignia "paused" la distingue en la lista de flota.
+	Disabled bool `json:"disabled"`
 	// ConsolePolling (issue #863): sondeo HTTP de la consola RTLPlayground del
 	// switch. true (default) = el server logra en la consola para fw/uptime/MAC;
 	// false = nunca (el firmware tiene una sola sesión global y cada login
@@ -909,6 +937,12 @@ type RouterConfig struct {
 	// de este router. NULL/ausente = DefaultTempThreshold (65). Un router que
 	// corre más caliente sube el suyo sin ocultar problemas en los más frescos.
 	TempThreshold *int `json:"temp_threshold,omitempty"`
+	// RouterOS: credenciales de la REST API nativa (Type "routeros"). User no
+	// es secreto; Password nunca se serializa de vuelta (json:"-"), igual que
+	// la clave privada ed25519 del servidor.
+	RouterOSUser     string `json:"routeros_user,omitempty"`
+	RouterOSPassword string `json:"-"`
+	RouterOSInsecure bool   `json:"routeros_insecure"` // acepta TLS autofirmado (RouterOS de fábrica)
 }
 
 // TempThresholdValue resuelve el umbral efectivo de temperatura alta (°C) de

+ 65 - 5
server-go/internal/alerts/alerts.go

@@ -187,6 +187,10 @@ type Engine struct {
 	mu       sync.Mutex
 	db       *db.DB // nil → solo memoria (tests)
 	notifier Notifier
+	// startedAt: arranque de ESTA instancia. Las alertas con Ts anterior a
+	// startedAt vienen de una sesión previa: si se re-emiten (update), es
+	// un episodio nuevo tras el reinicio y vuelven a no-leídas (#1094).
+	startedAt time.Time
 	now      func() time.Time
 
 	cfg        map[string]string
@@ -228,6 +232,7 @@ func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
 		db:         d,
 		notifier:   n,
 		now:        time.Now,
+		startedAt:  time.Now(),
 		cfg:        DefaultConfig(),
 		dedup:      map[string]int64{},
 		readSet:    map[string]bool{},
@@ -273,6 +278,10 @@ func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
 		}
 		e.purgeVolatileHistoryLocked()
 		e.loadPersistedLocked()
+		// #1034: poda por antigüedad al arrancar (además de la horaria de
+		// main): una retención bajada mientras el daemon estaba parado se
+		// aplica en el primer arranque posterior.
+		e.PruneLogByRetention()
 	}
 	return e
 }
@@ -589,13 +598,45 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 		e.mu.Unlock()
 		return false
 	}
+	// #1074: mismo default de Ts/Time que en Emit (#914) ANTES de insertar y
+	// notificar. La rama de inserción pasaba la `ev` original a Notify: si el
+	// emisor no fijaba Ts (p. ej. agent-outdated), el notifier recibía Ts=0
+	// y el push pintaba la hora estática 16:00:00 (epoch en zona UTC-8).
+	if ev.Ts == 0 {
+		ev.Ts = e.now().Unix()
+	}
+	if ev.Time == "" {
+		ev.Time = "just now"
+	}
 	now := e.now()
 	for i := range e.list {
 		if e.list[i].ID == ev.ID {
 			old := e.list[i]
 			ev.Ts = now.Unix()
 			ev.Time = "just now"
-			ev.Read = old.Read
+			// #1094: episodio nuevo tras reinicio (la alerta no se había
+			// refrescado desde el arranque): vuelve a no-leída, que el
+			// humano la vea. Un refresh de episodio en curso (p. ej. port
+			// flapping, que re-emite cada ciclo) conserva su read.
+			if old.Ts >= e.startedAt.Unix() {
+				ev.Read = old.Read
+			} else {
+				// #1094: Read se DERIVA de readSet en List(), y el kv guarda
+				// readOrd: hay que purgar ambos (y el espejo en alert_log)
+				// o la alerta reviviría leída.
+				ev.Read = false
+				delete(e.readSet, ev.ID)
+				for j, rid := range e.readOrd {
+					if rid == ev.ID {
+						e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
+						break
+					}
+				}
+				e.saveReadLocked()
+				if e.db != nil {
+					_, _ = e.db.Exec("UPDATE alert_log SET read_flag = 0 WHERE id = ?", ev.ID)
+				}
+			}
 			if ev.RouterID == "" {
 				ev.RouterID = old.RouterID
 			}
@@ -811,7 +852,11 @@ func (e *Engine) idInListLocked(id string) bool {
 	return false
 }
 
-// MarkAllRead marca leídas todas las alertas actuales.
+// MarkAllRead marca leídas todas las alertas actuales (#1034): SOLO toca el
+// read-set (persistido en kv y espejado en alert_log.read_flag). NO borra
+// nada de alert_log ni del conjunto dismissed: el feed sigue mostrando las
+// alertas como leídas y el toggle "Solo no leídas" es lo que limpia la vista.
+// Vaciar el log es la acción destructiva aparte (DismissAll).
 func (e *Engine) MarkAllRead() {
 	e.mu.Lock()
 	ids := make([]string, 0, len(e.list))
@@ -864,9 +909,10 @@ func (e *Engine) Dismiss(ids ...string) {
 	e.list = kept
 }
 
-// DismissAll limpia TODAS las alertas del feed (issue #971, botón "Marcar
-// todo como leído"): equivale a Dismiss sobre cada ID presente en la lista.
-// Las persistentes se borran de alert_log y su ID queda en el conjunto
+// DismissAll limpia TODAS las alertas del feed: equivale a Dismiss sobre
+// cada ID presente en la lista. Es la acción destructiva "Vaciar registro"
+// (#1034; antes el botón "Marcar todo como leído" la invocaba, #971). Las
+// persistentes se borran de alert_log y su ID queda en el conjunto
 // dismissed (kv), así que el feed vacío sobrevive a un reload; las volátiles
 // (agent-down) también salen, pero si su condición sigue viva el emisor las
 // re-emite con el mismo ID y vuelven (semántica "alerta viva": lo que no
@@ -916,6 +962,20 @@ func (e *Engine) Resolve(id string) {
 			break
 		}
 	}
+	// #1107: la alerta resuelta es un episodio CERRADO. El read-set es
+	// append-only (kv readOrd) y sobrevivía al Resolve: si la condición se
+	// re-dispara con el mismo ID estable (p. ej. "Agent outdated" tras
+	// actualizar el server y quedar otra vez desactualizado), el episodio
+	// nuevo heredaba el leído viejo en List()/UnreadCount(). Mismo criterio
+	// que Remove (#846): al cerrarse, se olvida el leído.
+	delete(e.readSet, id)
+	for j, rid := range e.readOrd {
+		if rid == id {
+			e.readOrd = append(e.readOrd[:j], e.readOrd[j+1:]...)
+			break
+		}
+	}
+	e.saveReadLocked()
 	if e.db != nil {
 		_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
 	}

+ 146 - 0
server-go/internal/alerts/alerts_test.go

@@ -279,6 +279,152 @@ func TestSeedSkipsConfigButKeepsDedup(t *testing.T) {
 	}
 }
 
+
+// TestEmitOrUpdateReepisodeAfterRestart (#1094): una alerta leída en una
+// sesión previa que se re-emite tras el arranque (p. ej. "Agent outdated"
+// al reiniciar el server) vuelve a NO-leída: es un episodio nuevo y el
+// humano debe verla. Un refresh del mismo episodio (Ts posterior al
+// arranque, p. ej. port flapping) conserva su read.
+func TestEmitOrUpdateReepisodeAfterRestart(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer d.Close()
+
+	// Sesión 1: la alerta se emite y el humano la marca leída.
+	e1 := New(d, nil)
+	if !e1.EmitOrUpdate(ev("r1", CatSystem, false)) {
+		t.Fatal("insert sesión 1")
+	}
+	e1.MarkRead("r1")
+	if !e1.List()[0].Read {
+		t.Fatal("setup: r1 debería estar leída en la sesión 1")
+	}
+
+	// "Reinicio": engine nuevo sobre la MISMA bd (el log persiste read=1).
+	// startedAt se adelanta para simular un arranque posterior de verdad:
+	// todo el test ocurre dentro del mismo segundo unix.
+	e2 := New(d, nil)
+	e2.startedAt = time.Now().Add(2 * time.Second)
+	if got := e2.List(); len(got) != 1 || !got[0].Read {
+		t.Fatalf("restore: %+v", got)
+	}
+	// El agente vuelve a detectar la condición → re-emite (update).
+	if !e2.EmitOrUpdate(ev("r1", CatSystem, false)) {
+		t.Fatal("re-emisión tras reinicio")
+	}
+	if e2.List()[0].Read {
+		t.Fatalf("episodio nuevo tras reinicio debe volver a no-leído: %+v", e2.List()[0])
+	}
+
+	// Mismo episodio en curso (refresh rápido): conserva el read.
+	e2.startedAt = time.Now().Add(-2 * time.Second)
+	e2.MarkRead("r1")
+	e2b := ev("r2", CatSystem, false)
+	if !e2.EmitOrUpdate(e2b) {
+		t.Fatal("insert r2")
+	}
+	e2.MarkRead("r2")
+	if !e2.EmitOrUpdate(ev("r2", CatSystem, false)) {
+		t.Fatal("refresh del mismo episodio")
+	}
+	found := false
+	for _, x := range e2.List() {
+		if x.ID == "r2" {
+			found = x.Read
+		}
+	}
+	if !found {
+		t.Fatal("refresh en curso debe conservar el read")
+	}
+}
+
+// TestResolveForgetsRead (#1107): una alerta leída que se RESUELVE (episodio
+// cerrado, p. ej. "Agent outdated" que desaparece al actualizar el agente)
+// no debe dejar rastro en el read-set. Antes el kv readOrd conservaba el ID
+// y List()/UnreadCount() derivan el read de ahí: al re-dispararse la misma
+// condición con ID estable (otra actualización del server vuelve a dejar el
+// agente desactualizado), el episodio nuevo heredaba el leído viejo y el
+// humano no veía la alerta. Mismo criterio que Remove (#846).
+func TestResolveForgetsRead(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer d.Close()
+
+	e1 := New(d, nil)
+	if !e1.EmitOrUpdate(ev("agent-outdated-sw1", CatSystem, false)) {
+		t.Fatal("insert episodio 1")
+	}
+	e1.MarkRead("agent-outdated-sw1")
+	e1.Resolve("agent-outdated-sw1")
+
+	// El agente se actualiza (episodio cerrado) y meses después otra
+	// actualización del server vuelve a dejarlo desactualizado: mismo ID,
+	// episodio nuevo.
+	if !e1.EmitOrUpdate(ev("agent-outdated-sw1", CatSystem, false)) {
+		t.Fatal("re-emisión tras Resolve")
+	}
+	if e1.List()[0].Read {
+		t.Fatalf("episodio nuevo tras Resolve debe ser no-leído: %+v", e1.List()[0])
+	}
+	if e1.UnreadCount() != 1 {
+		t.Fatalf("unread tras re-emisión: %d", e1.UnreadCount())
+	}
+
+	// El read purgado no revive tras un reinicio (kv readOrd limpio).
+	e2 := New(d, nil)
+	if got := e2.List(); len(got) != 1 || got[0].Read {
+		t.Fatalf("el read resucitó tras reinicio: %+v", got)
+	}
+}
+
+// TestEmitOrUpdateInsertNotificaConTs (#1074): la rama de INSERCIÓN de
+// EmitOrUpdate notificaba la `ev` original sin el default de Ts que
+// insertaLocked aplica a su copia local: el notifier recibía Ts=0 y los
+// pushes (ntfy/Telegram) pintaban la hora estática 16:00:00 (epoch en
+// UTC-8). El default debe aplicarse ANTES de Notify, como en Emit (#914).
+func TestEmitOrUpdateInsertNotificaConTs(t *testing.T) {
+	spy := &spyNotifier{}
+	e := New(nil, spy)
+	ev := ev("ou1", CatSystem, false)
+	ev.Ts = 0
+	if !e.EmitOrUpdate(ev) {
+		t.Fatal("EmitOrUpdate insert debe pasar")
+	}
+	if len(spy.got) != 1 {
+		t.Fatalf("notifier: %+v", spy.got)
+	}
+	if spy.got[0].Ts == 0 {
+		t.Fatalf("el notifier recibió Ts=0: %+v", spy.got[0])
+	}
+}
+
+// TestEmitOrUpdateUpdateSobreescribeTs (#1074): la rama de UPDATE sigue
+// refrescando el timestamp a ahora (comportamiento previo, regresión).
+func TestEmitOrUpdateUpdateSobreescribeTs(t *testing.T) {
+	spy := &spyNotifier{}
+	e := New(nil, spy)
+	base := ev("ou2", CatSystem, false)
+	base.Ts = 123
+	if !e.EmitOrUpdate(base) {
+		t.Fatal("primer EmitOrUpdate debe insertar")
+	}
+	upd := ev("ou2", CatSystem, false)
+	upd.Ts = 0 // el emisor no fija Ts en la actualización
+	if !e.EmitOrUpdate(upd) {
+		t.Fatal("segundo EmitOrUpdate debe actualizar")
+	}
+	if len(spy.got) != 2 {
+		t.Fatalf("notifier: %+v", spy.got)
+	}
+	if spy.got[1].Ts <= 123 {
+		t.Fatalf("el update debe refrescar Ts a ahora: %+v", spy.got[1])
+	}
+}
+
 // TestEmitOrUpdateConsolida (#271): re-emitir con el MISMO ID actualiza la
 // alerta existente (ts nuevo, al frente, sin duplicar) en vez de insertar.
 func TestEmitOrUpdateConsolida(t *testing.T) {

+ 201 - 34
server-go/internal/channelplan/store.go

@@ -14,11 +14,19 @@ import (
 // Store persiste scans y calcula recomendaciones de canal.
 type Store struct {
 	db *sql.DB
+	// ownSeeds devuelve BSSIDs exactos reportados como propios por los
+	// agentes (dawn/usteer local=true, #1082); opcional, se cablea en main.
+	ownSeeds func() []string
 }
 
 // NewStore crea el store sobre una conexión SQLite ya abierta.
 func NewStore(db *sql.DB) *Store { return &Store{db: db} }
 
+// SetOwnSeeds fija el proveedor de BSSIDs propios exactos (p. ej.
+// AgentRegistry.LocalBssids). Se combinan con el prefijo MAC de routers.mac
+// y la transitividad por SSID.
+func (s *Store) SetOwnSeeds(f func() []string) { s.ownSeeds = f }
+
 // SaveScan guarda los resultados de un scan pasivo recibido en un push.
 func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) error {
 	if len(scans) == 0 {
@@ -31,8 +39,8 @@ func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) er
 	defer tx.Rollback()
 
 	stmt, err := tx.Prepare(`
-		INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, ts)
-		VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+		INSERT INTO wifi_scans (router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, ts)
+		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
 	`)
 	if err != nil {
 		return err
@@ -40,7 +48,7 @@ func (s *Store) SaveScan(routerID string, ts int64, scans []probe.ScanResult) er
 	defer stmt.Close()
 
 	for _, sc := range scans {
-		if _, err := stmt.Exec(routerID, sc.Iface, strings.ToUpper(sc.BSSID), sc.SSID, sc.Channel, sc.Freq, sc.Signal, ts); err != nil {
+		if _, err := stmt.Exec(routerID, sc.Iface, strings.ToUpper(sc.BSSID), sc.SSID, sc.Channel, sc.Freq, sc.Signal, sc.WidthMhz, ts); err != nil {
 			return err
 		}
 	}
@@ -55,8 +63,15 @@ type ScanRow struct {
 	Channel  int    `json:"channel"`
 	Freq     int    `json:"freq"`
 	Signal   int    `json:"signal"`
+	// WidthMhz: ancho anunciado por el vecino (#1087); 0 = desconocido
+	// (agente viejo o BSS sin HT/VHT): la UI dibuja 20 MHz de fallback.
+	WidthMhz int    `json:"widthMhz"`
 	Ts       int64  `json:"ts"`
 	RouterID string `json:"routerId"`
+	// Own marca los BSSIDs de la propia malla (#1070): comparten los 5
+	// primeros octetos con la MAC de un router monitorizado. La UI los
+	// destaca (cascada y tabla) en vez de pintarlos como vecinos ajenos.
+	Own bool `json:"own"`
 }
 
 // RecentScans devuelve los vecinos vistos recientemente (opcionalmente
@@ -68,11 +83,26 @@ type ScanRow struct {
 // fila del máximo (https://sqlite.org/lang_select.html#bareagg).
 func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, error) {
 	cutoff := time.Now().Add(-within).Unix()
+	// Semillas exactas de los agentes (dawn/usteer local=true, #1082).
+	exactOwn := map[string]bool{}
+	if s.ownSeeds != nil {
+		for _, mac := range s.ownSeeds() {
+			if mac = strings.ToUpper(strings.TrimSpace(mac)); mac != "" {
+				exactOwn[mac] = true
+			}
+		}
+	}
+	// Los prefijos de la malla propia se leen ANTES de la query principal:
+	// el pool de SQLite va con MaxOpenConns(1) (internal/db) y
+	// ownMeshPrefixes hace su propia Query; con las dos vivas a la vez el
+	// segundo db.Query se queda esperando conexión para siempre (deadlock
+	// detectado con -timeout: 90 s colgado en db.conn).
+	prefixes := s.ownMeshPrefixes()
 	var rows *sql.Rows
 	var err error
 	if routerID != "" {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, MAX(ts)
 			FROM wifi_scans
 			WHERE router_id = ? AND ts >= ?
 			GROUP BY bssid
@@ -80,7 +110,7 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 		`, routerID, cutoff)
 	} else {
 		rows, err = s.db.Query(`
-			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, MAX(ts)
+			SELECT router_id, iface, bssid, ssid, channel, freq, signal_dbm, width_mhz, MAX(ts)
 			FROM wifi_scans
 			WHERE ts >= ?
 			GROUP BY router_id, bssid
@@ -92,15 +122,41 @@ func (s *Store) RecentScans(routerID string, within time.Duration) ([]ScanRow, e
 	}
 	defer rows.Close()
 
-	var out []ScanRow
+	out := make([]ScanRow, 0)
 	for rows.Next() {
 		var r ScanRow
-		if err := rows.Scan(&r.RouterID, &r.Iface, &r.BSSID, &r.SSID, &r.Channel, &r.Freq, &r.Signal, &r.Ts); err != nil {
+		if err := rows.Scan(&r.RouterID, &r.Iface, &r.BSSID, &r.SSID, &r.Channel, &r.Freq, &r.Signal, &r.WidthMhz, &r.Ts); err != nil {
 			return nil, err
 		}
+		if exactOwn[strings.ToUpper(strings.TrimSpace(r.BSSID))] {
+			r.Own = true
+		} else {
+			r.Own = isOwnMeshBSSID(r.BSSID, prefixes)
+		}
 		out = append(out, r)
 	}
-	return out, rows.Err()
+	if err := rows.Err(); err != nil {
+		return nil, err
+	}
+	// #1076: transitividad por SSID. Los BSSIDs de una misma unidad pueden
+	// no compartir prefijo con routers.mac (p. ej. el guest de un GL.iNet);
+	// si CUALQUIER BSSID de un SSID es propio por prefijo, todo ese SSID se
+	// considera de la malla. Riesgo de falso positivo: un vecino con el
+	// mismo ESSID (raro en SSIDs personalizados; aceptable en uso doméstico).
+	ownSSIDs := map[string]bool{}
+	for _, r := range out {
+		if r.Own && r.SSID != "" {
+			ownSSIDs[r.SSID] = true
+		}
+	}
+	if len(ownSSIDs) > 0 {
+		for i := range out {
+			if !out[i].Own && out[i].SSID != "" && ownSSIDs[out[i].SSID] {
+				out[i].Own = true
+			}
+		}
+	}
+	return out, nil
 }
 
 // Radio es un resumen de una radio propia con su canal actual y recomendación.
@@ -112,11 +168,94 @@ type Radio struct {
 	Recommended  int    `json:"recommended"` // canal recomendado; 0 = sin datos
 	CurrentScore int    `json:"currentScore"`
 	BestScore    int    `json:"bestScore"`
+	// Scores puntúa TODOS los canales/bloques de la banda (no solo los
+	// recomendables), para el panel de puntuación del informe (#1070/#1076):
+	// 2.4 GHz canal a canal; 5 GHz bloque a bloque a su ancho, DFS incluidos
+	// (informativos, no recomendables).
+	Scores []ChannelScore `json:"scores,omitempty"`
 	// Section es la sección UCI de la radio ("radio0") reportada por el
 	// agente (#500); vacía con agentes antiguos (la UI deshabilita apply).
 	Section string `json:"section,omitempty"`
 }
 
+// ChannelScore puntúa un canal (2.4 GHz) o bloque a su ancho (5 GHz) de la
+// banda del radio. Score es el weighted neighbor score; menor = más limpio.
+// DFS marca bloques que en ETSI requieren detección de radar (usables, pero
+// no los recomienda el motor). Recommendable = no-DFS y apto para sugerir.
+type ChannelScore struct {
+	Channel       int  `json:"channel"`
+	Score         int  `json:"score"`
+	Neighbors     int  `json:"neighbors"`
+	Strongest     int  `json:"strongest"` // dBm de la vecina más fuerte considerada
+	DFS           bool `json:"dfs"`
+	Recommendable bool `json:"recommendable"`
+}
+
+// bandBlocks devuelve TODOS los canales/bloques puntuables de la banda a su
+// ancho (#1076): 2.4 GHz canal a canal (20 MHz); 5 GHz primarios cuyo bloque
+// completo cabe en la banda (DFS incluidos); 6 GHz solo los no-DFS (no
+// mantenemos la tabla PSC).
+func bandBlocks(band string, widthMhz int) []ChannelScore {
+	mk := func(ch int, dfs bool) ChannelScore {
+		return ChannelScore{Channel: ch, DFS: dfs, Recommendable: !dfs}
+	}
+	switch band {
+	case "2.4 GHz":
+		// Se puntúan los 13 canales, pero el motor solo SUGIERE los no
+		// solapados 1/6/11 (#631): el resto se muestra en la tira (informa
+		// de la congestión real) sin ser recomendables.
+		out := make([]ChannelScore, 0, 13)
+		for ch := 1; ch <= 13; ch++ {
+			orthodox := ch == 1 || ch == 6 || ch == 11
+			c := mk(ch, false)
+			c.Recommendable = orthodox
+			out = append(out, c)
+		}
+		return out
+	case "5 GHz":
+		n := widthMhz / 20
+		if n < 1 {
+			n = 1
+		}
+		// Bloques NO solapados: el salto es el ancho del bloque (n canales
+		// de 20 MHz), alineados a los dos rangos de canales (36-144 y
+		// 149-165). Con salto fijo de 4 los bloques de 40/80 MHz se
+		// solapaban entre sí y la tira de puntuación duplicaba el mismo
+		// espectro (#1076).
+		stride := n * 4
+		out := make([]ChannelScore, 0, 12)
+		for _, base := range [2]int{36, 149} {
+			for ch := base; ch <= 165; ch += stride {
+				if base == 36 && ch > 144 {
+					break
+				}
+				if ch+(n-1)*4 > 165 {
+					continue
+				}
+				dfs := false
+				for i := 0; i < n; i++ {
+					if isDFSChannel(ch + i*4) {
+						dfs = true
+					}
+				}
+				// Recomendables solo UNII-1 (36-48) y UNII-3 (149-161): el
+				// rango 68-92 (5350-5470 MHz) no está asignado a RLAN en
+				// ETSI, aunque no sea DFS (#1076).
+				c := mk(ch, dfs)
+				c.Recommendable = !dfs && (ch <= 48 || ch >= 149)
+				out = append(out, c)
+			}
+		}
+		return out
+	default:
+		out := make([]ChannelScore, 0, len(candidateChannels(band, widthMhz)))
+		for _, ch := range candidateChannels(band, widthMhz) {
+			out = append(out, mk(ch, false))
+		}
+		return out
+	}
+}
+
 // Recommend recibe el estado wireless del router (radios propias) y devuelve
 // una recomendación de canal por radio, ponderando por intensidad de señal.
 func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Duration) ([]Radio, error) {
@@ -125,17 +264,15 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		return nil, err
 	}
 
-	// #631: la malla propia (los APs de los routers monitorizados) NO debe
-	// contarse como "vecino": sus BSSIDs comparten los primeros 5 octetos con
-	// la MAC del router (radios = MAC base, +1, +2...). Se excluyen del
-	// scoring para que la recomendación optimice contra interferencia externa
-	// y no sugiera canales que la propia malla ya ocupa (autointerferencia).
-	ownPrefixes := s.ownMeshPrefixes()
+	// #631 + #1080: la malla propia NO congestiona. La exclusion usa el flag
+	// Own de los propios ScanRow: prefijo MAC de routers.mac + transitividad
+	// por SSID (#1076), asi el guest de una unidad con MAC ajena tampoco
+	// penaliza. Fuente unica con lo que la UI pinta como "Tu red".
 
 	// Agrupar scans por banda y canal (descartando la propia malla).
 	byBand := map[string]map[int][]ScanRow{}
 	for _, sc := range scans {
-		if isOwnMeshBSSID(sc.BSSID, ownPrefixes) {
+		if sc.Own {
 			continue
 		}
 		band := bandForFreq(sc.Freq)
@@ -162,18 +299,24 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		if rec.Iface == "" {
 			rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
 		}
-		candidates := candidateChannels(band, r.WidthMhz)
+		blocks := bandBlocks(band, r.WidthMhz)
 		bestCh, bestScore := 0, math.MaxInt
 		currentScore := math.MaxInt
-		for _, ch := range candidates {
-			score := channelScore(byBand[band], ch)
-			if ch == r.Channel {
-				currentScore = score
+		scores := make([]ChannelScore, 0, len(blocks))
+		for _, b := range blocks {
+			b.Score, b.Neighbors, b.Strongest = channelScoreDetailed(byBand[band], b.Channel)
+			if b.Channel == r.Channel {
+				currentScore = b.Score
 			}
-			if score < bestScore {
-				bestScore = score
-				bestCh = ch
+			// El motor recomienda solo el mejor bloque no-DFS (#518/#631).
+			if b.Recommendable && b.Score < bestScore {
+				bestScore = b.Score
+				bestCh = b.Channel
 			}
+			scores = append(scores, b)
+		}
+		if len(scores) > 0 {
+			rec.Scores = scores
 		}
 		// #518: el canal ACTUAL puede ser DFS (52/100/112/116...) y no estar en
 		// candidateChannels (solo no-DFS para recomendar). Su score es
@@ -192,25 +335,49 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 	return out, nil
 }
 
-// channelScore pondera APs vecinos por canal: señales más fuertas (menos
-// negativas) pesan más. Se suma una penalización por APs en canales adyacentes
-// (sobre todo en 2.4 GHz).
-func channelScore(scans map[int][]ScanRow, channel int) int {
-	score := 0.0
+// channelScoreDetailed pondera APs vecinos por canal: señales más fuertes
+// (menos negativas) pesan más y se penalizan APs en canales adyacentes
+// (sobre todo en 2.4 GHz). Además cuenta cuántas vecinas participan y la
+// más fuerte entre ellas, para el panel de puntuación del informe (#1070).
+func channelScoreDetailed(scans map[int][]ScanRow, channel int) (score int, neighbors int, strongest int) {
+	total := 0.0
+	strongest = math.MinInt
 	for ch, list := range scans {
 		for _, ap := range list {
 			diff := abs(ch - channel)
+			weighted := false
 			if diff == 0 {
-				// Mismo canal: peso completo. Señal fuerte (+60 dBm) suma 60;
-				// señal débil (-90 dBm) suma 10.
-				score += float64(-ap.Signal) / 1.5
+				// Mismo canal: peso completo, en dominio de potencia (#1080):
+				// w = 10^((s+60)/10); una vecina a -50 pesa ~3000x una a -85.
+				total += math.Pow(10, float64(ap.Signal+60)/10)
+				weighted = true
 			} else if diff <= 2 {
-				// Canal adyacente: peso reducido. Importante en 2.4 GHz.
-				score += float64(-ap.Signal) / 5.0
+				// Canal adyacente (+-2): un cuarto (-6 dB), sobre todo en 2.4.
+				total += math.Pow(10, float64(ap.Signal+60)/10) / 4
+				weighted = true
+			}
+			if !weighted {
+				continue
+			}
+			neighbors++
+			if strongest == math.MinInt || ap.Signal > strongest {
+				strongest = ap.Signal
 			}
 		}
 	}
-	return int(score)
+	if neighbors == 0 {
+		// Sin vecinas no hay "más fuerte": 0 en vez de MinInt, que en JSON
+		// sale como -9223372036854775808 y rompe la tabla.
+		strongest = 0
+	}
+	// x1000 para conservar resolucion al pasar a int (w(-90 dBm) ~= 0.001).
+	return int(total * 1000), neighbors, strongest
+}
+
+// channelScore es la puntuación ponderada pura (menor = canal más limpio).
+func channelScore(scans map[int][]ScanRow, channel int) int {
+	score, _, _ := channelScoreDetailed(scans, channel)
+	return score
 }
 
 // candidateChannels devuelve los canales candidatos no-DFS para la banda,

+ 270 - 0
server-go/internal/channelplan/store_test.go

@@ -36,6 +36,276 @@ func TestSaveAndRecentScans(t *testing.T) {
 	}
 }
 
+// TestRecommendDevuelveScores (#1070/#1076): el informe puntúa TODOS los
+// bloques de la banda a su ancho, DFS incluidos (informativos); los
+// recomendables son no-DFS y el mejor de ellos es el Recommended.
+func TestRecommendDevuelveScores(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "5 GHz", Channel: 36, WidthMhz: 80}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 || len(recs[0].Scores) == 0 {
+		t.Fatalf("esperaba scores, got %+v", recs)
+	}
+	byCh := map[int]channelplan.ChannelScore{}
+	var dfsCount int
+	for _, c := range recs[0].Scores {
+		if c.DFS {
+			dfsCount++
+		}
+		byCh[c.Channel] = c
+	}
+	if dfsCount == 0 {
+		t.Errorf("a 80 MHz deben puntuarse también bloques DFS: %+v", recs[0].Scores)
+	}
+	rec := recs[0]
+	best := byCh[rec.Recommended]
+	if best.DFS || !best.Recommendable {
+		t.Errorf("el recomendado debe ser un bloque no-DFS recomendable: %+v", best)
+	}
+	// #1076: el rango 68-92 (5350-5470 MHz) no es RLAN en ETSI: se puntúa
+	// pero nunca se recomienda.
+	if b, ok := byCh[68]; ok && b.Recommendable {
+		t.Errorf("el bloque 68 no debe ser recomendable (no RLAN ETSI): %+v", b)
+	}
+	if b, ok := byCh[52]; !ok || !b.DFS {
+		t.Errorf("el bloque 52-64 debe marcarse DFS: %+v", b)
+	}
+	if best.Score != rec.BestScore {
+		t.Errorf("el score del bloque recomendado debe ser BestScore: %+v, rec %+v", best, rec)
+	}
+}
+
+// TestRecommendScores24GHzTodosLosCanales (#1076): a 2.4 GHz se puntúan los
+// 13 canales (no solo los no solapados 1/6/11), todos recomendables.
+func TestRecommendScores24GHzTodosLosCanales(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 || len(recs[0].Scores) != 13 {
+		t.Fatalf("esperaba 13 scores en 2.4 GHz, got %+v", recs)
+	}
+	for _, s := range recs[0].Scores {
+		want := s.Channel == 1 || s.Channel == 6 || s.Channel == 11
+		if s.Recommendable != want || s.DFS {
+			t.Errorf("recommendable solo en 1/6/11 (#631): %+v", s)
+		}
+	}
+}
+
+// TestRecentScansOwnPorSemillaExacta (#1082): un BSSID que el agente
+// reporta como propio (dawn/usteer local=true) se marca own aunque no case
+// ni por prefijo ni por transitividad de SSID.
+func TestRecentScansOwnPorSemillaExacta(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	st.SetOwnSeeds(func() []string { return []string{"1e:bf:ce:02:7f:48"} })
+	now := time.Now().Unix()
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "1E:BF:CE:02:7F:48", SSID: "Casa-2.4", Channel: 1, Freq: 2412, Signal: -53},
+		{Iface: "wlan0", BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 6, Freq: 2437, Signal: -60},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got, err := st.RecentScans("rt1", time.Hour)
+	if err != nil {
+		t.Fatalf("recent: %v", err)
+	}
+	bySSID := map[string]bool{}
+	for _, r := range got {
+		bySSID[r.SSID] = r.Own
+	}
+	if !bySSID["Casa-2.4"] {
+		t.Errorf("la semilla exacta debe marcar own: %+v", got)
+	}
+	if bySSID["vecino"] {
+		t.Errorf("vecino NO debe ser own: %+v", got)
+	}
+}
+
+// TestRecentScansOwnPorSSIDTransitable (#1076): si un BSSID de un SSID es
+// propio por prefijo MAC, el resto de filas del mismo SSID también se
+// marcan propias aunque su MAC no case (guest de la misma unidad).
+func TestRecentScansOwnPorSSIDTransitable(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.DB.Exec(`INSERT INTO routers (id, name, host, type, mac, is_gateway, created_at)
+		VALUES ('rt2', 'RT2 AX6', '192.168.1.2', 'openwrt', '8C:DE:F9:33:71:58', 0, ?)`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	// La main BSS de la malla casa con el prefijo; la guest (misma unidad,
+	// MAC distinta) no.
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "8C:DE:F9:33:71:59", SSID: "casa-guest", Channel: 6, Freq: 2437, Signal: -30},
+		{Iface: "wlan0", BSSID: "1E:BF:CE:02:7F:48", SSID: "casa-guest", Channel: 6, Freq: 2437, Signal: -53},
+		{Iface: "wlan0", BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 11, Freq: 2462, Signal: -80},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got, err := st.RecentScans("rt1", time.Hour)
+	if err != nil {
+		t.Fatalf("recent: %v", err)
+	}
+	bySSID := map[string]bool{}
+	for _, r := range got {
+		bySSID[r.SSID] = r.Own
+	}
+	if !bySSID["casa-guest"] {
+		t.Errorf("toda fila de casa-guest debe ser own (transitividad): %+v", got)
+	}
+	if bySSID["vecino"] {
+		t.Errorf("vecino NO debe ser own: %+v", got)
+	}
+}
+
+// TestRecommendGuestSSIDNoCongestiona (#1080): el scoring excluye las redes
+// propias por el flag Own (prefijo MAC + transitividad SSID): el guest de una
+// unidad, con MAC que no casa pero mismo SSID que una BSS de flota, no debe
+// ensuciar su canal ni empujar la recomendación a otro.
+func TestRecommendGuestSSIDNoCongestiona(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.DB.Exec(`INSERT INTO routers (id, name, host, type, mac, is_gateway, created_at)
+		VALUES ('rt2', 'RT2 AX6', '192.168.1.2', 'openwrt', '8C:DE:F9:33:71:58', 0, ?)`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "8C:DE:F9:33:71:59", SSID: "casa", Channel: 11, Freq: 2462, Signal: -30},
+		{Iface: "wlan0", BSSID: "1E:BF:CE:02:7F:48", SSID: "casa", Channel: 1, Freq: 2412, Signal: -30},
+		{Iface: "wlan0", BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 6, Freq: 2437, Signal: -60},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 {
+		t.Fatalf("esperaba 1 radio, got %+v", recs)
+	}
+	// El guest de "casa" en ch1 no congestiona: con ch6 ocupada por el vecino
+	// (-60) y ch11 por la propia, el 1 (limpio y ortodoxo) es el sugerido.
+	if recs[0].Recommended != 1 {
+		t.Fatalf("el guest propio no debe congestinar: rec %+v", recs[0])
+	}
+}
+
+// TestRecommendFuerzaSobreCantidad (#1080): con ponderación en dominio de
+// potencia, UNA vecina fuerte (-50) ensucia su canal más que CUATRO de
+// juguete (-85): el motor sugiere el de las débiles.
+func TestRecommendFuerzaSobreCantidad(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	// ch6: UNA vecina fuerte (-50). ch11: CUATRO de juguete (-85).
+	// ch1: dos mediocres (-70) que no alteran el orden 11 < 1 << 6.
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "AA:AA:AA:AA:AA:01", SSID: "fuerte", Channel: 6, Freq: 2437, Signal: -50},
+		{Iface: "wlan0", BSSID: "CC:CC:CC:CC:CC:01", SSID: "m1", Channel: 1, Freq: 2412, Signal: -70},
+		{Iface: "wlan0", BSSID: "CC:CC:CC:CC:CC:02", SSID: "m2", Channel: 1, Freq: 2412, Signal: -70},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:01", SSID: "d1", Channel: 11, Freq: 2462, Signal: -85},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:02", SSID: "d2", Channel: 11, Freq: 2462, Signal: -85},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:03", SSID: "d3", Channel: 11, Freq: 2462, Signal: -85},
+		{Iface: "wlan0", BSSID: "BB:BB:BB:BB:BB:04", SSID: "d4", Channel: 11, Freq: 2462, Signal: -85},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 1, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 1 {
+		t.Fatalf("esperaba 1 radio, got %+v", recs)
+	}
+	if recs[0].Recommended != 11 {
+		t.Fatalf("una vecina fuerte debe pesar mas que cuatro de juguete: rec %+v", recs[0])
+	}
+}
+
+// TestRecentScansMarcaMallaPropia (#1070): los BSSIDs de la propia flota
+// deben llegar a la UI marcados (own) para destacarse en el informe.
+func TestRecentScansMarcaMallaPropia(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	if _, err := d.DB.Exec(`INSERT INTO routers (id, name, host, type, mac, is_gateway, created_at)
+		VALUES ('rt2', 'RT2 AX6', '192.168.1.2', 'openwrt', '8C:DE:F9:33:71:58', 0, ?)`,
+		time.Now().UnixMilli()); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+	scans := []probe.ScanResult{
+		{Iface: "wlan0", BSSID: "8C:DE:F9:33:71:59", SSID: "propia", Channel: 1, Freq: 2412, Signal: -30},
+		{Iface: "wlan0", BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 6, Freq: 2437, Signal: -62},
+	}
+	if err := st.SaveScan("rt1", now, scans); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+
+	got, err := st.RecentScans("rt1", time.Hour)
+	if err != nil {
+		t.Fatalf("recent: %v", err)
+	}
+	if len(got) != 2 {
+		t.Fatalf("esperaba 2 scans, got %d", len(got))
+	}
+	for _, r := range got {
+		if r.SSID == "propia" && !r.Own {
+			t.Errorf("la malla propia debe marcarse own: %+v", r)
+		}
+		if r.SSID == "vecino" && r.Own {
+			t.Errorf("el vecino ajeno NO debe marcarse own: %+v", r)
+		}
+	}
+}
+
 // TestRecentScansDedupBSSID (#475): cada push reinserta los vecinos; la
 // lectura debe devolver UNA fila por BSSID (la observación más reciente).
 func TestRecentScansDedupBSSID(t *testing.T) {

+ 16 - 0
server-go/internal/config/config.go

@@ -69,6 +69,7 @@ type Config struct {
 	AgentAutoenroll  bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
 	Onbox            bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
 	GhostPortEnabled bool   // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
+	MCPEnabled       bool   // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false
 	// NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
 	// default 443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
 	// idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no
@@ -454,6 +455,20 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_MCP_ENABLED: '0'|'1', opcional (#1114) - default false. Activa
+	// el endpoint /mcp (streamable-HTTP) para asistentes AI; SOLO auth por API
+	// token Bearer, nunca cookie de sesión. El puerto debe quedar en LAN.
+	mcpEnabled := false
+	if v, ok := env["NETPULSE_MCP_ENABLED"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			mcpEnabled = true
+		default:
+			errs.issues = append(errs.issues, issue{"NETPULSE_MCP_ENABLED", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
 	// NETPULSE_RTL_PASS / NETPULSE_RTL_POLL_S: sondeo HTTP de la consola de
 	// switches RTLPlayground (KP-9000) para firmware + uptime (#639). La pass
 	// por defecto es la del firmware tras flasheo; la cadencia 300 s (5 min).
@@ -624,6 +639,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		AgentAutoenroll:   agentAutoenroll,
 		Onbox:             onbox,
 		GhostPortEnabled:  ghostPortEnabled,
+		MCPEnabled:        mcpEnabled,
 		RTLConsolePass:    rtlPass,
 		RTLConsolePollSec: rtlPollSec,
 		PollIntervalSec:   pollIntervalSec,

+ 93 - 0
server-go/internal/db/db.go

@@ -133,6 +133,13 @@ CREATE TABLE IF NOT EXISTS device_seen (
   first_seen INTEGER NOT NULL,
   last_seen  INTEGER NOT NULL
 );
+-- #1151: cliente con varias MACs (un hostname, nunca simultáneas): cada fila
+-- dice "esta MAC es el mismo cliente que canonical". Clave = alias; el
+-- canónico no tiene fila propia (ausencia de fila = MAC canónica).
+CREATE TABLE IF NOT EXISTS device_links (
+  mac       TEXT PRIMARY KEY,
+  canonical TEXT NOT NULL
+);
 -- Routers configurados
 CREATE TABLE IF NOT EXISTS routers (
   id TEXT PRIMARY KEY,
@@ -341,6 +348,7 @@ CREATE TABLE IF NOT EXISTS wifi_scans (
   channel     INTEGER NOT NULL,
   freq        INTEGER NOT NULL,
   signal_dbm  INTEGER NOT NULL,
+  width_mhz   INTEGER NOT NULL DEFAULT 0,
   ts          INTEGER NOT NULL
 );
 CREATE INDEX IF NOT EXISTS idx_wifi_scans_router_ts ON wifi_scans(router_id, ts DESC);
@@ -399,6 +407,66 @@ CREATE TABLE IF NOT EXISTS alert_log (
 );
 CREATE INDEX IF NOT EXISTS idx_alert_log_ts ON alert_log(ts DESC);
 
+-- Rack canvas (fase 1): racks, montajes, cables y perfil físico por MAC.
+-- La identidad de dispositivo en NetPulse es la MAC (no hay tabla devices):
+-- rack_mounts.device_mac apunta a esa identidad y device_rack_profile guarda
+-- el modelo físico compartido (faceplate, altura U, span de columnas,
+-- color y puertos con posición). Los montajes con device_mac NULL son
+-- accesorios (blank, shelf, patch panel, PDU): su tamaño lo define el
+-- faceplate del catálogo.
+CREATE TABLE IF NOT EXISTS racks (
+  id TEXT PRIMARY KEY,
+  name TEXT NOT NULL,
+  u_height INTEGER NOT NULL,
+  width_standard TEXT NOT NULL DEFAULT '19',   -- '19' | '10'
+  numbering TEXT NOT NULL DEFAULT 'bottom-up', -- solo cambia etiquetas, nunca la geometría
+  style_json TEXT NOT NULL DEFAULT '{}',
+  location TEXT,
+  position_x REAL NOT NULL DEFAULT 0,
+  position_y REAL NOT NULL DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS device_rack_profile (
+  mac TEXT PRIMARY KEY,
+  faceplate_id TEXT NOT NULL DEFAULT '',
+  u_height INTEGER NOT NULL DEFAULT 1,
+  col_span INTEGER NOT NULL DEFAULT 12,
+  color TEXT NOT NULL DEFAULT '',
+  ports_json TEXT NOT NULL DEFAULT '[]'
+);
+
+CREATE TABLE IF NOT EXISTS rack_mounts (
+  id TEXT PRIMARY KEY,
+  rack_id TEXT NOT NULL REFERENCES racks(id) ON DELETE CASCADE,
+  device_mac TEXT REFERENCES device_rack_profile(mac) ON DELETE SET NULL, -- NULL = accesorio
+  faceplate_id TEXT NOT NULL DEFAULT '',  -- accesorios; el de dispositivos vive en device_rack_profile
+  u_start INTEGER NOT NULL,               -- 1-based, SIEMPRE contado desde el rail inferior
+  col_start INTEGER NOT NULL DEFAULT 0,   -- 0-based
+  label TEXT,
+  status_pin TEXT NOT NULL DEFAULT 'auto',      -- 'auto' → seguir el estado que conoce el poller
+  port_visibility TEXT NOT NULL DEFAULT 'auto'
+);
+CREATE INDEX IF NOT EXISTS idx_rack_mounts_rack ON rack_mounts(rack_id);
+
+-- Cables port-to-port (relación propia, no edges del canvas lógico).
+-- Pueden cruzar racks. Un puerto normal admite exactamente 1 cable; los
+-- patch panels (pass-through) admiten 2 (tirada de pared al rear + patch al
+-- switch al front). Cobre vs fibra se deriva del puerto de origen del patch.
+CREATE TABLE IF NOT EXISTS rack_cables (
+  id TEXT PRIMARY KEY,
+  from_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
+  from_port TEXT NOT NULL,
+  to_mount TEXT NOT NULL REFERENCES rack_mounts(id) ON DELETE CASCADE,
+  to_port TEXT NOT NULL,
+  type TEXT NOT NULL DEFAULT 'ethernet',       -- 'ethernet' | 'fiber'
+  label TEXT,
+  properties_json TEXT NOT NULL DEFAULT '{}',  -- key/value libre
+  origin TEXT NOT NULL DEFAULT 'manual',       -- 'manual' | 'imported' | 'detected'
+  created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
+CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
+
 `
 
 // DB envuelve *sql.DB con los jobs y helpers de paridad.
@@ -503,10 +571,17 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
 	// issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
 	migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
+	// Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.
+	migrate(sqldb, "wifi_scans", "width_mhz", "ALTER TABLE wifi_scans ADD COLUMN width_mhz INTEGER NOT NULL DEFAULT 0")
 	// issue #241: target de firmware por router (string libre; NULL/"" = sin comprobar).
 	migrate(sqldb, "routers", "firmware_target", "ALTER TABLE routers ADD COLUMN firmware_target TEXT")
 	// issue #309: SNMP polling for managed switches.
 	migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
+	// #1145: último nombre conocido del cliente (retención indefinida).
+	migrate(sqldb, "device_seen", "name", "ALTER TABLE device_seen ADD COLUMN name TEXT NOT NULL DEFAULT ''")
+	// #1151: última IP conocida (los fantasmas la conservan para la lista y
+	// las sugerencias de enlace).
+	migrate(sqldb, "device_seen", "ip", "ALTER TABLE device_seen ADD COLUMN ip TEXT NOT NULL DEFAULT ''")
 	// issue #863: sondeo HTTP de la consola de switches RTLPlayground. DEFAULT 1
 	// = comportamiento previo; se desactiva por router (la consola del firmware
 	// tiene una sola sesión global y cada login tumba la sesión humana).
@@ -517,6 +592,10 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
 	// issue #605: puerto SSH por router (dropbear en puerto no estándar).
 	migrate(sqldb, "routers", "ssh_port", "ALTER TABLE routers ADD COLUMN ssh_port INTEGER NOT NULL DEFAULT 22")
+	// issue #1085: pausa de una unidad de flota (sin sondeo ni alertas, con
+	// insignia en la lista y fuera de los desplegables; el histórico se
+	// conserva). 0/ausente (columna nueva) = activa.
+	migrate(sqldb, "routers", "disabled", "ALTER TABLE routers ADD COLUMN disabled INTEGER NOT NULL DEFAULT 0")
 	// issue #716: umbral de alerta por temperatura alta (°C). NULL = 65 default.
 	migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
 	// issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
@@ -537,6 +616,20 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 		}
 	}
 
+	// RouterOS (Type "routeros"): credenciales de la REST API nativa.
+	migrate(sqldb, "routers", "routeros_user", "ALTER TABLE routers ADD COLUMN routeros_user TEXT")
+	migrate(sqldb, "routers", "routeros_password", "ALTER TABLE routers ADD COLUMN routeros_password TEXT")
+	migrate(sqldb, "routers", "routeros_insecure", "ALTER TABLE routers ADD COLUMN routeros_insecure INTEGER NOT NULL DEFAULT 0")
+
+	// #1129: las MACs de roam_events se ingirieron en minúsculas (así vienen
+	// en los logs hostapd/dawn/usteer) mientras el resto de la app canonicaliza
+	// a MAYÚSCULAS (#960): el filtro por cliente no casaba con el histórico.
+	// Normalización one-shot de las filas existentes (la ingesta nueva ya
+	// normaliza, ver roamevents.ParseLogreadLine).
+	if _, err := sqldb.Exec("UPDATE roam_events SET mac = UPPER(mac) WHERE mac IS NOT NULL AND mac != UPPER(mac)"); err != nil {
+		log.Printf("[netpulse] aviso: no se pudieron normalizar las MACs de roam_events: %v", err)
+	}
+
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// DB para que el siguiente arranque no dispare una "migración" espuria
 	// (backup + reset de login_attempts) sobre una DB ya Go.

+ 31 - 5
server-go/internal/httpapi/config.go

@@ -100,6 +100,8 @@ type routerInput struct {
 	Type      string  `json:"type"`
 	Gateway   bool    `json:"gateway"`
 	AgentOnly bool    `json:"agent_only"`
+	// Disabled (issue #1085): pausa la unidad (nil = no tocar).
+	Disabled *bool `json:"disabled"`
 	// FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
 	FirmwareTarget *string `json:"firmware_target"`
 	// SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
@@ -115,6 +117,10 @@ type routerInput struct {
 	// TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
 	// Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
 	TempThreshold *int `json:"temp_threshold"`
+	// RouterOS: credenciales de la REST API nativa (Type "routeros").
+	RouterOSUser     *string `json:"routeros_user"`
+	RouterOSPassword *string `json:"routeros_password"`
+	RouterOSInsecure *bool   `json:"routeros_insecure"`
 }
 
 // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
@@ -192,8 +198,8 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 	if typ == "" {
 		typ = "openwrt"
 	}
-	if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
-		writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
+	if typ != "glinet" && typ != "openwrt" && typ != "routeros" && typ != "managed-switch" && typ != "external" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
 		return
 	}
 	var firmwareTarget string
@@ -239,11 +245,24 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 		}
 		sshPort = p
 	}
+	routerosUser := ""
+	if in.RouterOSUser != nil {
+		routerosUser = strings.TrimSpace(*in.RouterOSUser)
+	}
+	routerosPassword := ""
+	if in.RouterOSPassword != nil {
+		routerosPassword = *in.RouterOSPassword
+	}
+	routerosInsecure := false
+	if in.RouterOSInsecure != nil {
+		routerosInsecure = *in.RouterOSInsecure
+	}
 	created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
 		Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
-		SSHPort: sshPort,
+		SSHPort:        sshPort,
+		RouterOSUser:   routerosUser, RouterOSPassword: routerosPassword, RouterOSInsecure: routerosInsecure,
 	})
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
@@ -304,8 +323,8 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 	var typ *string
 	if in.Type != "" {
 		t := in.Type
-		if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
-			writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
+		if t != "glinet" && t != "openwrt" && t != "routeros" && t != "managed-switch" && t != "external" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
 			return
 		}
 		typ = &t
@@ -358,14 +377,21 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		}
 		tempThreshold = &v
 	}
+	var routerosUser *string
+	if in.RouterOSUser != nil {
+		v := strings.TrimSpace(*in.RouterOSUser)
+		routerosUser = &v
+	}
 	updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
 		Name: name, Host: host, Type: typ,
 		IsGateway: &gw, AgentOnly: &ao,
+		Disabled:       in.Disabled,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
 		SSHPort:        sshPort,
 		TempThreshold:  tempThreshold,
 		ConsolePolling: in.ConsolePolling,
+		RouterOSUser:   routerosUser, RouterOSPassword: in.RouterOSPassword, RouterOSInsecure: in.RouterOSInsecure,
 	})
 	if !ok {
 		writeError(w, http.StatusNotFound, "not_found")

+ 41 - 0
server-go/internal/httpapi/config_test.go

@@ -534,6 +534,47 @@ func TestConfigRoutersSNMP(t *testing.T) {
 	}
 }
 
+func TestConfigRoutersRouterOS(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// POST RouterOS con credenciales
+	res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"name":"mikrotik","host":"192.168.8.1","type":"routeros","routeros_user":"admin","routeros_password":"secretpassword","routeros_insecure":true}`)
+	if res.StatusCode != 201 {
+		t.Fatalf("POST router: %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	router := body["router"].(map[string]any)
+	if router["type"] != "routeros" {
+		t.Fatalf("type: %v", router["type"])
+	}
+	if router["routeros_user"] != "admin" {
+		t.Fatalf("routeros_user: %v", router["routeros_user"])
+	}
+	if router["routeros_insecure"] != true {
+		t.Fatalf("routeros_insecure: %v", router["routeros_insecure"])
+	}
+	if _, present := router["routeros_password"]; present {
+		t.Fatalf("routeros_password no debe devolverse en la API: %v", router)
+	}
+
+	// PUT actualiza usuario e insecure
+	res = doReq(t, "PUT", srv.URL+"/api/config/routers/mikrotik", cookie,
+		`{"host":"192.168.8.1","routeros_user":"netpulse","routeros_insecure":false}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT router: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	rt := body["router"].(map[string]any)
+	if rt["routeros_user"] != "netpulse" {
+		t.Fatalf("routeros_user tras PUT: %v", rt["routeros_user"])
+	}
+	if rt["routeros_insecure"] != false {
+		t.Fatalf("routeros_insecure tras PUT: %v", rt["routeros_insecure"])
+	}
+}
+
 // TestProxmoxConfig (#561): PUT/GET /api/config/proxmox
 //   - guardar url+token, GET no devuelve el secret (solo tokenSet)
 //   - url vacía desactiva (limpia kv)

+ 43 - 8
server-go/internal/httpapi/data.go

@@ -13,6 +13,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/clientbw"
+	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
 	"github.com/gnacho/netpulse/server-go/internal/roamcfg"
@@ -256,9 +257,41 @@ func (s *server) handleDevices(w http.ResponseWriter, r *http.Request) {
 	}
 	out := paginate(filtered, page, pageSize)
 	out["typeCounts"] = typeCounts
+	// #1151: candidatos a "mismo dispositivo con varias MACs" (hostname+IP
+	// compartidos, nunca simultáneos). Solo sugerencia: el enlazado es manual.
+	if suggestions := adapters.LinkSuggestions(items, loadDeviceLinks(s.db)); len(suggestions) > 0 {
+		out["linkSuggestions"] = suggestions
+	}
 	writeJSON(w, http.StatusOK, out)
 }
 
+// loadDeviceLinks: mapa alias → canónico desde la tabla device_links (una
+// query; vacío si no hay BD o no hay enlaces).
+func loadDeviceLinks(d *db.DB) map[string]string {
+	out := map[string]string{}
+	if d == nil {
+		return out
+	}
+	rows, err := d.Query(`SELECT mac, canonical FROM device_links`)
+	if err != nil {
+		return out
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var alias, canonical string
+		if err := rows.Scan(&alias, &canonical); err != nil {
+			continue
+		}
+		out[normalizeMACKey(alias)] = normalizeMACKey(canonical)
+	}
+	return out
+}
+
+// normalizeMACKey: identidad canónica de enlace (mayúsculas, ':').
+func normalizeMACKey(mac string) string {
+	return strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(mac), "-", ":"))
+}
+
 // deviceMatches: substring (minúsculas) sobre name|hostname|ip|mac|manufacturer.
 func deviceMatches(d adapters.Device, query string) bool {
 	for _, v := range []string{d.Name, d.Hostname, d.IP, d.MAC, d.Manufacturer} {
@@ -348,12 +381,13 @@ func (s *server) handleAlertsReadAll(w http.ResponseWriter, _ *http.Request) {
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
 }
 
-// handleAlertsClear (POST, issue #971): VACÍA el feed - limpia (dismiss)
-// todas las alertas actualmente visibles. Es lo que el botón "Marcar todo
-// como leído" hace desde #971: las alertas salen del feed (badge a 0) y no
-// reaparecen tras un reload (borradas de alert_log + conjunto dismissed en
-// kv). Una alerta viva (volátil, p.ej. agent-down con el agente aún caído)
-// puede volver al re-evaluarse su condición; el histórico NO vuelve.
+// handleAlertsClear (POST): acción destructiva "Vaciar registro" (#1034) -
+// limpia (dismiss) todas las alertas actualmente visibles. Las borra de
+// alert_log y guarda sus IDs en el conjunto dismissed (kv): el feed queda
+// vacío y no se repuebla tras un reload. Una alerta viva (volátil, p.ej.
+// agent-down con el agente aún caído) puede volver al re-evaluarse su
+// condición; el histórico NO vuelve. Para SOLO marcar leídas sin borrar,
+// POST /api/alerts/read-all.
 func (s *server) handleAlertsClear(w http.ResponseWriter, _ *http.Request) {
 	s.adapter.AlertsEngine().DismissAll()
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
@@ -514,7 +548,7 @@ func (s *server) handleSurvey(w http.ResponseWriter, r *http.Request) {
 }
 
 // handleRoamEvents: lista paginada de eventos hostapd/DAWN desde SQLite.
-// Query params: limit (default 100, máx 1000), since (epoch ms), router, type.
+// Query params: limit (default 100, máx 1000), since (epoch ms), router, type, mac.
 func (s *server) handleRoamEvents(w http.ResponseWriter, r *http.Request) {
 	limit := 100
 	if v := r.URL.Query().Get("limit"); v != "" {
@@ -530,7 +564,8 @@ func (s *server) handleRoamEvents(w http.ResponseWriter, r *http.Request) {
 	}
 	routerID := r.URL.Query().Get("router")
 	eventType := r.URL.Query().Get("type")
-	events, err := roamevents.ListEvents(s.db.DB, limit, since, routerID, eventType)
+	mac := r.URL.Query().Get("mac")
+	events, err := roamevents.ListEvents(s.db.DB, limit, since, routerID, eventType, mac)
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
 		return

+ 26 - 0
server-go/internal/httpapi/device_overrides.go

@@ -179,3 +179,29 @@ func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
 	_ = body
 	writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
 }
+
+// handleDeviceDelete: borra un cliente del registro device_seen (#1145,
+// retención indefinida con control explícito). Si el cliente sigue viéndose
+// en vivo, el siguiente ciclo del poller lo vuelve a dar de alta: borrar
+// elimina el recuerdo, no el equipo físico (la UI lo documenta en el
+// diálogo de confirmación).
+func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) {
+	raw := strings.TrimSpace(r.PathValue("mac"))
+	mac := strings.ToUpper(strings.ReplaceAll(raw, "-", ":"))
+	if mac == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
+		return
+	}
+	// BDs legadas pueden guardar la MAC sin normalizar (con guiones): se
+	// borran ambas formas (#1145).
+	res, err := s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?", mac, raw)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "storage_error", "")
+		return
+	}
+	if n, _ := res.RowsAffected(); n == 0 {
+		writeError(w, http.StatusNotFound, "not_found", "")
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 79 - 0
server-go/internal/httpapi/device_overrides_test.go

@@ -4,6 +4,7 @@ package httpapi
 
 import (
 	"encoding/json"
+	"net/http"
 	"net/http/httptest"
 	"strings"
 	"testing"
@@ -116,3 +117,81 @@ func TestDeviceOverrideValidation(t *testing.T) {
 		t.Errorf("tipo válil debió dar 200, dio %d", rec.Code)
 	}
 }
+
+// #1145: DELETE /api/devices/{mac} borra la fila del registro y 404 si no
+// existe. El handler requiere admin (el test llama al handler directamente
+// con PathValue, como el resto de tests de handlers con PathValue).
+func TestDeviceDelete(t *testing.T) {
+	s := panelTestServer(t)
+	if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('AA:BB:CC:DD:EE:FF', 1, 2, 'watch')", ); err != nil {
+		t.Fatalf("seed: %v", err)
+	}
+
+	r := httptest.NewRequest(http.MethodDelete, "/api/devices/aa-bb-cc-dd-ee-ff", nil)
+	r.SetPathValue("mac", "aa-bb-cc-dd-ee-ff")
+	rec := httptest.NewRecorder()
+	s.handleDeviceDelete(rec, r)
+	if rec.Code != http.StatusNoContent {
+		t.Fatalf("status = %d, want 204", rec.Code)
+	}
+	var n int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM device_seen WHERE mac = 'AA:BB:CC:DD:EE:FF'").Scan(&n); err != nil {
+		t.Fatal(err)
+	}
+	if n != 0 {
+		t.Fatalf("rows = %d, want 0 (borrado)", n)
+	}
+
+	// MAC desconocida: 404.
+	rec = httptest.NewRecorder()
+	r = httptest.NewRequest(http.MethodDelete, "/api/devices/11-22-33-44-55-66", nil)
+	r.SetPathValue("mac", "11-22-33-44-55-66")
+	s.handleDeviceDelete(rec, r)
+	if rec.Code != http.StatusNotFound {
+		t.Fatalf("status = %d, want 404", rec.Code)
+	}
+}
+
+// #1151: link con validaciones (self 400, ok 200, ya enlazada 409, target
+// alias 409) y unlink (204 / 404).
+func TestDeviceLinkPutDelete(t *testing.T) {
+	s := panelTestServer(t)
+	do := func(method, mac, body string) *httptest.ResponseRecorder {
+		r := httptest.NewRequest(method, "/api/devices/"+mac+"/link", strings.NewReader(body))
+		r.SetPathValue("mac", mac)
+		if body != "" {
+			r.Header.Set("Content-Type", "application/json")
+		}
+		rec := httptest.NewRecorder()
+		if method == http.MethodPut {
+			s.handleDeviceLinkPut(rec, r)
+		} else {
+			s.handleDeviceLinkDelete(rec, r)
+		}
+		return rec
+	}
+
+	// self-link: 400
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:01", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusBadRequest {
+		t.Fatalf("self link = %d, want 400", rec.Code)
+	}
+	// ok: 200
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusOK {
+		t.Fatalf("link = %d, want 200", rec.Code)
+	}
+	// ya enlazada: 409
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:09"}`); rec.Code != http.StatusConflict {
+		t.Fatalf("relink = %d, want 409", rec.Code)
+	}
+	// target es a su vez alias: 409
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:03", `{"target":"AA:AA:AA:00:00:02"}`); rec.Code != http.StatusConflict {
+		t.Fatalf("target alias = %d, want 409", rec.Code)
+	}
+	// unlink: 204 y 404
+	if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNoContent {
+		t.Fatalf("unlink = %d, want 204", rec.Code)
+	}
+	if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNotFound {
+		t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
+	}
+}

+ 11 - 10
server-go/internal/httpapi/firmware_test.go

@@ -7,6 +7,7 @@ import (
 	"net/http"
 	"net/http/httptest"
 	"strings"
+	"sync/atomic"
 	"testing"
 	"time"
 
@@ -71,14 +72,14 @@ func firmwareTestServerWithAdapter(t *testing.T, adapter adapters.Snapshotter, r
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
 	chPlan := channelplan.NewStore(d.DB)
 	handler := httpapi.NewHandler(httpapi.Deps{
-		Config:       cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret, Started: time.Now(),
-		ConfigBackup: configBackup,
-		Orchestr:     orchestrMgr,
-		Firmware:     fwStore,
+		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret, Started: time.Now(),
+		ConfigBackup:  configBackup,
+		Orchestr:      orchestrMgr,
+		Firmware:      fwStore,
 		FirmwareImage: imageResolver,
-		AgentHub:     agentHub,
-		ChannelPlan:  chPlan,
-		Agents:       agents,
+		AgentHub:      agentHub,
+		ChannelPlan:   chPlan,
+		Agents:        agents,
 	})
 	srv := httptest.NewServer(handler)
 	ts := &testServer{Server: srv, db: d, secret: secret}
@@ -237,7 +238,7 @@ func TestFirmwareUpgradeRequested(t *testing.T) {
 	// Conectar un agente falso al SSE para que Send tenga éxito.
 	ctx, cancel := context.WithCancel(context.Background())
 	defer cancel()
-	var connected bool
+	var connected atomic.Bool
 	done := make(chan struct{})
 	go func() {
 		defer close(done)
@@ -248,7 +249,7 @@ func TestFirmwareUpgradeRequested(t *testing.T) {
 			return
 		}
 		defer resp.Body.Close()
-		connected = true
+		connected.Store(true)
 		// Leemos hasta que se cancele el contexto o cierre el servidor.
 		buf := make([]byte, 1024)
 		for {
@@ -262,7 +263,7 @@ func TestFirmwareUpgradeRequested(t *testing.T) {
 	}()
 	// Dar tiempo a que el stream se registre.
 	time.Sleep(200 * time.Millisecond)
-	if !connected {
+	if !connected.Load() {
 		t.Fatal("el stream SSE no se conectó")
 	}
 

+ 4 - 2
server-go/internal/httpapi/rtlconsole.go

@@ -90,12 +90,14 @@ func (c *rtlConsoleCache) snapshot(slug, host string) *rtlConsoleEntry {
 		go c.poll(slug, host)
 		c.mu.Lock()
 	}
-	out := e
+	// Copia bajo el lock: el caller lee los campos ya fuera del mutex y el
+	// poll en background los puede estar escribiendo en paralelo (#1167).
+	out := *e
 	c.mu.Unlock()
 	if out.Firmware == "" {
 		return nil
 	}
-	return out
+	return &out
 }
 
 // invalidate marca la entrada para re-poll inmediato (reboot detectado por el

+ 45 - 2
server-go/internal/httpapi/server.go

@@ -39,6 +39,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
 	"github.com/gnacho/netpulse/server-go/internal/internethealth"
+	"github.com/gnacho/netpulse/server-go/internal/mcp"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
@@ -56,7 +57,7 @@ import (
 // Version es la versión del backend (app.js:18). Es una var (no const) para
 // que goreleaser la inyecte con -X httpapi.Version={{.Version}} y el health
 // reporte la versión del tag; los builds locales caen al fallback.
-var Version = "2.28.43"
+var Version = "2.31.1"
 
 // Deps son las dependencias del servidor API (como createApp de app.js).
 type Deps struct {
@@ -135,6 +136,10 @@ type Deps struct {
 	AlertEmitter interface {
 		Emit(ev alerts.AlertEvent) bool
 	}
+	// MCP: servidor MCP embebido (#1114). nil → sin endpoint /mcp. Cuando se
+	// monta, va FUERA de RequireAuth (auth Bearer propia por API token, nunca
+	// cookie) con rate limit y fail-closed sin TokenStore.
+	MCP *mcp.Server
 }
 
 type server struct {
@@ -213,6 +218,9 @@ type server struct {
 	// TokenStore: bearer tokens de API (#330). nil = sin tokens.
 	tokenStore *apitoken.Store
 
+	// MCP: servidor MCP embebido (#1114). nil = sin endpoint /mcp.
+	mcp *mcp.Server
+
 	// CollectorReader: lector read-only de metrics.db del sidecar (#328).
 	collectorReader *collectorreader.Reader
 
@@ -261,6 +269,7 @@ func NewHandler(d Deps) http.Handler {
 		ingestLimit:     newIPRateLimit(ingestRateLimit, ingestRateWindow),
 		upgrades:        newUpgradeTracker(),
 		tokenStore:      d.TokenStore,
+		mcp:             d.MCP,
 		collectorReader: d.CollectorReader,
 		baselines:       d.Baselines,
 		internetHealth:  d.InternetHealth,
@@ -347,6 +356,9 @@ func NewHandler(d Deps) http.Handler {
 	mux.Handle("PUT /api/devices/{mac}/override", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceOverridePut)))
 	mux.Handle("GET /api/devices/{mac}/override", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceOverrideGet)))
 	mux.Handle("PUT /api/devices/{mac}/ban", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceBanPut)))
+	mux.Handle("PUT /api/devices/{mac}/link", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceLinkPut)))
+	mux.Handle("DELETE /api/devices/{mac}/link", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceLinkDelete)))
+	mux.Handle("DELETE /api/devices/{mac}", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceDelete)))
 	// Onboarding de desconocidos (#772): "dejar como anónimo" silencia la
 	// alerta first-seen de la MAC sin darle nombre (el alta reutiliza
 	// known-macs + override + reservation).
@@ -529,6 +541,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Copias de seguridad (issue #158) ---
 	s.registerBackupRoutes(mux)
 
+	// --- Rack canvas (fase 1) ---
+	s.registerRackRoutes(mux)
+
 	// Avisos externos para todas las instancias (siempre: también en demo).
 	s.startAnnouncements()
 	s.registerAnnouncementRoutes(mux)
@@ -565,7 +580,35 @@ func NewHandler(d Deps) http.Handler {
 		tv = s.tokenStore
 	}
 	s.registerHTTPS(mux)
-	return requestID(security.Middleware(s.hsts, auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))))
+	// /mcp (#1114): streamable-HTTP MCP con auth Bearer propia (API token) y
+	// rate limit. Va en un mux EXTERNO al de sesión: RequireAuth queda fuera
+	// a propósito (nunca acepta cookie; spec fase 3.5) y security headers + HSTS
+	// siguen aplicando al envolver el mux externo completo.
+	var h http.Handler = auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, tv, s.demoReadOnly(noStoreMux(mux))))
+	if d.MCP != nil {
+		outer := http.NewServeMux()
+		// Gate de integración (#1114): con el toggle apagado el endpoint
+		// DESAPARECE (404, no 403: no confirma su existencia a un escáner).
+		// Va antes de la auth Bearer propia del MCP.
+		outer.Handle("/mcp", s.mcpIntegrationGate(d.MCP.Handler(s.tokenStore)))
+		outer.Handle("/", h)
+		h = outer
+	}
+	return requestID(security.Middleware(s.hsts, h))
+}
+
+// mcpIntegrationGate deja pasar /mcp solo con la integración activada en
+// Ajustes (#1114). El gate lee la kv por petición: el toggle aplica sin
+// reiniciar. Default activo cuando el endpoint está montado (el opt-in fue
+// el env del despliegue); la UI puede apagarlo.
+func (s *server) mcpIntegrationGate(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if !kvGetDefaultOn(s.db.DB, integrationMCPKey) {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
 }
 
 // requestID lee o genera un x-request-id para cada petición y lo expone en

+ 23 - 8
server-go/internal/httpapi/settings.go

@@ -26,6 +26,10 @@ const (
 	integrationNtfyKey     = "settings.integrations.ntfy"
 	integrationTelegramKey = "settings.integrations.telegram"
 	integrationProxmoxKey  = "settings.integrations.proxmox"
+	// integrationMCPKey: toggle del endpoint /mcp (#1114). El endpoint solo
+	// EXISTE si el env NETPULSE_MCP_ENABLED=1 (opt-in duro del despliegue);
+	// esta clave (default activa) permite apagarlo desde Ajustes sin reinicio.
+	integrationMCPKey = "settings.integrations.mcp"
 )
 
 // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
@@ -152,12 +156,13 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 			Telegram *bool `json:"telegram"`
 			Proxmox  *bool `json:"proxmox"`
 			MQTT     *bool `json:"mqtt"`
+			MCP      *bool `json:"mcp"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
-		if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil {
+		if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil && body.MCP == nil {
 			writeError(w, http.StatusBadRequest, "invalid_input", "at least one integration key is required")
 			return
 		}
@@ -173,6 +178,7 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 			{body.Ntfy, integrationNtfyKey, "ntfy.enabled"},
 			{body.Telegram, integrationTelegramKey, "telegram.enabled"},
 			{body.Proxmox, integrationProxmoxKey, ""},
+			{body.MCP, integrationMCPKey, ""},
 		} {
 			if p.flag == nil {
 				continue
@@ -275,20 +281,29 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 
 // integrationsView: estado efectivo de los toggles server-side (#968).
 // Ausente = activo para ntfy/telegram/proxmox; MQTT refleja la config
-// efectiva del manager (env + kv).
-func (s *server) integrationsView() map[string]bool {
+// efectiva del manager (env + kv). MCP (#1114): false con mcpLocked=true
+// cuando el despliegue no lo habilitó por env (el endpoint no existe).
+func (s *server) integrationsView() map[string]any {
 	mqtt := kvGet(s.db.DB, "mqtt.enabled") == "true"
 	if s.mqtt != nil {
 		mqtt = s.mqtt.Config().Enabled
 	}
-	return map[string]bool{
-		"ntfy":     kvGetDefaultOn(s.db.DB, integrationNtfyKey),
-		"telegram": kvGetDefaultOn(s.db.DB, integrationTelegramKey),
-		"proxmox":  kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
-		"mqtt":     mqtt,
+	return map[string]any{
+		"ntfy":      kvGetDefaultOn(s.db.DB, integrationNtfyKey),
+		"telegram":  kvGetDefaultOn(s.db.DB, integrationTelegramKey),
+		"proxmox":   kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
+		"mqtt":      mqtt,
+		"mcp":       s.mcpMounted() && kvGetDefaultOn(s.db.DB, integrationMCPKey),
+		"mcpLocked": !s.mcpMounted(),
 	}
 }
 
+// mcpMounted: el endpoint /mcp existe en este proceso (opt-in duro por env,
+// #1114). El toggle de integración solo puede apagarlo, nunca montarlo.
+func (s *server) mcpMounted() bool {
+	return s.cfg != nil && s.cfg.MCPEnabled && s.mcp != nil
+}
+
 // setMQTTEnabled cambia SOLO el flag enabled del publisher MQTT (#968): carga
 // la config efectiva, conmuta y reaplica (sin tocar host/credenciales). Sin
 // manager (tests) cae a escribir la clave kv directamente.

+ 6 - 1
server-go/internal/httpapi/speedtest_api_test.go

@@ -66,13 +66,18 @@ func makeSpeedtestServer(t *testing.T, runner speedtest.Runner) *testServer {
 	if err != nil {
 		t.Fatalf("speedtest store: %v", err)
 	}
+	sched := speedtest.NewScheduler(stStore, d.DB, runner)
+	// #1037: el default es NDT y los providers HTTP van por su propio runner;
+	// sin inyectarlos estos tests ejecutarían runners de red reales.
+	sched.SetNDTRunner(runner)
+	sched.SetHTTPRunner(runner)
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(),
 		Hub: sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
 		Secret: secret, Agents: adapters.NewAgentRegistry(0),
 		TokenStore:  apitoken.NewStore(d, secret),
 		ChannelPlan: channelplan.NewStore(d.DB),
-		Speedtest:   speedtest.NewScheduler(stStore, d.DB, runner),
+		Speedtest:   sched,
 		Started:     time.Now(),
 	})
 	srv := httptest.NewServer(handler)

+ 23 - 6
server-go/internal/httpapi/thresholds_settings.go

@@ -1,6 +1,7 @@
-// thresholds_settings.go - umbrales server-wide (#904). Hoy solo el de señal
-// débil; el endpoint es genérico para sumar más (latencia WAN, etc.) sin
-// multiplicar rutas. GET devuelve el valor efectivo; PUT valida y persiste.
+// thresholds_settings.go - umbrales y retención server-wide (#904, #1034).
+// Empezó solo con el de señal débil; el endpoint es genérico para sumar más
+// valores de "Datos y umbrales" (retención del log de alertas, etc.) sin
+// multiplicar rutas. GET devuelve los valores efectivos; PUT valida y persiste.
 package httpapi
 
 import (
@@ -15,13 +16,15 @@ func (s *server) registerThresholdsRoutes(mux *http.ServeMux) {
 	kv := &dbKVAdapter{db: s.db.DB}
 	mux.Handle("GET /api/settings/thresholds", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
 		writeJSON(w, http.StatusOK, map[string]any{
-			"weakSignalDbm": alerts.WeakSignalDbm(s.db.DB),
+			"weakSignalDbm":      alerts.WeakSignalDbm(s.db.DB),
+			"alertRetentionDays": alerts.RetentionDays(s.db.DB),
 		})
 	})))
 
 	mux.Handle("PUT /api/settings/thresholds", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		var body struct {
-			WeakSignalDbm *int `json:"weakSignalDbm"`
+			WeakSignalDbm      *int `json:"weakSignalDbm"`
+			AlertRetentionDays *int `json:"alertRetentionDays"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			writeBodyError(w, st, "invalid_body", "body JSON inválido")
@@ -37,8 +40,22 @@ func (s *server) registerThresholdsRoutes(mux *http.ServeMux) {
 				return
 			}
 		}
+		// #1034: retención del log de alertas en días (0 = poda temporal off;
+		// la cota de 500 filas sigue aplicando). Efecto sin reinicio: la poda
+		// horaria y la de arranque leen el kv en cada pasada.
+		if body.AlertRetentionDays != nil {
+			if *body.AlertRetentionDays < 0 || *body.AlertRetentionDays > 365 {
+				writeError(w, http.StatusBadRequest, "invalid_value", "alertRetentionDays debe estar entre 0 y 365")
+				return
+			}
+			if err := kv.Set(alerts.KeyRetentionDays, strconv.Itoa(*body.AlertRetentionDays)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error", err.Error())
+				return
+			}
+		}
 		writeJSON(w, http.StatusOK, map[string]any{
-			"weakSignalDbm": alerts.WeakSignalDbm(s.db.DB),
+			"weakSignalDbm":      alerts.WeakSignalDbm(s.db.DB),
+			"alertRetentionDays": alerts.RetentionDays(s.db.DB),
 		})
 	})))
 }

+ 10 - 1
server-go/internal/httpapi/wifi_channelplan.go

@@ -78,9 +78,18 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 		}
 		slug := agentSlugForRouter(routerID)
 
+		// #1080: solo Fresh() convertía cualquier hueco de frescura del
+		// agente (reconexión, backhaul, reinicio) en "no reporta radios".
+		// Es una vista de análisis: mejor el último payload conocido aunque
+		// pase el TTL que fingir que el equipo no tiene WiFi. El aviso solo
+		// tiene sentido si no existe payload alguno (o no trae wireless).
 		var radios []probe.Radio
 		if s.agents != nil {
-			if payload, ok := s.agents.Fresh(slug); ok && payload.Data.Wireless != nil {
+			payload, ok := s.agents.Fresh(slug)
+			if !ok {
+				payload, _ = s.agents.StalePayload(slug)
+			}
+			if payload != nil && payload.Data.Wireless != nil {
 				radios = payload.Data.Wireless.Radios
 			}
 		}

+ 36 - 5
server-go/internal/mqttpub/manager.go

@@ -1,19 +1,26 @@
 // manager.go: ciclo de vida del publisher MQTT (#838). Los Ajustes lo
 // reconfiguran en caliente (cancel + rearranque) sin reiniciar NetPulse.
+
 package mqttpub
 
 import (
 	"context"
 	"log"
 	"sync"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 )
 
+// shutdownWait: cuánto espera Apply a que el publisher viejo termine su
+// cierre (offline retenido + DISCONNECT) antes de arrancar el nuevo (#1158).
+const shutdownWait = 5 * time.Second
+
 // Manager posee el publisher en marcha y permite sustituirlo.
 type Manager struct {
 	mu       sync.Mutex
 	cancel   context.CancelFunc
+	done     chan struct{} // se cierra cuando el goroutine del publisher sale
 	cfg      Config
 	version  string
 	snapshot func() *adapters.Overview
@@ -45,8 +52,35 @@ func (m *Manager) startLocked() {
 		return
 	}
 	ctx, cancel := context.WithCancel(context.Background())
+	done := make(chan struct{})
 	m.cancel = cancel
-	New(m.cfg, m.version, m.snapshot, m.demo).Start(ctx)
+	m.done = done
+	pub := New(m.cfg, m.version, m.snapshot, m.demo)
+	go func() {
+		defer close(done)
+		pub.Run(ctx)
+	}()
+}
+
+// stopLocked cancela el publisher en marcha y espera (acotado) a que su
+// goroutine termine, de modo que su offline retenido SIEMPRE aterriza antes
+// de que el siguiente publisher publique online (#1158): si el offline del
+// viejo llegase después del online del nuevo, el broker retendría offline y
+// las entidades de HA quedarían unavailable con datos fluyendo.
+func (m *Manager) stopLocked() {
+	if m.cancel == nil {
+		return
+	}
+	m.cancel()
+	m.cancel = nil
+	if m.done != nil {
+		select {
+		case <-m.done:
+		case <-time.After(shutdownWait):
+			log.Printf("[mqtt] publisher shutdown timed out after %s; starting the new one anyway", shutdownWait)
+		}
+		m.done = nil
+	}
 }
 
 // Apply sustituye la configuración y rearranca el publisher cuando cambia.
@@ -56,10 +90,7 @@ func (m *Manager) Apply(cfg Config) {
 	if cfg == m.cfg {
 		return
 	}
-	if m.cancel != nil {
-		m.cancel()
-		m.cancel = nil
-	}
+	m.stopLocked()
 	m.cfg = cfg
 	m.startLocked()
 }

+ 33 - 10
server-go/internal/mqttpub/mqttpub.go

@@ -14,6 +14,7 @@ import (
 	"os"
 	"strconv"
 	"strings"
+	"sync"
 	"time"
 
 	"github.com/gonzalop/mq"
@@ -92,6 +93,11 @@ type Publisher struct {
 	snapshot func() *adapters.Overview
 	demo     bool
 
+	// mu guards the fields below: publishCycle runs on the publisher
+	// goroutine AND from the client's OnConnect hook (initial connect and
+	// every reconnect), so the alert/router state must not be touched
+	// without the lock.
+	mu          sync.Mutex
 	seenAlerts  map[string]struct{}
 	seenInit    bool
 	lastRouters string
@@ -121,10 +127,12 @@ func (p *Publisher) Start(ctx context.Context) {
 		}
 		return
 	}
-	go p.run(ctx)
+	go p.Run(ctx)
 }
 
-func (p *Publisher) run(ctx context.Context) {
+// Run es el bucle del publisher; los callers que necesitan saber cuándo ha
+// terminado (Manager, #1158) lo invocan en su propio goroutine.
+func (p *Publisher) Run(ctx context.Context) {
 	backoff := initialBackoff
 	for {
 		if ctx.Err() != nil {
@@ -145,10 +153,6 @@ func (p *Publisher) run(ctx context.Context) {
 		backoff = initialBackoff
 		log.Printf("[mqtt] connected to %s:%d as instance %q", p.cfg.Host, p.cfg.Port, p.cfg.Instance)
 
-		p.publishAvailability(client, "online")
-		p.publishDiscovery(client)
-		p.publishCycle(client)
-
 		p.loop(ctx, client)
 
 		// The retained availability must not stay "online" after an
@@ -195,11 +199,18 @@ func (p *Publisher) loop(ctx context.Context, client *mq.Client) {
 	}
 	t := time.NewTicker(interval)
 	defer t.Stop()
+	// Log reconnect bursts once each so an unstable broker connection is
+	// visible in the journal instead of only in broker-side logs (#1153).
+	var loggedReconnects uint64
 	for {
 		select {
 		case <-ctx.Done():
 			return
 		case <-t.C:
+			if n := client.GetStats().ReconnectCount; n > loggedReconnects {
+				log.Printf("[mqtt] client reconnected %d time(s): broker connection unstable", n)
+				loggedReconnects = n
+			}
 			if client.IsConnected() {
 				p.publishCycle(client)
 			}
@@ -218,9 +229,14 @@ func (p *Publisher) publishCycle(client *mq.Client) {
 	p.publishRouters(client, ov)
 	p.publishNewAlerts(client, ov)
 
-	key := routerSetKey(ov)
-	if key != p.lastRouters {
-		p.lastRouters = key
+	newKey := routerSetKey(ov)
+	p.mu.Lock()
+	changed := newKey != p.lastRouters
+	if changed {
+		p.lastRouters = newKey
+	}
+	p.mu.Unlock()
+	if changed {
 		p.publishDiscovery(client)
 	}
 }
@@ -228,6 +244,7 @@ func (p *Publisher) publishCycle(client *mq.Client) {
 // publishNewAlerts emits an event per unseen alert. The first overview only
 // seeds the set, so a fresh server start does not replay the whole backlog.
 func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
+	p.mu.Lock()
 	if !p.seenInit {
 		for _, a := range ov.Alerts {
 			if a.ID != "" {
@@ -235,8 +252,10 @@ func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
 			}
 		}
 		p.seenInit = true
+		p.mu.Unlock()
 		return
 	}
+	var fresh []alertEvent
 	for _, a := range ov.Alerts {
 		if a.ID == "" {
 			continue
@@ -245,10 +264,14 @@ func (p *Publisher) publishNewAlerts(client *mq.Client, ov *adapters.Overview) {
 			continue
 		}
 		p.seenAlerts[a.ID] = struct{}{}
-		payload, err := json.Marshal(alertEvent{
+		fresh = append(fresh, alertEvent{
 			ID: a.ID, Severity: a.Severity, Title: a.Title, Description: a.Description,
 			RouterID: a.RouterID, Urgent: a.Urgent, Ts: a.Ts,
 		})
+	}
+	p.mu.Unlock()
+	for _, ev := range fresh {
+		payload, err := json.Marshal(ev)
 		if err != nil {
 			continue
 		}

+ 37 - 0
server-go/internal/mqttpub/mqttpub_test.go

@@ -3,6 +3,7 @@ package mqttpub
 import (
 	"context"
 	"testing"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 )
@@ -189,3 +190,39 @@ func TestHAEntitiesSelfExposeMarkedForRemoval(t *testing.T) {
 		t.Fatal("routerSetKey must change when a router starts self-exposing")
 	}
 }
+
+// #1158: Apply debe esperar al publisher viejo (bounded) antes de arrancar el
+// nuevo, sin colgarse aunque el broker sea inalcanzable (el goroutine viejo
+// sale en cuanto procesa el cancel).
+func TestManagerApplyReplacesPublisher(t *testing.T) {
+	snapshot := func() *adapters.Overview { return &adapters.Overview{} }
+	m := NewManager(Config{Enabled: true, Host: "127.0.0.1", Port: 1, Instance: "t"}, "test", snapshot, false)
+	m.Start()
+	if !m.Running() {
+		t.Fatal("publisher should be running after Start")
+	}
+
+	start := time.Now()
+	m.Apply(Config{Enabled: true, Host: "127.0.0.1", Port: 2, Instance: "t"})
+	if elapsed := time.Since(start); elapsed > shutdownWait+2*time.Second {
+		t.Fatalf("Apply took %v, the old publisher shutdown must be bounded", elapsed)
+	}
+	if !m.Running() {
+		t.Fatal("publisher should still be running after Apply")
+	}
+	if got := m.Config(); got.Port != 2 {
+		t.Fatalf("config port = %d, want 2", got.Port)
+	}
+
+	// Misma config: no-op (no rearranca ni cuelga).
+	m.Apply(Config{Enabled: true, Host: "127.0.0.1", Port: 2, Instance: "t"})
+	if !m.Running() {
+		t.Fatal("publisher must keep running after a no-op Apply")
+	}
+
+	// Deshabilitar: el publisher para.
+	m.Apply(Config{Enabled: false, Host: "127.0.0.1", Port: 2, Instance: "t"})
+	if m.Running() {
+		t.Fatal("publisher must stop when disabled")
+	}
+}

+ 4 - 0
server-go/internal/ntfy/ntfy.go

@@ -350,6 +350,10 @@ func formatMessage(ev alerts.AlertEvent) string {
 	if ev.Urgent {
 		severity = "🔴"
 	}
+	// #1074: Ts<=0 (epoch) por cualquier vía → hora actual, no "16:00:00".
+	if ev.Ts <= 0 {
+		ev.Ts = time.Now().Unix()
+	}
 	ts := time.Unix(ev.Ts, 0).Format("15:04:05")
 	var b strings.Builder
 	fmt.Fprintf(&b, "%s %s\n", severity, ev.Title)

+ 58 - 21
server-go/internal/roamevents/collector.go

@@ -163,6 +163,30 @@ func InsertEvent(db *sql.DB, ev Event) error {
 	return err
 }
 
+// csvValues divide una lista separada por comas en valores recortados no
+// vacíos (#1127: filtros multi-select de la vista de eventos).
+func csvValues(raw string) []string {
+	if strings.TrimSpace(raw) == "" {
+		return nil
+	}
+	parts := strings.Split(raw, ",")
+	out := make([]string, 0, len(parts))
+	for _, p := range parts {
+		if v := strings.TrimSpace(p); v != "" {
+			out = append(out, v)
+		}
+	}
+	return out
+}
+
+// placeholders devuelve "?,?,?" con n marcadores.
+func placeholders(n int) string {
+	if n <= 0 {
+		return ""
+	}
+	return strings.TrimSuffix(strings.Repeat("?,", n), ",")
+}
+
 // contentHash calcula el hash de dedup: minute + router + type + mac + iface.
 // Granularidad minuto: dos eventos idénticos en el mismo minuto = dup.
 // En práctica raro (un cliente no se conecta dos veces en 60s al mismo AP).
@@ -174,21 +198,34 @@ func contentHash(ev Event) string {
 }
 
 // ListEvents lee eventos desde SQLite ordenados por ts DESC. Filtros opcionales.
-func ListEvents(db *sql.DB, limit int, sinceMs int64, routerID, eventType string) ([]Event, error) {
+func ListEvents(db *sql.DB, limit int, sinceMs int64, routerID, eventType, mac string) ([]Event, error) {
 	if limit <= 0 || limit > 1000 {
 		limit = 100
 	}
 	q := "SELECT id, ts_ms, router_id, type, COALESCE(mac,''), COALESCE(iface,''), COALESCE(detail,'') FROM roam_events WHERE ts_ms >= ?"
 	args := []any{sinceMs}
-	if routerID != "" {
-		q += " AND router_id = ?"
-		args = append(args, routerID)
+	// #1127: router y mac aceptan listas separadas por comas (filtro
+	// multi-select): OR dentro del filtro, AND entre filtros.
+	if ids := csvValues(routerID); len(ids) > 0 {
+		q += " AND router_id IN (" + placeholders(len(ids)) + ")"
+		for _, id := range ids {
+			args = append(args, id)
+		}
+	}
+	if macs := csvValues(mac); len(macs) > 0 {
+		q += " AND mac IN (" + placeholders(len(macs)) + ")"
+		for _, m := range macs {
+			args = append(args, strings.ToUpper(m))
+		}
 	}
 	if eventType != "" {
 		q += " AND type = ?"
 		args = append(args, eventType)
 	}
-	q += " ORDER BY ts_ms DESC LIMIT ?"
+	// #1097: ts_ms tiene precisión de segundo en los logs de OpenWrt (sin
+	// millis) y eventos del mismo segundo quedaban en orden arbitrario. El
+	// id autoincrement preserva el orden de inserción (== orden del log).
+	q += " ORDER BY ts_ms DESC, id DESC LIMIT ?"
 	args = append(args, limit)
 	rows, err := db.Query(q, args...)
 	if err != nil {
@@ -269,27 +306,27 @@ func ParseLogreadLine(line, routerID string) (Event, bool) {
 		return Event{}, false
 	}
 
+	var ev Event
+	var ok bool
 	switch prog {
 	case "hostapd":
-		ev, ok := parseHostapd(rest, routerID, ts)
-		if !ok {
-			return Event{}, false
-		}
-		return ev, true
+		ev, ok = parseHostapd(rest, routerID, ts)
 	case "dawn":
-		ev, ok := parseDawn(rest, routerID, ts)
-		if !ok {
-			return Event{}, false
-		}
-		return ev, true
+		ev, ok = parseDawn(rest, routerID, ts)
 	case "usteer":
-		ev, ok := parseUsteer(rest, routerID, ts)
-		if !ok {
-			return Event{}, false
-		}
-		return ev, true
+		ev, ok = parseUsteer(rest, routerID, ts)
+	default:
+		return Event{}, false
 	}
-	return Event{}, false
+	if !ok {
+		return Event{}, false
+	}
+	// #1129: los logs (hostapd/dawn/usteer) emiten la MAC en minúsculas y
+	// el resto de la app canonicaliza a MAYÚSCULAS (#960). Normalizando en
+	// la ingesta, el filtro por cliente de /api/roam-events (que compara en
+	// mayúsculas) casa con lo guardado y el nameByMac del frontend también.
+	ev.MAC = strings.ToUpper(ev.MAC)
+	return ev, true
 }
 
 func parseHostapd(rest, routerID string, ts int64) (Event, bool) {

+ 80 - 7
server-go/internal/roamevents/collector_test.go

@@ -10,6 +10,79 @@ import (
 
 // TestParseLogreadFlint2 usa líneas reales de logread del Flint2 (capturadas
 // vía SSH durante el diseño de Fase 14.5).
+// TestListEventsSameSecondOrdering (#1097): los logs de OpenWrt no llevan
+// millis, y un burst del mismo segundo debe conservar el orden del log:
+// el desempate es el id autoincrement (orden de inserción), no el azar.
+func TestListEventsSameSecondOrdering(t *testing.T) {
+	db := openMemDB(t)
+	// Mismo ts_ms, inserción en orden: conectado primero, desconectado después.
+	ordered := []Event{
+		{TsMs: 5000, RouterID: "rt1", Type: TypeConnected, MAC: "AA:AA:AA:AA:AA:01", Iface: "wlan0"},
+		{TsMs: 5000, RouterID: "rt1", Type: TypeDisconnected, MAC: "AA:AA:AA:AA:AA:01", Iface: "wlan0"},
+	}
+	for _, ev := range ordered {
+		if err := InsertEvent(db, ev); err != nil {
+			t.Fatal(err)
+		}
+	}
+	got, err := ListEvents(db, 10, 0, "", "", "")
+	if err != nil || len(got) != 2 {
+		t.Fatalf("list: %v %+v", err, got)
+	}
+	// Más reciente arriba: el desconectado (insertado después, id mayor).
+	if got[0].Type != TypeDisconnected || got[1].Type != TypeConnected {
+		t.Fatalf("orden a mismo segundo roto: %+v", got)
+	}
+	// Filtro por cliente (#1097): MAC en minúsculas debe normalizarse.
+	one, err := ListEvents(db, 10, 0, "", "", "aa:aa:aa:aa:aa:01")
+	if err != nil || len(one) != 2 {
+		t.Fatalf("filtro mac: %v %+v", err, one)
+	}
+	none, _ := ListEvents(db, 10, 0, "", "", "BB:BB:BB:BB:BB:02")
+	if len(none) != 0 {
+		t.Fatalf("filtro mac negativo: %+v", none)
+	}
+}
+
+// TestListEventsMultiSelect (#1127): router y mac aceptan listas separadas
+// por comas (filtros multi-select de la vista de eventos): OR dentro del
+// filtro, AND entre filtros. Las MACs del filtro se comparan en mayúsculas
+// (#1129: la ingesta canonicaliza a mayúsculas desde los logs en minúsculas).
+func TestListEventsMultiSelect(t *testing.T) {
+	db := openMemDB(t)
+	seed := []Event{
+		{TsMs: 1000, RouterID: "rt1", Type: TypeConnected, MAC: "AA:AA:AA:AA:AA:01", Iface: "wlan0"},
+		{TsMs: 2000, RouterID: "rt2", Type: TypeDisconnected, MAC: "AA:AA:AA:AA:AA:02", Iface: "wlan1"},
+		{TsMs: 3000, RouterID: "rt1", Type: TypeDawnDecision, MAC: "AA:AA:AA:AA:AA:03"},
+		{TsMs: 4000, RouterID: "rt3", Type: TypeConnected, MAC: "AA:AA:AA:AA:AA:01", Iface: "wlan0"},
+	}
+	for _, ev := range seed {
+		if err := InsertEvent(db, ev); err != nil {
+			t.Fatal(err)
+		}
+	}
+	// OR de MACs (una en minúsculas en el parámetro -> normaliza).
+	got, err := ListEvents(db, 10, 0, "", "", "aa:aa:aa:aa:aa:01,AA:AA:AA:AA:AA:02")
+	if err != nil || len(got) != 3 {
+		t.Fatalf("filtro mac multi: %v %+v", err, got)
+	}
+	// AND router x mac.
+	got, err = ListEvents(db, 10, 0, "rt1", "", "AA:AA:AA:AA:AA:01")
+	if err != nil || len(got) != 1 || got[0].RouterID != "rt1" {
+		t.Fatalf("filtro router+mac: %v %+v", err, got)
+	}
+	// OR de routers.
+	got, err = ListEvents(db, 10, 0, "rt2,rt3", "", "")
+	if err != nil || len(got) != 2 {
+		t.Fatalf("filtro router multi: %v %+v", err, got)
+	}
+	// Lista con vacíos/espacios no rompe.
+	got, err = ListEvents(db, 10, 0, " rt1 , , rt2 ", "", "")
+	if err != nil || len(got) != 3 {
+		t.Fatalf("filtro router multi con vacíos: %v %+v", err, got)
+	}
+}
+
 func TestParseLogreadFlint2(t *testing.T) {
 	lines := []string{
 		"Sat Aug  8 19:21:45 2026 daemon.notice hostapd: wlan1: BEACON-RESP-RX 1e:4e:75:a0:6f:6f 35 04",
@@ -50,12 +123,12 @@ func TestParseUsteer(t *testing.T) {
 		{
 			"Sat Aug  8 19:21:58 2026 user.info usteer: station 04:95:e6:76:55:a1 connected to node 04:95:e6:76:55:b2",
 			TypeConnected,
-			"04:95:e6:76:55:a1",
+			"04:95:E6:76:55:A1",
 		},
 		{
 			"Sat Aug  8 19:21:59 2026 user.info usteer: station 04:95:e6:76:55:a1 disconnected from node 04:95:e6:76:55:b2",
 			TypeDisconnected,
-			"04:95:e6:76:55:a1",
+			"04:95:E6:76:55:A1",
 		},
 	}
 	for _, tc := range cases {
@@ -153,7 +226,7 @@ func TestParseHostapdConnected(t *testing.T) {
 			if ev.Iface != c.iface {
 				t.Errorf("iface = %q, want %q", ev.Iface, c.iface)
 			}
-			if ev.MAC != "04:95:e6:76:55:a1" {
+			if ev.MAC != "04:95:E6:76:55:A1" {
 				t.Errorf("mac = %q", ev.MAC)
 			}
 		})
@@ -277,7 +350,7 @@ func TestListEventsFilters(t *testing.T) {
 	}
 
 	// Sin filtro: 3 eventos, orden DESC por ts.
-	got, err := ListEvents(db, 100, 0, "", "")
+	got, err := ListEvents(db, 100, 0, "", "", "")
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -288,17 +361,17 @@ func TestListEventsFilters(t *testing.T) {
 		t.Errorf("primero debería ser ts=3000 (DESC), got %d", got[0].TsMs)
 	}
 
-	got, _ = ListEvents(db, 100, 0, "rt1", "")
+	got, _ = ListEvents(db, 100, 0, "rt1", "", "")
 	if len(got) != 2 {
 		t.Errorf("filtro router rt1: %d, want 2", len(got))
 	}
 
-	got, _ = ListEvents(db, 100, 0, "", TypeConnected)
+	got, _ = ListEvents(db, 100, 0, "", TypeConnected, "")
 	if len(got) != 1 {
 		t.Errorf("filtro tipo connected: %d, want 1", len(got))
 	}
 
-	got, _ = ListEvents(db, 100, 2000, "", "")
+	got, _ = ListEvents(db, 100, 2000, "", "", "")
 	if len(got) != 2 {
 		t.Errorf("filtro since 2000: %d, want 2", len(got))
 	}

+ 51 - 6
server-go/internal/routerstore/routerstore.go

@@ -27,7 +27,7 @@ const probeTimeout = 4 * time.Second
 // ListRouters devuelve la tabla routers ordenada is_gateway DESC,
 // created_at ASC, con is_gateway como booleano.
 func ListRouters(db *sql.DB) []adapters.RouterConfig {
-	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, temp_threshold, console_polling FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, temp_threshold, console_polling, routeros_user, routeros_password, routeros_insecure, disabled FROM routers ORDER BY is_gateway DESC, created_at ASC")
 	if err != nil {
 		return []adapters.RouterConfig{}
 	}
@@ -35,16 +35,17 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 	out := []adapters.RouterConfig{}
 	for rows.Next() {
 		var r adapters.RouterConfig
-		var gw, ao, snmpEn, snmpPort, snmpInterval, sshPort, consolePoll int
-		var name, ft, snmpComm sql.NullString
+		var gw, ao, snmpEn, snmpPort, snmpInterval, sshPort, consolePoll, roInsecure, disabled int
+		var name, ft, snmpComm, roUser, roPass sql.NullString
 		var tt sql.NullInt64
-		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort, &tt, &consolePoll); err != nil {
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort, &tt, &consolePoll, &roUser, &roPass, &roInsecure, &disabled); err != nil {
 			continue
 		}
 		// DEFAULT 1 de la migración, pero una fila insertada antes de la
 		// columna con valor 0 explícito cuenta como desactivada; el NULL no
 		// aplica (NOT NULL DEFAULT 1).
 		r.ConsolePolling = consolePoll == 1
+		r.Disabled = disabled == 1
 		r.Name = name.String
 		r.FirmwareTarget = ft.String
 		r.IsGateway = gw == 1
@@ -58,6 +59,9 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 			v := int(tt.Int64)
 			r.TempThreshold = &v
 		}
+		r.RouterOSUser = roUser.String
+		r.RouterOSPassword = roPass.String
+		r.RouterOSInsecure = roInsecure == 1
 		out = append(out, r)
 	}
 	return out
@@ -147,6 +151,10 @@ type AddInput struct {
 	// ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
 	// nil = default ON (el sondeo no se desactiva por omisión).
 	ConsolePolling *bool
+	// RouterOS: credenciales de la REST API nativa (Type "routeros").
+	RouterOSUser     string
+	RouterOSPassword string
+	RouterOSInsecure bool
 }
 
 // AddRouter inserta un router (si IsGateway, el resto pierde el flag —
@@ -199,9 +207,13 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 	if in.ConsolePolling != nil && !*in.ConsolePolling {
 		consolePoll = 0
 	}
+	roInsecure := 0
+	if in.RouterOSInsecure {
+		roInsecure = 1
+	}
 	if _, err := tx.Exec(
-		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, console_polling) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
-		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, sshPort, consolePoll,
+		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, console_polling, routeros_user, routeros_password, routeros_insecure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, sshPort, consolePoll, in.RouterOSUser, in.RouterOSPassword, roInsecure,
 	); err != nil {
 		return adapters.RouterConfig{}, err
 	}
@@ -234,6 +246,9 @@ type UpdateInput struct {
 	Type      *string
 	IsGateway *bool
 	AgentOnly *bool
+	// Disabled (issue #1085): nil = no tocar; true = pausar la unidad
+	// (sin sondeo ni alertas, insignia y fuera de desplegables).
+	Disabled *bool
 	// FirmwareTarget: versión objetivo (issue #241). nil = no tocar; "" = limpiar.
 	FirmwareTarget *string
 	// SNMP (issue #309): nil = no tocar; puntero a bool/string/int = aplicar.
@@ -249,6 +264,12 @@ type UpdateInput struct {
 	// ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
 	// nil = no tocar. DEFAULT ON (la columna migra a 1).
 	ConsolePolling *bool
+	// RouterOS: nil = no tocar. Password: string vacía se ignora (no borra
+	// una password ya guardada) — dejar el campo en blanco en el form de
+	// edición conserva la credencial existente.
+	RouterOSUser     *string
+	RouterOSPassword *string
+	RouterOSInsecure *bool
 }
 
 // UpdateRouter actualiza un router existente por id. Si IsGateway pasa a true,
@@ -302,6 +323,14 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 		sets = append(sets, "agent_only = ?")
 		args = append(args, ao)
 	}
+	if in.Disabled != nil {
+		v := 0
+		if *in.Disabled {
+			v = 1
+		}
+		sets = append(sets, "disabled = ?")
+		args = append(args, v)
+	}
 	if in.FirmwareTarget != nil {
 		sets = append(sets, "firmware_target = ?")
 		args = append(args, *in.FirmwareTarget)
@@ -355,6 +384,22 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 			sets = append(sets, "temp_threshold = NULL")
 		}
 	}
+	if in.RouterOSUser != nil {
+		sets = append(sets, "routeros_user = ?")
+		args = append(args, *in.RouterOSUser)
+	}
+	if in.RouterOSPassword != nil && *in.RouterOSPassword != "" {
+		sets = append(sets, "routeros_password = ?")
+		args = append(args, *in.RouterOSPassword)
+	}
+	if in.RouterOSInsecure != nil {
+		v := 0
+		if *in.RouterOSInsecure {
+			v = 1
+		}
+		sets = append(sets, "routeros_insecure = ?")
+		args = append(args, v)
+	}
 	if len(sets) > 0 {
 		args = append(args, id)
 		if _, err := tx.Exec("UPDATE routers SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...); err != nil {

+ 42 - 4
server-go/internal/snmp/ifTable.go

@@ -13,6 +13,13 @@ type PortStats struct {
 	Name       string
 	Descr      string
 	Alias      string
+	Type       int
+	// Familia de la interfaz para las NO físicas (#1125): "lag", "vlan",
+	// "bridge", "tunnel" o "virtual". Vacío = boca física (o ifType no
+	// reportado por walk fallido: se conserva en el grupo físico, la misma
+	// defensa de la #1115). El frontend las agrupa colapsadas al pie de la
+	// tarjeta de puertos en vez de ocultarlas.
+	Family     string
 	SpeedBps   uint64
 	HighSpeedMbps uint32
 	OperUp     bool
@@ -45,8 +52,11 @@ func (p PortStats) SpeedString() string {
 }
 
 func (p PortStats) DisplayName() string {
-	if p.Alias != "" {
-		return p.Alias
+	// #1077: algunos vendors (p.ej. TP-Link Omada) persisten un espacio en
+	// blanco como port label y lo emiten en ifAlias; un alias vacío tras
+	// recortar NO cuenta como etiqueta.
+	if a := strings.TrimSpace(p.Alias); a != "" {
+		return a
 	}
 	if p.Name != "" {
 		return p.Name
@@ -59,7 +69,7 @@ func (p PortStats) DisplayName() string {
 
 func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
 	oids := []string{
-		OidIfIndex, OidIfDescr, OidIfSpeed, OidIfOperStatus,
+		OidIfIndex, OidIfDescr, OidIfType, OidIfSpeed, OidIfOperStatus,
 		OidIfInOctets, OidIfInErrors, OidIfOutOctets, OidIfOutErrors,
 		OidIfName, OidIfHighSpeed, OidIfAlias,
 	}
@@ -84,18 +94,44 @@ func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
 	}
 	out := make([]PortStats, 0, len(byIdx))
 	for _, ps := range byIdx {
+		ps.Family = ifFamily(ps.Type)
 		out = append(out, *ps)
 	}
 	sortByIndex(out)
 	return out, nil
 }
 
+// nonPhysicalIfTypeFamilies: ifTypes (IANA) que NO son una boca física del
+// switch, con su familia para el grupo colapsado de la tarjeta (#1125,
+// alternativa a ocultarlas de la #1115: nada se pierde y las referencias
+// FDB/LLDP por ifIndex siguen resolviendo). Verificado en un Linksys LGS310C
+// real: po1-8 llegan como ieee8023adLag(161) y vlan1 como l3ipvlan(136).
+// Todo ifType que NO esté en el mapa (incluido Type=0 por walk fallido) se
+// trata como físico: la defensa por exclusión de la #1115 se conserva.
+var nonPhysicalIfTypeFamilies = map[int]string{
+	24:  "virtual", // softwareLoopback
+	53:  "virtual", // propVirtual
+	131: "tunnel",  // tunnel
+	135: "vlan",    // l2vlan
+	136: "vlan",    // l3ipvlan
+	161: "lag",     // ieee8023adLag
+	209: "bridge",  // bridge
+}
+
+// ifFamily clasifica una interfaz por su ifType: "" = física (o desconocida),
+// en otro caso la familia del grupo virtual (#1125).
+func ifFamily(t int) string {
+	return nonPhysicalIfTypeFamilies[t]
+}
+
 func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {
 	switch oid {
 	case OidIfIndex:
 		ps.Index = int(uint64Val(pdu))
 	case OidIfDescr:
 		ps.Descr = stringVal(pdu)
+	case OidIfType:
+		ps.Type = int(uint64Val(pdu))
 	case OidIfSpeed:
 		ps.SpeedBps = uint64Val(pdu)
 	case OidIfOperStatus:
@@ -116,7 +152,9 @@ func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {
 			ps.HighSpeedMbps = uint32(v)
 		}
 	case OidIfAlias:
-		ps.Alias = stringVal(pdu)
+		// #1077: recortar siempre; un ifAlias de solo espacios (Omada guarda
+		// el label vacío como " ") no debe ganarle al ifName en DisplayName.
+		ps.Alias = strings.TrimSpace(stringVal(pdu))
 	}
 }
 

+ 7 - 0
server-go/internal/snmp/oids.go

@@ -32,4 +32,11 @@ const (
 	// OidDot1qTpFdbPort: tabla FDB de Q-BRIDGE MIB (RFC 4363). Algunos
 	// switches gestionados solo la exponen (y no la dot1d) → fallback (#661).
 	OidDot1qTpFdbPort = ".1.3.6.1.2.1.17.7.1.2.2.1.2"
+
+	// LLDP-MIB (IEEE 802.1AB): tabla de vecinos remotos y sus direcciones de
+	// gestión (#931). Los switches SNMP que la exponen anuncian qué equipo
+	// cuelga de cada puerto; alimenta routerPolled.lldp con el mismo
+	// contrato que la sonda lldpd de los routers (#300).
+	OidLldpRemTable   = ".1.0.8802.1.1.2.1.4.1.1"
+	OidLldpRemManAddr = ".1.0.8802.1.1.2.1.4.2.1"
 )

+ 42 - 0
server-go/internal/snmp/snmp_test.go

@@ -106,6 +106,9 @@ func TestPortStatsDisplayName(t *testing.T) {
 		{PortStats{Descr: "GigabitEthernet0/1"}, "GigabitEthernet0/1"},
 		{PortStats{Index: 5}, "port-5"},
 		{PortStats{Alias: "Uplink", Name: "eth0"}, "Uplink"},
+		{PortStats{Alias: " ", Name: "gi1/0/8"}, "gi1/0/8"},
+		{PortStats{Alias: "   "}, "port-0"},
+		{PortStats{Alias: " Uplink ", Name: "eth0"}, "Uplink"},
 	}
 	for _, tt := range tests {
 		got := tt.ps.DisplayName()
@@ -141,6 +144,15 @@ func TestApplyPortField(t *testing.T) {
 	if ps.RxBytes != 123456789 {
 		t.Errorf("RxBytes = %d; want 123456789", ps.RxBytes)
 	}
+	// #1077: un ifAlias de solo espacios se normaliza a vacío en el parseo.
+	applyPortField(ps, OidIfAlias, gosnmp.SnmpPDU{Value: " "})
+	if ps.Alias != "" {
+		t.Errorf("Alias = %q; want empty for whitespace-only ifAlias", ps.Alias)
+	}
+	applyPortField(ps, OidIfAlias, gosnmp.SnmpPDU{Value: " Uplink "})
+	if ps.Alias != "Uplink" {
+		t.Errorf("Alias = %q; want Uplink (trimmed)", ps.Alias)
+	}
 }
 
 func TestSystemInfoParsing(t *testing.T) {
@@ -204,3 +216,33 @@ func TestSortByIndex(t *testing.T) {
 		}
 	}
 }
+
+// #1125 (alternativa a la exclusión de la #1115): el ifTable conserva TODAS
+// las interfaces y cada una se clasifica por familia; las no físicas (LAG,
+// VLAN, bridge, túnel, virtual) van al grupo colapsado de la tarjeta en el
+// frontend en vez de desaparecer. Verificado en un LGS310C real: po1-8
+// (ieee8023adLag) y vlan1 (l3ipvlan) clasificados; un ifType no listado o no
+// reportado (Type=0 por walk fallido) sigue siendo físico (defensa #1115).
+func TestIfFamilyClassification(t *testing.T) {
+	cases := []struct {
+		typ    int
+		family string
+	}{
+		{6, ""},          // ethernetCsmacd: física
+		{117, ""},        // gigabitEthernet: física
+		{161, "lag"},     // ieee8023adLag (LGS310C poN)
+		{136, "vlan"},    // l3ipvlan (LGS310C vlan1)
+		{135, "vlan"},    // l2vlan
+		{209, "bridge"},  // bridge
+		{131, "tunnel"},  // tunnel
+		{24, "virtual"},  // softwareLoopback
+		{53, "virtual"},  // propVirtual
+		{0, ""},          // sin ifType: físico (walk fallido conserva todo)
+		{9999, ""},       // desconocido: se trata como físico por exclusión
+	}
+	for _, c := range cases {
+		if got := ifFamily(c.typ); got != c.family {
+			t.Errorf("ifFamily(%d) = %q, esperaba %q", c.typ, got, c.family)
+		}
+	}
+}

+ 2 - 1
server-go/internal/speedtest/http_runner.go

@@ -33,10 +33,11 @@ const (
 	ProviderCloudflare = "cloudflare" // speed.cloudflare.com por HTTP directo
 	ProviderLibrespeed = "librespeed" // instancia LibreSpeed (serverURL = base)
 	ProviderCustom     = "custom"     // endpoint HTTP libre (#1001): serverURL es la URL completa
+	ProviderNDT        = "ndt"        // M-Lab NDT (#1037): locate automático, serverURL = FQDN opcional
 )
 
 func validProvider(v string) bool {
-	return v == ProviderOokla || v == ProviderCloudflare || v == ProviderLibrespeed || v == ProviderCustom
+	return v == ProviderOokla || v == ProviderCloudflare || v == ProviderLibrespeed || v == ProviderCustom || v == ProviderNDT
 }
 
 // Limites de la medicion HTTP: al menos minDur midiendo (precision en

+ 3 - 3
server-go/internal/speedtest/http_runner_test.go

@@ -179,9 +179,9 @@ func TestSpeedtestProviderSettings(t *testing.T) {
 	}
 	sched := NewScheduler(st, d.DB, fakeRunner{})
 
-	// Default: provider vacio (ookla) en instalaciones sin la clave.
-	if got := sched.LoadSettings(); got.Provider != "" {
-		t.Fatalf("provider default = %q, want vacio (ookla)", got.Provider)
+	// Default: NDT (#1037) en instalaciones sin la clave (privacidad).
+	if got := sched.LoadSettings(); got.Provider != ProviderNDT {
+		t.Fatalf("provider default = %q, want ndt", got.Provider)
 	}
 	// Roundtrip cloudflare.
 	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderCloudflare}); err != nil {

+ 137 - 11
server-go/internal/speedtest/scheduler.go

@@ -40,8 +40,21 @@ var ValidIntervals = []int{6, 12, 24, 168, 720}
 const (
 	DefaultIntervalHours = 12
 	DefaultAlertPct      = 50
-	testTimeout          = 3 * time.Minute
-	tickEvery            = 30 * time.Second
+	// DefaultSchedTime (#1066): hora por defecto de la programación. Era
+	// 01:00; a las 03:00 local el tráfico residencial suele estar en su
+	// mínimo, así el test no compite con el uso real de la línea.
+	DefaultSchedTime = "03:00"
+	testTimeout      = 3 * time.Minute
+	tickEvery        = 30 * time.Second
+)
+
+// #1066: programación "auto": el scheduler elige la hora de menos tráfico
+// de su propio histórico (tabla metrics, últimos 7 días); sin datos, cae a
+// la hora por defecto (03:00).
+const (
+	scheduleKindAuto  = "auto"
+	defaultQuietHour  = 3
+	quietHourLookback = 7 * 24 * time.Hour
 )
 
 // Settings persistidas en kv (claves settings.speedtest.*).
@@ -57,7 +70,9 @@ type Settings struct {
 	Provider string `json:"provider,omitempty"`
 	// Programación (#744): "interval" (cada IntervalHours, comportamiento
 	// histórico) | "weekly" (DayOfWeek a la Time local) | "monthly"
-	// (DayOfMonth a la Time local; si el mes no tiene ese día, el último).
+	// (DayOfMonth a la Time local; si el mes no tiene ese día, el último) |
+	// "auto" (#1066: diaria a la hora de menos tráfico del histórico propio;
+	// Time la deriva el scheduler y se ignora el valor persistido).
 	ScheduleKind string `json:"scheduleKind,omitempty"`
 	DayOfWeek    *int   `json:"dayOfWeek,omitempty"`  // 0=domingo..6=sábado (weekly)
 	DayOfMonth   *int   `json:"dayOfMonth,omitempty"` // 1..31 (monthly)
@@ -97,6 +112,10 @@ type Scheduler struct {
 	// en tests.
 	httpRunner Runner
 
+	// ndtRunner (#1037) ejecuta el provider M-Lab NDT; nil = NDTRunner{} por
+	// ejecución. Inyectable en tests.
+	ndtRunner Runner
+
 	// contractDown lee el plan contratado declarado (#151). Inyectada para
 	// no duplicar la lógica kv del httpapi; nil = nunca alertar.
 	contractDown func() (float64, bool)
@@ -107,7 +126,8 @@ type Scheduler struct {
 	running  atomic.Bool
 	mu       sync.Mutex
 	lastErr  string
-	belowPln bool // debounce de la alerta: true hasta que un test recupere
+	belowPln bool   // debounce de la alerta: true hasta que un test recupere
+	autoTime string // #1066: última hora elegida por kind "auto" ("HH:MM")
 }
 
 func NewScheduler(store *Store, db *sql.DB, runner Runner) *Scheduler {
@@ -125,9 +145,20 @@ func (s *Scheduler) SetAlertEmitter(e AlertEmitter) { s.emit = e }
 // SetHTTPRunner inyecta el runner de los providers HTTP (#976), para tests.
 func (s *Scheduler) SetHTTPRunner(r Runner) { s.httpRunner = r }
 
+// SetNDTRunner inyecta el runner del provider M-Lab NDT (#1037), para tests.
+func (s *Scheduler) SetNDTRunner(r Runner) { s.ndtRunner = r }
+
 // runnerFor elige la implementacion segun el provider configurado.
 func (s *Scheduler) runnerFor(provider string) Runner {
-	if provider == "" || provider == ProviderOokla {
+	// #1037: "" (no configurado) y el default NDT van al runner NDT; Ookla
+	// solo explícito.
+	if provider == "" || provider == ProviderNDT {
+		if s.ndtRunner != nil {
+			return s.ndtRunner
+		}
+		return NDTRunner{}
+	}
+	if provider == ProviderOokla {
 		return s.runner
 	}
 	if s.httpRunner != nil {
@@ -154,6 +185,11 @@ func (s *Scheduler) Start() {
 
 func (s *Scheduler) tick() {
 	st := s.LoadSettings()
+	if st.ScheduleKind == scheduleKindAuto {
+		// #1066: la hora se reevalúa en cada tick (el patrón de consumo
+		// cambia: findes, vacaciones) y queda cacheada para Status.
+		st.Time = s.resolveAutoTime()
+	}
 	if !st.Enabled || s.running.Load() {
 		return
 	}
@@ -237,6 +273,9 @@ type Status struct {
 	LastError string  `json:"lastError,omitempty"`
 	Last      *Result `json:"last,omitempty"`
 	NextRun   *int64  `json:"nextRunMs,omitempty"` // unix ms; nil = sin programar
+	// AutoTime (#1066): hora elegida por la programación "auto" ("HH:MM",
+	// hora local); solo presente con scheduleKind "auto".
+	AutoTime string `json:"autoTime,omitempty"`
 }
 
 // Status compone la foto actual (running, último error, último resultado y
@@ -244,6 +283,18 @@ type Status struct {
 func (s *Scheduler) Status() Status {
 	st := s.LoadSettings()
 	out := Status{Running: s.running.Load()}
+	if st.ScheduleKind == scheduleKindAuto {
+		// La hora la conoce el tick; si aún no ha pasado ninguno (server
+		// recién arrancado), se calcula ahora para que la UI pueda enseñarla.
+		s.mu.Lock()
+		auto := s.autoTime
+		s.mu.Unlock()
+		if auto == "" {
+			auto = s.resolveAutoTime()
+		}
+		st.Time = auto
+		out.AutoTime = auto
+	}
 	s.mu.Lock()
 	out.LastError = s.lastErr
 	s.mu.Unlock()
@@ -304,10 +355,56 @@ func (s *Scheduler) setLastError(err error) {
 	s.lastErr = err.Error()
 }
 
+// resolveAutoTime (#1066) calcula la hora elegida por la programación "auto"
+// (la de menos tráfico medio del histórico) y la cachea para Status.
+func (s *Scheduler) resolveAutoTime() string {
+	tm := fmt.Sprintf("%02d:00", s.quietHour(s.now()))
+	s.mu.Lock()
+	s.autoTime = tm
+	s.mu.Unlock()
+	return tm
+}
+
+// quietHour devuelve la hora del día (local) con menor tráfico medio
+// (bajada+subida) de los últimos 7 días según la tabla metrics; sin datos
+// suficientes devuelve defaultQuietHour (03:00). La hora se agrupa en la
+// zona horaria local del server (misma referencia que el resto del
+// scheduler), corrigiendo el epoch con el offset activo en `now`.
+func (s *Scheduler) quietHour(now time.Time) int {
+	if s.db == nil {
+		return defaultQuietHour
+	}
+	_, off := now.Zone()
+	rows, err := s.db.Query(
+		`SELECT ((ts/1000 + ?) % 86400) / 3600 AS h,
+		        AVG(COALESCE(rx_bps, 0) + COALESCE(tx_bps, 0)), COUNT(*)
+		 FROM metrics WHERE ts >= ? GROUP BY h`,
+		off, now.Add(-quietHourLookback).UnixMilli())
+	if err != nil {
+		return defaultQuietHour
+	}
+	defer rows.Close()
+	best, bestAvg, seen := 0, 0.0, false
+	for rows.Next() {
+		var h, n int
+		var avg float64
+		if err := rows.Scan(&h, &avg, &n); err != nil {
+			continue
+		}
+		if !seen || avg < bestAvg {
+			best, bestAvg, seen = h, avg, true
+		}
+	}
+	if !seen {
+		return defaultQuietHour
+	}
+	return best
+}
+
 // LoadSettings lee la configuración del kv con defaults sanos (valores
 // inválidos o ausentes → default, nunca error: el test debe poder arrancar).
 func (s *Scheduler) LoadSettings() Settings {
-	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct, ScheduleKind: "interval"}
+	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct, ScheduleKind: "interval", Time: DefaultSchedTime}
 	if s.db == nil {
 		return st
 	}
@@ -320,6 +417,9 @@ func (s *Scheduler) LoadSettings() Settings {
 	}
 	if v := kvGet(s.db, kvProvider); validProvider(v) {
 		st.Provider = v
+	} else {
+		// #1037: default NDT (privacidad) cuando no hay nada configurado.
+		st.Provider = ProviderNDT
 	}
 	if v, ok := kvInt(s.db, kvAlertPct); ok && v >= 0 && v <= 90 {
 		st.AlertPct = v
@@ -347,7 +447,7 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 		st.ScheduleKind = "interval"
 	}
 	if !validScheduleKind(st.ScheduleKind) {
-		return errors.New("scheduleKind debe ser interval, weekly o monthly")
+		return errors.New("scheduleKind debe ser interval, auto, weekly o monthly")
 	}
 	switch st.ScheduleKind {
 	case "weekly":
@@ -364,6 +464,9 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 		if !validTimeStr(st.Time) {
 			return errors.New("monthly exige time HH:MM")
 		}
+	case scheduleKindAuto:
+		// sin campos extra: la hora la deriva el scheduler del histórico y
+		// lo que llegue en Time se ignora (no se afirma una hora concreta).
 	default:
 		if !validInterval(st.IntervalHours) {
 			return fmt.Errorf("intervalo inválido (%d): permite %v", st.IntervalHours, ValidIntervals)
@@ -377,12 +480,14 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 	}
 	// Provider (#976): librespeed necesita la URL base de la instancia y
 	// custom (#1001) la URL completa del endpoint; los demás la ignoran
-	// (ookla: servidor concreto opcional; cloudflare: endpoints fijos).
+	// (ookla/ndt: servidor concreto opcional; cloudflare: endpoints fijos).
+	// Por defecto NDT (#1037): medición neutral y sin ánimo comercial, mejor
+	// privacidad que Ookla; los que ya tengan otro provider en kv lo conservan.
 	if st.Provider == "" {
-		st.Provider = ProviderOokla
+		st.Provider = ProviderNDT
 	}
 	if !validProvider(st.Provider) {
-		return errors.New("provider debe ser ookla, cloudflare, librespeed o custom")
+		return errors.New("provider debe ser ookla, cloudflare, librespeed, custom o ndt")
 	}
 	if st.Provider == ProviderLibrespeed && strings.TrimSpace(st.ServerURL) == "" {
 		return errors.New("librespeed exige serverUrl con la URL base de la instancia")
@@ -454,7 +559,7 @@ func trapServerURL(raw string) bool {
 }
 
 func validScheduleKind(v string) bool {
-	return v == "interval" || v == "weekly" || v == "monthly"
+	return v == "interval" || v == "weekly" || v == "monthly" || v == scheduleKindAuto
 }
 
 func validTimeStr(v string) bool {
@@ -512,6 +617,15 @@ func testDue(st Settings, last *Result, now time.Time) bool {
 		return false
 	}
 	switch st.ScheduleKind {
+	case scheduleKindAuto:
+		// Diario a la hora elegida. El tick resuelve st.Time con la hora de
+		// menos tráfico; el fallback cubre llamadas directas con Time vacío.
+		tm := st.Time
+		if !validTimeStr(tm) {
+			tm = DefaultSchedTime
+		}
+		slot := todaySlot(tm, now)
+		return !now.Before(slot) && (last == nil || last.TS.Before(slot))
 	case "weekly":
 		dow := 0
 		if st.DayOfWeek != nil {
@@ -543,6 +657,18 @@ func testDue(st Settings, last *Result, now time.Time) bool {
 func nextRunAt(st Settings, last *Result, now time.Time) time.Time {
 	h, m := parseTimeHHMM(st.Time)
 	switch st.ScheduleKind {
+	case scheduleKindAuto:
+		tm := st.Time
+		if !validTimeStr(tm) {
+			tm = DefaultSchedTime
+		}
+		ah, am := parseTimeHHMM(tm)
+		slot := todaySlot(tm, now)
+		if now.Before(slot) || last == nil || last.TS.Before(slot) {
+			return slot
+		}
+		d := now.AddDate(0, 0, 1)
+		return time.Date(d.Year(), d.Month(), d.Day(), ah, am, 0, 0, now.Location())
 	case "weekly":
 		dow := 0
 		if st.DayOfWeek != nil {

+ 1 - 1
server-go/internal/speedtest/scheduler744_test.go

@@ -129,7 +129,7 @@ func TestExecuteDiscardsGarbageResult(t *testing.T) {
 	st, sched := openStore(t)
 	sched.runner = garbageRunner{}
 	sched.now = func() time.Time { return time.Unix(1_700_000_000, 0) }
-	stSettings := Settings{Enabled: true, IntervalHours: 6}
+	stSettings := Settings{Enabled: true, IntervalHours: 6, Provider: ProviderOokla}
 	if err := sched.SaveSettings(stSettings); err != nil {
 		t.Fatalf("save: %v", err)
 	}

+ 2 - 1
server-go/internal/speedtest/speedtest_test.go

@@ -93,7 +93,7 @@ func TestTickRunsWhenDueAndNotBefore(t *testing.T) {
 	runner := &countingRunner{}
 	sched.runner = runner
 	sched.now = func() time.Time { return time.Unix(1_700_000_000, 0) }
-	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6}); err != nil {
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, Provider: ProviderOokla}); err != nil {
 		t.Fatalf("save: %v", err)
 	}
 	// Sin resultados previos: el tick ejecuta (primera activación).
@@ -129,6 +129,7 @@ func TestRunNowSingleFlight(t *testing.T) {
 	_, sched := openStore(t)
 	runner := &blockingRunner{release: make(chan struct{})}
 	sched.runner = runner
+	sched.SetNDTRunner(runner)
 	if err := sched.RunNow(); err != nil {
 		t.Fatalf("runnow: %v", err)
 	}

+ 4 - 0
server-go/internal/telegram/telegram.go

@@ -250,6 +250,10 @@ func formatMessage(ev alerts.AlertEvent) string {
 		severity = "🔴"
 	}
 
+	// #1074: Ts<=0 (epoch) por cualquier vía → hora actual, no "16:00:00".
+	if ev.Ts <= 0 {
+		ev.Ts = time.Now().Unix()
+	}
 	ts := time.Unix(ev.Ts, 0).Format("15:04:05")
 	text := fmt.Sprintf("%s%s <b>%s</b>\n", severity, emoji, htmlEscape(ev.Title))
 	if ev.Description != "" {

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä