Ver código fonte

feat: overview redesign, integrations hub, alerts/clients/reports UX and settings overhaul (#1004)

Accumulated UX and settings batch, validated on a live instance.

Closes #958, #964, #965, #966, #967, #968, #970, #971, #972, #973, #974, #975, #976, #977, #978, #979, #980, #981, #982, #983, #984, #985, #986, #987, #989, #990, #991, #992, #993, #994, #995, #996, #997, #998, #999, #1000, #1001, #1002, #1003
Nacho 2 meses atrás
pai
commit
a13580d855
74 arquivos alterados com 4589 adições e 1529 exclusões
  1. 106 89
      app/public/locales/en/translation.json
  2. 106 89
      app/public/locales/es/translation.json
  3. 5 3
      app/src/components/AlertItem.tsx
  4. 0 180
      app/src/components/DeviceTraffic.tsx
  5. 57 17
      app/src/components/HttpsCard.tsx
  6. 25 0
      app/src/components/InfoTip.tsx
  7. 75 55
      app/src/components/KnownMacsManager.tsx
  8. 36 68
      app/src/components/Layout.tsx
  9. 3 3
      app/src/components/MqttCard.tsx
  10. 7 5
      app/src/components/NtfyCard.tsx
  11. 0 175
      app/src/components/PresenceTimeline.tsx
  12. 20 0
      app/src/components/RowAction.tsx
  13. 5 2
      app/src/components/TelegramCard.tsx
  14. 22 22
      app/src/components/ThemeToggle.tsx
  15. 51 12
      app/src/components/UpdateDialog.tsx
  16. 0 7
      app/src/components/routers/AgentsSection.tsx
  17. 78 29
      app/src/components/routers/WanLatency.tsx
  18. 12 6
      app/src/components/topology/LegendCard.tsx
  19. 0 2
      app/src/components/topology/TopologyOverridesManager.tsx
  20. 2 1
      app/src/components/topology/UsteerPanel.tsx
  21. 57 3
      app/src/components/topology/model.ts
  22. 1 1
      app/src/components/ui/dialog.tsx
  23. 15 19
      app/src/data/DataProvider.tsx
  24. 0 2
      app/src/data/alertFeed.ts
  25. 1 1
      app/src/data/types.ts
  26. 89 0
      app/src/hooks/useIntegrations.ts
  27. 29 0
      app/src/hooks/useWeakSignalDbm.ts
  28. 20 0
      app/src/index.css
  29. 18 0
      app/src/lib/theme-boot.ts
  30. 16 39
      app/src/pages/Alerts.tsx
  31. 373 238
      app/src/pages/Devices.tsx
  32. 2 0
      app/src/pages/Help.tsx
  33. 24 22
      app/src/pages/Home.tsx
  34. 267 104
      app/src/pages/Reports.tsx
  35. 4 16
      app/src/pages/Roaming.tsx
  36. 510 123
      app/src/pages/Settings.tsx
  37. 12 10
      app/src/pages/Topology.tsx
  38. 130 25
      app/src/sections/HeroStrip.tsx
  39. 8 3
      app/src/sections/RecentAlerts.tsx
  40. 59 4
      app/src/sections/WanTraffic.tsx
  41. 6 6
      docs/https.md
  42. 35 3
      server-go/cmd/netpulse/main.go
  43. 12 4
      server-go/internal/adapters/agent.go
  44. 21 0
      server-go/internal/adapters/proxmox.go
  45. 76 0
      server-go/internal/adapters/proxmox_gate_test.go
  46. 144 10
      server-go/internal/alerts/alerts.go
  47. 144 0
      server-go/internal/alerts/alerts_volatile_test.go
  48. 48 0
      server-go/internal/alerts/dismiss_test.go
  49. 9 3
      server-go/internal/config/config.go
  50. 4 4
      server-go/internal/config/config_test.go
  51. 6 3
      server-go/internal/db/db.go
  52. 85 0
      server-go/internal/httpapi/adguard_detect.go
  53. 102 0
      server-go/internal/httpapi/adguard_detect_internal_test.go
  54. 24 1
      server-go/internal/httpapi/alerts_api_test.go
  55. 90 27
      server-go/internal/httpapi/availability_test.go
  56. 2 0
      server-go/internal/httpapi/config.go
  57. 11 0
      server-go/internal/httpapi/data.go
  58. 22 1
      server-go/internal/httpapi/https_settings.go
  59. 6 2
      server-go/internal/httpapi/mqtt_settings.go
  60. 39 0
      server-go/internal/httpapi/presence.go
  61. 46 0
      server-go/internal/httpapi/presence_api_test.go
  62. 143 0
      server-go/internal/httpapi/proxmox_detect.go
  63. 148 0
      server-go/internal/httpapi/proxmox_detect_internal_test.go
  64. 201 66
      server-go/internal/httpapi/reports.go
  65. 21 17
      server-go/internal/httpapi/reports_test.go
  66. 9 0
      server-go/internal/httpapi/server.go
  67. 101 0
      server-go/internal/httpapi/settings.go
  68. 76 0
      server-go/internal/httpapi/settings_integrations_test.go
  69. 1 1
      server-go/internal/reinstall/reinstall.go
  70. 265 0
      server-go/internal/speedtest/http_runner.go
  71. 253 0
      server-go/internal/speedtest/http_runner_test.go
  72. 45 1
      server-go/internal/speedtest/scheduler.go
  73. 83 5
      server-go/internal/tlsmode/manager.go
  74. 66 0
      server-go/internal/tlsmode/manager_test.go

+ 106 - 89
app/public/locales/en/translation.json

@@ -1,6 +1,5 @@
 {
   "alerts": {
-    "allKinds": "All types",
     "allRead": "All read — the network is quiet",
     "chipCritical": "critical",
     "chipCriticalCaption": "There has never been a critical one. Touch wood.",
@@ -16,15 +15,7 @@
     "emptyTitle": "Total silence",
     "eventCount_one": "1 event",
     "eventCount_other": "{{count}} alerts",
-    "filterByKind": "Filter by type",
     "filterBySeverity": "Filter by severity",
-    "kinds": {
-      "adguard": "AdGuard",
-      "dispositivos": "Devices",
-      "router": "Router",
-      "sistema": "System",
-      "wireguard": "WireGuard"
-    },
     "loadingOld": "Loading older alerts…",
     "markAllRead": "Mark all as read",
     "moreActions": "More actions",
@@ -372,9 +363,9 @@
       "vm": "VM",
       "vmTip": "Virtual machine on {{host}}"
     },
-    "bandAll": "All",
     "changeView": "Change view",
     "clearFilters": "Clear filters",
+    "connection": "Connection",
     "colBand": "Band",
     "colDevice": "Device",
     "colFirstSeen": "First seen",
@@ -382,6 +373,10 @@
     "colSignal": "Signal",
     "colTraffic": "Traffic",
     "colType": "Type",
+    "columns": {
+      "action": "Show or hide columns",
+      "title": "Columns"
+    },
     "copyIp": "Copy IP",
     "detail": {
       "dhcpLease": "DHCP lease",
@@ -390,12 +385,6 @@
       "infra": "Infrastructure",
       "manufacturer": "Manufacturer (OUI)",
       "protected": "Protected",
-      "rename": "Rename device",
-      "renameLocal": "Only saved in this browser.",
-      "traffic24h": "Traffic 24 h",
-      "trafficCurrent": "Current traffic",
-      "traffic": "Client traffic",
-      "trafficNoSource": "No per-client traffic: wired clients need nlbwmon on the router (WiFi uses hostapd counters).",
       "unfiltered": "Unfiltered",
       "connectedTo": "Connected to"
     },
@@ -404,6 +393,7 @@
     "emptyTitle": "Nothing here",
     "filterByBand": "Filter by band",
     "filterByRouter": "Filter by router",
+    "fleet": "Fleet",
     "gridView": "Grid view",
     "groups": {
       "infra": "Infra",
@@ -425,7 +415,6 @@
     "leaseUnlimited": "unlimited",
     "edit": {
       "title": "Edit device",
-      "description": "Change this device's name and icon.",
       "action": "Edit",
       "name": "Name",
       "nameHint": "Empty = automatic name (DHCP hostname)",
@@ -466,7 +455,6 @@
     "onlineOffline": "Offline",
     "filterByOnline": "Filter by status",
     "removeFilter": "Remove filter {{label}}",
-    "routerAll": "All",
     "searchAria": "Search devices",
     "searchPlaceholder": "Search by name, IP or MAC…",
     "showing": "Showing",
@@ -504,7 +492,7 @@
       "tv": "TV"
     },
     "wiredConnection": "Wired connection",
-    "weakChip": "{{count}} with weak signal",
+    "weakChip": "{{count}} with weak signal (< {{dbm}} dBm)",
     "via": "via {{name}}",
     "unknownManufacturer": "Unknown",
     "onboarding": {
@@ -526,13 +514,6 @@
       "banner_one": "{{count}} connected device not identified",
       "banner_other": "{{count}} connected devices not identified",
       "bannerAction": "Identify"
-    },
-    "presence": {
-      "title": "Presence (7 days)",
-      "empty": "No presence data for the last 7 days.",
-      "online": "Connected to {{router}}",
-      "offline": "Disconnected",
-      "flappy": "{{count}} AP connections in the last 24 h"
     }
   },
   "home": {
@@ -544,14 +525,15 @@
     "healthAria": "{{caption}}: {{score}} of 100, {{label}}",
     "latency": "Latency",
     "recentAlerts": {
-      "lastCheck": "Last check 30s ago",
-      "unreadOnly": "Unread only",
       "allRead": "All caught up. No unread alerts.",
-      "recheck": "Check again"
+      "emptyTitle": "No alerts",
+      "lastCheck": "Last check 30s ago",
+      "recheck": "Check again",
+      "unreadOnly": "Unread only"
     },
     "routersRow": {
       "summary": "{{online}} online · {{warnings}} with warnings",
-      "title": "Your routers"
+      "title": "Your fleet"
     },
     "services": {
       "activePeers": "Active · {{count}} peers",
@@ -624,6 +606,8 @@
     "settings": "Settings",
     "settingsDesc": "Theme, units and installation",
     "theme": "Theme",
+    "themeToDark": "Switch to dark theme",
+    "themeToLight": "Switch to light theme",
     "topology": "Topology",
     "topologyDesc": "Visual network map",
     "collapse": "Collapse menu",
@@ -1024,9 +1008,6 @@
     "agents": {
       "subtitle": "{{total}} agent(s) · {{down}} not reporting",
       "empty": "No registered agents.",
-      "installChoice": "How to cover an OpenWrt router without an agent? NetGrip (recommended on routers that can host it) or the native agent. NetPulse does not install NetGrip: the choice happens at onboarding.",
-      "installChoiceNetgrip": "NetGrip: panel on the router (port 8090) with an embedded NetPulse agent and its own management (service toggles). Install it from the router itself; NetPulse then does not deploy the standalone agent over it.",
-      "installChoiceNative": "Native agent: lightweight telemetry managed from NetPulse (reinstall/upgrade), no web UI on the router.",
       "colDevice": "Device",
       "colStatus": "Status",
       "colLastSeen": "Last push",
@@ -1087,23 +1068,32 @@
     "noVitalsTip": "Monitored through SNMP or a beacon: this device does not report CPU, RAM or temperature"
   },
   "reports": {
-    "availability": "Availability",
-    "colAvg": "Average",
-    "colRouter": "Router",
-    "empty": "No data for this period yet. The nightly rollup populates the report each day.",
+    "availability": "Availability per router",
+    "coverage": "{{days}}/{{total}} days with data",
+    "downNone": "No gaps",
+    "downTime": "{{duration}} with no data",
+    "downloadCsv": "Download as CSV",
+    "empty": "No data for this period yet. Today is measured live; history is filled in by the nightly rollup.",
     "error": "Could not load the report. Check the connection and try again.",
-    "footnote": "Availability = minutes with data over the period total. The current period is shown as partial.",
-    "latency": "Average latency",
+    "explain": "Minutes with data received from each router during {{window}} (5-minute resolution). 100% means no gaps.",
+    "fleetAvg": "Fleet average",
+    "footnote": "Availability = minutes with data received (5-minute buckets) over the days with data in the window; the current period is shown as partial. A gap usually means the router was down, but it can also mean the monitor had no data. Green: at least 99%. Amber: at least 95%. Red: below 95%, needs attention.",
+    "insufficient": "Not enough data",
     "loading": "Loading report…",
     "noApi": "Available only with a live backend.",
     "rangeLabel": "Range to show",
-    "subtitle": "Availability and performance per router.",
+    "status_danger": "Needs attention",
+    "status_ok": "Stable",
+    "status_warn": "Minor gaps",
     "tabDay": "Daily",
-    "tabWeek": "Weekly",
     "tabMonth": "Monthly",
-    "traffic": "Total traffic (↓+↑)",
-    "upMin": "Minutes with data",
-    "downloadCsv": "Download as CSV"
+    "tabWeek": "Weekly",
+    "tipToday": "Today, data up to {{time}} (in progress)",
+    "totalDown": "Total time without data",
+    "windowDay": "the last {{n}} days",
+    "windowMonth": "the last {{n}} months",
+    "windowWeek": "the last {{n}} weeks",
+    "worstRouter": "Router with most gaps"
   },
   "topology": {
     "animateFlow": "Animate packet flow",
@@ -1233,8 +1223,7 @@
         "error": "Could not create backup",
         "done": "Backup created successfully"
       },
-      "orchestration": "Network orchestration",
-      "orchestrationDesc": "Shows the orchestration menu (apply and roll back changes on routers). It is a write surface, so it is off until you enable it."
+      "orchestration": "Network orchestration"
     },
     "adoption": {
       "title": "Agent adoption",
@@ -1303,7 +1292,11 @@
       "save": "Save",
       "saving": "Saving…",
       "errorGeneric": "Could not save.",
-      "hint": "GL.iNet mode logs into the router UI through SSH and queries port 3000. Standard mode connects directly to a remote AdGuard Home instance over HTTP; the default port is 3000. The password is stored only on the server."
+      "hint": "GL.iNet mode logs into the router UI through SSH and queries port 3000. Standard mode connects directly to a remote AdGuard Home instance over HTTP; the default port is 3000. The password is stored only on the server.",
+      "detect": "Detect",
+      "detecting": "Detecting…",
+      "detectFound": "AdGuard Home detected at {{host}} - confirm the password and save",
+      "detectNotFound": "AdGuard Home was not found on the gateway or the fleet"
     },
     "appearance": "Appearance",
     "appearanceCaption": "Applies instantly and is remembered on this device",
@@ -1315,7 +1308,6 @@
       "latencyLabel": "WAN latency",
       "paused": "Paused",
       "refresh": "Interface refresh",
-      "refreshNote": "How often the interface re-fetches data when it loses the realtime connection. The server's SSH polling is configured on the server (NETPULSE_POLL_INTERVAL, 30 s by default).",
       "signalCaption_one": "1 device below the threshold (drives the weak-signal alert)",
       "signalCaption_other": "{{count}} devices below the threshold (drives the weak-signal alert)",
       "signalCaptionNone": "No devices below the threshold",
@@ -1326,9 +1318,13 @@
       "tempLabel": "Warning temperature",
       "tempNote": "The high-temperature threshold is set per router in \"Devices\" (65 °C by default).",
       "title": "Data & thresholds",
-      "units": "Traffic units",
+      "units": "Traffic",
       "unitsTitle": "Measurement units",
-      "tempUnit": "Temperature unit",
+      "tempUnit": "Temperature",
+      "limitHistory": "Limit history",
+      "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",
       "presenceRetention": "Presence history retention",
       "presenceRetentionDays": "days (0 = keep forever)",
       "presenceRetentionNote": "Connect/disconnect and AP-roaming events older than this are pruned hourly. The 7-day client timeline only needs a week.",
@@ -1341,7 +1337,6 @@
       "disable": "Back to live mode",
       "disableDesc": "The server will restart in live mode, polling your real routers.",
       "enable": "Load sample data",
-      "enableDesc": "The server will restart and show a sample network (60+ devices). Your routers are untouched.",
       "restarting": "The server is restarting with the sample network…",
       "title": "Demo mode"
     },
@@ -1355,27 +1350,22 @@
     "notif": {
       "badge": "Alerts badge in the navigation",
       "badgeCaption": "Counter next to \"Alerts\"",
-      "caption": "In-app notices",
-      "note": "These are only in-app notices. To get alerts when the app is closed, enable “Push notifications”.",
+      "caption": "In-app notices and push on this device",
+      "ntfyCaption": "Push notifications via ntfy",
       "pulse": "Pulsing dot on devices with warnings",
       "pulseCaption": "Animated dot on cards with warn",
       "sound": "Sound when an alert arrives",
       "soundOff": "Off",
       "soundOn": "On — plays a soft beep",
+      "telegramCaption": "Notifications to the Telegram bot",
       "testSound": "Test alert beep",
-      "title": "Visual notifications"
+      "title": "Notifications"
     },
     "push": {
       "title": "Push notifications",
-      "caption": "Urgent alerts even when the app is closed",
       "checking": "Checking support…",
-      "enable": "Enable",
-      "disable": "Disable",
-      "enabling": "Enabling…",
-      "disabling": "Disabling…",
       "stateOn": "Enabled",
-      "stateOnCaption": "This device receives urgent alerts even when NetPulse is closed.",
-      "stateOffCaption": "Get urgent alerts on this device even when the app is not open.",
+      "stateOff": "Disabled",
       "denied": "Permission denied in the browser. To re-enable it: click the lock (or tune) icon in the address bar → Permissions → Notifications → Allow, then reload the page.",
       "unsupported": "This browser does not support push notifications (it needs Service Worker, the Push API and the Notifications API).",
       "insecure": "Push notifications need HTTPS, and this page is open over plain HTTP. Open NetPulse at its HTTPS address to enable them on this device - an admin turns HTTPS on in Settings > HTTPS (port 3443 by default).",
@@ -1393,7 +1383,8 @@
       "bot": "Bot",
       "chat": "Chat",
       "sendTest": "Send test",
-      "incomplete": "Fill in the bot token and chat ID or enable notifications"
+      "incomplete": "Fill in the bot token and chat ID or enable notifications",
+      "botTokenHint": "Create the bot with @BotFather on Telegram and paste its token here."
     },
     "pwa": {
       "caption": "Installable app · PWA",
@@ -1516,7 +1507,6 @@
     },
     "labs": {
       "title": "Labs",
-      "caption": "External devices that push data via API (scrapers, non-OpenWrt switches…). Not polled via SSH.",
       "empty": "No external devices yet. Add your first device.",
       "addDevice": "Add external device",
       "namePlaceholder": "Name (becomes the device slug)",
@@ -1544,15 +1534,19 @@
     },
     "saved": "Preferences saved",
     "services": {
-      "title": "Services",
-      "caption": "Which services are shown and monitored",
+      "title": "Integrations",
+      "caption": "Visible network services and active server integrations",
       "adguardCaption": "Filtered DNS on the gateway",
       "wireguardCaption": "WireGuard VPN tunnels",
       "openvpnCaption": "OpenVPN tunnels (coming soon)",
       "labs": "Labs (experimental features)",
-      "labsCaption": "Enable features in development: orchestration, scrapers, and more",
+      "labsCaption": "In development. They write to your routers",
       "orchestrationHint": "Manage routers from the UI (AdGuard, guest Wi-Fi, DDNS…)",
-      "note": "Only checked services are shown and monitored. More services coming soon."
+      "networkGroup": "Network services",
+      "integrationsGroup": "Integrations",
+      "proxmoxCaption": "Cluster inventory (hypervisors and CTs)",
+      "mqttCaption": "Fleet state published to the MQTT broker",
+      "configure": "Configure {{name}}"
     },
     "session": {
       "active": "Active session on this device",
@@ -1615,7 +1609,6 @@
       "invalid": "Enter speeds greater than 0 and at most 100000 Mbps",
       "saveError": "Could not save the speed",
       "runTest": "Run speed test",
-      "testCaption": "Measures the real speed from the server and fills the fields with the result. Then press Save.",
       "testApplied": "Measurement applied: {{down}} ↓ / {{up}} ↑ Mbps",
       "testFailed": "The speed test failed",
       "testHint": "The test saturates the link for a few seconds. You can leave this page; fields are filled when it finishes.",
@@ -1625,22 +1618,18 @@
     },
     "knownMacs": {
       "title": "Trusted devices",
-      "caption": "The MAC no longer warns as an 'unknown device' and its name is used as an alias",
-      "hint": "Devices you own (routers, TVs, scales…) that come and go normally. Marking them here stops unknown-device alerts.",
-      "empty": "No trusted devices yet. Add one with the 'Add' button.",
       "add": "Add",
       "adding": "Adding…",
       "mac": "MAC address",
       "macPlaceholder": "AA:BB:CC:DD:EE:FF",
       "name": "Name (alias)",
       "namePlaceholder": "e.g. Withings scale",
-      "save": "Save",
-      "saving": "Saving…",
       "delete": "Remove",
       "invalidMac": "Invalid MAC address (format AA:BB:CC:DD:EE:FF)",
       "saveError": "Could not save the device",
       "deleteError": "Could not remove the device",
-      "loadError": "Could not load trusted devices"
+      "loadError": "Could not load trusted devices",
+      "info": "Trusted MACs do not raise \"unknown device\" alerts and their name is used as an alias on the network."
     },
     "palette": "Palette",
     "paletteCaption": "Palette changes all interface colors. Accent only changes the primary color.",
@@ -1650,8 +1639,18 @@
     "paletteElectric": "Electric",
     "speedtest": {
       "title": "WAN speed test",
-      "caption": "Real periodic measurement from the server against speedtest.net",
+      "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.",
+      "providerOokla": "Speedtest.net (Ookla)",
+      "providerCloudflare": "Cloudflare",
+      "providerLibrespeed": "LibreSpeed",
+      "providerCustom": "Custom",
+      "librespeedUrl": "LibreSpeed instance URL",
+      "librespeedPlaceholder": "https://librespeed.example.com",
+      "customUrl": "Measurement endpoint URL",
+      "customPlaceholder": "https://my-server/endpoint",
       "interval": "Interval",
       "intervalH": "every {{hours}} h",
       "intervalWeek": "every week",
@@ -1688,12 +1687,12 @@
       "originAuto": "Auto",
       "originManual": "Manual",
       "colServer": "Server",
-      "noRecent": "No tests recorded yet"
+      "noRecent": "No tests recorded yet",
+      "recentHide": "Hide"
     },
     "proxmox": {
       "title": "Proxmox VE",
       "caption": "Cluster inventory to identify hosts and their containers",
-      "hint": "Connects to the Proxmox cluster read-only API (token with Sys.Audit and VM.Audit privileges). The inventory seals the host as hypervisor and its CTs/VMs as containers attached to it in Devices, with real names and IPs. Create the token in Datacenter > Permissions > API Tokens.",
       "configured": "Configured",
       "notConfigured": "Not configured",
       "edit": "Edit Proxmox configuration",
@@ -1711,7 +1710,8 @@
       "instanceId": "Identifier (slug, not editable later)",
       "test": "Test",
       "testOk": "Connected: Proxmox {{version}} · {{nodes}} node(s), {{vms}} VM(s), {{cts}} CT(s)",
-      "testLimited": "The token authenticates but cannot see any guest: Proxmox returns the lists empty when the token lacks audit rights. Grant it PVEAuditor on \"/\" — on the Proxmox host: pveum acl modify / --tokens 'USER@REALM!TOKEN' --roles PVEAuditor. A token with privilege separation needs the permission itself, not just its user."
+      "testLimited": "The token authenticates but cannot see any guest: Proxmox returns the lists empty when the token lacks audit rights. Grant it PVEAuditor on \"/\" — on the Proxmox host: pveum acl modify / --tokens 'USER@REALM!TOKEN' --roles PVEAuditor. A token with privilege separation needs the permission itself, not just its user.",
+      "hintShort": "Read-only API: the token needs the Sys.Audit and VM.Audit permissions. The steps to create it are on the Help page."
     },
     "sections": {
       "personalization": "Configuration",
@@ -1782,16 +1782,17 @@
     },
     "alertsLang": {
       "title": "Notification language",
-      "description": "Language used for ntfy, Telegram and webhook alerts (alerts are composed in Spanish and translated when published).",
-      "label": "Alert language"
+      "description": "Language used for ntfy, Telegram and webhook alerts (alerts are composed in Spanish and translated when published)."
     },
-        "https": {
+    "https": {
       "title": "HTTPS",
-      "caption": "Serve NetPulse over HTTPS with its own certificate authority, and retire plain HTTP step by step.",
       "loadError": "Could not load the HTTPS settings.",
       "unavailable": "HTTPS is managed outside this page: {{reason}}.",
-      "enabled": "HTTPS on port {{port}}",
+      "enabled": "HTTPS",
       "enabledHint": "Only adds the HTTPS port. Plain HTTP keeps working until you choose a stricter mode below.",
+      "portTitle": "Port",
+      "portHint": "Applies at once, no restart. Agents and NetGrip pointing at the current port must update their URL.",
+      "portApply": "Change",
       "locked": "Fixed in the server's environment file; change it there.",
       "rootTitle": "Root certificate",
       "rootHint": "Install it once on each phone and computer you use NetPulse from. Before trusting it, check that the fingerprint your device shows matches this one, and the one in the server's log.",
@@ -1804,15 +1805,15 @@
       "modes": {
         "full": {
           "title": "Everything (as before)",
-          "hint": "Plain HTTP serves everything. Safe while you install the root certificate and move agents."
+          "hint": "Plain HTTP serves everything, as before."
         },
         "migrate": {
           "title": "Agents only",
-          "hint": "Browsers are sent to HTTPS; sign-ins and API calls over plain HTTP are refused. Agents keep reporting over plain HTTP until each one has moved."
+          "hint": "Browsers go to HTTPS; agents keep reporting over HTTP until moved."
         },
         "redirect": {
           "title": "Nothing",
-          "hint": "Plain HTTP only redirects to HTTPS and hands out the root certificate. Agents still on plain HTTP stop reporting."
+          "hint": "Plain HTTP only redirects to HTTPS; agents still on HTTP stop reporting."
         }
       },
       "agentsOnHttp": "Still reporting over plain HTTP",
@@ -1842,7 +1843,6 @@
   "topbar": {
     "alertsUnread": "Alerts, {{count}} unread",
     "demoMode": "Demo mode",
-    "gatewayStatus": "Gateway status",
     "live": "Live",
     "networkHealth": "Network health: {{score}}",
     "networkHealth100": "Network health: {{score}} of 100",
@@ -1913,7 +1913,12 @@
       "viewCompare": "View the full comparison on GitHub",
       "changelogFallback": "Could not load changelog.",
       "changelogLink": "View release notes on GitHub",
-      "downNotice": "The service will be down while it restarts"
+      "downNotice": "The service will be down while it restarts",
+      "versionUpdate": "Version update",
+      "eta": "Estimated time: 2-5 minutes",
+      "backupNote": "A backup will be created automatically before the update",
+      "prerequisites": "Prerequisites",
+      "ack": "I understand the service will be briefly unavailable during the update"
     },
     "errors": {
       "exitRestart": "The server restarted itself to apply the update (the normal final step). If the version has not changed in a few minutes, check for updates again.",
@@ -2348,6 +2353,18 @@
           "Follow the progress on the same page; the final result lands when the router finishes booting."
         ],
         "tip": "After a flash only /etc survives: the agent's self-heal restores the binary at boot, and ⟦Reinstall⟧ puts everything fresh if needed."
+      },
+      "proxmoxToken": {
+        "title": "Connect a Proxmox cluster",
+        "subtitle": "Create the read-only API token the integration asks for",
+        "intro": "The Proxmox integration seals each host as a hypervisor and hangs its CTs and VMs under it in ⟦Devices⟧, with real names and IPs. It only needs read access: an API token with audit permissions.",
+        "steps": [
+          "In the Proxmox web UI go to ⟦Datacenter⟧ → ⟦Permissions⟧ → ⟦API Tokens⟧ and create a token for the user of your choice (e.g. root@pam!netpulse).",
+          "Grant audit permissions: under ⟦Permissions⟧ → ⟦Add⟧ assign the PVEAuditor role on path / to the token (if the token has privilege separation, the permission must belong to the token itself - the user's own is not enough).",
+          "In NetPulse open ⟦Settings⟧ → ⟦Services⟧ and click the configure icon of ⟦Proxmox VE⟧: add the cluster URL (https://host:8006), the Token ID (user@realm!name) and the Secret.",
+          "Click ⟦Test⟧: if the token authenticates but sees no guests, it is missing the permissions from step 2."
+        ],
+        "tip": "The secret is sent only once and never comes back from the server: to change it, edit the instance and type the new one."
       }
     }
   },
@@ -2355,4 +2372,4 @@
     "link": "See more",
     "dismiss": "Dismiss announcement"
   }
-}
+}

+ 106 - 89
app/public/locales/es/translation.json

@@ -1,6 +1,5 @@
 {
   "alerts": {
-    "allKinds": "Todos los tipos",
     "allRead": "Todo leído — la red está tranquila",
     "chipCritical": "críticos",
     "chipCriticalCaption": "Nunca ha habido uno crítico. Toca madera.",
@@ -16,15 +15,7 @@
     "emptyTitle": "Silencio total",
     "eventCount_one": "1 evento",
     "eventCount_other": "{{count}} alertas",
-    "filterByKind": "Filtrar por tipo",
     "filterBySeverity": "Filtrar por severidad",
-    "kinds": {
-      "adguard": "AdGuard",
-      "dispositivos": "Dispositivos",
-      "router": "Router",
-      "sistema": "Sistema",
-      "wireguard": "WireGuard"
-    },
     "loadingOld": "Cargando alertas antiguas…",
     "markAllRead": "Marcar todo como leído",
     "moreActions": "Más acciones",
@@ -372,9 +363,9 @@
       "vm": "VM",
       "vmTip": "Máquina virtual en {{host}}"
     },
-    "bandAll": "Todas",
     "changeView": "Cambiar vista",
     "clearFilters": "Limpiar filtros",
+    "connection": "Conexión",
     "colBand": "Banda",
     "colDevice": "Dispositivo",
     "colFirstSeen": "Vista por primera vez",
@@ -382,6 +373,10 @@
     "colSignal": "Señal",
     "colTraffic": "Tráfico",
     "colType": "Tipo",
+    "columns": {
+      "action": "Mostrar u ocultar columnas",
+      "title": "Columnas"
+    },
     "copyIp": "Copiar IP",
     "detail": {
       "dhcpLease": "Concesión DHCP",
@@ -390,12 +385,6 @@
       "infra": "Infraestructura",
       "manufacturer": "Fabricante (OUI)",
       "protected": "Protegido",
-      "rename": "Renombrar dispositivo",
-      "renameLocal": "Solo se guarda en este navegador.",
-      "traffic24h": "Tráfico 24 h",
-      "trafficCurrent": "Tráfico actual",
-      "traffic": "Tráfico por cliente",
-      "trafficNoSource": "Sin tráfico por cliente: los clientes por cable necesitan nlbwmon en el router (los WiFi usan los contadores de hostapd).",
       "unfiltered": "Sin filtrar",
       "connectedTo": "Conectado a"
     },
@@ -404,6 +393,7 @@
     "emptyTitle": "Nada por aquí",
     "filterByBand": "Filtrar por banda",
     "filterByRouter": "Filtrar por router",
+    "fleet": "Flota",
     "gridView": "Vista de tarjetas",
     "groups": {
       "infra": "Infra",
@@ -425,7 +415,6 @@
     "leaseUnlimited": "ilimitado",
     "edit": {
       "title": "Editar dispositivo",
-      "description": "Cambia el nombre y el icono de este dispositivo.",
       "action": "Editar",
       "name": "Nombre",
       "nameHint": "Vacío = nombre automático (hostname DHCP)",
@@ -466,7 +455,6 @@
     "onlineOffline": "Offline",
     "filterByOnline": "Filtrar por estado",
     "removeFilter": "Quitar filtro {{label}}",
-    "routerAll": "Todos",
     "searchAria": "Buscar dispositivos",
     "searchPlaceholder": "Buscar por nombre, IP o MAC…",
     "showing": "Mostrando",
@@ -504,7 +492,7 @@
       "tv": "TV"
     },
     "wiredConnection": "Conexión por cable",
-    "weakChip": "{{count}} con señal débil",
+    "weakChip": "{{count}} con señal débil (< {{dbm}} dBm)",
     "via": "vía {{name}}",
     "unknownManufacturer": "Desconocido",
     "onboarding": {
@@ -526,13 +514,6 @@
       "banner_one": "{{count}} dispositivo conectado sin identificar",
       "banner_other": "{{count}} dispositivos conectados sin identificar",
       "bannerAction": "Identificar"
-    },
-    "presence": {
-      "title": "Presencia (7 días)",
-      "empty": "Sin datos de presencia en los últimos 7 días.",
-      "online": "Conectado a {{router}}",
-      "offline": "Desconectado",
-      "flappy": "{{count}} conexiones a AP en las últimas 24 h"
     }
   },
   "home": {
@@ -544,14 +525,15 @@
     "healthAria": "{{caption}}: {{score}} de 100, {{label}}",
     "latency": "Latencia",
     "recentAlerts": {
-      "lastCheck": "Última comprobación hace 30 s",
-      "unreadOnly": "Solo no leídas",
       "allRead": "Todo en orden. No hay alertas sin leer.",
-      "recheck": "Volver a comprobar"
+      "emptyTitle": "Sin alertas",
+      "lastCheck": "Última comprobación hace 30 s",
+      "recheck": "Volver a comprobar",
+      "unreadOnly": "Solo no leídas"
     },
     "routersRow": {
       "summary": "{{online}} online · {{warnings}} con aviso",
-      "title": "Tus routers"
+      "title": "Tu flota"
     },
     "services": {
       "activePeers": "Activo · {{count}} peers",
@@ -624,6 +606,8 @@
     "settings": "Ajustes",
     "settingsDesc": "Tema, unidades e instalación",
     "theme": "Tema",
+    "themeToDark": "Cambiar a tema oscuro",
+    "themeToLight": "Cambiar a tema claro",
     "topology": "Topología",
     "topologyDesc": "Mapa visual de la red",
     "collapse": "Plegar menú",
@@ -1024,9 +1008,6 @@
     "agents": {
       "subtitle": "{{total}} agente(s) · {{down}} sin reportar",
       "empty": "Sin agentes registrados.",
-      "installChoice": "¿Cómo cubrir un router OpenWrt sin agente? NetGrip (recomendado en routers que puedan alojarlo) o agente nativo. NetPulse no instala NetGrip: la elección se hace al alta.",
-      "installChoiceNetgrip": "NetGrip: panel en el router (puerto 8090) con agente NetPulse embebido y su propia gestión (toggles de servicios). Se instala desde el propio router; luego NetPulse no despliega el agente standalone encima.",
-      "installChoiceNative": "Agente nativo: telemetría ligera gestionada desde NetPulse (reinstalar/actualizar), sin web UI en el router.",
       "colDevice": "Equipo",
       "colStatus": "Estado",
       "colLastSeen": "Último push",
@@ -1087,23 +1068,32 @@
     "noVitalsTip": "Monitorizado por SNMP o beacon: este dispositivo no reporta CPU, RAM ni temperatura"
   },
   "reports": {
-    "availability": "Disponibilidad",
-    "colAvg": "Media",
-    "colRouter": "Router",
-    "empty": "Todavía no hay datos para este período. El rollup nocturno rellena el informe cada día.",
+    "availability": "Disponibilidad por router",
+    "coverage": "{{days}}/{{total}} días con datos",
+    "downNone": "Sin huecos",
+    "downTime": "{{duration}} sin datos",
+    "downloadCsv": "Descargar como CSV",
+    "empty": "Todavía no hay datos para este período. El día en curso se mide en vivo; el histórico lo rellena el rollup nocturno.",
     "error": "No se pudo cargar el informe. Comprueba la conexión e inténtalo de nuevo.",
-    "footnote": "Disponibilidad = minutos con datos sobre el total del período. El período en curso se muestra parcial.",
-    "latency": "Latencia media",
+    "explain": "Minutos con datos recibidos de cada router durante {{window}} (resolución de 5 min). 100% significa sin huecos.",
+    "fleetAvg": "Media de la red",
+    "footnote": "Disponibilidad = minutos con datos recibidos (buckets de 5 min) sobre los días con datos de la ventana; el período en curso se muestra parcial. Un hueco suele ser el router caído, pero también puede ser el monitor sin datos. Verde: al menos 99%. Ámbar: al menos 95%. Rojo: menos del 95%, requiere atención.",
+    "insufficient": "Sin datos suficientes",
     "loading": "Cargando informe…",
     "noApi": "Disponible solo con backend en vivo.",
     "rangeLabel": "Rango a mostrar",
-    "subtitle": "Disponibilidad y rendimiento por router.",
+    "status_danger": "Necesita atención",
+    "status_ok": "Estable",
+    "status_warn": "Huecos menores",
     "tabDay": "Diario",
-    "tabWeek": "Semanal",
     "tabMonth": "Mensual",
-    "traffic": "Tráfico total (↓+↑)",
-    "upMin": "Minutos con datos",
-    "downloadCsv": "Descargar como CSV"
+    "tabWeek": "Semanal",
+    "tipToday": "Hoy, datos hasta las {{time}} (en curso)",
+    "totalDown": "Tiempo sin datos total",
+    "windowDay": "los últimos {{n}} días",
+    "windowMonth": "los últimos {{n}} meses",
+    "windowWeek": "las últimas {{n}} semanas",
+    "worstRouter": "Router con más huecos"
   },
   "topology": {
     "animateFlow": "Animar flujo de paquetes",
@@ -1233,8 +1223,7 @@
         "error": "No se pudo hacer el respaldo",
         "done": "Respaldo creado correctamente"
       },
-      "orchestration": "Orquestación de red",
-      "orchestrationDesc": "Muestra el menú de orquestación (aplicar y revertir cambios en routers). Es una superficie de escritura; se activa solo si lo quieres."
+      "orchestration": "Orquestación de red"
     },
     "adoption": {
       "title": "Adopción de agentes",
@@ -1303,7 +1292,11 @@
       "save": "Guardar",
       "saving": "Guardando…",
       "errorGeneric": "No se pudo guardar.",
-      "hint": "El modo GL.iNet inicia sesión en la interfaz del router por SSH y consulta el puerto 3000. El modo estándar conecta directamente a una instancia remota de AdGuard Home por HTTP; el puerto por defecto es 3000. La contraseña se guarda solo en el servidor."
+      "hint": "El modo GL.iNet inicia sesión en la interfaz del router por SSH y consulta el puerto 3000. El modo estándar conecta directamente a una instancia remota de AdGuard Home por HTTP; el puerto por defecto es 3000. La contraseña se guarda solo en el servidor.",
+      "detect": "Detectar",
+      "detecting": "Detectando…",
+      "detectFound": "AdGuard Home detectado en {{host}} - confirma la contraseña y guarda",
+      "detectNotFound": "No se encontró AdGuard Home ni en la puerta de enlace ni en la flota"
     },
     "appearance": "Apariencia",
     "appearanceCaption": "Se aplica al instante y se recuerda en este dispositivo",
@@ -1315,7 +1308,6 @@
       "latencyLabel": "Latencia WAN",
       "paused": "Pausado",
       "refresh": "Refresco de la interfaz",
-      "refreshNote": "Cadencia con la que la interfaz reconsulta los datos cuando pierde la conexión en tiempo real. El sondeo SSH del servidor se configura en el servidor (NETPULSE_POLL_INTERVAL, 30 s por defecto).",
       "signalCaption_one": "1 dispositivo por debajo del umbral (dispara la alerta de señal débil)",
       "signalCaption_other": "{{count}} dispositivos por debajo del umbral (dispara la alerta de señal débil)",
       "signalCaptionNone": "Ningún dispositivo por debajo del umbral",
@@ -1326,9 +1318,13 @@
       "tempLabel": "Temperatura de aviso",
       "tempNote": "El umbral de temperatura alta se configura por router en «Dispositivos» (65 °C por defecto).",
       "title": "Datos y umbrales",
-      "units": "Unidades de tráfico",
+      "units": "Tráfico",
       "unitsTitle": "Unidades de medida",
-      "tempUnit": "Unidad de temperatura",
+      "tempUnit": "Temperatura",
+      "limitHistory": "Limitar historial",
+      "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",
       "presenceRetention": "Retención del historial de presencia",
       "presenceRetentionDays": "días (0 = conservar siempre)",
       "presenceRetentionNote": "Los eventos de conexión/desconexión y roaming más antiguos se podan cada hora. El timeline de 7 días de cada cliente solo necesita una semana.",
@@ -1341,7 +1337,6 @@
       "disable": "Volver al modo live",
       "disableDesc": "El servidor se reiniciará en modo live, sondeando tus routers reales.",
       "enable": "Cargar datos de ejemplo",
-      "enableDesc": "El servidor se reiniciará y mostrará una red de ejemplo (60+ dispositivos). Tus routers no se tocan.",
       "restarting": "El servidor se está reiniciando con la red de ejemplo…",
       "title": "Modo demo"
     },
@@ -1355,27 +1350,22 @@
     "notif": {
       "badge": "Badge de avisos en la navegación",
       "badgeCaption": "Contador junto a «Alertas»",
-      "caption": "Avisos dentro de la app",
-      "note": "Son solo avisos dentro de la app. Para recibir alertas con la app cerrada, activa las «Notificaciones push».",
+      "caption": "Avisos dentro de la app y push en este dispositivo",
+      "ntfyCaption": "Notificaciones push por ntfy",
       "pulse": "Punto pulsante en equipos con aviso",
       "pulseCaption": "Dot animado en tarjetas con warn",
       "sound": "Sonido al llegar una alerta",
       "soundOff": "Desactivado",
       "soundOn": "Activado — suena un beep suave",
+      "telegramCaption": "Notificaciones al bot de Telegram",
       "testSound": "Probar beep de alerta",
-      "title": "Notificaciones visuales"
+      "title": "Notificaciones"
     },
     "push": {
       "title": "Notificaciones push",
-      "caption": "Alertas urgentes incluso con la app cerrada",
       "checking": "Comprobando soporte…",
-      "enable": "Activar",
-      "disable": "Desactivar",
-      "enabling": "Activando…",
-      "disabling": "Desactivando…",
       "stateOn": "Activadas",
-      "stateOnCaption": "Este dispositivo recibe las alertas urgentes aunque NetPulse esté cerrado.",
-      "stateOffCaption": "Recibe las alertas urgentes en este dispositivo aunque no tengas la app abierta.",
+      "stateOff": "Desactivadas",
       "denied": "Permiso denegado en el navegador. Para reactivarlo: pulsa el candado (o el icono de ajustes) de la barra de direcciones → Permisos → Notificaciones → Permitir, y recarga la página.",
       "unsupported": "Este navegador no admite notificaciones push (hacen falta Service Worker, Push API y la API de notificaciones).",
       "insecure": "Las notificaciones push necesitan HTTPS, y esta página está abierta por HTTP. Abre NetPulse en su dirección HTTPS para activarlas en este dispositivo; un administrador activa HTTPS en Ajustes > HTTPS (puerto 3443 por defecto).",
@@ -1393,7 +1383,8 @@
       "bot": "Bot",
       "chat": "Chat",
       "sendTest": "Enviar prueba",
-      "incomplete": "Completa el token del bot y el ID del chat o activa las notificaciones"
+      "incomplete": "Completa el token del bot y el ID del chat o activa las notificaciones",
+      "botTokenHint": "Crea el bot con @BotFather en Telegram y pega aquí su token."
     },
     "pwa": {
       "caption": "App instalable · PWA",
@@ -1516,7 +1507,6 @@
     },
     "labs": {
       "title": "Labs",
-      "caption": "Dispositivos externos que envían datos vía API (scrapers, switches no OpenWrt…). No se sondean por SSH.",
       "empty": "Sin dispositivos externos. Añade tu primer dispositivo.",
       "addDevice": "Añadir dispositivo externo",
       "namePlaceholder": "Nombre (será el slug del dispositivo)",
@@ -1544,15 +1534,19 @@
     },
     "saved": "Preferencias guardadas",
     "services": {
-      "title": "Servicios",
-      "caption": "Qué servicios se muestran y monitorizan",
+      "title": "Integraciones",
+      "caption": "Servicios de red visibles e integraciones activas en el servidor",
       "adguardCaption": "DNS filtrado en la puerta de enlace",
       "wireguardCaption": "Túneles VPN WireGuard",
       "openvpnCaption": "Túneles VPN OpenVPN (próximamente)",
       "labs": "Labs (aplicaciones experimentales)",
-      "labsCaption": "Activa funcionalidades en desarrollo: orquestación, scrapers y más",
+      "labsCaption": "En desarrollo. Escriben en los routers",
       "orchestrationHint": "Permite gestionar routers desde la interfaz (AdGuard, WiFi invitados, DDNS…)",
-      "note": "Solo se muestran y se monitorizan los servicios marcados. Más servicios próximamente."
+      "networkGroup": "Servicios de red",
+      "integrationsGroup": "Integraciones",
+      "proxmoxCaption": "Inventario del cluster (hipervisores y CTs)",
+      "mqttCaption": "Publicación del estado en el broker MQTT",
+      "configure": "Configurar {{name}}"
     },
     "session": {
       "active": "Sesión activa en este dispositivo",
@@ -1615,7 +1609,6 @@
       "invalid": "Introduce velocidades mayores que 0 y como máximo 100000 Mbps",
       "saveError": "No se pudo guardar la velocidad",
       "runTest": "Hacer test de velocidad",
-      "testCaption": "Mide la velocidad real desde el servidor y rellena los campos con el resultado. Luego pulsa Guardar.",
       "testApplied": "Medición aplicada: {{down}} ↓ / {{up}} ↑ Mbps",
       "testFailed": "El test de velocidad falló",
       "testHint": "El test satura el enlace unos segundos. Puedes dejar la página; al terminar se rellenan los campos.",
@@ -1625,22 +1618,18 @@
     },
     "knownMacs": {
       "title": "Dispositivos de confianza",
-      "caption": "La MAC no se avisa como «dispositivo desconocido» y su nombre se usa como alias",
-      "hint": "Dispositivos propios (routers, TV, básculas…) que entran y salen de la red con normalidad. Al marcarlos aquí dejan de generar alertas de desconocido.",
-      "empty": "Sin dispositivos de confianza todavía. Añade uno con el botón «Añadir».",
       "add": "Añadir",
       "adding": "Añadiendo…",
       "mac": "Dirección MAC",
       "macPlaceholder": "AA:BB:CC:DD:EE:FF",
       "name": "Nombre (alias)",
       "namePlaceholder": "p. ej. Báscula Withings",
-      "save": "Guardar",
-      "saving": "Guardando…",
       "delete": "Quitar",
       "invalidMac": "Dirección MAC inválida (formato AA:BB:CC:DD:EE:FF)",
       "saveError": "No se pudo guardar el dispositivo",
       "deleteError": "No se pudo quitar el dispositivo",
-      "loadError": "No se pudieron cargar los dispositivos de confianza"
+      "loadError": "No se pudieron cargar los dispositivos de confianza",
+      "info": "Las MACs de confianza no avisan como «dispositivo desconocido» y su nombre se usa como alias en la red."
     },
     "palette": "Paleta",
     "paletteCaption": "La paleta cambia todos los colores de la interfaz. El acento solo cambia el color principal.",
@@ -1650,8 +1639,18 @@
     "paletteElectric": "Electrico",
     "speedtest": {
       "title": "Test de velocidad WAN",
-      "caption": "Medición periódica real desde el servidor contra speedtest.net",
+      "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.",
+      "providerOokla": "Speedtest.net (Ookla)",
+      "providerCloudflare": "Cloudflare",
+      "providerLibrespeed": "LibreSpeed",
+      "providerCustom": "Personalizado",
+      "librespeedUrl": "URL de la instancia LibreSpeed",
+      "librespeedPlaceholder": "https://librespeed.example.com",
+      "customUrl": "URL del endpoint de medición",
+      "customPlaceholder": "https://mi-servidor/endpoint",
       "interval": "Intervalo",
       "intervalH": "cada {{hours}} h",
       "intervalWeek": "cada semana",
@@ -1688,12 +1687,12 @@
       "originAuto": "Auto",
       "originManual": "Manual",
       "colServer": "Servidor",
-      "noRecent": "Aún no hay tests registrados"
+      "noRecent": "Aún no hay tests registrados",
+      "recentHide": "Ocultar"
     },
     "proxmox": {
       "title": "Proxmox VE",
       "caption": "Inventario del cluster para identificar hosts y sus contenedores",
-      "hint": "Conecta con la API de solo lectura del cluster Proxmox (token con permisos Sys.Audit y VM.Audit). El inventario sella el host como hipervisor y sus CTs/VMs como contenedores colgados de él en Dispositivos, con nombres e IPs reales. Crea el token en Datacenter > Permisos > API Tokens.",
       "configured": "Configurado",
       "notConfigured": "Sin configurar",
       "edit": "Editar configuración de Proxmox",
@@ -1711,7 +1710,8 @@
       "instanceId": "Identificador (slug, no editable luego)",
       "test": "Probar",
       "testOk": "Conectado: Proxmox {{version}} · {{nodes}} nodo(s), {{vms}} VM(s), {{cts}} CT(s)",
-      "testLimited": "El token autentica pero no ve ningún invitado: Proxmox devuelve las listas vacías cuando al token le faltan permisos de auditoría. Dale PVEAuditor en \"/\" — en el host Proxmox: pveum acl modify / --tokens 'USUARIO@REALM!TOKEN' --roles PVEAuditor. Un token con separación de privilegios necesita el permiso él mismo, no basta con el de su usuario."
+      "testLimited": "El token autentica pero no ve ningún invitado: Proxmox devuelve las listas vacías cuando al token le faltan permisos de auditoría. Dale PVEAuditor en \"/\" — en el host Proxmox: pveum acl modify / --tokens 'USUARIO@REALM!TOKEN' --roles PVEAuditor. Un token con separación de privilegios necesita el permiso él mismo, no basta con el de su usuario.",
+      "hintShort": "API de solo lectura: el token necesita los permisos Sys.Audit y VM.Audit. Los pasos para crearlo están en la página de Ayuda."
     },
     "sections": {
       "personalization": "Configuración",
@@ -1782,16 +1782,17 @@
     },
     "alertsLang": {
       "title": "Idioma de las notificaciones",
-      "description": "Idioma en que se envían los avisos de ntfy, Telegram y webhook (las alertas se componen en español y se traducen al publicar).",
-      "label": "Idioma de los avisos"
+      "description": "Idioma en que se envían los avisos de ntfy, Telegram y webhook (las alertas se componen en español y se traducen al publicar)."
     },
-        "https": {
+    "https": {
       "title": "HTTPS",
-      "caption": "Sirve NetPulse por HTTPS con su propia autoridad de certificación y retira el HTTP plano paso a paso.",
       "loadError": "No se pudieron cargar los ajustes de HTTPS.",
       "unavailable": "HTTPS se gestiona fuera de esta página: {{reason}}.",
-      "enabled": "HTTPS en el puerto {{port}}",
+      "enabled": "HTTPS",
       "enabledHint": "Solo añade el puerto HTTPS. El HTTP plano sigue funcionando hasta que elijas un modo más estricto abajo.",
+      "portTitle": "Puerto",
+      "portHint": "Se aplica al momento, sin reiniciar. Los agentes y NetGrip que apuntan al puerto actual deben actualizar su URL.",
+      "portApply": "Cambiar",
       "locked": "Fijado en el archivo de entorno del servidor; cámbialo allí.",
       "rootTitle": "Certificado raíz",
       "rootHint": "Instálalo una vez en cada móvil y ordenador desde el que uses NetPulse. Antes de confiar en él, comprueba que la huella que muestra tu dispositivo coincide con esta y con la del log del servidor.",
@@ -1804,15 +1805,15 @@
       "modes": {
         "full": {
           "title": "Todo (como antes)",
-          "hint": "El HTTP plano lo sirve todo. Seguro mientras instalas el certificado raíz y mueves los agentes."
+          "hint": "El HTTP plano lo sirve todo, como hasta ahora."
         },
         "migrate": {
           "title": "Solo agentes",
-          "hint": "Los navegadores van a HTTPS; los inicios de sesión y las llamadas a la API por HTTP plano se rechazan. Los agentes siguen reportando por HTTP plano hasta que cada uno se mueva."
+          "hint": "Los navegadores van a HTTPS; los agentes siguen por HTTP hasta moverlos."
         },
         "redirect": {
           "title": "Nada",
-          "hint": "El HTTP plano solo redirige a HTTPS y entrega el certificado raíz. Los agentes que sigan en HTTP plano dejan de reportar."
+          "hint": "El HTTP plano solo redirige a HTTPS; los agentes que sigan en HTTP dejan de reportar."
         }
       },
       "agentsOnHttp": "Siguen reportando por HTTP plano",
@@ -1842,7 +1843,6 @@
   "topbar": {
     "alertsUnread": "Alertas, {{count}} sin leer",
     "demoMode": "Modo demo",
-    "gatewayStatus": "Estado de la puerta de enlace",
     "live": "En vivo",
     "networkHealth": "Salud de la red: {{score}}",
     "networkHealth100": "Salud de la red: {{score}} de 100",
@@ -1913,7 +1913,12 @@
       "viewCompare": "Ver la comparación completa en GitHub",
       "changelogFallback": "No se ha podido cargar el changelog.",
       "changelogLink": "Ver notas del release en GitHub",
-      "downNotice": "El servicio estará caído mientras se reinicia"
+      "downNotice": "El servicio estará caído mientras se reinicia",
+      "versionUpdate": "Actualización de versión",
+      "eta": "Tiempo estimado: 2-5 minutos",
+      "backupNote": "Se creará una copia de seguridad automática antes de actualizar",
+      "prerequisites": "Prerrequisitos",
+      "ack": "Entiendo que el servicio quedará no disponible brevemente durante la actualización"
     },
     "errors": {
       "exitRestart": "El servidor se reinició para aplicar la actualización (el paso final normal). Si en unos minutos la versión no ha cambiado, vuelve a comprobar actualizaciones.",
@@ -2348,6 +2353,18 @@
           "Sigue el progreso desde la misma página; el resultado definitivo llega cuando el router termina de arrancar."
         ],
         "tip": "Tras un flash solo sobrevive lo de /etc: el self-heal del agente restaura el binario al arrancar, y ⟦Reinstalar⟧ lo deja todo fresco si hiciera falta."
+      },
+      "proxmoxToken": {
+        "title": "Conectar un cluster Proxmox",
+        "subtitle": "Crear el token de API de solo lectura que pide la integración",
+        "intro": "La integración de Proxmox sella cada host como hipervisor y cuelga sus CTs y VMs de él en ⟦Dispositivos⟧, con nombres e IPs reales. Solo necesita lectura: un token de API con permisos de auditoría.",
+        "steps": [
+          "En la web de Proxmox ve a ⟦Datacenter⟧ → ⟦Permisos⟧ → ⟦API Tokens⟧ y crea un token para el usuario que prefieras (p. ej. root@pam!netpulse).",
+          "Dale permisos de auditoría: en ⟦Permisos⟧ → ⟦Añadir⟧ asigna el rol PVEAuditor sobre la ruta / al token (si el token tiene separación de privilegios, el permiso tiene que ser del propio token, no basta con el de su usuario).",
+          "En NetPulse abre ⟦Ajustes⟧ → ⟦Servicios⟧ y pulsa el icono de configuración de ⟦Proxmox VE⟧: añade la URL del cluster (https://host:8006), el Token ID (usuario@realm!nombre) y el Secret.",
+          "Pulsa ⟦Probar⟧: si el token autentica pero no ve invitados, le faltan los permisos del paso 2."
+        ],
+        "tip": "El secret solo se envía una vez y no vuelve del servidor: para cambiarlo, edita la instancia y escribe el nuevo."
       }
     }
   },
@@ -2355,4 +2372,4 @@
     "link": "Ver más",
     "dismiss": "Descartar aviso"
   }
-}
+}

+ 5 - 3
app/src/components/AlertItem.tsx

@@ -1,4 +1,4 @@
-import { AlertTriangle, CheckCircle2, CircleArrowUp, Eraser, Fingerprint, Info, OctagonX } from 'lucide-react'
+import { AlertTriangle, Check, CheckCircle2, CircleArrowUp, Fingerprint, Info, OctagonX } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import { useNavigate } from 'react-router'
@@ -82,17 +82,19 @@ export function AlertItem({ alert, onClick, onDismiss, className }: AlertItemPro
                 icon={action.icon}
                 label={action.title}
                 title={action.title}
+                iconOnly
                 onClick={(e) => { e.stopPropagation(); action.onClick() }}
                 className="text-text-muted hover:text-accent"
               />
             )}
             {onDismiss && (
               <RowAction
-                icon={Eraser}
+                icon={Check}
                 label={t('alerts.actions.dismiss')}
                 title={t('alerts.actions.dismiss')}
+                iconOnly
                 onClick={(e) => { e.stopPropagation(); onDismiss(alert.id) }}
-                className="text-text-muted hover:text-text-primary"
+                className="text-text-muted hover:text-ok"
               />
             )}
             <span className="text-caption text-text-muted">{alertRelTime(alert)}</span>

+ 0 - 180
app/src/components/DeviceTraffic.tsx

@@ -1,180 +0,0 @@
-import { useEffect, useMemo, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Sparkline } from '@/components/Sparkline'
-import { fmtEs } from '@/data/mock'
-
-interface TrafficPoint {
-  ts: string
-  rxBytes: number
-  txBytes: number
-  rxBps: number
-  txBps: number
-}
-
-interface TrafficResponse {
-  points: TrafficPoint[]
-  resolution: string
-}
-
-/** Formatea bytes a unidad legible estilo "2,1 GB" / "340 MB" (locale activo). */
-function fmtBytes(b: number): string {
-  const gb = b / 1e9
-  if (gb >= 1) return `${fmtEs(gb, 1)} GB`
-  const mb = b / 1e6
-  if (mb >= 1) return `${fmtEs(mb, mb >= 10 ? 0 : 1)} MB`
-  const kb = b / 1e3
-  return `${fmtEs(kb, kb >= 10 ? 0 : 1)} KB`
-}
-
-const RANGES = [
-  { key: '24h', secs: 24 * 3600 },
-  { key: '7d', secs: 7 * 24 * 3600 },
-  { key: '30d', secs: 30 * 24 * 3600 },
-] as const
-type RangeKey = (typeof RANGES)[number]['key']
-
-function MiniBwChart({ points }: { points: TrafficPoint[] }) {
-  if (points.length < 2) return null
-  const W = 220
-  const H = 34
-  const PAD = 3
-  const max = Math.max(...points.map((p) => p.rxBps + p.txBps), 1)
-  const stepX = (W - PAD * 2) / (points.length - 1)
-  const line = (key: 'rxBps' | 'txBps') =>
-    points
-      .map((p, i) => {
-        const x = PAD + i * stepX
-        const y = H - PAD - ((p[key] / max) * (H - PAD * 2))
-        return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`
-      })
-      .join(' ')
-  return (
-    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} className="block" aria-hidden="true">
-      <path d={line('rxBps')} fill="none" stroke="#3b82f6" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
-      <path d={line('txBps')} fill="none" stroke="#10b981" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
-    </svg>
-  )
-}
-
-/**
- * Tráfico real por cliente (#551). Fetch bajo demanda del detalle en live
- * (patrón PortSeriesChart); en demo no se monta (los campos del canon ya
- * viajan en el snapshot y el endpoint no existe).
- */
-export function DeviceTrafficDetail({ mac, online }: { mac: string; online: boolean }) {
-  const { t } = useTranslation()
-  const [range, setRange] = useState<RangeKey>('24h')
-  const [points, setPoints] = useState<TrafficPoint[] | null>(null)
-  const [loading, setLoading] = useState(false)
-
-  useEffect(() => {
-    let cancelled = false
-    if (!online || mac === '—') {
-      setPoints([])
-      return
-    }
-    const secs = RANGES.find((r) => r.key === range)!.secs
-    setLoading(true)
-    const now = Math.floor(Date.now() / 1000)
-    const from = now - secs
-    fetch(`/api/devices/${encodeURIComponent(mac)}/traffic?from=${from}&to=${now}`)
-      .then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
-      .then((json: TrafficResponse) => {
-        if (!cancelled) setPoints(json.points ?? [])
-      })
-      .catch(() => {
-        if (!cancelled) setPoints([])
-      })
-      .finally(() => {
-        if (!cancelled) setLoading(false)
-      })
-    return () => {
-      cancelled = true
-    }
-  }, [mac, online, range])
-
-  const summary = useMemo(() => {
-    if (!points || points.length === 0) return null
-    const rx = points.reduce((a, p) => a + (p.rxBytes || 0), 0)
-    const tx = points.reduce((a, p) => a + (p.txBytes || 0), 0)
-    const last = points[points.length - 1]
-    const mbps = last ? ((last.rxBps || 0) + (last.txBps || 0)) / 1e6 : 0
-    return { rx, tx, mbps }
-  }, [points])
-
-  if (!online) return null
-
-  return (
-    <div className="rounded-xl border border-border bg-elevated/40 px-3 py-2.5">
-      <div className="flex items-center justify-between gap-2">
-        <span className="text-caption font-medium text-text-secondary">
-          {t('devices.detail.traffic')}
-        </span>
-        <div className="flex gap-1">
-          {RANGES.map((r) => (
-            <button
-              key={r.key}
-              type="button"
-              onClick={() => setRange(r.key)}
-              className={`rounded px-1.5 py-0.5 text-[10px] font-medium transition-colors ${
-                range === r.key ? 'bg-accent/15 text-accent' : 'text-text-muted hover:bg-canvas hover:text-text-secondary'
-              }`}
-            >
-              {r.key}
-            </button>
-          ))}
-        </div>
-      </div>
-      {loading ? (
-        <div className="flex h-8 items-center justify-center text-caption text-text-muted">...</div>
-      ) : summary && points && points.length > 1 ? (
-        <div className="mt-1.5 space-y-1">
-          <div className="flex items-center justify-between gap-2">
-            <span className="font-mono text-mono-sm text-text-secondary">
-              ↓ {fmtBytes(summary.rx)} · ↑ {fmtBytes(summary.tx)}
-            </span>
-            <span className="font-mono text-mono-sm text-accent">
-              {summary.mbps >= 1 ? fmtEs(summary.mbps, 1) : fmtEs(summary.mbps, 2)} Mbps
-            </span>
-          </div>
-          <MiniBwChart points={points} />
-        </div>
-      ) : (
-        <div className="flex h-8 items-center justify-center text-caption text-text-muted">
-          {t('devices.detail.trafficNoSource')}
-        </div>
-      )}
-    </div>
-  )
-}
-
-/** Sparkline del tráfico actual (24 h) para filas compactas en live. */
-export function DeviceTrafficSparkline({ mac, online, width = 60, height = 20 }: { mac: string; online: boolean; width?: number; height?: number }) {
-  const [points, setPoints] = useState<TrafficPoint[]>([])
-  useEffect(() => {
-    let cancelled = false
-    if (!online || mac === '—') {
-      setPoints([])
-      return
-    }
-    const now = Math.floor(Date.now() / 1000)
-    const from = now - 24 * 3600
-    fetch(`/api/devices/${encodeURIComponent(mac)}/traffic?from=${from}&to=${now}`)
-      .then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
-      .then((json: TrafficResponse) => {
-        if (!cancelled) setPoints(json.points ?? [])
-      })
-      .catch(() => {
-        if (!cancelled) setPoints([])
-      })
-    return () => {
-      cancelled = true
-    }
-  }, [mac, online])
-  const data = useMemo(
-    () => points.filter((_, i, a) => a.length <= 48 || i % Math.ceil(a.length / 48) === 0).map((p) => (p.rxBps + p.txBps) / 1e6),
-    [points],
-  )
-  if (data.length < 2) return null
-  return <Sparkline data={data} width={width} height={height} className="text-accent" />
-}

+ 57 - 17
app/src/components/HttpsCard.tsx

@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'
 import { useSearchParams } from 'react-router'
 import { Loader2, Check, Lock, Download, Copy, ShieldCheck, TriangleAlert, ExternalLink, RefreshCw } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
+import { InfoTip } from '@/components/InfoTip'
 
 // FORK: Settings > HTTPS (server: internal/httpapi/https_settings.go).
 //
@@ -21,6 +22,7 @@ interface HttpsStatus {
   mode: Mode
   modeLocked: boolean
   port: number
+  portLocked?: boolean
   rootSha256?: string
   fingerprint?: string
   names?: string[]
@@ -32,7 +34,7 @@ interface HttpsStatus {
   agentsOnHttp?: { slug: string; lastSeen: string }[] | null
 }
 
-type Change = { enabled?: boolean; mode?: Mode; force?: boolean }
+type Change = { enabled?: boolean; mode?: Mode; port?: number; force?: boolean }
 
 const MODES: Mode[] = ['full', 'migrate', 'redirect']
 
@@ -50,7 +52,10 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
   const [copied, setCopied] = useState(false)
   const [renewing, setRenewing] = useState(false)
   const [renewNote, setRenewNote] = useState('')
+  const [portDraft, setPortDraft] = useState(0)
   const confirming = useRef(false)
+  const changeRef = useRef(change)
+  changeRef.current = change
 
   const load = useCallback(async () => {
     try {
@@ -61,6 +66,8 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
       }
       const d = (await r.json()) as HttpsStatus
       setSt({ ...d, agentsOnHttp: d.agentsOnHttp ?? [], names: d.names ?? [] })
+      // No pisar el borrador si hay un cambio de puerto pendiente (#978).
+      if (!changeRef.current?.port) setPortDraft(d.port)
     } catch {
       setLoadError(t('settings.https.loadError'))
     }
@@ -179,20 +186,50 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
 
   return (
     <div className="space-y-4">
-      {/* On / off */}
-      <div className="flex items-center justify-between gap-4">
-        <div>
-          <div className="text-sm font-medium text-text-primary">{t('settings.https.enabled', { port: st.port })}</div>
-          <p className="text-[11px] text-text-muted">{t('settings.https.enabledHint')}</p>
+      {/* Activar HTTPS + puerto del listener (#978) en UNA fila (#995): el
+          cambio de puerto se aplica en caliente - el listener se reconecta
+          al puerto nuevo sin reiniciar el servidor. */}
+      <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">
+        <div className="flex items-center gap-3">
+          <span className="flex items-center gap-1 text-sm font-medium text-text-primary">
+            {t('settings.https.enabled', { port: st.port })}
+            <InfoTip text={t('settings.https.enabledHint')} />
+          </span>
+          <Switch
+            checked={change?.enabled ?? st.enabled}
+            disabled={st.enabledLocked || busy}
+            onCheckedChange={(v) => setChange(v === st.enabled ? null : { enabled: v })}
+            aria-label={t('settings.https.enabled', { port: st.port })}
+          />
+        </div>
+        <div className="flex items-center gap-2">
+          <span className="flex items-center gap-1 text-sm font-medium text-text-primary">
+            {t('settings.https.portTitle')}
+            <InfoTip text={t('settings.https.portHint')} />
+          </span>
+          <input
+            type="number"
+            min={1}
+            max={65535}
+            value={portDraft || ''}
+            onChange={(e) => setPortDraft(Number(e.target.value))}
+            disabled={st.portLocked || busy}
+            aria-label={t('settings.https.portTitle')}
+            className={`${inputCls} w-24 text-right font-mono`}
+          />
+          <button
+            type="button"
+            disabled={st.portLocked || busy || !portDraft || portDraft === st.port}
+            onClick={() => {
+              if (portDraft >= 1 && portDraft <= 65535) setChange({ port: portDraft })
+            }}
+            className="inline-flex h-8 items-center rounded-lg border border-border bg-surface px-2.5 text-xs font-medium text-text-primary hover:bg-hover disabled:opacity-50"
+          >
+            {t('settings.https.portApply')}
+          </button>
         </div>
-        <Switch
-          checked={change?.enabled ?? st.enabled}
-          disabled={st.enabledLocked || busy}
-          onCheckedChange={(v) => setChange(v === st.enabled ? null : { enabled: v })}
-          aria-label={t('settings.https.enabled', { port: st.port })}
-        />
       </div>
-      {st.enabledLocked && <p className="text-[11px] text-text-muted">{t('settings.https.locked')}</p>}
+      {(st.enabledLocked || st.portLocked) && <p className="text-[11px] text-text-muted">{t('settings.https.locked')}</p>}
       {st.error && <p className="text-xs text-danger">{st.error}</p>}
 
       {st.enabled && (
@@ -202,8 +239,8 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
             <div className="mb-1 flex items-center gap-2 text-sm font-medium text-text-primary">
               <ShieldCheck className="h-4 w-4 text-accent" strokeWidth={2} />
               {t('settings.https.rootTitle')}
+              <InfoTip text={t('settings.https.rootHint')} />
             </div>
-            <p className="mb-2 text-[11px] leading-relaxed text-text-secondary">{t('settings.https.rootHint')}</p>
             <div className="mb-2 break-all font-mono text-[11px] text-text-primary">{st.rootSha256}</div>
             <div className="flex flex-wrap gap-2">
               <a
@@ -244,13 +281,17 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
                 {renewing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
                 {t('settings.https.renew')}
               </button>
-              <span className="text-[11px] text-text-muted">{renewNote || t('settings.https.renewHint')}</span>
+              <InfoTip text={t('settings.https.renewHint')} />
+              {renewNote && <span className="text-[11px] text-text-muted">{renewNote}</span>}
             </div>
           </div>
 
           {/* The pin for agents */}
           <div>
-            <div className="text-[11px] font-medium uppercase tracking-wider text-text-muted">{t('settings.https.agentPin')}</div>
+            <div className="flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-text-muted">
+              {t('settings.https.agentPin')}
+              <InfoTip text={t('settings.https.agentPinHint', { port: st.port })} />
+            </div>
             <div className="mt-1 flex items-center gap-2">
               <code className="flex-1 break-all rounded-md border border-border bg-elevated px-2 py-1 font-mono text-[11px] text-text-primary">
                 {st.fingerprint}
@@ -268,7 +309,6 @@ export default function HttpsCard({ onSaved }: { onSaved: () => void }) {
                 {copied ? <Check className="h-3.5 w-3.5 text-ok" /> : <Copy className="h-3.5 w-3.5" />}
               </button>
             </div>
-            <p className="mt-1 text-[11px] text-text-muted">{t('settings.https.agentPinHint', { port: st.port })}</p>
           </div>
 
           {/* What plain HTTP may still do */}

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

@@ -0,0 +1,25 @@
+import { Info } from 'lucide-react'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+
+// InfoTip (#975): icono (i) con el texto largo en un tooltip al pasar el
+// ratón, para que la sección quede con lo justo. Reusa el Tooltip radix de
+// la app (mismo patrón que PortPanel). Compartido por Settings y las cards
+// de integración (#1002).
+export function InfoTip({ text }: { text: string }) {
+  return (
+    <Tooltip>
+      <TooltipTrigger asChild>
+        <button
+          type="button"
+          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"
+        >
+          <Info className="h-3.5 w-3.5" strokeWidth={1.75} />
+        </button>
+      </TooltipTrigger>
+      <TooltipContent side="top" className="max-w-xs text-left leading-relaxed">
+        {text}
+      </TooltipContent>
+    </Tooltip>
+  )
+}

+ 75 - 55
app/src/components/KnownMacsManager.tsx

@@ -1,11 +1,13 @@
 /**
- * NetPulse — Gestor de dispositivos de confianza (issue #196).
+ * NetPulse - Gestor de dispositivos de confianza (issue #196).
  * Allowlist de MACs que no avisan como «dispositivo desconocido» y cuyo
  * nombre se usa como alias. CRUD contra /api/settings/known-macs (admin).
+ * Versión mínima (#1000): botón Añadir + listado; el contexto vive en el
+ * InfoTip de la tarjeta.
  */
 import { useCallback, useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
-import { Plus, ShieldCheck, Trash2 } from 'lucide-react'
+import { Plus, Trash2 } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
 
@@ -27,6 +29,7 @@ export function KnownMacsManager({ onSaved }: Props) {
   const [list, setList] = useState<KnownMacItem[]>([])
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState<string | null>(null)
+  const [showForm, setShowForm] = useState(false)
   const [mac, setMac] = useState('')
   const [name, setName] = useState('')
   const [submitting, setSubmitting] = useState(false)
@@ -68,6 +71,7 @@ export function KnownMacsManager({ onSaved }: Props) {
       if (!res.ok) throw new Error(`HTTP ${res.status}`)
       setMac('')
       setName('')
+      setShowForm(false)
       await load()
       refresh()
       onSaved?.()
@@ -93,23 +97,68 @@ export function KnownMacsManager({ onSaved }: Props) {
   const macInvalid = mac.trim() !== '' && !MAC_RE.test(mac.trim())
 
   return (
-    <div className="mt-4 space-y-3 border-t border-border pt-4">
-      <div className="flex items-start justify-between gap-3">
-        <div>
-          <div className="text-sm font-medium text-text-primary">{t('settings.knownMacs.title')}</div>
-          <div className="text-caption text-text-muted">{t('settings.knownMacs.caption')}</div>
-          <p className="mt-1 text-caption text-text-muted">{t('settings.knownMacs.hint')}</p>
-        </div>
-        <ShieldCheck className="h-5 w-5 shrink-0 text-ok" strokeWidth={1.75} aria-hidden="true" />
-      </div>
+    <div className="space-y-3">
+      {showForm && (
+        <form onSubmit={submit} className="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_1fr_auto]">
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.knownMacs.mac')}</span>
+            <input
+              type="text"
+              inputMode="text"
+              value={mac}
+              onChange={(e) => setMac(e.target.value)}
+              placeholder={t('settings.knownMacs.macPlaceholder')}
+              aria-label={t('settings.knownMacs.mac')}
+              aria-invalid={macInvalid}
+              autoFocus
+              className={cn(
+                'mt-1 w-full rounded-lg border bg-canvas px-3 py-2 font-mono text-mono-sm text-text-primary placeholder:text-text-muted focus:outline-none',
+                macInvalid ? 'border-danger' : 'border-border focus:border-accent',
+              )}
+            />
+          </label>
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.knownMacs.name')}</span>
+            <input
+              type="text"
+              value={name}
+              onChange={(e) => setName(e.target.value)}
+              placeholder={t('settings.knownMacs.namePlaceholder')}
+              aria-label={t('settings.knownMacs.name')}
+              className="mt-1 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"
+            />
+          </label>
+          <div className="flex items-end gap-2">
+            <button
+              type="submit"
+              disabled={submitting || macInvalid || mac.trim() === ''}
+              className="inline-flex h-[38px] shrink-0 items-center gap-1.5 rounded-lg border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors disabled:cursor-not-allowed disabled:opacity-50"
+            >
+              <Plus className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />
+              {submitting ? t('settings.knownMacs.adding') : t('settings.knownMacs.add')}
+            </button>
+            <button
+              type="button"
+              onClick={() => {
+                setShowForm(false)
+                setMac('')
+                setName('')
+                setError(null)
+              }}
+              className="inline-flex h-[38px] shrink-0 items-center rounded-lg border border-border px-3 text-[13px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+            >
+              {t('common.cancel')}
+            </button>
+          </div>
+        </form>
+      )}
+
+      {macInvalid && <p className="text-xs text-danger">{t('settings.knownMacs.invalidMac')}</p>}
+      {error && <p role="alert" className="text-xs text-danger">{error}</p>}
 
       {loading ? (
-        <div className="py-4 text-caption text-text-muted">…</div>
-      ) : list.length === 0 ? (
-        <div className="rounded-lg border border-border bg-elevated px-3 py-4 text-center text-caption text-text-muted">
-          {t('settings.knownMacs.empty')}
-        </div>
-      ) : (
+        <div className="py-2 text-caption text-text-muted">…</div>
+      ) : list.length > 0 ? (
         <ul className="space-y-2">
           {list.map((item) => (
             <li
@@ -133,50 +182,21 @@ export function KnownMacsManager({ onSaved }: Props) {
             </li>
           ))}
         </ul>
-      )}
+      ) : null}
 
-      <form onSubmit={submit} className="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_1fr_auto]">
-        <label className="block">
-          <span className="text-label uppercase text-text-muted">{t('settings.knownMacs.mac')}</span>
-          <input
-            type="text"
-            inputMode="text"
-            value={mac}
-            onChange={(e) => setMac(e.target.value)}
-            placeholder={t('settings.knownMacs.macPlaceholder')}
-            aria-label={t('settings.knownMacs.mac')}
-            aria-invalid={macInvalid}
-            className={cn(
-              'mt-1 w-full rounded-lg border bg-canvas px-3 py-2 font-mono text-mono-sm text-text-primary placeholder:text-text-muted focus:outline-none',
-              macInvalid ? 'border-danger' : 'border-border focus:border-accent',
-            )}
-          />
-        </label>
-        <label className="block">
-          <span className="text-label uppercase text-text-muted">{t('settings.knownMacs.name')}</span>
-          <input
-            type="text"
-            value={name}
-            onChange={(e) => setName(e.target.value)}
-            placeholder={t('settings.knownMacs.namePlaceholder')}
-            aria-label={t('settings.knownMacs.name')}
-            className="mt-1 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"
-          />
-        </label>
-        <div className="flex items-end">
+      {/* Añadir: debajo del listado, a la izquierda */}
+      {!showForm && (
+        <div className="flex justify-start">
           <button
-            type="submit"
-            disabled={submitting || macInvalid || mac.trim() === ''}
-            className="inline-flex h-[38px] shrink-0 items-center gap-1.5 rounded-lg border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors disabled:cursor-not-allowed disabled:opacity-50"
+            type="button"
+            onClick={() => setShowForm(true)}
+            className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105"
           >
             <Plus className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />
-            {submitting ? t('settings.knownMacs.adding') : t('settings.knownMacs.add')}
+            {t('settings.knownMacs.add')}
           </button>
         </div>
-      </form>
-
-      {macInvalid && <p className="text-xs text-danger">{t('settings.knownMacs.invalidMac')}</p>}
-      {error && <p role="alert" className="text-xs text-danger">{error}</p>}
+      )}
     </div>
   )
 }

+ 36 - 68
app/src/components/Layout.tsx

@@ -65,8 +65,8 @@ const NAV_ITEMS: NavItem[] = [
   { 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' },
-  { to: '/help', labelKey: 'nav.help', icon: CircleHelp },
   { to: '/settings', labelKey: 'nav.settings', icon: Settings },
+  { to: '/help', labelKey: 'nav.help', icon: CircleHelp },
 ]
 
 /** Badge de alertas sin leer, desde el DataProvider */
@@ -171,39 +171,23 @@ function NavItemBadge({ to, variant }: { to: string; variant: 'sidebar' | 'rail'
   )
 }
 
-/** Tarjeta "Estado del gateway" al pie del sidebar (datos del provider) */
-function GatewayStatus() {
+/** Punto de estado live compacto (#981): variante icon-only del LivePill para
+ *  el sidebar colapsado y el rail de tablet, que no tienen sitio para la pill. */
+function LiveDot() {
   const { t } = useTranslation()
-  const { routers } = useNetPulse()
-  const gw = routers.find((r) => r.roleBadge === 'Principal') ?? routers[0]
-  if (!gw) {
-    return (
-      <div className="flex items-center gap-2.5 rounded-xl bg-elevated px-3 py-2.5">
-        <span className="relative flex h-2 w-2">
-          <span className="relative inline-flex h-2 w-2 rounded-full bg-text-muted" />
-        </span>
-        <div className="min-w-0">
-          <div className="truncate text-caption font-semibold text-text-secondary">{t('topbar.gatewayStatus')}</div>
-          <div className="truncate font-mono text-caption text-text-muted">—</div>
-        </div>
-      </div>
-    )
-  }
-  const statusLabel = t(`common.status.${gw.status}`)
-  const dotClass = gw.status === 'online' ? 'bg-ok' : gw.status === 'warn' ? 'bg-warn' : 'bg-danger'
+  const { connectionStatus } = useNetPulse()
+  const reconnecting = connectionStatus === 'reconnecting'
+  const label = t(reconnecting ? 'topbar.reconnecting' : 'topbar.live')
   return (
-    <div className="flex items-center gap-2.5 rounded-xl bg-elevated px-3 py-2.5">
-      <span className="relative flex h-2 w-2">
-        <span className={cn('absolute inline-flex h-full w-full rounded-full opacity-75 animate-ping-soft', dotClass)} />
-        <span className={cn('relative inline-flex h-2 w-2 rounded-full', dotClass)} />
-      </span>
-      <div className="min-w-0">
-        <div className="truncate text-caption font-semibold text-text-secondary">{t('topbar.gatewayStatus')}</div>
-        <div className="truncate font-mono text-caption text-text-muted">
-          {gw.modelShort.replace('GL.iNet ', '')} · {statusLabel} · {gw.uptime}
-        </div>
-      </div>
-    </div>
+    <span className="relative flex h-2 w-2" role="status" title={label} aria-label={label}>
+      <span
+        className={cn(
+          'absolute inline-flex h-full w-full rounded-full opacity-75 animate-ping-soft',
+          reconnecting ? 'bg-warn' : 'bg-ok',
+        )}
+      />
+      <span className={cn('relative inline-flex h-2 w-2 rounded-full', reconnecting ? 'bg-warn' : 'bg-ok')} />
+    </span>
   )
 }
 
@@ -238,10 +222,6 @@ function useVisibleNavItems(): NavItem[] {
 function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggleCollapse: () => void }) {
   const { t } = useTranslation()
   const items = useVisibleNavItems()
-  const main = items.filter((i) => i.to !== '/settings')
-  // Settings siempre es el último ítem de NAV_ITEMS y los filtros de
-  // useVisibleNavItems nunca lo quitan → garantizado definido.
-  const settings = items[items.length - 1]!
 
   if (collapsed) {
     // Sidebar colapsado = raíl de iconos en lg (persiste en localStorage)
@@ -276,8 +256,8 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
             </NavLink>
           ))}
         </nav>
-        <div className="flex flex-col items-center gap-2 border-t border-border py-3">
-          <ThemeToggle />
+        <div className="flex flex-col items-center gap-3 border-t border-border py-3">
+          <LiveDot />
           <button
             type="button"
             onClick={onToggleCollapse}
@@ -297,7 +277,7 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
         <Logo />
       </div>
       <nav className="flex-1 space-y-1 px-3 py-2" aria-label={t('nav.mainNav')}>
-        {main.map((item) => (
+        {items.map((item) => (
           <NavLink
             key={item.to}
             to={item.to}
@@ -331,31 +311,19 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
           </NavLink>
         ))}
       </nav>
-      <div className="space-y-3 border-t border-border p-3">
-        <GatewayStatus />
-        <div className="flex items-center gap-2">
-          <ThemeToggle />
-          <NavLink
-            to={settings.to}
-            className={({ isActive }) =>
-              cn(
-                'flex h-9 flex-1 items-center gap-2 rounded-lg px-3 text-sm font-medium transition-colors duration-150',
-                isActive ? 'bg-accent-soft text-accent' : 'text-text-secondary hover:bg-hover hover:text-text-primary',
-              )
-            }
-          >
-            <settings.icon className="h-[18px] w-[18px]" strokeWidth={1.75} />
-            {t('nav.settings')}
-          </NavLink>
-          <button
-            type="button"
-            onClick={onToggleCollapse}
-            aria-label={t('nav.collapse')}
-            className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg border border-border bg-elevated text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
-          >
-            <ChevronsLeft className="h-4 w-4" strokeWidth={1.75} />
-          </button>
-        </div>
+      {/* Pie del sidebar (#981): indicador "En vivo" + boton de plegar en la
+          misma fila (sustituye a la antigua tarjeta de estado del gateway). */}
+      <div className="flex items-center gap-2 border-t border-border p-3">
+        <LivePill />
+        <button
+          type="button"
+          onClick={onToggleCollapse}
+          aria-label={t('nav.collapse')}
+          className="flex h-9 min-w-0 flex-1 items-center justify-center gap-2 rounded-lg border border-border bg-elevated text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+        >
+          <ChevronsLeft className="h-4 w-4 shrink-0" strokeWidth={1.75} />
+          <span className="truncate">{t('nav.collapse')}</span>
+        </button>
       </div>
     </aside>
   )
@@ -399,8 +367,8 @@ function Rail() {
           </NavLink>
         ))}
       </nav>
-      <div className="border-t border-border py-3">
-        <ThemeToggle />
+      <div className="flex items-center justify-center border-t border-border py-3">
+        <LiveDot />
       </div>
     </aside>
   )
@@ -435,7 +403,7 @@ function BellButton() {
 // Topbar (≥768px) — h-14
 // ---------------------------------------------------------------------------
 
-/** Pill de estado de conexión en el topbar (live: "En vivo"; reconectando: amber) */
+/** Pill de estado de conexión en el pie del sidebar (#981): verde "En vivo"; amber "Reconectando". */
 function LivePill() {
   const { t } = useTranslation()
   const { connectionStatus } = useNetPulse()
@@ -500,7 +468,7 @@ function Topbar() {
             strokeWidth={1.75}
           />
         </button>
-        <LivePill />
+        <ThemeToggle />
         <BellButton />
       </div>
     </header>

+ 3 - 3
app/src/components/MqttCard.tsx

@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Send, Loader2, Check, Eye, EyeOff, Radio, Share2 } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
+import { InfoTip } from '@/components/InfoTip'
 
 type MqttState = 'loading' | 'idle' | 'saving' | 'testing' | 'propagating' | 'saved' | 'error'
 
@@ -185,8 +186,9 @@ export default function MqttCard({ onSaved, bare = true }: { onSaved: () => void
 
       <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
         <div>
-          <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+          <label className="mb-1 flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-text-muted">
             {t('settings.mqtt.host')}
+            <InfoTip text={t('settings.mqtt.hint')} />
           </label>
           <input
             type="text"
@@ -272,8 +274,6 @@ export default function MqttCard({ onSaved, bare = true }: { onSaved: () => void
         </div>
       </div>
 
-      <p className="mt-2 text-[11px] leading-relaxed text-text-muted">{t('settings.mqtt.hint')}</p>
-
       {error && <p className="mt-2 text-xs text-danger">{error}</p>}
 
       {results && (

+ 7 - 5
app/src/components/NtfyCard.tsx

@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Send, Loader2, Check, Eye, EyeOff, Bell } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
+import { InfoTip } from '@/components/InfoTip'
 
 type NtfyState = 'loading' | 'idle' | 'saving' | 'testing' | 'saved' | 'error'
 
@@ -127,14 +128,16 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
       </div>
 
       <div className="flex items-center justify-between gap-4 py-1">
-        <span className="text-sm font-medium text-text-primary">{t('settings.ntfy.urgentOnly')}</span>
+        <span className="flex items-center gap-1 text-sm font-medium text-text-primary">
+          {t('settings.ntfy.urgentOnly')}
+          <InfoTip text={t('settings.ntfy.urgentOnlyHint')} />
+        </span>
         <Switch
           checked={cfg.urgentOnly}
           onCheckedChange={(v) => setCfg((c) => ({ ...c, urgentOnly: v }))}
           aria-label={t('settings.ntfy.urgentOnly')}
         />
       </div>
-      <p className="-mt-1 mb-1 text-[11px] leading-relaxed text-text-muted">{t('settings.ntfy.urgentOnlyHint')}</p>
 
       <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
         <div>
@@ -151,8 +154,9 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
         </div>
 
         <div>
-          <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+          <label className="mb-1 flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-text-muted">
             {t('settings.ntfy.topic')}
+            <InfoTip text={t('settings.ntfy.hint')} />
           </label>
           <input
             type="text"
@@ -189,8 +193,6 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
         </div>
       </div>
 
-      <p className="mt-2 text-[11px] leading-relaxed text-text-muted">{t('settings.ntfy.hint')}</p>
-
       {error && <p className="mt-2 text-xs text-danger">{error}</p>}
 
       <div className="mt-3 flex items-center gap-2">

+ 0 - 175
app/src/components/PresenceTimeline.tsx

@@ -1,175 +0,0 @@
-import { useEffect, useMemo, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { Activity } from 'lucide-react'
-import { relTimeFromTs } from '@/i18n'
-import { fetchJson } from '@/lib/utils'
-import { useNetPulse } from '@/data/DataProvider'
-
-// PresenceSection — timeline de presencia de un cliente (#771): bandas de
-// 24 h por día con los tramos conectado coloreados por AP (router), más el
-// feed de eventos recientes. Los datos salen de GET
-// /api/devices/{mac}/presence (device_events #184 fundidos con los
-// AP-STA-CONNECTED de roam_events, Fase 14.5).
-
-interface Interval {
-  routerId: string
-  startMs: number
-  endMs: number | null
-}
-
-interface PresenceEvent {
-  ts_ms: number
-  state: string
-  router_id?: string
-}
-
-interface PresenceData {
-  mac: string
-  days: number
-  nowMs: number
-  intervals: Interval[]
-  events: PresenceEvent[]
-  connects24h: number
-}
-
-/** Color estable por router: hue derivado del id (misma AP = mismo color). */
-function routerHue(id: string): number {
-  let h = 0
-  for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) % 360
-  return h
-}
-
-const DAY_MS = 24 * 3600 * 1000
-
-export function PresenceSection({ mac }: { mac: string }) {
-  const { t, i18n } = useTranslation()
-  const { isDemo } = useNetPulse()
-  const [data, setData] = useState<PresenceData | null>(null)
-  const [error, setError] = useState(false)
-
-  useEffect(() => {
-    if (isDemo) return // la muestra la genera useMemo de abajo
-    let cancelled = false
-    fetchJson<PresenceData>(`/api/devices/${encodeURIComponent(mac)}/presence?days=7`)
-      .then((res) => {
-        if (cancelled) return
-        if (res.ok && res.data) setData(res.data)
-        else setError(true)
-      })
-      .catch(() => {
-        if (!cancelled) setError(true)
-      })
-    return () => {
-      cancelled = true
-    }
-  }, [mac, isDemo])
-
-  // Demo: muestra determinista local (el modo demo no tiene sesión API;
-  // mismo criterio que el resto del dataset demo).
-  const demoData = useMemo<PresenceData | null>(() => {
-    if (!isDemo) return null
-    const nowMs = Date.now()
-    const now = new Date(nowMs)
-    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
-    let h = 0
-    for (let i = 0; i < mac.length; i++) h = (h * 31 + mac.charCodeAt(i)) % 240
-    const mk = (dayStart: number, h1: number, h2: number, router: string): Interval => ({
-      routerId: router,
-      startMs: dayStart + h1 * 3600_000 + (h % 60) * 60_000,
-      endMs: h2 >= 0 ? dayStart + h2 * 3600_000 : null,
-    })
-    const intervals: Interval[] = [
-      mk(todayStart - DAY_MS, 18, 23, 'salon'),
-      mk(todayStart, 8, 12, 'salon'),
-      mk(todayStart, 13, -1, h % 2 === 0 ? 'patio' : 'salon'),
-    ]
-    return { mac, days: 7, nowMs, intervals, events: [], connects24h: 2 + (h % 3) }
-  }, [isDemo, mac])
-
-  const effective = data ?? demoData
-
-  // Bandas de los últimos N días (hoy primero) con sus tramos recortados al día.
-  const days = useMemo(() => {
-    if (!effective) return []
-    const data = effective
-    const now = new Date(data.nowMs)
-    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()
-    const out: { label: string; startMs: number; endMs: number; bars: { left: number; width: number; hue: number; router: string }[] }[] = []
-    for (let d = 0; d < data.days; d++) {
-      const dayStart = todayStart - d * DAY_MS
-      const dayEnd = dayStart + DAY_MS
-      const bars = data.intervals
-        .map((iv) => {
-          const s = Math.max(iv.startMs, dayStart)
-          const e = Math.min(iv.endMs ?? data.nowMs, Math.min(dayEnd, data.nowMs))
-          if (e <= s) return null
-          return {
-            left: ((s - dayStart) / DAY_MS) * 100,
-            width: ((e - s) / DAY_MS) * 100,
-            hue: routerHue(iv.routerId),
-            router: iv.routerId,
-          }
-        })
-        .filter((b): b is NonNullable<typeof b> => b !== null)
-      const dt = new Date(dayStart)
-      const label = new Intl.DateTimeFormat(i18n.language, { weekday: 'short', day: 'numeric' }).format(dt)
-      out.push({ label, startMs: dayStart, endMs: dayEnd, bars })
-    }
-    return out
-  }, [effective, i18n.language])
-
-  if (error) return null // sin datos de presencia: la sección no se muestra
-
-  return (
-    <div className="col-span-2 space-y-3 md:col-span-3">
-      <div className="flex items-center gap-2">
-        <Activity className="h-4 w-4 text-accent" strokeWidth={1.75} />
-        <span className="text-label uppercase text-text-muted">{t('devices.presence.title')}</span>
-      </div>
-      {!effective ? (
-        <p className="text-caption text-text-muted">{t('common.loading')}</p>
-      ) : days.every((d) => d.bars.length === 0) ? (
-        <p className="text-caption text-text-muted">{t('devices.presence.empty')}</p>
-      ) : (
-        <div className="space-y-1.5">
-          {days.map((d) => (
-            <div key={d.startMs} className="flex items-center gap-2">
-              <span className="w-16 shrink-0 truncate text-caption capitalize text-text-muted">{d.label}</span>
-              <div className="relative h-3 flex-1 overflow-hidden rounded-full bg-border/40">
-                {d.bars.map((b, i) => (
-                  <div
-                    key={i}
-                    title={b.router}
-                    className="absolute top-0 h-full rounded-full"
-                    style={{
-                      left: `${b.left}%`,
-                      width: `${Math.max(b.width, 0.4)}%`,
-                      backgroundColor: `hsl(${b.hue} 65% 55%)`,
-                    }}
-                  />
-                ))}
-              </div>
-            </div>
-          ))}
-        </div>
-      )}
-      {effective && effective.events.length > 0 && (
-        <ul className="space-y-0.5 pt-1">
-          {effective.events.slice(0, 6).map((ev, i) => (
-            <li key={i} className="flex items-center gap-2 text-caption text-text-secondary">
-              <span className={ev.state === 'online' ? 'text-ok' : 'text-text-muted'}>
-                {ev.state === 'online'
-                  ? t('devices.presence.online', { router: ev.router_id || '—' })
-                  : t('devices.presence.offline')}
-              </span>
-              <span className="ml-auto shrink-0 text-text-muted">{relTimeFromTs(Math.floor(ev.ts_ms / 1000))}</span>
-            </li>
-          ))}
-        </ul>
-      )}
-      {effective && effective.connects24h > 1 && (
-        <p className="text-caption text-warn">{t('devices.presence.flappy', { count: effective.connects24h })}</p>
-      )}
-    </div>
-  )
-}

+ 20 - 0
app/src/components/RowAction.tsx

@@ -9,19 +9,39 @@ import { cn } from '@/lib/utils'
 // coarse) no existe hover: acción e etiqueta se muestran SIEMPRE y con área
 // de clic mayor (#862 parte táctil). Compartida por el feed (Alerts.tsx) y el
 // resumen (AlertItem.tsx).
+// iconOnly (#965): la etiqueta NO se muestra nunca (queda en el title); el
+// botón es siempre visible con área de clic cómoda, sin depender del hover.
 export function RowAction({
   icon: Icon,
   label,
   onClick,
   className,
   title,
+  iconOnly = false,
 }: {
   icon: LucideIcon
   label: string
   onClick: (e: ReactMouseEvent) => void
   className?: string
   title: string
+  iconOnly?: boolean
 }) {
+  if (iconOnly) {
+    return (
+      <button
+        type="button"
+        onClick={onClick}
+        className={cn(
+          'flex items-center justify-center rounded-md p-1.5 opacity-0 transition-opacity duration-150 group-hover:opacity-100 pointer-coarse:p-2.5 pointer-coarse:opacity-100',
+          className,
+        )}
+        title={title}
+        aria-label={title}
+      >
+        <Icon className="h-4 w-4 shrink-0" strokeWidth={1.75} />
+      </button>
+    )
+  }
   return (
     <button
       type="button"

+ 5 - 2
app/src/components/TelegramCard.tsx

@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Send, Loader2, Check, Eye, EyeOff, Bell } from 'lucide-react'
 import { Switch } from '@/components/ui/switch'
+import { InfoTip } from '@/components/InfoTip'
 
 type TelegramState = 'loading' | 'idle' | 'saving' | 'testing' | 'saved' | 'error'
 
@@ -140,8 +141,9 @@ export default function TelegramCard({ onSaved, bare = false }: { onSaved: () =>
         <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
           {/* Bot token */}
           <div>
-            <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+            <label className="mb-1 flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-text-muted">
               {t('settings.telegram.botToken')}
+              <InfoTip text={t('settings.telegram.botTokenHint')} />
             </label>
             <div className="flex items-center gap-1">
               <input
@@ -236,8 +238,9 @@ export default function TelegramCard({ onSaved, bare = false }: { onSaved: () =>
         {/* Bot token + Chat ID en la misma fila */}
         <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
           <div>
-            <label className="mb-1 block text-[11px] font-medium uppercase tracking-wider text-text-muted">
+            <label className="mb-1 flex items-center gap-1 text-[11px] font-medium uppercase tracking-wider text-text-muted">
               {t('settings.telegram.botToken')}
+              <InfoTip text={t('settings.telegram.botTokenHint')} />
             </label>
             <div className="flex items-center gap-1">
               <input

+ 22 - 22
app/src/components/ThemeToggle.tsx

@@ -1,39 +1,39 @@
 import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
 import { Moon, Sun } from 'lucide-react'
 import { cn } from '@/lib/utils'
+import { readMode, resolveLight, setMode, THEME_CHANGE_EVENT } from '@/lib/theme-boot'
 
-const STORAGE_KEY = 'netpulse-theme'
-
-function applyTheme(light: boolean) {
-  const el = document.documentElement
-  el.classList.toggle('light', light)
-  el.classList.toggle('dark', !light)
-}
-
-/** Toggle de tema dark-first (default oscuro; .light para claro). Persiste en localStorage. */
+/**
+ * Toggle de tema claro/oscuro (#980). Delega en theme-boot.setMode, que
+ * persiste `netpulse-theme-mode`, conmuta las clases .light/.dark Y re-aplica
+ * la paleta como variables inline en <html> (sin esto ultimo las vars inline
+ * oscuras del boot ganaban a la regla `html.light` del stylesheet y el click
+ * no cambiaba ningun color). Se sincroniza entre instancias via
+ * THEME_CHANGE_EVENT.
+ */
 export function ThemeToggle({ className }: { className?: string }) {
-  const [light, setLight] = useState<boolean>(() => {
-    if (typeof window === 'undefined') return false
-    return localStorage.getItem(STORAGE_KEY) === 'light'
-  })
+  const { t } = useTranslation()
+  const [light, setLight] = useState<boolean>(() => resolveLight(readMode()))
 
   useEffect(() => {
-    applyTheme(light)
-  }, [light])
+    const sync = () => setLight(resolveLight(readMode()))
+    window.addEventListener(THEME_CHANGE_EVENT, sync)
+    return () => window.removeEventListener(THEME_CHANGE_EVENT, sync)
+  }, [])
 
   const toggle = useCallback(() => {
-    setLight((prev) => {
-      const next = !prev
-      localStorage.setItem(STORAGE_KEY, next ? 'light' : 'dark')
-      return next
-    })
-  }, [])
+    const next = !light
+    setMode(next ? 'light' : 'dark')
+    setLight(next)
+  }, [light])
 
   return (
     <button
       type="button"
       onClick={toggle}
-      aria-label={light ? 'Cambiar a tema oscuro' : 'Cambiar a tema claro'}
+      aria-label={light ? t('nav.themeToDark') : t('nav.themeToLight')}
+      title={light ? t('nav.themeToDark') : t('nav.themeToLight')}
       className={cn(
         'flex h-9 w-9 items-center justify-center rounded-lg border border-border bg-elevated text-text-secondary',
         'transition-colors duration-150 hover:border-accent/40 hover:text-accent',

+ 51 - 12
app/src/components/UpdateDialog.tsx

@@ -11,7 +11,9 @@ import {
   AlertTriangle,
   ArrowRight,
   Check,
+  CheckCircle2,
   Circle,
+  Clock,
   DownloadCloud,
   ExternalLink,
   Loader2,
@@ -299,7 +301,7 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
 
   return (
     <Dialog open={open} onOpenChange={(o) => !busy && onOpenChange(o)}>
-      <DialogContent className="max-w-md">
+      <DialogContent className="max-w-2xl">
         <DialogHeader>
           <DialogTitle className="flex items-center gap-2">
             <DownloadCloud className="h-5 w-5 text-accent" strokeWidth={1.75} aria-hidden="true" />
@@ -310,11 +312,27 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
 
         {phase === 'confirm' && (
           <div className="flex flex-col gap-4">
-            <div className="flex items-center justify-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
-              <span className="font-mono text-sm text-text-secondary">{status?.current ?? '—'}</span>
-              <ArrowRight className="h-4 w-4 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
-              <span className="font-mono text-sm font-semibold text-accent">
-                {status?.latest ?? '—'}
+            {/* 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">
+                {t('update.dialog.versionUpdate')}
+              </p>
+              <div className="flex items-center justify-center gap-4 rounded-xl border border-accent/40 bg-accent-soft px-4 py-3.5">
+                <span className="font-mono text-base text-text-secondary">{status?.current ?? '—'}</span>
+                <ArrowRight className="h-4 w-4 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+                <span className="font-mono text-base font-semibold text-accent">
+                  {status?.latest ?? '—'}
+                </span>
+              </div>
+            </div>
+            <div className="flex flex-col gap-1.5 text-caption">
+              <span className="flex items-center gap-2 text-text-secondary">
+                <Clock className="h-3.5 w-3.5 shrink-0 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+                {t('update.dialog.eta')}
+              </span>
+              <span className="flex items-center gap-2 text-ok">
+                <CheckCircle2 className="h-3.5 w-3.5 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+                {t('update.dialog.backupNote')}
               </span>
             </div>
             {status?.latestMsg && (
@@ -391,17 +409,29 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
                 </a>
               </p>
             )}
-            {status?.readiness && <ReadinessPanel readiness={status.readiness} compact />}
-            <label className="flex cursor-pointer items-start gap-2.5 rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-snug text-warn">
+            {status?.readiness && (
+              <div className="flex flex-col gap-1.5">
+                <p className="text-xs font-semibold uppercase tracking-wider text-text-muted">
+                  {t('update.dialog.prerequisites')}
+                </p>
+                <ReadinessPanel readiness={status.readiness} compact />
+              </div>
+            )}
+            {/* Aviso downtime (caja ámbar) + confirmación por separado */}
+            <div className="flex items-start gap-3 rounded-xl border border-warn/40 bg-warn/10 px-4 py-3">
+              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} aria-hidden="true" />
+              <p className="text-caption leading-snug text-warn">{t('update.dialog.downNotice')}</p>
+            </div>
+            <label className="flex cursor-pointer items-start gap-2.5 px-1 text-caption leading-snug text-text-secondary">
               <Checkbox
                 checked={ackDowntime}
                 onCheckedChange={(v) => setAckDowntime(v === true)}
                 className="mt-0.5"
-                aria-label={t('update.dialog.downNotice')}
+                aria-label={t('update.dialog.ack')}
               />
-              <span>{t('update.dialog.downNotice')}</span>
+              <span>{t('update.dialog.ack')}</span>
             </label>
-            <DialogFooter>
+            <DialogFooter className="border-t border-border pt-4">
               <Button variant="outline" onClick={() => onOpenChange(false)}>
                 {t('update.dialog.cancel')}
               </Button>
@@ -422,6 +452,12 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
 
         {phase === 'progress' && (
           <div className="flex flex-col gap-4" role="status">
+            {/* Cabecera de progreso estilo Pulse: spinner grande + paso actual */}
+            <div className="flex flex-col items-center gap-1.5 py-2">
+              <Loader2 className="h-10 w-10 animate-spin text-accent" strokeWidth={1.5} aria-hidden="true" />
+              <p className="text-sm font-medium text-text-primary">{t(`update.step.${visibleStep}`)}…</p>
+              <p className="text-caption text-text-muted">{t('update.dialog.progressLabel')}</p>
+            </div>
             <ul className="flex flex-col gap-2.5">
               {STEP_ORDER.map((s, i) => {
                 const done = activeIdx > i || step === 'done'
@@ -453,7 +489,10 @@ export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialog
                 <span className="font-mono">{pct}%</span>
               </div>
             </div>
-            <p className="text-center text-caption text-text-muted">{t('update.dialog.hideHint')}</p>
+            <div className="flex items-start gap-3 rounded-xl border border-warn/40 bg-warn/10 px-4 py-3">
+              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} aria-hidden="true" />
+              <p className="text-caption leading-snug text-warn">{t('update.dialog.hideHint')}</p>
+            </div>
           </div>
         )}
 

+ 0 - 7
app/src/components/routers/AgentsSection.tsx

@@ -557,13 +557,6 @@ export function AgentsSection() {
       <div className="mb-4">
         <h2 id="agents-section-title" className="font-display text-h2 text-text-primary">{t('routers.agents.title')}</h2>
         <p className="text-caption text-text-muted">{t('routers.agents.subtitle', { total, down })}</p>
-        {rows.length > 0 && (
-          <div className="mt-3 flex flex-col gap-1.5 rounded-xl border border-border/60 bg-canvas/50 px-3 py-2.5">
-            <p className="text-caption font-medium text-text-secondary">{t('routers.agents.installChoice')}</p>
-            <p className="text-caption text-text-muted">{t('routers.agents.installChoiceNetgrip')}</p>
-            <p className="text-caption text-text-muted">{t('routers.agents.installChoiceNative')}</p>
-          </div>
-        )}
       </div>
       <DiscoveredStrip />
       {rows.length === 0 ? (

+ 78 - 29
app/src/components/routers/WanLatency.tsx

@@ -140,11 +140,86 @@ type SpeedtestItem = {
   serverName?: string
 }
 
+/** Punto de la serie del histórico de speedtests (etiqueta ya formateada). */
+type SpeedtestPoint = { t: string; down: number; up: number }
+
+function toPoints(items: SpeedtestItem[]): SpeedtestPoint[] {
+  const fmt = new Intl.DateTimeFormat(undefined, { weekday: 'short', hour: '2-digit' })
+  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). */
+export function SpeedtestHistoryChart({ points, height = 64 }: { points: SpeedtestPoint[]; height?: number }) {
+  const { t } = useTranslation()
+  if (points.length <= 1) return null
+  return (
+    <div className="mt-2" style={{ height }} role="img" aria-label={t('routerDetail.wan.speedtestTitle')}>
+      <ResponsiveContainer width="100%" height="100%">
+        <AreaChart data={points} margin={{ top: 6, right: 4, bottom: 0, left: 4 }}>
+          <defs>
+            <linearGradient id="speedtest-hist-down" x1="0" y1="0" x2="0" y2="1">
+              <stop offset="0%" stopColor="#22D3EE" stopOpacity={0.22} />
+              <stop offset="100%" stopColor="#22D3EE" stopOpacity={0} />
+            </linearGradient>
+            <linearGradient id="speedtest-hist-up" x1="0" y1="0" x2="0" y2="1">
+              <stop offset="0%" stopColor="#A78BFA" stopOpacity={0.18} />
+              <stop offset="100%" stopColor="#A78BFA" stopOpacity={0} />
+            </linearGradient>
+          </defs>
+          <CartesianGrid vertical={false} stroke="rgb(var(--border) / 0.4)" strokeDasharray="3 6" />
+          <XAxis
+            dataKey="t"
+            tickLine={false}
+            axisLine={false}
+            interval="preserveStartEnd"
+            minTickGap={48}
+            tick={{ fill: 'rgb(var(--text-muted))', fontSize: 9, fontFamily: '"JetBrains Mono", monospace' }}
+          />
+          <Tooltip content={<WanTooltip />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
+          <Area type="stepAfter" dataKey="down" stroke="#22D3EE" strokeWidth={1.5} fill="url(#speedtest-hist-down)" dot={false} />
+          <Area type="stepAfter" dataKey="up" stroke="#A78BFA" strokeWidth={1.5} fill="url(#speedtest-hist-up)" dot={false} />
+        </AreaChart>
+      </ResponsiveContainer>
+    </div>
+  )
+}
+
 function useSpeedtestState() {
   const [running, setRunning] = useState(false)
   const [lastError, setLastError] = useState<string | null>(null)
   const [last, setLast] = useState<SpeedtestItem | null>(null)
-  const [points, setPoints] = useState<{ t: string; down: number; up: number }[]>([])
+  const [points, setPoints] = useState<SpeedtestPoint[]>([])
   const [starting, setStarting] = useState(false)
 
   const load = useCallback(async () => {
@@ -161,14 +236,7 @@ function useSpeedtestState() {
       }
       if (hRes.ok) {
         const h = await hRes.json()
-        const fmt = new Intl.DateTimeFormat(undefined, { weekday: 'short', hour: '2-digit' })
-        setPoints(
-          (h.items ?? []).map((it: SpeedtestItem) => ({
-            t: fmt.format(new Date(it.ts)),
-            down: it.downMbps,
-            up: it.upMbps,
-          })),
-        )
+        setPoints(toPoints(h.items ?? []))
       }
     } catch {
       // Sin red / sesión caducada: se conserva el último estado pintado.
@@ -272,26 +340,7 @@ export function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
               <span className="text-text-muted">· {t('routerDetail.wan.speedtestServer', { name: last.serverName })}</span>
             )}
           </div>
-          {points.length > 1 && (
-            <div className="mt-2 h-[64px]" role="img" aria-label={t('routerDetail.wan.speedtestTitle')}>
-              <ResponsiveContainer width="100%" height="100%">
-                <AreaChart data={points} margin={{ top: 6, right: 4, bottom: 0, left: 4 }}>
-                  <CartesianGrid vertical={false} stroke="rgb(var(--border) / 0.4)" strokeDasharray="3 6" />
-                  <XAxis
-                    dataKey="t"
-                    tickLine={false}
-                    axisLine={false}
-                    interval="preserveStartEnd"
-                    minTickGap={48}
-                    tick={{ fill: 'rgb(var(--text-muted))', fontSize: 9, fontFamily: '"JetBrains Mono", monospace' }}
-                  />
-                  <Tooltip content={<WanTooltip />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
-                  <Area type="stepAfter" dataKey="down" stroke="#22D3EE" strokeWidth={1.5} fill="url(#wan-detail-down)" dot={false} />
-                  <Area type="stepAfter" dataKey="up" stroke="#A78BFA" strokeWidth={1.5} fill="url(#wan-detail-up)" dot={false} />
-                </AreaChart>
-              </ResponsiveContainer>
-            </div>
-          )}
+          <SpeedtestHistoryChart points={points} />
         </>
       ) : (
         <p className="mt-2 text-caption text-text-muted">

+ 12 - 6
app/src/components/topology/LegendCard.tsx

@@ -9,15 +9,18 @@ import { useTranslation } from 'react-i18next'
 import { useNetPulse } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
 import type { TopologyModel } from './model'
-import { COLOR } from './model'
+import { BAND_HEX, COLOR, networkHasBand6 } from './model'
 
 // ---------------------------------------------------------------------------
 // Contenido compartido
 // ---------------------------------------------------------------------------
 
-const BAND_ROWS: { color: string; label?: string; labelKey?: string }[] = [
-  { color: COLOR.accent, label: '5 GHz' },
-  { color: COLOR.info, label: '2.4 GHz' },
+// Filas de banda: misma paleta centralizada BAND_HEX (issue #986), ascendente.
+// La fila 6 GHz solo se pinta si la red tiene 6 GHz (#991, networkHasBand6).
+const BAND_ROWS: { color: string; label?: string; labelKey?: string; band?: string }[] = [
+  { color: BAND_HEX['2.4 GHz'], label: '2.4 GHz' },
+  { color: BAND_HEX['5 GHz'], label: '5 GHz' },
+  { color: BAND_HEX['6 GHz'], label: '6 GHz', band: '6 GHz' },
   { color: COLOR.ok, labelKey: 'topology.legend.wired' },
   { color: COLOR.warn, labelKey: 'topology.weakSignal' },
 ]
@@ -108,8 +111,11 @@ function WgSample() {
 export function LegendContent({ model, compact = false }: { model: TopologyModel; compact?: boolean }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { deviceTotals } = useNetPulse()
+  const { deviceTotals, routers, devices } = useNetPulse()
   const { activeLinkCount, activePeerCount } = model
+  // #991: la fila 6 GHz desaparece si la red no tiene 6 GHz (networkHasBand6).
+  const hasBand6 = networkHasBand6(routers, devices)
+  const bandRows = hasBand6 ? BAND_ROWS : BAND_ROWS.filter((r) => r.band !== '6 GHz')
   const row = (i: number) =>
     reduce
       ? {}
@@ -124,7 +130,7 @@ export function LegendContent({ model, compact = false }: { model: TopologyModel
       <div>
         <div className="mb-2 text-label uppercase text-text-muted">{t('topology.legend.bandConnection')}</div>
         <ul className="grid grid-cols-2 gap-x-4 gap-y-2">
-          {BAND_ROWS.map((r) => (
+          {bandRows.map((r) => (
             <motion.li key={r.label ?? r.labelKey} className="flex items-center gap-2 text-sm text-text-secondary" {...row(i++)}>
               <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: r.color }} />
               {r.label ?? t(r.labelKey!)}

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

@@ -253,8 +253,6 @@ export function TopologyOverridesManager({ onSaved, initialMac }: Props) {
 
   return (
     <div className="space-y-3">
-      <p className="text-caption leading-relaxed text-text-muted">{t('settings.overrides.hint')}</p>
-
       {error && <p className="text-caption text-danger">{error}</p>}
 
       {/* Lista */}

+ 2 - 1
app/src/components/topology/UsteerPanel.tsx

@@ -8,6 +8,7 @@ import { Wifi } from 'lucide-react'
 import { SectionHeader } from '@/components/SectionHeader'
 import { redirectLogin } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
+import { bandBadgeClass } from './model'
 
 interface UsteerAp {
   ssid: string
@@ -86,7 +87,7 @@ export function UsteerPanel() {
           >
             <span className={cn(
               'flex h-8 w-8 shrink-0 items-center justify-center rounded-lg',
-              ap.band === '5 GHz' ? 'bg-accent-soft text-accent' : 'bg-info/10 text-info',
+              bandBadgeClass(ap.band),
             )}>
               <Wifi className="h-4 w-4" strokeWidth={1.75} />
             </span>

+ 57 - 3
app/src/components/topology/model.ts

@@ -192,11 +192,65 @@ export const COLOR = {
   info: '#60A5FA',
 } as const
 
+/**
+ * Paleta de bandas wifi (issue #986): una FAMILIA de color distinta por banda
+ * para que se diferencien de un vistazo en tema claro y oscuro (antes 2.4 GHz
+ * azul #60A5FA y 5 GHz cian #22D3EE eran dos azules casi iguales, y 6 GHz
+ * caía al verde por defecto, igual que el cable).
+ *   - 2.4 GHz: naranja (cálido; la banda legacy/lenta)
+ *   - 5 GHz:   cian (familia del acento de la app; la banda principal)
+ *   - 6 GHz:   fucsia (la banda más nueva; alejada del violeta de túneles WG)
+ *   - 60 GHz:  pizarra (WiGig, prácticamente inexistente en este ámbito)
+ * Reservados y por eso NO usados aquí: ámbar (señal débil y uplinks wifi),
+ * violeta (túneles WG) y verde (cable/estado ok). Mismo hex en ambos temas:
+ * nivel 500 de Tailwind, con saturación suficiente sobre el canvas claro
+ * (#F3F5F9) y el oscuro (#070B12).
+ */
+export const BAND_HEX = {
+  '2.4 GHz': '#F97316', // orange-500
+  '5 GHz': '#06B6D4', // cyan-500
+  '6 GHz': '#D946EF', // fuchsia-500
+  '60 GHz': '#94A3B8', // slate-400
+} as const
+
 export function bandColor(band: Band, weak: boolean): string {
   if (weak) return COLOR.warn
-  if (band === '5 GHz') return COLOR.accent
-  if (band === '2.4 GHz') return COLOR.info
-  return COLOR.ok
+  return BAND_HEX[band as keyof typeof BAND_HEX] ?? COLOR.ok
+}
+
+/**
+ * Clases Tailwind del badge de banda en DOM (panel usteer). Misma paleta que
+ * BAND_HEX: clases literales (el JIT no ve clases dinámicas), mantener en sync.
+ */
+export function bandBadgeClass(band: string): string {
+  switch (band) {
+    case '2.4 GHz':
+      return 'bg-[#F97316]/10 text-[#F97316]'
+    case '5 GHz':
+      return 'bg-[#06B6D4]/10 text-[#06B6D4]'
+    case '6 GHz':
+      return 'bg-[#D946EF]/10 text-[#D946EF]'
+    default:
+      return 'bg-info/10 text-info'
+  }
+}
+
+/**
+ * Detección de banda 6 GHz en la red (issue #991). El frontend no recibe un
+ * flag de capacidad hardware por router, así que la fuente de verdad es:
+ *   - algún router reporta clientes online en 6 GHz (Router.bandSplit.band6 > 0,
+ *     issue #645; misma fuente que el contador `clients`), O
+ *   - algún cliente figura con banda '6 GHz' (Device.band).
+ * Limitación conocida: una red con radio 6G pero sin clientes asociados aún
+ * no se detecta (no hay señal de hardware en los tipos). Cuando la red no
+ * tiene 6 GHz, la UI no la menciona (filtro Conexión de Clientes, leyenda de
+ * topología); BAND_HEX conserva la entrada por si la banda aparece.
+ */
+export function networkHasBand6(
+  routers: ReadonlyArray<Pick<Router, 'bandSplit'>>,
+  devices: ReadonlyArray<Pick<Device, 'band'>>,
+): boolean {
+  return routers.some((r) => (r.bandSplit?.band6 ?? 0) > 0) || devices.some((d) => d.band === '6 GHz')
 }
 
 export function statusColor(status: Router['status']): string {

+ 1 - 1
app/src/components/ui/dialog.tsx

@@ -58,7 +58,7 @@ function DialogContent({
       <DialogPrimitive.Content
         data-slot="dialog-content"
         className={cn(
-          "bg-background 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",
+          "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
         )}
         {...props}

+ 15 - 19
app/src/data/DataProvider.tsx

@@ -180,8 +180,8 @@ 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
-  /** POST /api/alerts/read-all (live). Demo: estado local. Optimista. */
-  markAllAlertsRead: () => void
+  /** #971: VACÍA el feed - POST /api/alerts/clear (live). 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
   /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
@@ -935,27 +935,23 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
-  const markAllAlertsRead = useCallback(() => {
-    setBundle((prev) => ({
-      ...prev,
-      alerts: prev.alerts.map((a) => ({ ...a, read: true })),
-      unreadAlerts: 0,
-    }))
+  // #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.
+  const clearAllAlerts = useCallback(() => {
+    setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
     if (modeRef.current !== 'live') return
     void (async () => {
       try {
-        const res = await fetch('/api/alerts/read-all', { method: 'POST' })
+        const res = await fetch('/api/alerts/clear', { method: 'POST' })
         if (res.status === 401) redirectLogin()
         // #891: un snapshot tomado ANTES de que el POST llegara al servidor
-        // puede haber pisado el estado optimista con read=false. Al resolver
-        // el POST, la verdad del servidor YA incluye el read-all, así que se
-        // re-aplica el estado leído por si llegó ese snapshot enrarecido.
+        // puede haber pisado el estado optimista. Al resolver el POST, la
+        // verdad del servidor YA incluye el clear, así que se re-aplica el
+        // feed vacío por si llegó ese snapshot enrarecido.
         if (res.ok) {
-          setBundle((prev) => ({
-            ...prev,
-            alerts: prev.alerts.map((a) => ({ ...a, read: true })),
-            unreadAlerts: 0,
-          }))
+          setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
         }
       } catch {
         /* idem: resync por snapshot */
@@ -1263,7 +1259,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       alertsConfig,
       setAlertConfig,
       markAlertsRead,
-      markAllAlertsRead,
+      clearAllAlerts,
       silenceAlert,
       dismissAlert,
       rearmAgent,
@@ -1273,7 +1269,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       uninstallAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, 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],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

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

@@ -30,8 +30,6 @@ export type FeedDay = 'hoy' | 'ayer' | '12nov'
 
 export const DAY_ORDER: FeedDay[] = ['hoy', 'ayer', '12nov']
 
-export const ALERT_KINDS: readonly AlertKind[] = ['router', 'dispositivos', 'wireguard', 'adguard', 'sistema']
-
 export interface FeedSpark {
   data: number[]
   color: string

+ 1 - 1
app/src/data/types.ts

@@ -188,7 +188,7 @@ export type DeviceType =
   | 'switch'
   | 'desconocido'
 
-export type Band = '5 GHz' | '2.4 GHz' | 'cable' | '—'
+export type Band = '6 GHz' | '5 GHz' | '2.4 GHz' | '60 GHz' | 'cable' | '—'
 
 /** Identificación LLDP de un vecino (switch gestionado, AP, host…). */
 export interface LldpInfo {

+ 89 - 0
app/src/hooks/useIntegrations.ts

@@ -0,0 +1,89 @@
+/**
+ * Integraciones server-side (#968): toggles de Proxmox/ntfy/Telegram/MQTT
+ * leídos de GET /api/settings/integrations y escritos con PUT partial-safe
+ * (solo la clave tocada). Ausente = activo en el servidor; MQTT refleja la
+ * config efectiva del publisher (env + kv).
+ */
+import { useCallback, useEffect, useState } from 'react'
+
+export interface IntegrationsState {
+  ntfy: boolean
+  telegram: boolean
+  proxmox: boolean
+  mqtt: boolean
+}
+
+const DEFAULTS: IntegrationsState = { ntfy: true, telegram: true, proxmox: true, mqtt: false }
+
+export function useIntegrations(enabled = true): {
+  integrations: IntegrationsState
+  loaded: boolean
+  setIntegration: (k: keyof IntegrationsState, v: boolean) => void
+} {
+  const [integrations, setIntegrations] = useState<IntegrationsState>(DEFAULTS)
+  const [loaded, setLoaded] = useState(false)
+
+  useEffect(() => {
+    if (!enabled) return
+    let alive = true
+    void fetch('/api/settings/integrations')
+      .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,
+        })
+        setLoaded(true)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [enabled])
+
+  const setIntegration = useCallback((k: keyof IntegrationsState, v: boolean) => {
+    // Optimista: el toggle responde al instante; si el PUT falla se revierte
+    // leyendo el estado real del servidor.
+    setIntegrations((prev) => ({ ...prev, [k]: v }))
+    void fetch('/api/settings/integrations', {
+      method: 'PUT',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ [k]: v }),
+    })
+      .then((r) => {
+        if (r.ok) return r.json()
+        throw new Error(`HTTP ${r.status}`)
+      })
+      .then((d) => {
+        if (d) {
+          setIntegrations({
+            ntfy: d.ntfy !== false,
+            telegram: d.telegram !== false,
+            proxmox: d.proxmox !== false,
+            mqtt: d.mqtt === true,
+          })
+        }
+      })
+      .catch(() => {
+        // Revertir con la verdad del servidor.
+        void fetch('/api/settings/integrations')
+          .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,
+              })
+            }
+          })
+          .catch(() => undefined)
+      })
+  }, [])
+
+  return { integrations, loaded, setIntegration }
+}

+ 29 - 0
app/src/hooks/useWeakSignalDbm.ts

@@ -0,0 +1,29 @@
+import { useEffect, useState } from 'react'
+import { useNetPulse } from '@/data/DataProvider'
+
+/** Fallback cuando el servidor aún no expone el ajuste (demo o build antiguo). */
+export const WEAK_SIGNAL_FALLBACK_DBM = -70
+
+/**
+ * Umbral global de "señal débil" (Ajustes → /api/settings/thresholds,
+ * #904). Lo comparten la página Clientes (#1003) y la matriz de roaming
+ * (#906): un solo fetch por consumidor, sin cachear entre páginas.
+ */
+export function useWeakSignalDbm(): number {
+  const { isDemo } = useNetPulse()
+  const [dbm, setDbm] = useState(WEAK_SIGNAL_FALLBACK_DBM)
+  useEffect(() => {
+    if (isDemo) return
+    let cancelled = false
+    fetch('/api/settings/thresholds')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((j) => {
+        if (!cancelled && j && typeof j.weakSignalDbm === 'number') setDbm(j.weakSignalDbm)
+      })
+      .catch(() => {})
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+  return dbm
+}

+ 20 - 0
app/src/index.css

@@ -373,3 +373,23 @@
     animation: none !important;
   }
 }
+
+/* Tabla de clientes (#958): grid con columnas dinamicas. Devices.tsx genera
+ * las plantillas segun las columnas visibles y las inyecta como custom
+ * properties; Tailwind no puede cubrir todas las combinaciones posibles.
+ * Los breakpoints replican md/lg/xl (48/64/80rem). */
+@media (min-width: 48rem) {
+  .devices-cols {
+    grid-template-columns: var(--devices-cols-md);
+  }
+}
+@media (min-width: 64rem) {
+  .devices-cols {
+    grid-template-columns: var(--devices-cols-lg);
+  }
+}
+@media (min-width: 80rem) {
+  .devices-cols {
+    grid-template-columns: var(--devices-cols-xl);
+  }
+}

+ 18 - 0
app/src/lib/theme-boot.ts

@@ -152,6 +152,24 @@ function applyPalette(light: boolean) {
   root.setAttribute('data-palette', id)
 }
 
+/** Evento de ventana que avisa a los toggles de tema de que el modo cambio. */
+export const THEME_CHANGE_EVENT = 'netpulse-theme-change'
+
+/**
+ * Punto unico para cambiar el modo desde la UI (ThemeToggle, #980): persiste
+ * MODE_KEY, re-aplica clases + paleta inline (applyTheme) y notifica al resto
+ * de instancias para que sincronicen su icono.
+ */
+export function setMode(mode: ThemeMode) {
+  try {
+    localStorage.setItem(MODE_KEY, JSON.stringify(mode))
+  } catch {
+    /* noop */
+  }
+  applyTheme(mode)
+  window.dispatchEvent(new Event(THEME_CHANGE_EVENT))
+}
+
 function applyDensity() {
   const d = readJson<string>(DENSITY_KEY)
   document.documentElement.style.fontSize = d === 'compacta' ? '13.5px' : ''

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

@@ -11,7 +11,6 @@ import {
   CheckCircle2,
   ChevronRight,
   CircleArrowUp,
-  Eraser,
   Fingerprint,
   Globe,
   Info,
@@ -36,21 +35,14 @@ import { CountUp } from '@/components/CountUp'
 import { EmptyState } from '@/components/EmptyState'
 import { RowAction } from '@/components/RowAction'
 import { SegmentedControl } from '@/components/SegmentedControl'
-import {
-  Select,
-  SelectContent,
-  SelectItem,
-  SelectTrigger,
-  SelectValue,
-} from '@/components/ui/select'
 import {
   DropdownMenu,
   DropdownMenuContent,
   DropdownMenuItem,
   DropdownMenuTrigger,
 } from '@/components/ui/dropdown-menu'
-import { buildAlertFeed, buildLiveFeed, DAY_ORDER, ALERT_KINDS } from '@/data/alertFeed'
-import type { AlertKind, FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
+import { buildAlertFeed, buildLiveFeed, DAY_ORDER } from '@/data/alertFeed'
+import type { FeedDay, FeedEvent, FeedSpark } from '@/data/alertFeed'
 import { useNetPulse } from '@/data/DataProvider'
 import { RulesManager } from '@/components/RulesManager'
 import { cn } from '@/lib/utils'
@@ -93,7 +85,6 @@ const LEVEL_ORDER: readonly AlertConfigLevel[] = ['urgent', 'all', 'none']
 // ---------------------------------------------------------------------------
 
 type SevFilter = 'todas' | 'avisos' | 'info' | 'resueltas'
-type KindFilter = 'todos' | AlertKind
 
 const SEV_OPTIONS = [
   { value: 'todas', labelKey: 'alerts.sevAll' },
@@ -387,23 +378,26 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDis
                 </button>
               )}
               {/* #833: acción propia de la alerta (solo cuando aplica) y
-                  limpiar alerta, siempre; icono + etiqueta con tooltip. */}
+                  limpiar alerta, siempre. #965: SOLO icono (sin etiqueta);
+                  el dismiss es un Check con hover verde. */}
               {action && (
                 <RowAction
                   icon={action.icon}
                   label={action.title}
                   title={action.title}
+                  iconOnly
                   onClick={(e) => { e.stopPropagation(); action.onClick() }}
                   className="text-text-muted hover:text-accent"
                 />
               )}
               {onDismiss && (
                 <RowAction
-                  icon={Eraser}
+                  icon={Check}
                   label={t('alerts.actions.dismiss')}
                   title={t('alerts.actions.dismiss')}
+                  iconOnly
                   onClick={(e) => { e.stopPropagation(); onDismiss(ev.id) }}
-                  className="text-text-muted hover:text-text-primary"
+                  className="text-text-muted hover:text-ok"
                 />
               )}
               <span className="font-mono text-caption text-text-muted">{alertRelTime(ev)}</span>
@@ -485,7 +479,7 @@ export default function Alerts() {
     alertsConfig,
     setAlertConfig,
     markAlertsRead,
-    markAllAlertsRead,
+    clearAllAlerts,
     silenceAlert,
     dismissAlert,
   } = useNetPulse()
@@ -498,7 +492,6 @@ export default function Alerts() {
     [alerts, wireguard, routers, isDemo],
   )
   const [sev, setSev] = useState<SevFilter>('todas')
-  const [kind, setKind] = useState<KindFilter>('todos')
   const [cats, setCats] = useState<ReadonlySet<AlertCategory>>(new Set())
   const [searchParams] = useSearchParams()
   const navigate = useNavigate()
@@ -517,7 +510,9 @@ export default function Alerts() {
   const unread = unreadAlerts
 
   const markAllRead = () => {
-    markAllAlertsRead()
+    // #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.
+    clearAllAlerts()
     setBurst((b) => b + 1)
   }
 
@@ -575,12 +570,11 @@ export default function Alerts() {
     () =>
       alertFeed.filter((ev) => {
         if (sev !== 'todas' && ev.severity !== SEV_MATCH[sev]) return false
-        if (kind !== 'todos' && ev.kind !== kind) return false
         if (cats.size > 0 && !cats.has(ev.category)) return false
         if (onlyUnread && isRead(ev)) return false
         return true
       }),
-    [alertFeed, sev, kind, cats, onlyUnread],
+    [alertFeed, sev, cats, onlyUnread],
   )
 
   const groups = useMemo(
@@ -608,7 +602,7 @@ export default function Alerts() {
     return () => io.disconnect()
   }, [loadState, filtered.length])
 
-  const filterKey = `${sev}|${kind}|${[...cats].sort().join(',')}|${onlyUnread}`
+  const filterKey = `${sev}|${[...cats].sort().join(',')}|${onlyUnread}`
 
   return (
     <div className="mx-auto w-full max-w-[1100px]">
@@ -663,7 +657,7 @@ export default function Alerts() {
           <button
             type="button"
             onClick={markAllRead}
-            disabled={unread === 0}
+            disabled={alertFeed.length === 0}
             className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-3 text-xs font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:cursor-not-allowed disabled:opacity-40"
           >
             <motion.span key={burst} animate={reduce ? undefined : { scale: [1, 1.2, 1] }} transition={{ duration: 0.35 }}>
@@ -692,7 +686,7 @@ export default function Alerts() {
                 {t('alerts.configButton')}
               </DropdownMenuItem>
               <DropdownMenuItem
-                disabled={unread === 0}
+                disabled={alertFeed.length === 0}
                 onSelect={markAllRead}
                 className="gap-2 text-text-primary focus:bg-hover"
               >
@@ -848,23 +842,6 @@ export default function Alerts() {
       {/* ③ Filtros */}
       <div className="mt-5 flex flex-wrap items-center gap-2.5 md:gap-3">
         <SegmentedControl options={SEV_OPTIONS.map((o) => ({ value: o.value, label: t(o.labelKey) }))} value={sev} onChange={(v) => setSev(v)} ariaLabel={t('alerts.filterBySeverity')} />
-        <Select value={kind} onValueChange={(v) => setKind(v as KindFilter)}>
-          <SelectTrigger
-            size="sm"
-            aria-label={t('alerts.filterByKind')}
-            className="h-8 rounded-lg border-border bg-elevated text-xs font-medium text-text-secondary shadow-none"
-          >
-            <SelectValue />
-          </SelectTrigger>
-          <SelectContent className="border-border bg-elevated">
-            <SelectItem value="todos" className="text-text-primary focus:bg-hover">{t('alerts.allKinds')}</SelectItem>
-            {ALERT_KINDS.map((k) => (
-              <SelectItem key={k} value={k} className="text-text-primary focus:bg-hover">
-                {t(`alerts.kinds.${k}`)}
-              </SelectItem>
-            ))}
-          </SelectContent>
-        </Select>
         <div role="group" aria-label={t('alerts.filterByCategory')} className="flex flex-wrap items-center gap-1.5">
           {ALERT_CATEGORIES.map((cat) => {
             const Icon = CATEGORY_META[cat].icon

+ 373 - 238
app/src/pages/Devices.tsx

@@ -9,6 +9,7 @@ import {
   ArrowUpDown,
   Check,
   ChevronDown,
+  Columns3,
   Filter,
   LayoutGrid,
   List,
@@ -25,8 +26,6 @@ import { DeviceRow, deviceIcon, SignalIcon } from '@/components/DeviceRow'
 import { CountUp } from '@/components/CountUp'
 import { EmptyState } from '@/components/EmptyState'
 import { SegmentedControl } from '@/components/SegmentedControl'
-import { Sparkline } from '@/components/Sparkline'
-import { DeviceTrafficDetail } from '@/components/DeviceTraffic'
 import { StatusPill } from '@/components/StatusPill'
 import {
   DropdownMenu,
@@ -48,11 +47,12 @@ import { dhcpLease, fmtSeenAgo, manufacturerLabel, numLocale } from '@/i18n'
 import { fmtEs, signalLevel } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
 import { useDashboard } from '@/hooks/useDashboard'
+import { useWeakSignalDbm } from '@/hooks/useWeakSignalDbm'
 import { DeviceEditSheet } from '@/components/DeviceEditSheet'
 import { OnboardingIntake } from '@/components/OnboardingIntake'
-import { PresenceSection } from '@/components/PresenceTimeline'
 import { cn, copyToClipboard, fetchJson } from '@/lib/utils'
 import { useParentName } from '@/lib/parent'
+import { networkHasBand6 } from '@/components/topology/model'
 import type { ClientDevice, FilterGroup } from '@/pages/devices-data'
 import { buildClientDevices, GROUP_ORDER } from '@/pages/devices-data'
 import type { DeviceType } from '@/data/mock'
@@ -62,7 +62,10 @@ import type { DeviceType } from '@/data/mock'
 // Constantes de la página
 // ---------------------------------------------------------------------------
 
-type BandFilter = 'all' | '5 GHz' | '2.4 GHz' | 'cable'
+type BandFilter = 'all' | '6 GHz' | '5 GHz' | '2.4 GHz' | 'cable'
+// #989: valor de banda seleccionable en el filtro multi (sin 'all': la
+// selección vacía ya equivale a "todas").
+type BandValue = Exclude<BandFilter, 'all'>
 type SortKey = 'name' | 'ip' | 'router' | 'band' | 'lease' | 'signal' | 'type' | 'traffic' | 'firstSeen' | 'lastSeen'
 
 // Persistencia de preferencias de visualización (issue #778): el modo
@@ -73,12 +76,16 @@ type SortState = { key: SortKey; dir: 1 | -1 } | null
 // #923: filtro de estado online triestado, persistente junto al resto de
 // preferencias de la página.
 type OnlineFilter = 'all' | 'online' | 'offline'
-type DevicesPrefs = { view: 'list' | 'grid'; sort: SortState; online: OnlineFilter }
+// #958: columnas ocultables de la tabla (todas menos el nombre). Se guardan
+// las OCULTAS; por defecto ninguna (tabla completa, como siempre).
+type DeviceColumn = 'type' | 'ip' | 'lease' | 'router' | 'band' | 'signal' | 'traffic' | 'firstSeen' | 'lastSeen'
+const DEVICE_COLUMNS: DeviceColumn[] = ['type', 'ip', 'lease', 'router', 'band', 'signal', 'traffic', 'firstSeen', 'lastSeen']
+type DevicesPrefs = { view: 'list' | 'grid'; sort: SortState; online: OnlineFilter; columns: DeviceColumn[] }
 
 const SORT_KEYS: SortKey[] = ['name', 'ip', 'router', 'band', 'lease', 'signal', 'type', 'traffic', 'firstSeen', 'lastSeen']
 
 function loadDevicesPrefs(): DevicesPrefs {
-  const fallback: DevicesPrefs = { view: 'list', sort: null, online: 'online' }
+  const fallback: DevicesPrefs = { view: 'list', sort: null, online: 'online', columns: [] }
   try {
     const raw = localStorage.getItem(DEVICES_PREFS_KEY)
     if (!raw) return fallback
@@ -89,7 +96,10 @@ function loadDevicesPrefs(): DevicesPrefs {
       sort = { key: v.sort.key, dir: v.sort.dir }
     }
     const online: OnlineFilter = v.online === 'all' || v.online === 'offline' ? v.online : 'online'
-    return { view, sort, online }
+    const columns = Array.isArray(v.columns)
+      ? v.columns.filter((c): c is DeviceColumn => DEVICE_COLUMNS.includes(c as DeviceColumn))
+      : []
+    return { view, sort, online, columns }
   } catch {
     return fallback
   }
@@ -103,22 +113,6 @@ function saveDevicesPrefs(p: DevicesPrefs) {
   }
 }
 
-/** Orden canónico de los tipos de dispositivo para los chips de filtro. */
-const TYPE_ORDER = [
-  'ordenador',
-  'portatil',
-  'movil',
-  'tablet',
-  'tv',
-  'consola',
-  'camara',
-  'altavoz',
-  'iot',
-  'servidor',
-  'switch',
-  'desconocido',
-] as const
-
 /** IP a número para ordenar (ipv4 "a.b.c.d" → entero). */
 function ipNum(ip: string): number {
   return ip.split('.').reduce((acc, o) => acc * 256 + (parseInt(o, 10) || 0), 0)
@@ -154,12 +148,67 @@ function SortHeader({
   )
 }
 
-const BAND_OPTIONS = [
-  { value: 'all', labelKey: 'devices.bandAll' },
+/** Selector de columnas visibles (#958): checkbox por columna en la cabecera
+ * de la tabla. El nombre (Dispositivo) es fijo y no se puede ocultar. */
+function ColumnPicker({ hidden, onToggle }: { hidden: DeviceColumn[]; onToggle: (c: DeviceColumn) => void }) {
+  const { t } = useTranslation()
+  const labels: Record<DeviceColumn, string> = {
+    type: t('devices.colType'),
+    ip: 'IP / MAC',
+    lease: t('devices.colLease'),
+    router: 'Router',
+    band: t('devices.colBand'),
+    signal: t('devices.colSignal'),
+    traffic: t('devices.colTraffic'),
+    firstSeen: t('devices.colFirstSeen'),
+    lastSeen: t('devices.colLastSeen'),
+  }
+  return (
+    <DropdownMenu>
+      <DropdownMenuTrigger asChild>
+        <button
+          type="button"
+          aria-label={t('devices.columns.action')}
+          title={t('devices.columns.action')}
+          onClick={(e) => e.stopPropagation()}
+          className="flex h-5 w-5 items-center justify-center justify-self-end rounded-md text-text-muted transition-colors hover:text-accent"
+        >
+          <Columns3 className="h-3.5 w-3.5" strokeWidth={1.75} />
+        </button>
+      </DropdownMenuTrigger>
+      <DropdownMenuContent align="end" className="w-52">
+        <DropdownMenuLabel>{t('devices.columns.title')}</DropdownMenuLabel>
+        <DropdownMenuSeparator />
+        <DropdownMenuCheckboxItem checked disabled onSelect={(e) => e.preventDefault()}>
+          {t('devices.colDevice')}
+        </DropdownMenuCheckboxItem>
+        {DEVICE_COLUMNS.map((c) => (
+          <DropdownMenuCheckboxItem
+            key={c}
+            checked={!hidden.includes(c)}
+            onCheckedChange={() => onToggle(c)}
+            onSelect={(e) => e.preventDefault()}
+          >
+            {labels[c]}
+          </DropdownMenuCheckboxItem>
+        ))}
+      </DropdownMenuContent>
+    </DropdownMenu>
+  )
+}
+
+// #970: la banda se filtra con un desplegable (era un SegmentedControl); #989
+// lo convierte en multi-selección acumulativa con el patrón del filtro "Tipo".
+// #991: la opción 6 GHz solo se ofrece si la red TIENE 6 GHz
+// (networkHasBand6: algún router con bandSplit.band6 > 0 o algún cliente con
+// banda '6 GHz'; no hay flag de capacidad hardware en los tipos). Sin 6G la
+// opción desaparece del menú y cualquier selección residual se ignora.
+const BAND_FILTERS: ReadonlyArray<{ value: BandValue; label?: string; labelKey?: string; band6?: boolean }> = [
   { value: '2.4 GHz', label: '2.4 GHz' },
   { value: '5 GHz', label: '5 GHz' },
+  { value: '6 GHz', label: '6 GHz', band6: true },
   { value: 'cable', labelKey: 'common.cable' },
-] as const
+]
 
 /** Color de identidad por router (devices.md §④) */
 const ROUTER_DOT: Record<string, string> = {
@@ -295,7 +344,10 @@ function StatsStrip({
   const { deviceTotals } = useNetPulse()
   const reduce = useReducedMotion()
   const newThisWeekDevices = allDevices.filter((d) => d.isNew)
-  const weakSignalCount = allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < -70).length
+  // #1003: el umbral de señal débil es el ajuste global (/api/settings/thresholds),
+  // no un -70 hardcodeado; mismo criterio que la matriz de roaming (#906).
+  const weakDbm = useWeakSignalDbm()
+  const weakSignalCount = allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < weakDbm).length
   const adguardProtected = allDevices.filter((d) => d.adguard).length
   // Salud de roaming (#771): MACs con más conexiones AP-STA en 24 h (los
   // primeros puestos son los que más rebotan). En demo, muestra local (el
@@ -376,7 +428,7 @@ function StatsStrip({
           <div className="font-mono text-stat text-text-primary">
             <CountUp value={weakSignalCount} nonce={refreshKey} />
           </div>
-          <div className="mt-1 text-caption text-text-muted">&lt; −70 dBm</div>
+          <div className="mt-1 text-caption text-text-muted">&lt; {weakDbm} dBm</div>
         </>
       ),
     },
@@ -476,14 +528,31 @@ function StatsStrip({
 // Barra de filtros (devices.md §③)
 // ---------------------------------------------------------------------------
 
+// #989: trigger homogéneo de los filtros desplegables (Flota, Conexión y
+// Tipo): icono Filter + etiqueta + badge con el nº de valores activos.
+function FilterMenuTrigger({ label, active }: { label: string; active: number }) {
+  return (
+    <button className="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">
+      <Filter className="h-3.5 w-3.5" strokeWidth={1.75} />
+      {label}
+      {active > 0 && (
+        <span className="rounded-full bg-accent-soft px-1.5 py-0.5 text-[10px] font-semibold text-accent">
+          {active}
+        </span>
+      )}
+    </button>
+  )
+}
+
 interface FilterBarProps {
-  router: string
-  setRouter: (v: string) => void
-  band: BandFilter
-  setBand: (v: BandFilter) => void
-  typeFilter: DeviceType | 'all'
-  setTypeFilter: (v: DeviceType | 'all') => void
-  typeCounts: Record<string, number>
+  routerIds: string[]
+  toggleRouterId: (id: string) => void
+  routerCounts: Record<string, number>
+  bands: BandValue[]
+  toggleBand: (b: BandValue) => void
+  bandCounts: Partial<Record<BandValue, number>>
+  /** #991: la red tiene banda 6 GHz (si no, la opción no se ofrece) */
+  hasBand6: boolean
   groups: FilterGroup[]
   toggleGroup: (g: FilterGroup) => void
   online: OnlineFilter
@@ -491,6 +560,8 @@ interface FilterBarProps {
   onlyWeak: boolean
   setOnlyWeak: (v: boolean) => void
   weakCount: number
+  /** #1003: umbral configurado, se muestra en la etiqueta del chip */
+  weakDbm: number
   view: 'list' | 'grid'
   setView: (v: 'list' | 'grid') => void
   shown: number
@@ -505,43 +576,55 @@ function FilterBar(p: FilterBarProps) {
   return (
     <div className="rounded-2xl border border-border bg-surface p-3 md:p-4">
       <div className="flex flex-wrap items-center gap-x-3 gap-y-3">
-        {/* Router: chips con dot de estado */}
-        <div
-          role="tablist"
-          aria-label={t('devices.filterByRouter')}
-          className="-mx-1 flex max-w-full items-center gap-1 overflow-x-auto px-1 py-0.5"
-        >
-          <RouterChip active={p.router === 'all'} label={t('devices.routerAll')} onClick={() => p.setRouter('all')} />
-          {routers.map((r) => (
-            <RouterChip
-              key={r.id}
-              active={p.router === r.id}
-              label={r.name}
-              dotClass={ROUTER_DOT[r.id] ?? 'bg-text-muted'}
-              onClick={() => p.setRouter(r.id)}
-            />
-          ))}
-        </div>
-        {/* Banda */}
-        <SegmentedControl<BandFilter>
-          options={BAND_OPTIONS.map((o) => ({ value: o.value, label: 'label' in o ? o.label : t(o.labelKey!) }))}
-          value={p.band}
-          onChange={p.setBand}
-          size="sm"
-          ariaLabel={t('devices.filterByBand')}
-        />
+        {/* Flota (#989): multi-selección acumulativa de routers; una píldora
+            por router no escala cuando la flota crece (6 -> ~15 routers). */}
+        <DropdownMenu>
+          <DropdownMenuTrigger asChild>
+            <FilterMenuTrigger label={t('devices.fleet')} active={p.routerIds.length} />
+          </DropdownMenuTrigger>
+          <DropdownMenuContent align="start" className="w-56">
+            <DropdownMenuLabel>{t('devices.filterByRouter')}</DropdownMenuLabel>
+            <DropdownMenuSeparator />
+            {routers.map((r) => (
+              <DropdownMenuCheckboxItem
+                key={r.id}
+                checked={p.routerIds.includes(r.id)}
+                onCheckedChange={() => p.toggleRouterId(r.id)}
+                onSelect={(e) => e.preventDefault()}
+              >
+                <span className={cn('mr-1.5 h-1.5 w-1.5 shrink-0 rounded-full', ROUTER_DOT[r.id] ?? 'bg-text-muted')} />
+                <span className="flex-1">{r.name}</span>
+                <span className="ml-2 font-mono text-caption text-text-muted">{p.routerCounts[r.id] ?? 0}</span>
+              </DropdownMenuCheckboxItem>
+            ))}
+          </DropdownMenuContent>
+        </DropdownMenu>
+        {/* Conexión (#989): multi-selección de banda/cable; 6 GHz solo si la
+            red la tiene (#991) */}
+        <DropdownMenu>
+          <DropdownMenuTrigger asChild>
+            <FilterMenuTrigger label={t('devices.connection')} active={p.bands.length} />
+          </DropdownMenuTrigger>
+          <DropdownMenuContent align="start" className="w-56">
+            <DropdownMenuLabel>{t('devices.filterByBand')}</DropdownMenuLabel>
+            <DropdownMenuSeparator />
+            {BAND_FILTERS.filter((o) => !o.band6 || p.hasBand6).map((o) => (
+              <DropdownMenuCheckboxItem
+                key={o.value}
+                checked={p.bands.includes(o.value)}
+                onCheckedChange={() => p.toggleBand(o.value)}
+                onSelect={(e) => e.preventDefault()}
+              >
+                <span className="flex-1">{o.label ?? t(o.labelKey!)}</span>
+                <span className="ml-2 font-mono text-caption text-text-muted">{p.bandCounts[o.value] ?? 0}</span>
+              </DropdownMenuCheckboxItem>
+            ))}
+          </DropdownMenuContent>
+        </DropdownMenu>
         {/* Tipo (multi) */}
         <DropdownMenu>
           <DropdownMenuTrigger asChild>
-            <button className="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">
-              <Filter className="h-3.5 w-3.5" strokeWidth={1.75} />
-              {t('devices.colType')}
-              {p.groups.length > 0 && (
-                <span className="rounded-full bg-accent-soft px-1.5 py-0.5 text-[10px] font-semibold text-accent">
-                  {p.groups.length}
-                </span>
-              )}
-            </button>
+            <FilterMenuTrigger label={t('devices.colType')} active={p.groups.length} />
           </DropdownMenuTrigger>
           <DropdownMenuContent align="start" className="w-56">
             <DropdownMenuLabel>{t('devices.deviceType')}</DropdownMenuLabel>
@@ -583,7 +666,7 @@ function FilterBar(p: FilterBarProps) {
             )}
           >
             <SignalLow className="h-3.5 w-3.5" strokeWidth={1.75} />
-            {t('devices.weakChip', { count: p.weakCount })}
+            {t('devices.weakChip', { count: p.weakCount, dbm: p.weakDbm })}
           </button>
         )}
         {/* Orden (#799): visible solo en móvil; en desktop la cabecera sticky
@@ -630,45 +713,10 @@ function FilterBar(p: FilterBarProps) {
           </div>
         </div>
       </div>
-      {/* Tipo de dispositivo: chips de filtro */}
-      <div
-        role="tablist"
-        aria-label={t('devices.deviceType')}
-        className="-mx-1 mt-3 flex max-w-full items-center gap-1 overflow-x-auto border-t border-border px-1 pt-3"
-      >
-        <RouterChip active={p.typeFilter === 'all'} label={t('devices.routerAll')} onClick={() => p.setTypeFilter('all')} />
-        {TYPE_ORDER.filter((ty) => (p.typeCounts[ty] ?? 0) > 0).map((ty) => (
-          <RouterChip
-            key={ty}
-            active={p.typeFilter === ty}
-            label={`${t(`devices.types.${ty}`)} · ${p.typeCounts[ty]}`}
-            onClick={() => p.setTypeFilter(ty)}
-          />
-        ))}
-      </div>
     </div>
   )
 }
 
-function RouterChip({ active, label, dotClass, onClick }: { active: boolean; label: string; dotClass?: string; onClick: () => void }) {
-  return (
-    <button
-      role="tab"
-      aria-selected={active}
-      onClick={onClick}
-      className={cn(
-        'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-lg border px-3 text-xs font-medium transition-colors duration-150',
-        active
-          ? 'border-accent/40 bg-accent-soft text-accent'
-          : 'border-border bg-elevated text-text-secondary hover:bg-hover hover:text-text-primary',
-      )}
-    >
-      {dotClass && <span className={cn('h-1.5 w-1.5 rounded-full', dotClass)} />}
-      {label}
-    </button>
-  )
-}
-
 function ViewButton({ active, onClick, label, children }: { active: boolean; onClick: () => void; label: string; children: React.ReactNode }) {
   return (
     <button
@@ -756,7 +804,6 @@ function DeviceDetail({
   onEdit: () => void
 }) {
   const { t } = useTranslation()
-  const { isDemo } = useNetPulse()
   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>
@@ -769,28 +816,6 @@ function DeviceDetail({
       <DetailItem label="Hostname" mono>
         {device.hostname}
       </DetailItem>
-      {/* #551: en demo el tráfico viene en el canon; en live se pide al
-          endpoint /api/devices/{mac}/traffic bajo demanda (patrón portseries). */}
-      {isDemo ? (
-        <>
-          <DetailItem label={t('devices.detail.traffic24h')} mono>
-            ↓ {device.traffic24hRx} · ↑ {device.traffic24hTx}
-          </DetailItem>
-          <div className="min-w-0">
-            <div className="text-label uppercase text-text-muted">{t('devices.detail.trafficCurrent')}</div>
-            <div className="mt-1 inline-flex items-center gap-2">
-              <span className="font-mono text-mono-sm text-accent">
-                {device.trafficMbps >= 1 ? fmtEs(device.trafficMbps, 1) : fmtEs(device.trafficMbps, 2)} Mbps
-              </span>
-              <Sparkline data={device.sparkline} width={60} height={20} className="text-accent" />
-            </div>
-          </div>
-        </>
-      ) : (
-        <div className="col-span-2 md:col-span-1">
-          <DeviceTrafficDetail mac={device.mac} online={device.online} />
-        </div>
-      )}
       <div className="min-w-0">
         <div className="text-label uppercase text-text-muted">AdGuard</div>
         <div className="mt-1.5">
@@ -812,13 +837,8 @@ function DeviceDetail({
           )}
         </DetailItem>
       )}
-      {/* Timeline de presencia (#771): tramos de los últimos 7 días por AP. */}
-      <PresenceSection mac={device.mac} />
-      <div className="col-span-2 flex items-center justify-between rounded-xl border border-border bg-elevated/40 px-4 py-3">
-        <div>
-          <div className="text-label uppercase text-text-muted">{t('devices.detail.rename')}</div>
-          <p className="mt-0.5 text-caption text-text-muted">{t('devices.edit.description')}</p>
-        </div>
+      {/* Editar a la derecha, sin texto auxiliar (#985). */}
+      <div className="col-span-2 flex justify-end md:col-span-3">
         <button
           type="button"
           onClick={onEdit}
@@ -974,8 +994,52 @@ function LeaseCell({ device }: { device: ClientDevice }) {
   return <span className="font-mono text-mono-sm text-warn">{t('devices.leaseMinutes', { minutes })}</span>
 }
 
-const ROW_GRID =
-  'md:grid-cols-[minmax(0,3fr)_minmax(0,1.1fr)_minmax(0,0.85fr)_minmax(0,0.95fr)_minmax(0,0.75fr)_1.5rem] lg:grid-cols-[minmax(0,3.4fr)_minmax(0,0.55fr)_minmax(0,0.95fr)_minmax(0,0.7fr)_minmax(0,0.85fr)_minmax(0,0.6fr)_minmax(0,0.75fr)_minmax(0,0.75fr)_1.5rem] xl:grid-cols-[minmax(0,3.4fr)_minmax(0,0.55fr)_minmax(0,0.95fr)_minmax(0,0.7fr)_minmax(0,0.85fr)_minmax(0,0.6fr)_minmax(0,0.75fr)_minmax(0,0.75fr)_minmax(0,0.7fr)_minmax(0,0.7fr)_1.5rem]'
+// #958: la tabla es un grid CSS cuyas columnas dependen de las columnas
+// visibles elegidas por el usuario. Las plantillas se generan aquí y se
+// inyectan como custom properties (--devices-cols-*) que la clase
+// `devices-cols` (index.css) aplica en cada breakpoint; Tailwind no puede
+// generar clases dinámicas para todas las combinaciones posibles.
+// Pesos fr NATURALES de cada columna (con todo visible, la plantilla es
+// idéntica al ROW_GRID original).
+const COLUMN_SPECS: Record<DeviceColumn, { md?: number; lg: number; xl?: number; xlOnly?: boolean }> = {
+  type: { lg: 0.55 },
+  ip: { lg: 0.95 },
+  lease: { lg: 0.7 },
+  router: { md: 1.1, lg: 0.85 },
+  band: { md: 0.85, lg: 0.6 },
+  signal: { md: 0.95, lg: 0.75 },
+  traffic: { md: 0.75, lg: 0.75, xl: 0.7 },
+  firstSeen: { lg: 0.7, xlOnly: true },
+  lastSeen: { lg: 0.7, xlOnly: true },
+}
+
+const DEVICE_COL_FR = { md: 3, lg: 3.4, xl: 3.4 } as const
+
+/** Reparto al ocultar columnas: el fr liberado se distribuye A PARTES IGUALES
+ *  entre las columnas visibles (dispositivo incluida). El reparto nativo de
+ *  CSS es proporcional al peso, así que la columna de dispositivo (3.4fr
+ *  frente a 0.55-1.1fr del resto) absorbía casi todo el hueco liberado. */
+function distributeColumns(all: { key: string; fr: number }[], vis: Set<DeviceColumn>): string {
+  const visibleCols = all.filter((c) => vis.has(c.key as DeviceColumn) || c.key === 'device')
+  const hiddenFr = all.filter((c) => !vis.has(c.key as DeviceColumn) && c.key !== 'device').reduce((a, c) => a + c.fr, 0)
+  const bonus = hiddenFr / visibleCols.length
+  return visibleCols.map((c) => `minmax(0,${(c.fr + bonus).toFixed(2)}fr)`).join(' ')
+}
+
+function columnTemplates(vis: Set<DeviceColumn>) {
+  const frOf = (c: DeviceColumn, bp: 'md' | 'lg' | 'xl'): number =>
+    bp === 'md' ? COLUMN_SPECS[c].md! : bp === 'lg' ? COLUMN_SPECS[c].lg : (COLUMN_SPECS[c].xl ?? COLUMN_SPECS[c].lg)
+  const colsFor = (bp: 'md' | 'lg' | 'xl'): { key: string; fr: number }[] => [
+    { key: 'device', fr: DEVICE_COL_FR[bp] },
+    ...DEVICE_COLUMNS.filter((c) =>
+      bp === 'md' ? !!COLUMN_SPECS[c].md : bp === 'lg' ? !COLUMN_SPECS[c].xlOnly : true,
+    ).map((c) => ({ key: c as string, fr: frOf(c, bp) })),
+  ]
+  const md = [distributeColumns(colsFor('md'), vis), '1.5rem'].join(' ')
+  const lg = [distributeColumns(colsFor('lg'), vis), '1.5rem'].join(' ')
+  const xl = [distributeColumns(colsFor('xl'), vis), '1.5rem'].join(' ')
+  return { '--devices-cols-md': md, '--devices-cols-lg': lg, '--devices-cols-xl': xl } as React.CSSProperties
+}
 
 /** Fila de tabla desktop (md+) */
 function ListRow({
@@ -983,6 +1047,8 @@ function ListRow({
   infra,
   expanded,
   index,
+  vis,
+  colsStyle,
   onToggle,
   onCopyIp,
   onNavigateRouter,
@@ -992,6 +1058,8 @@ function ListRow({
   infra?: InfraInfo
   expanded: boolean
   index: number
+  vis: Set<DeviceColumn>
+  colsStyle: React.CSSProperties
   onToggle: () => void
   onCopyIp: (ip: string) => void
   onNavigateRouter: (id: string) => void
@@ -1018,9 +1086,9 @@ function ListRow({
             onToggle()
           }
         }}
+        style={colsStyle}
         className={cn(
-          'hidden cursor-pointer items-center gap-4 pr-6 pl-3 py-2 transition-colors duration-150 hover:bg-hover md:grid',
-          ROW_GRID,
+          'devices-cols hidden cursor-pointer items-center gap-4 pr-6 pl-3 py-2 transition-colors duration-150 hover:bg-hover md:grid',
           !device.online && 'opacity-55',
           expanded && 'bg-hover/60',
         )}
@@ -1051,53 +1119,71 @@ function ListRow({
           </div>
         </div>
         {/* Tipo */}
-        <div className="hidden lg:block">
-          <TypeBadge type={device.type} />
-        </div>
+        {vis.has('type') && (
+          <div className="hidden lg:block">
+            <TypeBadge type={device.type} />
+          </div>
+        )}
         {/* IP / MAC */}
-        <button
-          onClick={(e) => {
-            e.stopPropagation()
-            onCopyIp(device.ip)
-          }}
-          title={t('devices.copyIp')}
-          className="hidden w-fit min-w-0 flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-elevated lg:flex"
-        >
-          <span className="font-mono text-mono-sm text-text-primary">{device.ip}</span>
-          <span className="font-mono text-caption text-text-muted">{device.mac}</span>
-        </button>
+        {vis.has('ip') && (
+          <button
+            onClick={(e) => {
+              e.stopPropagation()
+              onCopyIp(device.ip)
+            }}
+            title={t('devices.copyIp')}
+            className="hidden w-fit min-w-0 flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-elevated lg:flex"
+          >
+            <span className="font-mono text-mono-sm text-text-primary">{device.ip}</span>
+            <span className="font-mono text-caption text-text-muted">{device.mac}</span>
+          </button>
+        )}
         {/* Tiempo restante del lease */}
-        <div className="hidden lg:block">
-          <LeaseCell device={device} />
-        </div>
+        {vis.has('lease') && (
+          <div className="hidden lg:block">
+            <LeaseCell device={device} />
+          </div>
+        )}
         {/* Router, and the box the client actually hangs off */}
-        <div className="min-w-0">
-          <RouterChipLink routerId={device.routerId} onNavigate={onNavigateRouter} />
-          <ParentLine device={device} className="mt-0.5 pl-1" />
-        </div>
+        {vis.has('router') && (
+          <div className="min-w-0">
+            <RouterChipLink routerId={device.routerId} onNavigate={onNavigateRouter} />
+            <ParentLine device={device} className="mt-0.5 pl-1" />
+          </div>
+        )}
         {/* Banda */}
-        <div>
-          <BandChip band={device.band} />
-        </div>
+        {vis.has('band') && (
+          <div>
+            <BandChip band={device.band} />
+          </div>
+        )}
         {/* Señal */}
-        <div>
-          <SignalCell device={device} />
-        </div>
+        {vis.has('signal') && (
+          <div>
+            <SignalCell device={device} />
+          </div>
+        )}
         {/* Tráfico en vivo (#799): la columna que ordena el default */}
-        <div>
-          <span className="font-mono text-mono-sm text-accent">
-            {device.online
-              ? `${device.trafficMbps >= 1 ? fmtEs(device.trafficMbps, 1) : fmtEs(device.trafficMbps, 2)} Mbps`
-              : '—'}
-          </span>
-        </div>
+        {vis.has('traffic') && (
+          <div>
+            <span className="font-mono text-mono-sm text-accent">
+              {device.online
+                ? `${device.trafficMbps >= 1 ? fmtEs(device.trafficMbps, 1) : fmtEs(device.trafficMbps, 2)} Mbps`
+                : '—'}
+            </span>
+          </div>
+        )}
         {/* First/Last seen (#954): solo en xl para no engordar la tabla */}
-        <div className="hidden xl:block">
-          <span className="text-caption text-text-secondary">{fmtSeenAgo(device.firstSeenMs)}</span>
-        </div>
-        <div className="hidden xl:block">
-          <span className="text-caption text-text-secondary">{fmtSeenAgo(device.lastSeenMs)}</span>
-        </div>
+        {vis.has('firstSeen') && (
+          <div className="hidden xl:block">
+            <span className="text-caption text-text-secondary">{fmtSeenAgo(device.firstSeenMs)}</span>
+          </div>
+        )}
+        {vis.has('lastSeen') && (
+          <div className="hidden xl:block">
+            <span className="text-caption text-text-secondary">{fmtSeenAgo(device.lastSeenMs)}</span>
+          </div>
+        )}
         <ChevronDown
           className={cn('h-4 w-4 justify-self-end text-text-muted transition-transform duration-200', expanded && 'rotate-180')}
           strokeWidth={1.75}
@@ -1305,15 +1391,19 @@ export default function Devices() {
     const hit = allDevices.find((d) => d.mac.toUpperCase() === mac.toUpperCase())
     if (hit) setIntakeId(hit.id)
   }, [searchParams, allDevices])
-  const [router, setRouter] = useState('all')
-  const [band, setBand] = useState<BandFilter>('all')
-  const [typeFilter, setTypeFilter] = useState<DeviceType | 'all'>('all')
+  // #989: flota y conexión son multi-selección acumulativa (varios routers o
+  // bandas a la vez, OR dentro del filtro y AND entre filtros), con el mismo
+  // patrón de desplegable con checkboxes que el filtro "Tipo".
+  const [routerIds, setRouterIds] = useState<string[]>([])
+  const [bands, setBands] = useState<BandValue[]>([])
   const [groups, setGroups] = useState<FilterGroup[]>([])
   const [online, setOnlineState] = useState<OnlineFilter>(() => loadDevicesPrefs().online)
   const setOnline = useCallback((v: OnlineFilter) => {
     setOnlineState(v)
   }, [])
   const [onlyWeak, setOnlyWeak] = useState(false)
+  // #1003: umbral de señal débil desde el ajuste global (como Roaming #906).
+  const weakDbm = useWeakSignalDbm()
   // Filtro "sin proteger por AdGuard" (#959): se activa/desactiva desde la
   // stat card de AdGuard; se muestra como pill de filtro activo.
   const [onlyUnprotected, setOnlyUnprotected] = useState(false)
@@ -1333,8 +1423,8 @@ export default function Devices() {
   }, [searchParams, setOnline])
 
   const weakCount = useMemo(
-    () => allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < -70).length,
-    [allDevices],
+    () => allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < weakDbm).length,
+    [allDevices, weakDbm],
   )
   // #772: conectados ahora sin identificar (sin nombre ni hostname DHCP):
   // candidatos a la tarjeta de alta. Un dispositivo conocido que reconecta
@@ -1344,6 +1434,13 @@ export default function Devices() {
     [allDevices],
   )
   const [view, setView] = useState<'list' | 'grid'>(() => loadDevicesPrefs().view)
+  // #958: columnas ocultas de la tabla (persistidas en DevicesPrefs).
+  const [hiddenColumns, setHiddenColumns] = useState<DeviceColumn[]>(() => loadDevicesPrefs().columns)
+  const toggleColumn = useCallback((c: DeviceColumn) => {
+    setHiddenColumns((prev) => (prev.includes(c) ? prev.filter((x) => x !== c) : [...prev, c]))
+  }, [setHiddenColumns])
+  const visibleColumns = useMemo(() => new Set(DEVICE_COLUMNS.filter((c) => !hiddenColumns.includes(c))), [hiddenColumns])
+  const colsStyle = useMemo(() => columnTemplates(visibleColumns), [visibleColumns])
   const [expandedId, setExpandedId] = useState<string | null>(null)
   // Alta guiada de desconocidos (#772): se abre con ?intake=<mac> (deep-link
   // desde la alerta "dispositivo desconocido") o desde el banner de sin
@@ -1371,12 +1468,30 @@ export default function Devices() {
     return counts
   }, [allDevices])
 
-  const typeCounts = useMemo(() => {
+  // #989: contadores por router y por banda para los menús multi-selección.
+  const routerCounts = useMemo(() => {
     const counts: Record<string, number> = {}
-    for (const d of allDevices) counts[d.type] = (counts[d.type] ?? 0) + 1
+    for (const d of allDevices) counts[d.routerId] = (counts[d.routerId] ?? 0) + 1
     return counts
   }, [allDevices])
 
+  const bandCounts = useMemo(() => {
+    const counts: Partial<Record<BandValue, number>> = {}
+    for (const d of allDevices) {
+      const b = d.band as BandValue
+      counts[b] = (counts[b] ?? 0) + 1
+    }
+    return counts
+  }, [allDevices])
+
+  // #991: 6 GHz solo existe en la UI si la red la tiene. bandsEffective
+  // descarta una selección 6 GHz residual si la banda desaparece del bundle.
+  const hasBand6 = useMemo(() => networkHasBand6(routers, devices), [routers, devices])
+  const bandsEffective = useMemo(
+    () => (hasBand6 ? bands : bands.filter((b) => b !== '6 GHz')),
+    [bands, hasBand6],
+  )
+
   const [sort, setSort] = useState<SortState>(() => loadDevicesPrefs().sort)
   const toggleSort = useCallback((key: SortKey) => {
     setSort((prev) => (prev?.key === key ? { key, dir: prev.dir === 1 ? -1 : 1 } : { key, dir: 1 }))
@@ -1388,21 +1503,20 @@ export default function Devices() {
     setSort(key === null ? null : { key, dir: 1 })
   }, [setSort])
 
-  // Persiste vista + orden en cada cambio (issue #778). El write inicial
-  // reescribe el mismo valor cargado; es inofensivo.
+  // Persiste vista + orden + columnas en cada cambio (issues #778, #958).
+  // El write inicial reescribe el mismo valor cargado; es inofensivo.
   useEffect(() => {
-    saveDevicesPrefs({ view, sort, online })
-  }, [view, sort, online])
+    saveDevicesPrefs({ view, sort, online, columns: hiddenColumns })
+  }, [view, sort, online, hiddenColumns])
 
   const filtered = useMemo(() => {
     const out = allDevices.filter((d) => {
       if (online === 'online' && !d.online) return false
       if (online === 'offline' && d.online) return false
-      if (onlyWeak && !(d.online && d.signalDbm !== null && d.signalDbm < -70)) return false
+      if (onlyWeak && !(d.online && d.signalDbm !== null && d.signalDbm < weakDbm)) return false
       if (onlyUnprotected && d.adguard) return false
-      if (router !== 'all' && d.routerId !== router) return false
-      if (band !== 'all' && d.band !== band) return false
-      if (typeFilter !== 'all' && d.type !== typeFilter) return false
+      if (routerIds.length > 0 && !routerIds.includes(d.routerId)) return false
+      if (bandsEffective.length > 0 && !bandsEffective.includes(d.band as BandValue)) return false
       if (groups.length > 0 && !groups.includes(d.group)) return false
       if (q) {
         const hay = `${d.name} ${d.ip} ${d.mac} ${d.manufacturer} ${d.hostname}`.toLowerCase()
@@ -1466,21 +1580,30 @@ export default function Devices() {
       }
       return a.name.localeCompare(b.name, numLocale())
     })
-  }, [allDevices, online, onlyWeak, onlyUnprotected, router, band, typeFilter, groups, q, sort, routers])
+  }, [allDevices, online, onlyWeak, weakDbm, onlyUnprotected, routerIds, bandsEffective, groups, q, sort, routers])
+
+  const toggleRouterId = useCallback(
+    (id: string) => setRouterIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])),
+    [setRouterIds],
+  )
+
+  const toggleBand = useCallback(
+    (b: BandValue) => setBands((prev) => (prev.includes(b) ? prev.filter((x) => x !== b) : [...prev, b])),
+    [setBands],
+  )
 
   const toggleGroup = useCallback(
     (g: FilterGroup) => setGroups((prev) => (prev.includes(g) ? prev.filter((x) => x !== g) : [...prev, g])),
-    [],
+    [setGroups],
   )
 
   const clearFilters = useCallback(() => {
-    setRouter('all')
-    setBand('all')
-    setTypeFilter('all')
+    setRouterIds([])
+    setBands([])
     setGroups([])
     setOnline('online')
     setOnlyUnprotected(false)
-  }, [setOnline])
+  }, [setRouterIds, setBands, setGroups, setOnline, setOnlyUnprotected])
 
   const clearAll = useCallback(() => {
     clearFilters()
@@ -1559,15 +1682,12 @@ export default function Devices() {
 
   const pills = useMemo<Pill[]>(() => {
     const list: Pill[] = []
-    if (router !== 'all') {
-      const routerName = routers.find((r) => r.id === router)?.name ?? router
-      list.push({ key: `router-${router}`, label: routerName, clear: () => setRouter('all') })
+    for (const id of routerIds) {
+      const routerName = routers.find((r) => r.id === id)?.name ?? id
+      list.push({ key: `router-${id}`, label: routerName, clear: () => toggleRouterId(id) })
     }
-    if (band !== 'all') {
-      list.push({ key: `band-${band}`, label: band === 'cable' ? t('common.cable') : band, clear: () => setBand('all') })
-    }
-    if (typeFilter !== 'all') {
-      list.push({ key: `type-${typeFilter}`, label: t(`devices.types.${typeFilter}`), clear: () => setTypeFilter('all') })
+    for (const b of bandsEffective) {
+      list.push({ key: `band-${b}`, label: b === 'cable' ? t('common.cable') : b, clear: () => toggleBand(b) })
     }
     for (const g of groups) {
       list.push({ key: `group-${g}`, label: t(`devices.groups.${g}`), clear: () => toggleGroup(g) })
@@ -1579,7 +1699,7 @@ export default function Devices() {
       list.push({ key: 'online', label: t(online === 'online' ? 'devices.onlineOnly' : 'devices.onlineOffline'), clear: () => setOnline('all') })
     }
     return list
-  }, [router, routers, band, typeFilter, groups, online, onlyUnprotected, setOnline, toggleGroup, t])
+  }, [routerIds, routers, bandsEffective, groups, online, onlyUnprotected, setOnline, toggleRouterId, toggleBand, toggleGroup, t])
 
   const searchBox = (className?: string, autoFocus = false) => (
     <div className={cn('relative', className)}>
@@ -1661,13 +1781,13 @@ export default function Devices() {
 
       {/* ③ Filter bar */}
       <FilterBar
-        router={router}
-        setRouter={setRouter}
-        band={band}
-        setBand={setBand}
-        typeFilter={typeFilter}
-        setTypeFilter={setTypeFilter}
-        typeCounts={typeCounts}
+        routerIds={routerIds}
+        toggleRouterId={toggleRouterId}
+        routerCounts={routerCounts}
+        bands={bandsEffective}
+        toggleBand={toggleBand}
+        bandCounts={bandCounts}
+        hasBand6={hasBand6}
         groups={groups}
         toggleGroup={toggleGroup}
         online={online}
@@ -1675,6 +1795,7 @@ export default function Devices() {
         onlyWeak={onlyWeak}
         setOnlyWeak={setOnlyWeak}
         weakCount={weakCount}
+        weakDbm={weakDbm}
         view={view}
         setView={setView}
         shown={filtered.length}
@@ -1717,32 +1838,44 @@ export default function Devices() {
         <div className="rounded-2xl border border-border bg-surface">
           {/* Cabecera de tabla sticky (desktop) */}
           <div
+            style={colsStyle}
             className={cn(
-              'sticky top-14 z-10 hidden items-center gap-4 pr-6 pl-3 py-2 rounded-t-2xl border-b border-border bg-surface text-label uppercase text-text-muted md:grid',
-              ROW_GRID,
+              'devices-cols sticky top-14 z-10 hidden items-center gap-4 pr-6 pl-3 py-2 rounded-t-2xl border-b border-border bg-surface text-label uppercase text-text-muted md:grid',
             )}
           >
             <SortHeader label={t('devices.colDevice')} k="name" sort={sort} onSort={toggleSort} />
-            <span className="hidden lg:block">
-              <SortHeader label={t('devices.colType')} k="type" sort={sort} onSort={toggleSort} />
-            </span>
-            <span className="hidden lg:block">
-              <SortHeader label="IP / MAC" k="ip" sort={sort} onSort={toggleSort} />
-            </span>
-            <span className="hidden lg:block">
-              <SortHeader label={t('devices.colLease')} k="lease" sort={sort} onSort={toggleSort} />
-            </span>
-            <SortHeader label="Router" k="router" sort={sort} onSort={toggleSort} />
-            <SortHeader label={t('devices.colBand')} k="band" sort={sort} onSort={toggleSort} />
-            <SortHeader label={t('devices.colSignal')} k="signal" sort={sort} onSort={toggleSort} />
-            <SortHeader label={t('devices.colTraffic')} k="traffic" sort={sort} onSort={toggleSort} />
-            <span className="hidden xl:block">
-              <SortHeader label={t('devices.colFirstSeen')} k="firstSeen" sort={sort} onSort={toggleSort} />
-            </span>
-            <span className="hidden xl:block">
-              <SortHeader label={t('devices.colLastSeen')} k="lastSeen" sort={sort} onSort={toggleSort} />
-            </span>
-            <span />
+            {visibleColumns.has('type') && (
+              <span className="hidden lg:block">
+                <SortHeader label={t('devices.colType')} k="type" sort={sort} onSort={toggleSort} />
+              </span>
+            )}
+            {visibleColumns.has('ip') && (
+              <span className="hidden lg:block">
+                <SortHeader label="IP / MAC" k="ip" sort={sort} onSort={toggleSort} />
+              </span>
+            )}
+            {visibleColumns.has('lease') && (
+              <span className="hidden lg:block">
+                <SortHeader label={t('devices.colLease')} k="lease" sort={sort} onSort={toggleSort} />
+              </span>
+            )}
+            {visibleColumns.has('router') && <SortHeader label="Router" k="router" sort={sort} onSort={toggleSort} />}
+            {visibleColumns.has('band') && <SortHeader label={t('devices.colBand')} k="band" sort={sort} onSort={toggleSort} />}
+            {visibleColumns.has('signal') && <SortHeader label={t('devices.colSignal')} k="signal" sort={sort} onSort={toggleSort} />}
+            {visibleColumns.has('traffic') && <SortHeader label={t('devices.colTraffic')} k="traffic" sort={sort} onSort={toggleSort} />}
+            {visibleColumns.has('firstSeen') && (
+              <span className="hidden xl:block">
+                <SortHeader label={t('devices.colFirstSeen')} k="firstSeen" sort={sort} onSort={toggleSort} />
+              </span>
+            )}
+            {visibleColumns.has('lastSeen') && (
+              <span className="hidden xl:block">
+                <SortHeader label={t('devices.colLastSeen')} k="lastSeen" sort={sort} onSort={toggleSort} />
+              </span>
+            )}
+            {/* #958: selector de columnas visibles (la última celda, sobre el
+                chevron de expansión). El nombre no se puede ocultar. */}
+            <ColumnPicker hidden={hiddenColumns} onToggle={toggleColumn} />
           </div>
           <div className="divide-y divide-border p-1.5 md:p-2">
             <AnimatePresence initial={false}>
@@ -1753,6 +1886,8 @@ export default function Devices() {
                   infra={infraById.get(d.id)}
                   expanded={expandedId === d.id}
                   index={i}
+                  vis={visibleColumns}
+                  colsStyle={colsStyle}
                   onToggle={() => setExpandedId((prev) => (prev === d.id ? null : d.id))}
                   onCopyIp={copyIp}
                   onNavigateRouter={navigateRouter}

+ 2 - 0
app/src/pages/Help.tsx

@@ -18,6 +18,7 @@ import {
   KeyRound,
   ListChecks,
   Router as RouterIcon,
+  Server,
   Wifi,
 } from 'lucide-react'
 import {
@@ -56,6 +57,7 @@ const FLOWS = [
   { key: 'installAgent', icon: CircleHelp },
   { key: 'channelPlan', icon: Wifi },
   { key: 'firmware', icon: Cpu },
+  { key: 'proxmoxToken', icon: Server },
 ] as const
 
 export default function Help() {

+ 24 - 22
app/src/pages/Home.tsx

@@ -10,39 +10,34 @@ import { WanTraffic } from '@/sections/WanTraffic'
 import { useNetPulse } from '@/data/DataProvider'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 
-/** Página Resumen `/` (home.md) */
+/** Página Resumen `/` (home.md). Layout #965: hero compacto + alertas 50/50,
+ *  tráfico WAN a todo lo ancho, flota, collector, SLEs y los servicios del
+ *  gateway (AdGuard/WireGuard) AL FINAL. */
 export default function Home() {
   const { isDemo } = useNetPulse()
   const [services] = useServicesVisibility()
   // Clave ESTABLE por tarjeta (#223): si AdGuard/WireGuard se deshabilitan en
-  // Ajustes la lista se reordena y, con key={i}, React remontaría RecentAlerts
-  // y perdería su readIds. Cada id identifica al hijo, no su posición.
-  const cards: { id: string; node: ReactNode }[] = []
-  if (services.adguard) cards.push({ id: 'adguard', node: <AdGuardCard /> })
-  if (services.wireguard) cards.push({ id: 'wireguard', node: <WireGuardCard /> })
-  cards.push({ id: 'alerts', node: <RecentAlerts /> })
-  const span = Math.max(4, Math.floor(12 / cards.length))
-  const spanCls = {
-    4: 'lg:col-span-4',
-    6: 'lg:col-span-6',
-    12: 'lg:col-span-12',
-  }[span]
+  // Ajustes la lista se reordena y, con key={i}, React remontaría los paneles.
+  // Cada id identifica al hijo, no su posición. Orden #983: AdGuard primero.
+  const serviceCards: { id: string; node: ReactNode }[] = []
+  if (services.adguard) serviceCards.push({ id: 'adguard', node: <AdGuardCard /> })
+  if (services.wireguard) serviceCards.push({ id: 'wireguard', node: <WireGuardCard /> })
+  const serviceSpan = serviceCards.length >= 2 ? 'lg:col-span-6' : 'lg:col-span-12'
   return (
     <div className="grid grid-cols-1 gap-4 md:gap-5 lg:grid-cols-12">
-      {/* ① Hero 50% + Tráfico 50% */}
+      {/* ① Hero compacto 50% + Alertas 50% (el alto lo marca la tarjeta de
+          alertas; ambas secciones son h-full) */}
       <div className="lg:col-span-6">
-        <HeroStrip />
+        <HeroStrip compact />
       </div>
       <div className="lg:col-span-6">
+        <RecentAlerts />
+      </div>
+      {/* ② Tráfico WAN a todo lo ancho (la gráfica de velocidad vive aquí) */}
+      <div className="lg:col-span-12">
         <WanTraffic />
       </div>
-      {/* ② Servicios marcados en Ajustes + Alertas en una fila */}
-      {cards.map((c) => (
-        <div key={c.id} className={spanCls}>
-          {c.node}
-        </div>
-      ))}
-      {/* ③ Routers */}
+      {/* ③ Tu flota */}
       <div className="lg:col-span-12">
         <RoutersRow />
       </div>
@@ -58,6 +53,13 @@ export default function Home() {
           <WiFiSLECard />
         </div>
       )}
+      {/* ⑥ Servicios del gateway (AdGuard/WireGuard) AL FINAL, span 6/12
+          según cuántos sean visibles */}
+      {serviceCards.map((c) => (
+        <div key={c.id} className={serviceSpan}>
+          {c.node}
+        </div>
+      ))}
       {/* Top dispositivos: solo demo (en live no hay tráfico por dispositivo) */}
       {isDemo && (
         <div className="lg:col-span-12">

+ 267 - 104
app/src/pages/Reports.tsx

@@ -3,9 +3,10 @@ import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
-import { CalendarDays, Download, RefreshCw } from 'lucide-react'
+import { Activity, AlertTriangle, CalendarDays, Clock, Download, RefreshCw } from 'lucide-react'
 import { cn, fetchJson } from '@/lib/utils'
 import { useNetPulse } from '@/data/DataProvider'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
 
 // ---------------------------------------------------------------------------
 // Tipos del contrato GET /api/reports/availability (server-go/internal/httpapi/reports.go)
@@ -35,36 +36,107 @@ const DEFAULT_N: Record<Range, number> = { day: 30, week: 8, month: 12 }
 const SUFFIX: Record<Range, string> = { day: 'd', week: 'w', month: 'm' }
 const RANGE_TABS: Range[] = ['day', 'week', 'month']
 
-/** Formatea bytes a unidad legible (mismo estilo que fmtEs de tráfico). */
-function fmtBytes(b: number): string {
-  const gb = b / 1e9
-  if (gb >= 1) return `${gb.toFixed(1)} GB`
-  const mb = b / 1e6
-  if (mb >= 1) return `${mb.toFixed(0)} MB`
-  return `${(b / 1e3).toFixed(0)} KB`
+// ---------------------------------------------------------------------------
+// Umbrales de color (issue #973): el rojo solo marca un problema accionable.
+//   >= 99%  ok      (verde)  menos de ~1 h 40 min de huecos a la semana: ruido normal.
+//   >= 95%  warn    (ámbar)  huecos menores, hasta ~8 h a la semana.
+//   <  95%  danger  (rojo)   más de ~8 h sin datos a la semana (~1,5 días al mes): requiere atención.
+// Un 94% semanal son >8 h sin datos, así que sigue siendo rojo, pero ahora el
+// rojo aparece UNA vez por router con su tiempo sin datos, no como muro de barras.
+// Lo que se mide son minutos con datos recibidos (buckets de 5 min, #987): un
+// hueco suele ser el router caído, pero también puede ser el monitor sin datos.
+// ---------------------------------------------------------------------------
+
+type Status = 'ok' | 'warn' | 'danger'
+
+function statusOf(pct: number): Status {
+  if (pct >= 99) return 'ok'
+  if (pct >= 95) return 'warn'
+  return 'danger'
 }
 
-/** Barra de disponibilidad con color semántico (design.md §10.11). */
-function AvailabilityBar({ pct }: { pct: number }) {
-  const color = pct >= 99 ? 'bg-ok' : pct >= 95 ? 'bg-warn' : 'bg-danger'
-  return (
-    <div className="flex items-center gap-2">
-      <div className="h-1.5 w-20 overflow-hidden rounded-full bg-elevated" role="presentation">
-        <motion.div
-          initial={{ width: 0 }}
-          animate={{ width: `${Math.min(100, Math.max(0, pct))}%` }}
-          transition={{ duration: 0.4, ease: 'easeOut' }}
-          className={cn('h-full rounded-full', color)}
-        />
-      </div>
-      <span className="font-mono text-mono-sm text-text-secondary">{pct >= 99.9 ? '100%' : `${pct.toFixed(1)}%`}</span>
-    </div>
-  )
+const STATUS_DOT: Record<Status, string> = {
+  ok: 'bg-ok',
+  warn: 'bg-warn',
+  danger: 'bg-danger',
+}
+const STATUS_TEXT: Record<Status, string> = {
+  ok: 'text-ok',
+  warn: 'text-warn',
+  danger: 'text-danger',
+}
+
+/**
+ * Minutos medibles de un bucket según la semántica del server (#987): el
+ * divisor de upPct son los minutos del bucket en los que se puede afirmar
+ * algo (1440 por día con datos; el día en curso solo cuenta los minutos
+ * transcurridos, medidos del raw). Como upPct = upMin/divisor, se recupera
+ * el divisor sin rehacer aritmética de fechas en el cliente.
+ */
+function bucketMinutes(e: AvailabilityEntry): number {
+  if (e.upPct > 0) return e.upMin / (e.upPct / 100)
+  return e.days * 1440
+}
+
+/** Minutos sin datos de un bucket = duración medible - minutos con datos. */
+function bucketDownMin(e: AvailabilityEntry): number {
+  return Math.max(0, bucketMinutes(e) - e.upMin)
+}
+
+/** Días que cubre la ventana seleccionada (mes = media de 30,44 días). */
+function expectedDays(range: Range, n: number): number {
+  if (range === 'day') return n
+  if (range === 'week') return n * 7
+  return Math.round(n * 30.44)
+}
+
+/**
+ * Cobertura mínima para resumir la ventana con un número (#987): con menos
+ * de la mitad de los días con datos, un % o un tiempo sin datos no representa
+ * la ventana y la UI dice "sin datos suficientes" en vez de inventar cifras.
+ */
+const MIN_COVERAGE = 0.5
+
+/** Formatea minutos a unidades humanas: "45 min", "2 h 14 min", "1 d 3 h". */
+function fmtDuration(min: number): string {
+  const m = Math.round(min)
+  if (m < 60) return `${m} min`
+  const h = Math.floor(m / 60)
+  const mm = m % 60
+  if (h < 48) return mm > 0 ? `${h} h ${mm} min` : `${h} h`
+  const d = Math.floor(h / 24)
+  const hh = h % 24
+  return hh > 0 ? `${d} d ${hh} h` : `${d} d`
+}
+
+interface RouterSummary {
+  id: string
+  pct: number
+  downMin: number
+  status: Status
+  days: number // días con datos en la ventana
+  sufficient: boolean // cobertura suficiente para resumir la ventana (#987)
+  buckets: AvailabilityEntry[] // ordenados de más antiguo a más reciente
+}
+
+/** Lunes y domingo (UTC) de una semana ISO "2026-W31", para el tooltip de la barra (#993). */
+function isoWeekSpan(bucket: string): [Date, Date] | null {
+  const m = /^(\d{4})-W(\d{2})$/.exec(bucket)
+  if (!m) return null
+  const year = Number(m[1])
+  const week = Number(m[2])
+  const jan4 = new Date(Date.UTC(year, 0, 4))
+  const dow = jan4.getUTCDay() || 7 // lunes = 1
+  const monday = new Date(jan4)
+  monday.setUTCDate(jan4.getUTCDate() - dow + 1 + (week - 1) * 7)
+  const sunday = new Date(monday)
+  sunday.setUTCDate(monday.getUTCDate() + 6)
+  return [monday, sunday]
 }
 
-/** Página `/reports` — Informe de disponibilidad (reports.md). */
+/** Página `/reports` - Informe de disponibilidad (reports.md, rediseño #973). */
 export default function Reports() {
-  const { t } = useTranslation()
+  const { t, i18n } = useTranslation()
   const reduce = useReducedMotion()
   const { isDemo } = useNetPulse()
   const [range, setRange] = useState<Range>('week')
@@ -139,10 +211,60 @@ export default function Reports() {
     [range],
   )
 
-  // Agrupa por router y coloca los buckets en columnas (fila = router).
-  const routerIds = [...new Set(items.map((i) => i.routerId))].sort()
-  const buckets = [...new Set(items.map((i) => i.bucket))].sort().reverse()
-  const byRouter = (id: string) => items.filter((i) => i.routerId === id)
+  // Agregado por router sobre TODA la ventana seleccionada (no por bucket):
+  // un solo % y un solo tiempo sin datos por router, ponderado por la
+  // duración medible de cada bucket. Si el router tiene datos de menos de la
+  // mitad de la ventana, no se resume con un número (#987).
+  const routers: RouterSummary[] = [...new Set(items.map((i) => i.routerId))]
+    .sort()
+    .map((id) => {
+      const rows = items.filter((i) => i.routerId === id)
+      const totalMin = rows.reduce((a, r) => a + bucketMinutes(r), 0)
+      const upMin = rows.reduce((a, r) => a + r.upMin, 0)
+      const days = rows.reduce((a, r) => a + r.days, 0)
+      const pct = totalMin > 0 ? Math.min(100, (upMin / totalMin) * 100) : 100
+      return {
+        id,
+        pct,
+        downMin: Math.max(0, totalMin - upMin),
+        status: statusOf(pct),
+        days,
+        sufficient: days >= Math.max(2, expectedDays(range, n) * MIN_COVERAGE),
+        buckets: [...rows].sort((a, b) => a.bucket.localeCompare(b.bucket)),
+      }
+    })
+
+  // Los agregados de flota solo cuentan routers con cobertura suficiente:
+  // un router nuevo o sin datos no arrastra la media ni infla los huecos.
+  const rated = routers.filter((r) => r.sufficient)
+  const fleetPct = rated.length ? rated.reduce((a, r) => a + r.pct, 0) / rated.length : null
+  const worst = rated.length ? rated.reduce((a, r) => (r.pct < a.pct ? r : a)) : null
+  const totalDown = rated.reduce((a, r) => a + r.downMin, 0)
+
+  const windowText = t(range === 'day' ? 'reports.windowDay' : range === 'week' ? 'reports.windowWeek' : 'reports.windowMonth', { n })
+
+  // -- Barra de disponibilidad estilo Uptime Kuma (#993) -------------------
+  // Un segmento por bucket (día/semana/mes según la pestaña, la granularidad
+  // real del endpoint). El tooltip muestra la fecha del segmento; el día en
+  // curso, único bucket con hora real, muestra además la hora de corte.
+  const dayFmt = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', timeZone: 'UTC' })
+  const dayYearFmt = new Intl.DateTimeFormat(i18n.language, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })
+  const monthFmt = new Intl.DateTimeFormat(i18n.language, { month: 'long', year: 'numeric', timeZone: 'UTC' })
+  const todayKey = new Date().toISOString().slice(0, 10)
+  const nowTime = new Date().toLocaleTimeString(i18n.language, { hour: '2-digit', minute: '2-digit' })
+
+  function bucketLabel(b: AvailabilityEntry): string {
+    if (range === 'day') {
+      if (b.bucket === todayKey) return t('reports.tipToday', { time: nowTime })
+      return dayYearFmt.format(new Date(`${b.bucket}T00:00:00Z`))
+    }
+    if (range === 'week') {
+      const span = isoWeekSpan(b.bucket)
+      if (!span) return b.bucket
+      return `${dayFmt.format(span[0])} - ${dayYearFmt.format(span[1])}`
+    }
+    return monthFmt.format(new Date(`${b.bucket}-01T00:00:00Z`))
+  }
 
   const initial = reduce ? false : { opacity: 0, y: 12 }
 
@@ -168,7 +290,7 @@ export default function Reports() {
             transition={{ duration: 0.25, ease: 'easeOut', delay: 0.06 }}
           >
             <h1 className="font-display text-h1 text-text-primary">{t('nav.reports')}</h1>
-            <p className="text-caption text-text-muted">{t('reports.subtitle')}</p>
+            <p className="text-caption text-text-muted">{t('reports.explain', { window: windowText })}</p>
           </motion.div>
           <motion.div
             initial={initial}
@@ -263,11 +385,50 @@ export default function Reports() {
       )}
 
       {items.length > 0 && (
-        <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
-          <div className="mb-4 flex items-center gap-2">
-            <CalendarDays className="h-4 w-4 text-accent" strokeWidth={1.75} />
-            <h2 className="font-display text-h2 text-text-primary">{t('reports.availability')}</h2>
-            {items.length > 0 && (
+        <>
+          {/* ④ Resumen de la flota: media, peor router y tiempo sin datos total */}
+          <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+            <div className="rounded-2xl border border-border bg-surface p-4">
+              <div className="flex items-center gap-2 text-caption text-text-muted">
+                <Activity className="h-4 w-4 text-accent" strokeWidth={1.75} />
+                {t('reports.fleetAvg')}
+              </div>
+              <p className={cn('mt-1 font-display text-h2', fleetPct !== null ? STATUS_TEXT[statusOf(fleetPct)] : 'text-text-muted')}>
+                {fleetPct === null ? t('reports.insufficient') : fleetPct >= 99.9 ? '100%' : `${fleetPct.toFixed(1)}%`}
+              </p>
+            </div>
+            <div className="rounded-2xl border border-border bg-surface p-4">
+              <div className="flex items-center gap-2 text-caption text-text-muted">
+                <AlertTriangle className={cn('h-4 w-4', worst && worst.status !== 'ok' ? STATUS_TEXT[worst.status] : 'text-text-muted')} strokeWidth={1.75} />
+                {t('reports.worstRouter')}
+              </div>
+              {worst ? (
+                <p className="mt-1 font-display text-h2 text-text-primary">
+                  {worst.id}
+                  <span className={cn('ml-2 text-sm font-normal', STATUS_TEXT[worst.status])}>
+                    {worst.pct >= 99.9 ? '100%' : `${worst.pct.toFixed(1)}%`}
+                  </span>
+                </p>
+              ) : (
+                <p className="mt-1 font-display text-h2 text-text-muted">{t('reports.insufficient')}</p>
+              )}
+            </div>
+            <div className="rounded-2xl border border-border bg-surface p-4">
+              <div className="flex items-center gap-2 text-caption text-text-muted">
+                <Clock className="h-4 w-4 text-accent" strokeWidth={1.75} />
+                {t('reports.totalDown')}
+              </div>
+              <p className={cn('mt-1 font-display text-h2', rated.length === 0 ? 'text-text-muted' : totalDown >= 1 ? STATUS_TEXT[statusOf(fleetPct ?? 100)] : 'text-ok')}>
+                {rated.length === 0 ? t('reports.insufficient') : totalDown >= 1 ? fmtDuration(totalDown) : t('reports.downNone')}
+              </p>
+            </div>
+          </div>
+
+          {/* ⑤ Lista por router: un % y un tiempo sin datos por router */}
+          <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
+            <div className="mb-4 flex items-center gap-2">
+              <CalendarDays className="h-4 w-4 text-accent" strokeWidth={1.75} />
+              <h2 className="font-display text-h2 text-text-primary">{t('reports.availability')}</h2>
               <a
                 href={`/api/reports/availability?range=${range}&n=${n}&format=csv`}
                 download
@@ -277,76 +438,78 @@ export default function Reports() {
                 <Download className="h-3 w-3" strokeWidth={2} />
                 CSV
               </a>
-            )}
-          </div>
-          <div className="overflow-x-auto">
-            <table className="w-full text-left text-sm">
-              <thead>
-                <tr className="border-b border-border">
-                  <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('reports.colRouter')}</th>
-                  {buckets.map((b) => (
-                    <th key={b} className="pb-2.5 pr-3 font-mono text-caption font-medium normal-case text-text-muted">{b}</th>
-                  ))}
-                  <th className="pb-2.5 text-label font-medium uppercase text-text-muted">{t('reports.colAvg')}</th>
-                </tr>
-              </thead>
-              <tbody>
-                {routerIds.map((id) => {
-                  const rows = byRouter(id)
-                  const avg = rows.length ? rows.reduce((a, r) => a + r.upPct, 0) / rows.length : 0
-                  return (
-                    <tr key={id} className="border-b border-border/60 last:border-0 hover:bg-hover">
-                      <td className="py-3 pr-3 font-medium text-text-primary">{id}</td>
-                      {buckets.map((b) => {
-                        const e = rows.find((r) => r.bucket === b)
-                        return (
-                          <td key={b} className="py-3 pr-3">
-                            {e ? <AvailabilityBar pct={e.upPct} /> : <span className="text-caption text-text-muted">—</span>}
-                          </td>
-                        )
-                      })}
-                      <td className="py-3">
-                        <AvailabilityBar pct={avg} />
-                      </td>
-                    </tr>
-                  )
-                })}
-              </tbody>
-            </table>
-          </div>
-
-          {/* ④ Detalle por router: últimos buckets con tráfico/latencia */}
-          <div className="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2">
-            {routerIds.map((id) => {
-              const rows = [...byRouter(id)].sort((a, b) => b.bucket.localeCompare(a.bucket))
-              return (
-                <div key={id} className="rounded-xl border border-border bg-elevated p-4">
-                  <h3 className="mb-3 font-display text-h3 text-text-primary">{id}</h3>
-                  <div className="space-y-2">
-                    {rows.map((r) => (
-                      <div key={r.bucket} className="flex items-center justify-between gap-2 text-caption">
-                        <span className="font-mono text-text-muted">{r.bucket}</span>
-                        <span className="flex items-center gap-3 font-mono text-mono-sm text-text-secondary">
-                          <span title={t('reports.latency')}>
-                            {r.latAvg !== null ? `${r.latAvg.toFixed(1)} ms` : '—'}
-                          </span>
-                          <span title={t('reports.traffic')}>
-                            {fmtBytes(r.rxTotal + r.txTotal)}
-                          </span>
-                          <span title={t('reports.upMin')}>
-                            {r.upMin}′
-                          </span>
+            </div>
+            <ul className="divide-y divide-border/60">
+              {routers.map((r) => (
+                <li key={r.id} className="flex flex-wrap items-center gap-x-4 gap-y-2 py-3">
+                  {/* Nombre + estado */}
+                  <div className="flex min-w-40 items-center gap-2">
+                    <span className={cn('h-2 w-2 shrink-0 rounded-full', r.sufficient ? STATUS_DOT[r.status] : 'bg-border-strong')} aria-hidden="true" />
+                    <span className="font-medium text-text-primary">{r.id}</span>
+                    {r.sufficient ? (
+                      <span className={cn('text-caption', STATUS_TEXT[r.status])}>{t(`reports.status_${r.status}`)}</span>
+                    ) : (
+                      <span className="text-caption text-text-muted">{t('reports.insufficient')}</span>
+                    )}
+                  </div>
+                  {/* Barra de disponibilidad (#993): segmentos rectangulares
+                      contiguos, uno por bucket, con tooltip de fecha y tiempo
+                      sin datos. Atenuada si la cobertura es insuficiente (#987) */}
+                  <div className={cn('flex min-w-24 flex-1 items-center gap-0.5', !r.sufficient && 'opacity-60')}>
+                    {r.buckets.map((b) => {
+                      const down = bucketDownMin(b)
+                      const st = statusOf(b.upPct)
+                      const label = bucketLabel(b)
+                      const pctText = b.upPct >= 99.9 ? '100%' : `${b.upPct.toFixed(1)}%`
+                      const downText = down >= 1 ? t('reports.downTime', { duration: fmtDuration(down) }) : t('reports.downNone')
+                      return (
+                        <Tooltip key={b.bucket}>
+                          <TooltipTrigger
+                            aria-label={`${label}: ${pctText}, ${downText}`}
+                            className={cn(
+                              'h-4 min-w-1 flex-1 rounded-[2px] transition-transform duration-150 hover:scale-y-125',
+                              STATUS_DOT[st],
+                            )}
+                          />
+                          <TooltipContent
+                            side="top"
+                            sideOffset={6}
+                            className="border border-border-strong bg-elevated text-text-primary shadow-xl"
+                          >
+                            <p className="font-medium">{label}</p>
+                            <p className={cn('text-caption', STATUS_TEXT[st])}>
+                              {pctText} · {t(`reports.status_${st}`)}
+                            </p>
+                            <p className="text-caption text-text-secondary">{downText}</p>
+                          </TooltipContent>
+                        </Tooltip>
+                      )
+                    })}
+                  </div>
+                  {/* % agregado + tiempo sin datos en unidades humanas; con
+                      cobertura insuficiente no se inventa un número (#987) */}
+                  <div className="ml-auto text-right">
+                    {r.sufficient ? (
+                      <>
+                        <span className={cn('font-mono text-mono-sm font-semibold', STATUS_TEXT[r.status])}>
+                          {r.pct >= 99.9 ? '100%' : `${r.pct.toFixed(1)}%`}
                         </span>
-                      </div>
-                    ))}
+                        <p className="text-caption text-text-muted">
+                          {r.downMin >= 1 ? t('reports.downTime', { duration: fmtDuration(r.downMin) }) : t('reports.downNone')}
+                        </p>
+                      </>
+                    ) : (
+                      <p className="text-caption text-text-muted">
+                        {t('reports.coverage', { days: r.days, total: expectedDays(range, n) })}
+                      </p>
+                    )}
                   </div>
-                </div>
-              )
-            })}
-          </div>
-
-          <p className="mt-6 text-caption text-text-muted">{t('reports.footnote')}</p>
-        </section>
+                </li>
+              ))}
+            </ul>
+            <p className="mt-4 text-caption text-text-muted">{t('reports.footnote')}</p>
+          </section>
+        </>
       )}
       </div>
     </div>

+ 4 - 16
app/src/pages/Roaming.tsx

@@ -6,6 +6,7 @@ import { motion, useReducedMotion } from 'framer-motion'
 import { AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CheckCircle2, GitFork, History, RefreshCw, Wifi, X, XCircle } from 'lucide-react'
 import { cn, fetchJson } from '@/lib/utils'
 import { useNetPulse, redirectLogin } from '@/data/DataProvider'
+import { useWeakSignalDbm } from '@/hooks/useWeakSignalDbm'
 import ReanchorPanel from './ReanchorPanel'
 
 // ---------------------------------------------------------------------------
@@ -171,22 +172,9 @@ export default function Roaming() {
   const [band, setBand] = useState<Band>('all')
   const [weakOnly, setWeakOnly] = useState(false)
   // #906: el filtro "Weak signal only" usa el umbral server-wide del ajuste
-  // Weak signal (#904, /api/settings/thresholds); -70 es el fallback (demo o
-  // servidor antiguo).
-  const [weakDbm, setWeakDbm] = useState(-70)
-  useEffect(() => {
-    if (isDemo) return
-    let cancelled = false
-    fetch('/api/settings/thresholds')
-      .then((r) => (r.ok ? r.json() : null))
-      .then((j) => {
-        if (!cancelled && j && typeof j.weakSignalDbm === 'number') setWeakDbm(j.weakSignalDbm)
-      })
-      .catch(() => {})
-    return () => {
-      cancelled = true
-    }
-  }, [isDemo])
+  // Weak signal (#904, /api/settings/thresholds); hook compartido con la
+  // página Clientes (#1003), -70 de fallback (demo o servidor antiguo).
+  const weakDbm = useWeakSignalDbm()
   const [usteer, setUsteer] = useState<Usteer | null>(null)
   const [dot11r, setDot11r] = useState<Dot11rOverview | null>(null)
   const [dot11rLoading, setDot11rLoading] = useState(false)

Diferenças do arquivo suprimidas por serem muito extensas
+ 510 - 123
app/src/pages/Settings.tsx


+ 12 - 10
app/src/pages/Topology.tsx

@@ -237,8 +237,17 @@ export default function Topology() {
               </button>
             </motion.div>
           )}
+          {/* Toggle de etiquetas junto a "Etiquetar dispositivos" (#990): los
+              dos controles de rotulación del mapa van pegados. */}
+          <motion.label
+            {...controlMotion(1)}
+            className="flex cursor-pointer items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm font-medium text-text-secondary"
+          >
+            <Switch checked={showLabels} onCheckedChange={setShowLabels} aria-label={t('topology.showLabels')} />
+            {t('topology.labels')}
+          </motion.label>
           <motion.div
-            {...controlMotion(0)}
+            {...controlMotion(2)}
             className="flex items-center gap-0.5 rounded-xl border border-border bg-surface p-1"
           >
             <ControlButton
@@ -253,23 +262,16 @@ export default function Topology() {
             </ControlButton>
           </motion.div>
           <motion.div
-            {...controlMotion(1)}
+            {...controlMotion(3)}
             className="flex items-center gap-0.5 rounded-xl border border-border bg-surface p-1"
             role="group"
             aria-label={t('topology.zoomControls')}
           >
             {zoomControls}
           </motion.div>
-          <motion.label
-            {...controlMotion(2)}
-            className="flex cursor-pointer items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm font-medium text-text-secondary"
-          >
-            <Switch checked={showLabels} onCheckedChange={setShowLabels} aria-label={t('topology.showLabels')} />
-            {t('topology.labels')}
-          </motion.label>
           {canEdit && (
             <motion.div
-              {...controlMotion(3)}
+              {...controlMotion(4)}
               className="flex items-center gap-1.5 rounded-xl border border-border bg-surface p-1"
             >
               {editMode ? (

+ 130 - 25
app/src/sections/HeroStrip.tsx

@@ -48,8 +48,13 @@ function MiniStat({
 }
 
 /** ① Hero strip — saludo + estado arriba, donut de salud grande y centrado,
- *  stats en fila debajo (home.md §①) */
-export function HeroStrip() {
+ *  stats en fila debajo (home.md §①).
+ *  compact (#965, layout #979): dos mitades; a la izquierda el saludo
+ *  centrado con Latencia y Clientes debajo, a la derecha el anillo de
+ *  salud (128px) centrado. Conserva los subscores WAN/Wi-Fi/Infra/Servicios
+ *  (#334, con mini-barra) bajo las dos mitades, a todo el ancho; el desglose
+ *  de penalizaciones se queda en la variante grande. */
+export function HeroStrip({ compact = false }: { compact?: boolean }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const { refreshKey } = useDashboard()
@@ -78,6 +83,128 @@ export function HeroStrip() {
   const alerts = healthScore.breakdown?.length ?? 0
   const statusLine = alerts > 0 ? t('home.importantAlerts', { count: alerts }) : t('home.noImportantAlerts')
 
+  // Fragmento compartido de subscores (#334): mini-barras WAN/Wi-Fi/Infra/
+  // Servicios. En compact van debajo de latencia/clientes, a todo el ancho.
+  const subscoresBlock = healthScore.subscores && healthScore.subscores.length > 0 && (
+    <div className={cn('grid w-full grid-cols-2 gap-x-4 gap-y-1.5', compact ? 'mt-1' : 'mt-2 max-w-xs')}>
+      {healthScore.subscores.map((s) => (
+        <div key={s.key} className="flex items-center gap-2">
+          <span className="w-20 shrink-0 text-right text-[10px] font-medium uppercase tracking-wider text-text-muted">
+            {subscoreLabel(s.key, s.label)}
+          </span>
+          <div className="relative h-1.5 flex-1 overflow-hidden rounded-full bg-border">
+            <div
+              className={cn(
+                'h-full rounded-full transition-all duration-500',
+                s.score >= 90 ? 'bg-ok' : s.score >= 70 ? 'bg-warn' : 'bg-danger',
+              )}
+              style={{ width: `${s.score}%` }}
+            />
+          </div>
+          <span className="w-6 text-right font-mono text-[10px] text-text-secondary">
+            {s.score}
+          </span>
+        </div>
+      ))}
+    </div>
+  )
+
+  if (compact) {
+    return (
+      <section className="surface-featured mesh-bg relative h-full overflow-hidden rounded-2xl border bg-surface p-5">
+        {/* Halo radial cyan que respira */}
+        {!reduce && (
+          <motion.div
+            className="pointer-events-none absolute -right-24 -top-24 h-72 w-72 rounded-full bg-accent/[0.08] blur-3xl"
+            animate={{ scale: [1, 1.06, 1] }}
+            transition={{ duration: 6, repeat: Infinity, ease: 'easeInOut' }}
+          />
+        )}
+        <div className="relative flex h-full flex-col gap-3">
+          {/* Dos mitades: izquierda saludo centrado con latencia+clientes debajo, derecha anillo centrado */}
+          <div className="flex flex-1 items-stretch gap-4">
+            {/* Mitad izquierda: saludo + estado centrados, stats debajo */}
+            <div className="flex min-w-0 basis-1/2 flex-col items-center justify-center gap-3 text-center">
+              <div>
+                <h1 className="font-display text-h1 text-text-primary" aria-label={greeting}>
+                {words.map((w, i) => (
+                  <Fragment key={`${w}-${i}`}>
+                    <motion.span
+                      className="inline-block"
+                      initial={{ opacity: 0, y: 12 }}
+                      animate={{ opacity: 1, y: 0 }}
+                      transition={{ duration: 0.35, ease: 'easeOut', delay: i * 0.04 }}
+                    >
+                      {w}
+                    </motion.span>
+                    {i < words.length - 1 ? ' ' : ''}
+                  </Fragment>
+                ))}
+              </h1>
+              <motion.p
+                className="mt-1 flex items-center justify-center gap-1.5 text-sm font-medium text-text-secondary"
+                initial={{ opacity: 0 }}
+                animate={{ opacity: 1 }}
+                transition={{ delay: 0.25, duration: 0.4 }}
+              >
+                {alerts > 0 ? (
+                  <>
+                    <AlertTriangle className="h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} />
+                    {statusLine}
+                  </>
+                ) : (
+                  <>
+                    <CheckCircle2 className="h-4 w-4 shrink-0 text-ok" strokeWidth={1.75} />
+                    {statusLine}
+                  </>
+                )}
+              </motion.p>
+              </div>
+
+              {/* Latencia + Clientes: debajo del saludo, centrados en la mitad izquierda */}
+              <div className="flex items-center justify-center gap-8">
+                <MiniStat icon={Gauge} label={t('home.latency')} colorClass="text-ok" index={0}>
+                  <CountUp value={wan.latencyMs} nonce={refreshKey} /> ms
+                </MiniStat>
+                <MiniStat icon={MonitorSmartphone} label={t('home.devices')} colorClass="text-text-primary" index={1}>
+                  <CountUp value={deviceTotals.total} nonce={refreshKey} />
+                </MiniStat>
+              </div>
+            </div>
+
+            {/* Mitad derecha: anillo de salud centrado */}
+            <div className="flex basis-1/2 shrink-0 flex-col items-center justify-center gap-2">
+              <motion.div layoutId="health-ring">
+                <HealthRing
+                  value={healthScore.score}
+                  size={128}
+                  stroke={11}
+                  ariaLabel={t('home.healthAria', {
+                    caption: t('common.healthCaption'),
+                    score: healthScore.score,
+                    label: healthLabel(healthScore.label),
+                  })}
+                  center={
+                    <div className="flex flex-col items-center">
+                      <span className="kpi-value text-2xl font-bold text-text-primary">
+                        <CountUp value={healthScore.score} duration={1.2} nonce={refreshKey} />
+                      </span>
+                      <span className="font-mono text-[10px] text-text-muted">/100</span>
+                    </div>
+                  }
+                />
+              </motion.div>
+              <StatusPill tone="ok" label={healthLabel(healthScore.label)} />
+            </div>
+          </div>
+
+          {/* Subscores (#334) debajo de las dos mitades, a todo el ancho */}
+          {subscoresBlock}
+        </div>
+      </section>
+    )
+  }
+
   return (
     <section className="surface-featured mesh-bg relative h-full overflow-hidden rounded-2xl border bg-surface p-5 md:p-6">
       {/* Halo radial cyan que respira */}
@@ -152,29 +279,7 @@ export function HeroStrip() {
           <span className="text-caption text-text-muted">{t('common.healthCaption')}</span>
 
           {/* Subscore bars (#334) */}
-          {healthScore.subscores && healthScore.subscores.length > 0 && (
-            <div className="mt-2 grid w-full max-w-xs grid-cols-2 gap-x-4 gap-y-1.5">
-              {healthScore.subscores.map((s) => (
-                <div key={s.key} className="flex items-center gap-2">
-                  <span className="w-14 shrink-0 truncate text-right text-[10px] font-medium uppercase tracking-wider text-text-muted">
-                    {subscoreLabel(s.key, s.label)}
-                  </span>
-                  <div className="relative h-1.5 flex-1 overflow-hidden rounded-full bg-border">
-                    <div
-                      className={cn(
-                        'h-full rounded-full transition-all duration-500',
-                        s.score >= 90 ? 'bg-ok' : s.score >= 70 ? 'bg-warn' : 'bg-danger',
-                      )}
-                      style={{ width: `${s.score}%` }}
-                    />
-                  </div>
-                  <span className="w-6 text-right font-mono text-[10px] text-text-secondary">
-                    {s.score}
-                  </span>
-                </div>
-              ))}
-            </div>
-          )}
+          {subscoresBlock}
         </div>
 
         {/* Desglose del health score (#23): barras de penalizacion */}

+ 8 - 3
app/src/sections/RecentAlerts.tsx

@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNavigate } from 'react-router'
 import { motion } from 'framer-motion'
-import { RefreshCw } from 'lucide-react'
+import { RefreshCw, ShieldCheck } from 'lucide-react'
 import { AlertItem } from '@/components/AlertItem'
 import { SectionHeader } from '@/components/SectionHeader'
 import { useNetPulse } from '@/data/DataProvider'
@@ -74,9 +74,14 @@ export function RecentAlerts() {
           {t('home.recentAlerts.unreadOnly')}
         </button>
       </SectionHeader>
-      <div className="-mx-3 flex-1 space-y-1">
+      <div className="-mx-3 flex flex-1 flex-col space-y-1">
         {visible.length === 0 && (
-          <p className="px-3 py-6 text-center text-caption text-text-muted">{t('home.recentAlerts.allRead')}</p>
+          // Estado vacío (#992): icono + microtexto, centrado en la tarjeta.
+          <div className="flex flex-1 flex-col items-center justify-center gap-2 px-3 py-6 text-center">
+            <ShieldCheck className="h-8 w-8 text-ok" strokeWidth={1.5} aria-hidden="true" />
+            <p className="text-sm font-medium text-text-secondary">{t('home.recentAlerts.emptyTitle')}</p>
+            <p className="text-caption text-text-muted">{t('home.recentAlerts.allRead')}</p>
+          </div>
         )}
         {visible.map((a, i) => (
           <motion.div

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

@@ -1,14 +1,16 @@
 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 { SectionHeader } from '@/components/SectionHeader'
 import { SegmentedControl, TIME_RANGE_OPTIONS } from '@/components/SegmentedControl'
 import { StatusPill } from '@/components/StatusPill'
-import { SpeedtestStrip } from '@/components/routers/WanLatency'
+import { SpeedtestHistoryChart, useSpeedtestHistory } from '@/components/routers/WanLatency'
 
 // ---------------------------------------------------------------------------
 // Tooltip custom (design.md §7): superficie elevated, valores mono con unidad
@@ -51,6 +53,60 @@ 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()
@@ -227,9 +283,8 @@ export function WanTraffic() {
         </p>
       ) : null}
 
-      {/* Velocidad medida + botón de test (#511, movido al Overview en
-          #744 a petición del reportero: el gateway ya no la lleva). */}
-      <SpeedtestStrip contractDown={wan.contractDownMbps} />
+      {/* Velocidad medida (#982): gráfica del histórico de speedtests */}
+      <SpeedtestHistoryBlock contractDown={wan.contractDownMbps} />
     </section>
   )
 }

+ 6 - 6
docs/https.md

@@ -15,7 +15,7 @@ Nothing changes until an admin turns it on.
 
 ## Turning it on
 
-In **Settings → HTTPS** (admins only), switch on **HTTPS on port 3443**.
+In **Settings → HTTPS** (admins only), switch on **HTTPS on port 443**.
 Every change on that card asks for your password again.
 
 Turning HTTPS on only **adds** the HTTPS port. Plain HTTP on the usual port
@@ -29,7 +29,7 @@ root's fingerprint:
 [netpulse] TLS: agents pin 1f2e…
 ```
 
-The port is `NETPULSE_TLS_PORT` (3443 by default).
+The port is `NETPULSE_TLS_PORT` (443 by default).
 
 ## Installing the root certificate
 
@@ -63,7 +63,7 @@ journalctl -u netpulse | grep 'root certificate SHA-256'
   Certificates → Authorities → Import, then tick "Trust this CA to identify
   websites".
 
-Then open `https://<server>:3443`.
+Then open `https://<server>:443`.
 
 ### What the root can and cannot vouch for
 
@@ -109,9 +109,9 @@ moves in one of these ways:
 - **The install command** shown when adding an agent. Once HTTPS is on, it
   carries the root and the pin.
 - **NetGrip:** in its NetPulse settings, set the server to
-  `https://<server>:3443` and the server fingerprint to the **agent pin**
+  `https://<server>:443` and the server fingerprint to the **agent pin**
   shown on the HTTPS card.
-- **Any other agent:** set `NETPULSE_SERVER=https://<server>:3443` and
+- **Any other agent:** set `NETPULSE_SERVER=https://<server>:443` and
   `NETPULSE_SERVER_FP=<agent pin>` in its env file.
 - **Pairing with the pairing token:** an agent given only an https server URL
   and the pairing token proves the server's key with that token before
@@ -119,7 +119,7 @@ moves in one of these ways:
 - **`deploy/switch-scraper.sh`:** fetch the root once into a file its user
   can read (`curl -fsS http://127.0.0.1:3000/netpulse-ca.pem -o …`; the
   server's own copy is private to it), then set
-  `NETPULSE_URL=https://127.0.0.1:3443` and `NETPULSE_CA` to that file.
+  `NETPULSE_URL=https://127.0.0.1:443` and `NETPULSE_CA` to that file.
 
 Zero-touch enrolment (`AGENT_AUTOENROLL`) hands its token to anyone who asks
 over UDP, so it cannot prove anything. An agent enrolled that way trusts

+ 35 - 3
server-go/cmd/netpulse/main.go

@@ -392,10 +392,18 @@ func run() error {
 			chain = append(chain, urgencyGate{n: webhookNotifier, kv: kv, key: "webhook.urgent_only"})
 		}
 		if telegramNotifier != nil {
-			chain = append(chain, urgencyGate{n: telegramNotifier, kv: kv, key: "telegram.urgent_only"})
+			chain = append(chain, integrationGate{
+				n:   urgencyGate{n: telegramNotifier, kv: kv, key: "telegram.urgent_only"},
+				kv:  kv,
+				key: "settings.integrations.telegram",
+			})
 		}
 		if ntfyNotifier != nil {
-			chain = append(chain, urgencyGate{n: ntfyNotifier, kv: kv, key: "ntfy.urgent_only"})
+			chain = append(chain, integrationGate{
+				n:   urgencyGate{n: ntfyNotifier, kv: kv, key: "ntfy.urgent_only"},
+				kv:  kv,
+				key: "settings.integrations.ntfy",
+			})
 		}
 		notifyChain = chain
 	}
@@ -587,6 +595,8 @@ func run() error {
 		DB:          dbHandle,
 		DataDir:     cfg.DataDir,
 		Port:        cfg.TLSPort,
+		EnvPort:     cfg.TLSPortSet,
+		PlainPort:   cfg.Port,
 		Names:       cfg.TLSNames,
 		PublicURL:   cfg.PublicURL,
 		EnvEnabled:  tlsEnvEnabled,
@@ -650,13 +660,18 @@ func run() error {
 
 	// Retención de eventos de presencia/roaming (#771): poda horaria de
 	// device_events y roam_events según presence.retention_days (kv; 0 =
-	// conservar siempre). Sin esto ambas tablas crecen sin límite.
+	// 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).
 	presenceStop := make(chan struct{})
 	if !cfg.DemoMode {
 		go func() {
 			tick := time.NewTicker(time.Hour)
 			defer tick.Stop()
 			prune := func() {
+				if !httpapi.HistoryLimitEnabled(dbHandle.DB) {
+					return
+				}
 				retention := httpapi.PresenceRetentionDays(dbHandle.DB)
 				if retention <= 0 {
 					return
@@ -886,6 +901,23 @@ func (g urgencyGate) Notify(ev alerts.AlertEvent) {
 	g.n.Notify(ev)
 }
 
+// integrationGate implementa alerts.Notifier descartando TODOS los eventos
+// de un canal cuando su integración está desactivada en Ajustes (#968,
+// settings.integrations.<canal> = "false"). Ausente = activo. La lectura es
+// por evento (patrón urgencyGate): el toggle aplica sin reiniciar.
+type integrationGate struct {
+	n   alerts.Notifier
+	kv  *mainKVAdapter
+	key string
+}
+
+func (g integrationGate) Notify(ev alerts.AlertEvent) {
+	if v, ok := g.kv.Get(g.key); ok && v == "false" {
+		return
+	}
+	g.n.Notify(ev)
+}
+
 // notifierChain implementa alerts.Notifier encadenando varios notifiers
 // (push + webhook). El motor de alertas solo admite UNO (SetNotifier), así
 // que este compuesto reparte cada evento a todos los miembros no nulos.

+ 12 - 4
server-go/internal/adapters/agent.go

@@ -390,6 +390,10 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 		if l.agentDown[cfg.ID] {
 			l.agentDown[cfg.ID] = false
 			name := agentName(cfg)
+			// #966: la alerta de caída es VOLÁTIL con ID estable por router:
+			// al recuperarse el agente desaparece del feed (no acumula
+			// historial). "Agente recuperado" SÍ persiste (registro positivo).
+			l.engine.Remove("alert-agent-down-" + cfg.ID)
 			l.engine.Emit(AlertEvent{
 				ID:       fmt.Sprintf("alert-agent-ok-%s-%d", cfg.ID, time.Now().UnixMilli()),
 				Category: alerts.CatSystem, Urgent: false,
@@ -456,9 +460,13 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 				// urgente, comparable al offline, para que pase los filtros
 				// de notificación "solo urgentes del topic router". Con SSH
 				// disponible se degrada con gracia y sigue siendo system.
+				// #966: la alerta de caída es VOLÁTIL y con ID estable por
+				// router (alert-agent-down-<id>): no se persiste en
+				// alert_log, no sobrevive reinicios y al recuperarse el
+				// agente desaparece del feed (engine.Remove arriba).
 				if cfg.AgentOnly {
-					l.engine.Emit(AlertEvent{
-						ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
+					l.engine.EmitVolatile(AlertEvent{
+						ID:       "alert-agent-down-" + cfg.ID,
 						Category: alerts.CatRouter, Urgent: true,
 						Severity:    "critical",
 						Title:       fmt.Sprintf("Agente caído en %s", name),
@@ -469,8 +477,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 						Time:        "ahora mismo", RouterID: cfg.ID,
 					})
 				} else {
-					l.engine.Emit(AlertEvent{
-						ID:       fmt.Sprintf("alert-agent-down-%s-%d", cfg.ID, time.Now().UnixMilli()),
+					l.engine.EmitVolatile(AlertEvent{
+						ID:       "alert-agent-down-" + cfg.ID,
 						Category: alerts.CatSystem, Urgent: false,
 						Severity:    "warn",
 						Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),

+ 21 - 0
server-go/internal/adapters/proxmox.go

@@ -107,9 +107,30 @@ func (l *Live) pveClientsCached() []pveInstClient {
 	return l.pveClients
 }
 
+// pveIntegrationKey: toggle server-side de la integración Proxmox (#968).
+// Ausente = activo; "false" = la integración está desactivada y NO se hace
+// ni un solo request al PVE.
+const pveIntegrationKey = "settings.integrations.proxmox"
+
+// pveIntegrationEnabled: lectura por llamada (patrón urgencyGate): el toggle
+// de Ajustes aplica sin reiniciar.
+func (l *Live) pveIntegrationEnabled() bool {
+	if l.db == nil {
+		return true
+	}
+	var v string
+	if err := l.db.QueryRow("SELECT value FROM kv WHERE key = ?", pveIntegrationKey).Scan(&v); err != nil {
+		return true
+	}
+	return v != "false"
+}
+
 // pveInventoryCached: inventario PVE (VM→MAC→node) con TTL. Devuelve nil si
 // no configurado o si la consulta falla (no-op, no rompe el overview).
 func (l *Live) pveInventoryCached() *pveInventory {
+	if !l.pveIntegrationEnabled() {
+		return nil
+	}
 	clients := l.pveClientsCached()
 	if len(clients) == 0 {
 		return nil

+ 76 - 0
server-go/internal/adapters/proxmox_gate_test.go

@@ -0,0 +1,76 @@
+// proxmox_gate_test.go - toggle server-side de la integración Proxmox (#968):
+// con settings.integrations.proxmox="false" el adapter NO hace ni un solo
+// request al PVE; ausente o "true" sondea con normalidad.
+package adapters
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"sync/atomic"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/pve"
+)
+
+func TestPveInventoryGateDropsRequests(t *testing.T) {
+	var hits atomic.Int64
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		hits.Add(1)
+		w.Header().Set("Content-Type", "application/json")
+		switch r.URL.Path {
+		case "/api2/json/cluster/resources":
+			_, _ = w.Write([]byte(`{"data":[{"id":"node/pve1","node":"pve1","type":"node","status":"online"}]}`))
+		case "/api2/json/cluster/status":
+			_, _ = w.Write([]byte(`{"data":[{"type":"node","name":"pve1","ip":"192.0.2.2","online":1}]}`))
+		default:
+			_, _ = w.Write([]byte(`{"data":{}}`))
+		}
+	}))
+	defer srv.Close()
+
+	d := openLiveTestDB(t)
+	cfg := pve.Config{URL: srv.URL, TokenID: "netpulse@pam!t", Secret: "s"}
+	if err := pve.SaveInstances(d.DB, []pve.Instance{{ID: "acasa", Name: "casa", Config: cfg}}); err != nil {
+		t.Fatalf("SaveInstances: %v", err)
+	}
+	l := NewLive(nil, d, nil, nil)
+
+	// Integración OFF: 0 requests aunque haya instancia configurada.
+	if _, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", pveIntegrationKey, "false"); err != nil {
+		t.Fatalf("kv off: %v", err)
+	}
+	if inv := l.pveInventoryCached(); inv != nil {
+		t.Fatalf("gate off: inventario %v, esperado nil", inv)
+	}
+	if n := hits.Load(); n != 0 {
+		t.Fatalf("gate off: %d requests al PVE, esperado 0", n)
+	}
+
+	// Integración ON: sondea (resources + status + lo que pida el inventario).
+	if _, err := d.Exec("UPDATE kv SET value = ? WHERE key = ?", "true", pveIntegrationKey); err != nil {
+		t.Fatalf("kv on: %v", err)
+	}
+	l.pveClients = nil
+	l.pveKey = ""
+	if inv := l.pveInventoryCached(); inv == nil {
+		t.Fatal("gate on: inventario nil, esperado datos")
+	}
+	if n := hits.Load(); n == 0 {
+		t.Fatal("gate on: 0 requests al PVE, esperado sondeo real")
+	}
+}
+
+func TestPveInventoryGateDefaultOn(t *testing.T) {
+	// Clave ausente (instalación previa a #968) = integración activa.
+	d := openLiveTestDB(t)
+	l := NewLive(nil, d, nil, nil)
+	if !l.pveIntegrationEnabled() {
+		t.Fatal("clave ausente: integración desactivada, esperado activa")
+	}
+	if _, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?)", pveIntegrationKey, "false"); err != nil {
+		t.Fatalf("kv off: %v", err)
+	}
+	if l.pveIntegrationEnabled() {
+		t.Fatal("clave false: integración activa, esperado desactivada")
+	}
+}

+ 144 - 10
server-go/internal/alerts/alerts.go

@@ -79,6 +79,11 @@ type AlertEvent struct {
 	// SuppressedBy is the routerId of the parent router whose offline alert
 	// is suppressing this one (issue #332). Empty when not suppressed.
 	SuppressedBy string `json:"suppressedBy,omitempty"`
+	// Volatile (#966): la alerta vive SOLO en memoria (no se persiste en
+	// alert_log ni sobrevive a reinicios) y desaparece del feed cuando su
+	// condicion se resuelve (engine.Remove). Uso: caida de agente, cuya
+	// semantica es "viva por router", no un historico de incidentes.
+	Volatile bool `json:"-"`
 }
 
 // Stable alert-type slugs (issue #310): keys of the Hints map.
@@ -264,11 +269,26 @@ func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
 				}
 			}
 		}
+		e.purgeVolatileHistoryLocked()
 		e.loadPersistedLocked()
 	}
 	return e
 }
 
+// purgeVolatileHistoryLocked: purga one-shot al arrancar (#966). Las alertas
+// de caida de agente AHORA son volatiles (no se persisten), pero las
+// instalaciones previas acumularon un historico de agent-down* en alert_log
+// que seguiria reapareciendo tras cada reinicio. Se borran ANTES de cargar
+// el log, para que ni siquiera el primer arranque tras actualizar lo muestre.
+func (e *Engine) purgeVolatileHistoryLocked() {
+	if e.db == nil || !e.persistLog {
+		return
+	}
+	_, _ = e.db.Exec(
+		`DELETE FROM alert_log WHERE id LIKE 'alert-agent-down-%'
+		   OR type IN ('agent-down', 'agent-down-ssh')`)
+}
+
 // loadPersistedLocked restaura el log desde alert_log (issue #798): los
 // últimos MaxEvents eventos (más recientes primero), reconstruyendo el mapa
 // de dedup (para no re-notificar dentro de la ventana tras un reinicio) y
@@ -454,7 +474,7 @@ func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) boo
 // de verdad del leído es el read-set de kv y se espeja aparte en MarkRead.
 // Best-effort: un fallo de BD nunca debe romper el camino de alertado.
 func (e *Engine) persistLocked(ev AlertEvent) {
-	if e.db == nil || !e.persistLog || ev.ID == "" {
+	if e.db == nil || !e.persistLog || ev.ID == "" || ev.Volatile {
 		return
 	}
 	varsRaw := ""
@@ -597,6 +617,69 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 	return ok
 }
 
+// EmitVolatile (#966): emite una alerta VOLÁTIL (caída de agente): NUNCA se
+// persiste en alert_log y, si ya existe una alerta con el mismo ID, se
+// actualiza en sitio y se mueve al frente (semántica "viva por router": un
+// incidente abierto = una alerta con ID estable). Si quedara una copia
+// persistida antigua con ese ID, se borra. Config, silencio y supresión
+// topológica aplican igual que en Emit; el dedup de 5 min NO aplica (el
+// tracking del incidente vive en el emisor, patrón #846). Devuelve true si
+// el evento pasó la config.
+func (e *Engine) EmitVolatile(ev AlertEvent) bool {
+	ev.Volatile = true
+	e.mu.Lock()
+	if !e.pasaLocked(ev) {
+		e.mu.Unlock()
+		return false
+	}
+	if e.suppression != nil && ev.RouterID != "" {
+		if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
+			ev.SuppressedBy = parent
+		}
+	}
+	now := e.now()
+	if ev.Ts == 0 {
+		ev.Ts = now.Unix()
+	}
+	if ev.Time == "" {
+		ev.Time = "ahora mismo"
+	}
+	replaced := false
+	for i := range e.list {
+		if e.list[i].ID == ev.ID {
+			ev.Read = e.readSet[ev.ID]
+			e.list = append(e.list[:i], e.list[i+1:]...)
+			e.list = append([]AlertEvent{ev}, e.list...)
+			replaced = true
+			break
+		}
+	}
+	if !replaced {
+		// #833: si el ID estaba limpiado y la condición se re-dispara, la
+		// alerta vuelve al feed (igual que en insertaLocked).
+		if _, was := e.dismissed[ev.ID]; was {
+			delete(e.dismissed, ev.ID)
+			e.saveDismissedLocked()
+		}
+		ev.Read = false
+		e.list = append([]AlertEvent{ev}, e.list...)
+		if len(e.list) > MaxEvents {
+			e.list = e.list[:MaxEvents]
+		}
+	}
+	// Defensa en profundidad: ninguna copia persistida de una volátil debe
+	// sobrevivir (la purga de arranque cubre el histórico, esto el presente).
+	if e.db != nil && ev.ID != "" {
+		_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", ev.ID)
+	}
+	n := e.notifier
+	e.mu.Unlock()
+	if n != nil && ev.SuppressedBy == "" {
+		n.Notify(ev)
+	}
+	return true
+}
+
 // Seed inserta un evento histórico (arranque del modo demo) SIN aplicar el
 // filtro de config — el SPEC §5 exige que las 5 canon sobrevivan con los
 // defaults aunque "vpn:none"/"clients:urgent" descartarían 2 en creación —.
@@ -667,7 +750,8 @@ func (e *Engine) UnreadCount() int {
 	return n
 }
 
-// MarkRead marca IDs como leídos (persiste; cap 200 FIFO).
+// MarkRead marca IDs como leídos (persiste; cap 200 FIFO sobre los IDs que
+// ya NO son visibles; una alerta visible leída nunca vuelve a no-leída).
 func (e *Engine) MarkRead(ids ...string) {
 	e.mu.Lock()
 	defer e.mu.Unlock()
@@ -682,13 +766,49 @@ func (e *Engine) MarkRead(ids ...string) {
 			_, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
 		}
 	}
-	for len(e.readOrd) > MaxReadIDs {
-		delete(e.readSet, e.readOrd[0])
-		e.readOrd = e.readOrd[1:]
-	}
+	e.pruneReadOrdLocked()
 	e.saveReadLocked()
 }
 
+// pruneReadOrdLocked poda el FIFO del read-set, PERO sin expulsar IDs que
+// siguen en la lista (#966): con la poda FIFO a ciegas, marcar muchas
+// alertas como leídas podía expulsar del read-set una alerta AÚN VISIBLE,
+// que reaparecía como no leída (el badge volvía a subir tras "marcar todo
+// como leído"). Lo visible leído se queda leído; el cap aplica al resto.
+func (e *Engine) pruneReadOrdLocked() {
+	visible := 0
+	for _, id := range e.readOrd {
+		if e.idInListLocked(id) {
+			visible++
+		}
+	}
+	budget := len(e.readOrd) - visible - MaxReadIDs
+	if budget <= 0 {
+		return
+	}
+	kept := e.readOrd[:0]
+	for _, id := range e.readOrd {
+		if budget > 0 && !e.idInListLocked(id) {
+			delete(e.readSet, id)
+			budget--
+			continue
+		}
+		kept = append(kept, id)
+	}
+	e.readOrd = kept
+}
+
+// idInListLocked: ¿el ID sigue en la lista (potencialmente visible)?
+// Requiere e.mu ya tomado.
+func (e *Engine) idInListLocked(id string) bool {
+	for _, ev := range e.list {
+		if ev.ID == id {
+			return true
+		}
+	}
+	return false
+}
+
 // MarkAllRead marca leídas todas las alertas actuales.
 func (e *Engine) MarkAllRead() {
 	e.mu.Lock()
@@ -728,10 +848,7 @@ func (e *Engine) Dismiss(ids ...string) {
 			_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
 		}
 	}
-	for len(e.readOrd) > MaxReadIDs {
-		delete(e.readSet, e.readOrd[0])
-		e.readOrd = e.readOrd[1:]
-	}
+	e.pruneReadOrdLocked()
 	if changed {
 		e.saveDismissedLocked()
 		e.saveReadLocked()
@@ -745,6 +862,23 @@ 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
+// 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
+// vuelve es el histórico, no el presente).
+func (e *Engine) DismissAll() {
+	e.mu.Lock()
+	ids := make([]string, 0, len(e.list))
+	for _, ev := range e.list {
+		ids = append(ids, ev.ID)
+	}
+	e.mu.Unlock()
+	e.Dismiss(ids...)
+}
+
 // Has informa si un ID de alerta está actualmente en la lista (persistida
 // incluida). Lo usa el agent-outdated check tras un reinicio, cuando el flag
 // en memoria (agentOutdatedAlerted) no sobrevive pero la alerta sí (#833).

+ 144 - 0
server-go/internal/alerts/alerts_volatile_test.go

@@ -0,0 +1,144 @@
+// alerts_volatile_test.go - alertas volátiles (#966): la caída de agente no
+// se persiste, la purga de arranque limpia el histórico agent-down, y la
+// poda del read-set no reactiva alertas visibles.
+package alerts
+
+import (
+	"fmt"
+	"testing"
+	"time"
+)
+
+// alertLogCount: filas de alert_log que casan con el patrón LIKE dado.
+func alertLogCount(t *testing.T, e *Engine, like string) int {
+	t.Helper()
+	var n int
+	if err := e.db.QueryRow("SELECT COUNT(*) FROM alert_log WHERE id LIKE ?", like).Scan(&n); err != nil {
+		t.Fatalf("count alert_log: %v", err)
+	}
+	return n
+}
+
+// 1. La alerta volátil NO se persiste en alert_log (pero sí está en el feed).
+func TestVolatileAlertNotPersisted(t *testing.T) {
+	dir := t.TempDir()
+	e := newPersistTestEngine(t, dir, false)
+	ok := e.EmitVolatile(AlertEvent{
+		ID: "alert-agent-down-rt2", Category: CatSystem, Severity: "warn",
+		Title: "Agente caído en rt2", Type: HintAgentDownSSH, RouterID: "rt2",
+	})
+	if !ok {
+		t.Fatal("EmitVolatile no guardó el evento")
+	}
+	if list := e.List(); len(list) != 1 || list[0].ID != "alert-agent-down-rt2" {
+		t.Fatalf("feed: %+v", list)
+	}
+	if n := alertLogCount(t, e, "%"); n != 0 {
+		t.Fatalf("alert_log: %d filas, esperado 0 (volátil no persiste)", n)
+	}
+}
+
+// 2. Purga one-shot al arrancar: el histórico agent-down* acumulado por
+// versiones previas desaparece; el resto del log se conserva.
+func TestVolatileStartupPurge(t *testing.T) {
+	dir := t.TempDir()
+	e1 := newPersistTestEngine(t, dir, false)
+	now := time.Now().Unix()
+	// Histórico al estilo viejo (IDs con timestamp) + una alerta normal.
+	e1.Emit(AlertEvent{ID: "alert-agent-down-rt2-1717000000000", Category: CatSystem, Severity: "warn", Title: "Agente caído", Type: HintAgentDownSSH, RouterID: "rt2", Ts: now})
+	e1.Emit(AlertEvent{ID: "alert-agent-down-rt3-1717000001000", Category: CatRouter, Urgent: true, Severity: "critical", Title: "Agente caído", Type: HintAgentDown, RouterID: "rt3", Ts: now})
+	e1.Emit(AlertEvent{ID: "keep-me", Category: CatSystem, Severity: "info", Title: "Otra alerta", Ts: now})
+	if n := alertLogCount(t, e1, "alert-agent-down-%"); n != 2 {
+		t.Fatalf("siembra: %d filas agent-down, esperado 2", n)
+	}
+
+	e2 := newPersistTestEngine(t, dir, false)
+	if n := alertLogCount(t, e2, "alert-agent-down-%"); n != 0 {
+		t.Fatalf("purga: %d filas agent-down tras arrancar, esperado 0", n)
+	}
+	list := e2.List()
+	if len(list) != 1 || list[0].ID != "keep-me" {
+		t.Fatalf("feed tras purga: %+v (solo debía quedar keep-me)", list)
+	}
+}
+
+// 3. MarkRead no reactiva: la poda FIFO del read-set (cap 200) no puede
+// expulsar una alerta visible leída (el badge no vuelve a subir).
+func TestMarkReadDoesNotReactivateVisible(t *testing.T) {
+	dir := t.TempDir()
+	e := newPersistTestEngine(t, dir, false)
+	e.Emit(AlertEvent{ID: "live1", Category: CatSystem, Severity: "warn", Title: "visible", Ts: time.Now().Unix()})
+	e.MarkRead("live1")
+	if e.UnreadCount() != 0 {
+		t.Fatal("live1 debía quedar leída")
+	}
+	// 250 IDs ajenos fuerzan la rotación del read-set más allá del cap.
+	junk := make([]string, 0, 250)
+	for i := 0; i < 250; i++ {
+		junk = append(junk, fmt.Sprintf("junk-%d", i))
+	}
+	e.MarkRead(junk...)
+	if e.UnreadCount() != 0 {
+		t.Fatalf("live1 reapareció como no leída tras la poda (unread=%d)", e.UnreadCount())
+	}
+	list := e.List()
+	if len(list) != 1 || !list[0].Read {
+		t.Fatalf("feed: %+v (live1 debía seguir leída)", list)
+	}
+	if !e.readSet["live1"] {
+		t.Fatal("live1 expulsada del read-set estando visible")
+	}
+}
+
+// 4. MarkAllRead sobrevive a un reinicio (read-set persistido en kv).
+func TestMarkAllReadSurvivesRestart(t *testing.T) {
+	dir := t.TempDir()
+	e1 := newPersistTestEngine(t, dir, false)
+	now := time.Now().Unix()
+	for i := 0; i < 3; i++ {
+		e1.Emit(AlertEvent{ID: fmt.Sprintf("a%d", i), Category: CatSystem, Severity: "warn", Title: fmt.Sprintf("t%d", i), Ts: now + int64(i)})
+	}
+	if e1.UnreadCount() != 3 {
+		t.Fatalf("siembra: unread=%d, esperado 3", e1.UnreadCount())
+	}
+	e1.MarkAllRead()
+	if e1.UnreadCount() != 0 {
+		t.Fatalf("tras MarkAllRead: unread=%d", e1.UnreadCount())
+	}
+
+	e2 := newPersistTestEngine(t, dir, false)
+	if n := e2.UnreadCount(); n != 0 {
+		t.Fatalf("tras reinicio: unread=%d, esperado 0", n)
+	}
+}
+
+// 5. La alerta live es volátil: un reemit con el mismo ID no duplica, el
+// Remove al recuperar la saca del feed y un reinicio no la resucita.
+func TestVolatileAlertIsLiveOnly(t *testing.T) {
+	dir := t.TempDir()
+	e1 := newPersistTestEngine(t, dir, false)
+	ev := AlertEvent{
+		ID: "alert-agent-down-rt2", Category: CatSystem, Severity: "warn",
+		Title: "Agente caído en rt2", Type: HintAgentDownSSH, RouterID: "rt2",
+	}
+	e1.EmitVolatile(ev)
+	e1.EmitVolatile(ev) // reemisión con el mismo ID estable
+	if list := e1.List(); len(list) != 1 {
+		t.Fatalf("reemisión duplicó la alerta: %+v", list)
+	}
+
+	// Recuperación: desaparece del feed.
+	e1.Remove("alert-agent-down-rt2")
+	if list := e1.List(); len(list) != 0 {
+		t.Fatalf("tras Remove: %+v (debía quedar vacío)", list)
+	}
+	if e1.UnreadCount() != 0 {
+		t.Fatalf("unread tras Remove: %d", e1.UnreadCount())
+	}
+
+	// Reinicio: no resucita (nunca se persistió).
+	e2 := newPersistTestEngine(t, dir, false)
+	if list := e2.List(); len(list) != 0 {
+		t.Fatalf("tras reinicio: %+v (volátil resucitada)", list)
+	}
+}

+ 48 - 0
server-go/internal/alerts/dismiss_test.go

@@ -57,6 +57,54 @@ func TestDismissPersistsAcrossRestart(t *testing.T) {
 	}
 }
 
+// TestDismissAllEmptiesFeedAndSurvivesReload (issue #971): "Marcar todo como
+// leído" VACÍA el feed - las alertas se descartan, no solo se marcan - y el
+// vaciado sobrevive a un reload (alert_log borrado + dismissed en kv). Las
+// volátiles también salen, pero vuelven si su condición sigue viva.
+func TestDismissAllEmptiesFeedAndSurvivesReload(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	e := New(d, nil)
+	e.Emit(ev("a1", CatSystem, false))
+	e.Emit(ev("a2", CatRouter, true))
+	e.DismissAll()
+	if got := len(e.List()); got != 0 {
+		t.Fatalf("lista tras DismissAll: %d, esperaba 0", got)
+	}
+	if got := e.UnreadCount(); got != 0 {
+		t.Fatalf("unread tras DismissAll: %d, esperaba 0", got)
+	}
+
+	// Motor nuevo sobre la misma DB (reload simulado): el feed NO se repuebla.
+	e2 := New(d, nil)
+	if got := len(e2.List()); got != 0 {
+		t.Fatalf("lista tras reload: %d, esperaba 0 (el histórico no vuelve)", got)
+	}
+
+	// Las volátiles (agent-down) también salen del feed con DismissAll...
+	e2.EmitVolatile(AlertEvent{
+		ID: "alert-agent-down-r1", Category: CatSystem, Severity: "warn",
+		Title: "Agente caído", Type: HintAgentDown, RouterID: "r1",
+	})
+	e2.DismissAll()
+	if got := len(e2.List()); got != 0 {
+		t.Fatalf("lista tras DismissAll con volátil: %d, esperaba 0", got)
+	}
+	// ...pero si la condición se re-evalúa viva, la alerta vuelve (semántica
+	// "alerta viva": lo que no vuelve es el histórico, no el presente).
+	e2.EmitVolatile(AlertEvent{
+		ID: "alert-agent-down-r1", Category: CatSystem, Severity: "warn",
+		Title: "Agente caído", Type: HintAgentDown, RouterID: "r1",
+	})
+	if got := len(e2.List()); got != 1 {
+		t.Fatalf("volátil viva tras re-emitir: %d, esperaba 1", got)
+	}
+}
+
 func TestResolveRemovesAndAllowsImmediateReEmit(t *testing.T) {
 	e := New(nil, nil)
 	e.Emit(ev("a1", CatSystem, false))

+ 9 - 3
server-go/internal/config/config.go

@@ -70,11 +70,14 @@ type Config struct {
 	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
 	// NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
-	// default 3443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
+	// 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
 	// necesita esta variable (#696).
 	TLSEnabled bool
 	TLSPort    int
+	// TLSPortSet (#978): true cuando NETPULSE_TLS_PORT venía en el entorno -
+	// el puerto queda fijado por el env y Ajustes lo muestra bloqueado.
+	TLSPortSet bool
 	TLSCert    string // NETPULSE_TLS_CERT: path del cert del usuario (opcional; junto a TLSKey)
 	TLSKey     string // NETPULSE_TLS_KEY: path de la clave del usuario (opcional; junto a TLSCert)
 	// FORK: HTTPS with the server's own private CA (internal/tlsmode).
@@ -495,15 +498,17 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
-	// NETPULSE_TLS_PORT: int 1..65535, default 3443 (solo relevante si TLS
+	// NETPULSE_TLS_PORT: int 1..65535, default 443 (solo relevante si TLS
 	// está habilitado).
-	tlsPort := 3443
+	tlsPort := 443
+	tlsPortSet := false
 	if v, ok := env["NETPULSE_TLS_PORT"]; ok && v != "" {
 		n, err := strconv.Atoi(strings.TrimSpace(v))
 		if err != nil || n < 1 || n > 65535 {
 			errs.issues = append(errs.issues, issue{"NETPULSE_TLS_PORT", "Expected int 1..65535"})
 		} else {
 			tlsPort = n
+			tlsPortSet = true
 		}
 	}
 
@@ -624,6 +629,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		PollIntervalSec:   pollIntervalSec,
 		TLSEnabled:        tlsEnabled,
 		TLSPort:           tlsPort,
+		TLSPortSet:        tlsPortSet,
 		TLSCert:           tlsCert,
 		TLSKey:            tlsKey,
 		TLSCA:             tlsCA,

+ 4 - 4
server-go/internal/config/config_test.go

@@ -82,8 +82,8 @@ func TestLoadTLSDefaultOff(t *testing.T) {
 	if cfg.TLSEnabled {
 		t.Fatal("TLSEnabled debe ser false por defecto (arranque idéntico al actual)")
 	}
-	if cfg.TLSPort != 3443 {
-		t.Fatalf("TLSPort = %d, esperaba 3443 (default)", cfg.TLSPort)
+	if cfg.TLSPort != 443 {
+		t.Fatalf("TLSPort = %d, esperaba 443 (default)", cfg.TLSPort)
 	}
 	if cfg.TLSCert != "" || cfg.TLSKey != "" {
 		t.Fatalf("TLSCert/Key = %q/%q, esperaba vacíos por defecto", cfg.TLSCert, cfg.TLSKey)
@@ -98,8 +98,8 @@ func TestLoadTLSEnabledDefaultPort(t *testing.T) {
 	if !cfg.TLSEnabled {
 		t.Fatal("TLSEnabled debe ser true con NETPULSE_TLS_ENABLED=1")
 	}
-	if cfg.TLSPort != 3443 {
-		t.Fatalf("TLSPort = %d, esperaba 3443 (default)", cfg.TLSPort)
+	if cfg.TLSPort != 443 {
+		t.Fatalf("TLSPort = %d, esperaba 443 (default)", cfg.TLSPort)
 	}
 }
 

+ 6 - 3
server-go/internal/db/db.go

@@ -92,10 +92,13 @@ CREATE TABLE IF NOT EXISTS metrics_daily (
   cpu_avg REAL, ram_avg REAL, temp_avg REAL,
   lat_avg REAL, rx_avg REAL, tx_avg REAL,
   rx_total REAL, tx_total REAL,
-  -- up_min: minutos de recolección del día (SUM(n) * 5 / 60; n = muestras a
-  -- 5 s → día completo ≈ 17280 muestras ≈ 1440 min).
+  -- up_min: LEGACY (#987). Minutos de recolección asumiendo poll de 5 s
+  -- (SUM(n) * 5 / 60): con cualquier otro intervalo miente (con poll de 30 s
+  -- da 240 min/día). Los informes ya no lo leen; usan up_count.
   up_min INTEGER NOT NULL DEFAULT 0,
-  -- up_count: nº de buckets de 5 min con datos (288 = día completo).
+  -- up_count: nº de buckets de 5 min con datos (288 = día completo). Es la
+  -- base de la disponibilidad de los informes: agnóstica del intervalo de
+  -- poll mientras este sea < 5 min.
   up_count INTEGER NOT NULL DEFAULT 0,
   PRIMARY KEY (router_id, date)
 );

+ 85 - 0
server-go/internal/httpapi/adguard_detect.go

@@ -0,0 +1,85 @@
+// adguard_detect.go - POST /api/config/adguard/detect (#964): autodetección
+// de PRESENCIA de AdGuard Home (no credenciales; el usuario confirma la
+// password después). Sondea :3000/control/status primero en el gateway
+// (mode=glinet, source=gateway) y luego en la flota (mode=standard).
+package httpapi
+
+import (
+	"context"
+	"fmt"
+	"io"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// adguardDetectResponse es la forma JSON del detect: found=false si ningún
+// host de la flota sirve la API de AdGuard Home.
+type adguardDetectResponse struct {
+	Found  bool   `json:"found"`
+	Mode   string `json:"mode,omitempty"`   // "glinet" | "standard"
+	Host   string `json:"host,omitempty"`
+	Port   int    `json:"port,omitempty"`
+	Source string `json:"source,omitempty"` // "gateway" | "fleet"
+}
+
+// adguardStatusProbe pregunta a /control/status de un host (timeout 2s).
+// Variable de paquete para inyectar un fake en tests.
+var adguardStatusProbe = probeAdguardStatus
+
+// probeAdguardStatus detecta PRESENCIA: /control/status responde 200 sin
+// credenciales con un JSON que lleva dns_port/version. Cualquier otra cosa
+// (connection refused, timeout, 404 de otro servidor en :3000) = no está.
+func probeAdguardStatus(ctx context.Context, host string, port int) bool {
+	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+	defer cancel()
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet,
+		fmt.Sprintf("http://%s:%d/control/status", host, port), nil)
+	if err != nil {
+		return false
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return false
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		return false
+	}
+	body, err := io.ReadAll(io.LimitReader(res.Body, 8192))
+	if err != nil {
+		return false
+	}
+	return strings.Contains(string(body), `"dns_port"`) || strings.Contains(string(body), `"version"`)
+}
+
+// handleDetectAdguard: gateway primero (GL.iNet lleva AdGuard Home propio en
+// :3000), luego el resto de la flota en orden. El primer hallazgo gana.
+func (s *server) handleDetectAdguard(w http.ResponseWriter, r *http.Request) {
+	ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
+	defer cancel()
+	routers := routerstore.ListRouters(s.db.DB)
+	const port = 3000
+	for _, pass := range []struct {
+		mode, source string
+		gateway      bool
+	}{
+		{"glinet", "gateway", true},
+		{"standard", "fleet", false},
+	} {
+		for _, rt := range routers {
+			if rt.IsGateway != pass.gateway || rt.Host == "" {
+				continue
+			}
+			if adguardStatusProbe(ctx, rt.Host, port) {
+				writeJSON(w, http.StatusOK, adguardDetectResponse{
+					Found: true, Mode: pass.mode, Host: rt.Host, Port: port, Source: pass.source,
+				})
+				return
+			}
+		}
+	}
+	writeJSON(w, http.StatusOK, adguardDetectResponse{Found: false})
+}

+ 102 - 0
server-go/internal/httpapi/adguard_detect_internal_test.go

@@ -0,0 +1,102 @@
+// adguard_detect_internal_test.go - POST /api/config/adguard/detect (#964):
+// orden de sondeo (gateway primero, luego flota), modos y found=false.
+package httpapi
+
+import (
+	"context"
+	"encoding/json"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// fakeAdguardProbe sustituye el sondeo real y registra el orden de hosts.
+func fakeAdguardProbe(t *testing.T, found map[string]bool, probed *[]string) {
+	t.Helper()
+	old := adguardStatusProbe
+	t.Cleanup(func() { adguardStatusProbe = old })
+	adguardStatusProbe = func(_ context.Context, host string, _ int) bool {
+		*probed = append(*probed, host)
+		return found[host]
+	}
+}
+
+func detectAdguardCall(t *testing.T, s *server) adguardDetectResponse {
+	t.Helper()
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest("POST", "/api/config/adguard/detect", nil)
+	s.handleDetectAdguard(rec, req)
+	if rec.Code != 200 {
+		t.Fatalf("detect: status %d", rec.Code)
+	}
+	var out adguardDetectResponse
+	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+		t.Fatalf("detect json: %v", err)
+	}
+	return out
+}
+
+func TestDetectAdguardGatewayFirst(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "gw", Host: "192.0.2.1", IsGateway: true}); err != nil {
+		t.Fatalf("AddRouter gw: %v", err)
+	}
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "sat", Host: "192.0.2.2"}); err != nil {
+		t.Fatalf("AddRouter sat: %v", err)
+	}
+
+	// AdGuard vive en la flota, no en el gateway: el gateway se sondea
+	// PRIMERO (aunque falle) y el hallazgo es mode=standard, source=fleet.
+	probed := []string{}
+	fakeAdguardProbe(t, map[string]bool{"192.0.2.2": true}, &probed)
+	s := &server{db: d}
+	out := detectAdguardCall(t, s)
+	if !out.Found || out.Mode != "standard" || out.Host != "192.0.2.2" || out.Port != 3000 || out.Source != "fleet" {
+		t.Fatalf("respuesta: %+v", out)
+	}
+	if len(probed) < 2 || probed[0] != "192.0.2.1" {
+		t.Fatalf("orden de sondeo: %v (gateway primero)", probed)
+	}
+}
+
+func TestDetectAdguardGatewayHit(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "gw", Host: "192.0.2.1", IsGateway: true}); err != nil {
+		t.Fatalf("AddRouter gw: %v", err)
+	}
+	probed := []string{}
+	fakeAdguardProbe(t, map[string]bool{"192.0.2.1": true}, &probed)
+	s := &server{db: d}
+	out := detectAdguardCall(t, s)
+	if !out.Found || out.Mode != "glinet" || out.Host != "192.0.2.1" || out.Source != "gateway" {
+		t.Fatalf("respuesta: %+v", out)
+	}
+}
+
+func TestDetectAdguardNotFound(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "gw", Host: "192.0.2.1", IsGateway: true}); err != nil {
+		t.Fatalf("AddRouter gw: %v", err)
+	}
+	probed := []string{}
+	fakeAdguardProbe(t, map[string]bool{}, &probed)
+	s := &server{db: d}
+	out := detectAdguardCall(t, s)
+	if out.Found {
+		t.Fatalf("respuesta: %+v, esperado found=false", out)
+	}
+}

+ 24 - 1
server-go/internal/httpapi/alerts_api_test.go

@@ -220,8 +220,31 @@ func TestAlertsDismissEndpoint(t *testing.T) {
 	}
 }
 
+// POST /api/alerts/clear (issue #971): "Marcar todo como leído" VACÍA el
+// feed - las alertas se descartan, no solo se marcan - y el badge queda a 0.
+func TestAlertsClearAllEndpoint(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := doJSON(t, "POST", ts.URL, "/api/alerts/clear", cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("clear: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
+	if len(items) != 0 {
+		t.Fatalf("feed tras clear: %d, esperaba 0", len(items))
+	}
+	body := readJSON(t, get(t, ts.URL, "/api/overview", cookie))
+	if got := body["unreadAlerts"].(float64); got != 0 {
+		t.Fatalf("unreadAlerts tras clear: %v, esperaba 0", got)
+	}
+}
+
 // writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
-func TestAlertsNoTrailingNewline(t *testing.T) {	ts := makeTestServer(t)
+func TestAlertsNoTrailingNewline(t *testing.T) {
+	ts := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	res := get(t, ts.URL, "/api/alerts/config", cookie)
 	defer res.Body.Close()

+ 90 - 27
server-go/internal/httpapi/availability_test.go

@@ -53,8 +53,8 @@ func TestAvailabilityDayAgrupaPorDia(t *testing.T) {
 	// y hacían el test flaky según el calendario).
 	dayBefore := time.Now().UTC().AddDate(0, 0, -2).Format("2006-01-02")
 	yesterday := time.Now().UTC().AddDate(0, 0, -1).Format("2006-01-02")
-	insertDaily(t, ts, "gw", yesterday, 17280, sqlNull{true, 1.0}, 1e8, 5e7, 20, 60) // día completo
-	insertDaily(t, ts, "gw", dayBefore, 8640, sqlNull{true, 2.0}, 1e8, 5e7, 20, 60)  // medio día
+	insertDaily(t, ts, "gw", yesterday, 17280, 288, sqlNull{true, 1.0}, 1e8, 5e7, 20, 60) // día completo
+	insertDaily(t, ts, "gw", dayBefore, 8640, 144, sqlNull{true, 2.0}, 1e8, 5e7, 20, 60)  // medio día
 
 	status, items := getAvailability(t, ts, "?range=day&n=30")
 	if status != http.StatusOK {
@@ -74,7 +74,7 @@ func TestAvailabilityDayAgrupaPorDia(t *testing.T) {
 	if byDate[yesterday].UpPct < 99.9 {
 		t.Fatalf("día completo upPct=%v, esperaba ~100", byDate[yesterday].UpPct)
 	}
-	// El otro día es pasado completo → 8640 muestras = 720 min de 1440 → 50%.
+	// El otro día es pasado completo → 144 buckets = 720 min de 1440 → 50%.
 	if byDate[dayBefore].UpPct < 49.9 || byDate[dayBefore].UpPct > 50.1 {
 		t.Fatalf("medio día pasado upPct=%v, esperaba ~50", byDate[dayBefore].UpPct)
 	}
@@ -84,9 +84,9 @@ func TestAvailabilityDayAgrupaPorDia(t *testing.T) {
 func TestAvailabilityMonthAgrupaPorMes(t *testing.T) {
 	ts := makeTestServer(t)
 	// Tres días de 2026-07 para el mismo router → un bucket "2026-07".
-	insertDaily(t, ts, "gw", "2026-07-10", 17280, sqlNull{false, 0}, 0, 0, 20, 60)
-	insertDaily(t, ts, "gw", "2026-07-11", 17280, sqlNull{false, 0}, 0, 0, 20, 60)
-	insertDaily(t, ts, "gw", "2026-07-12", 17280, sqlNull{false, 0}, 0, 0, 20, 60)
+	insertDaily(t, ts, "gw", "2026-07-10", 17280, 288, sqlNull{false, 0}, 0, 0, 20, 60)
+	insertDaily(t, ts, "gw", "2026-07-11", 17280, 288, sqlNull{false, 0}, 0, 0, 20, 60)
+	insertDaily(t, ts, "gw", "2026-07-12", 17280, 288, sqlNull{false, 0}, 0, 0, 20, 60)
 
 	status, items := getAvailability(t, ts, "?range=month&n=12")
 	if status != http.StatusOK {
@@ -114,7 +114,7 @@ func TestAvailabilityWeekIgualQueWeekly(t *testing.T) {
 	// Usar una fecha dentro de las ultimas 4 semanas para que weekly?weeks=4
 	// la incluya independientemente de la fecha actual en CI.
 	date := time.Now().UTC().AddDate(0, 0, -7).Format("2006-01-02")
-	insertDaily(t, ts, "gw", date, 17280, sqlNull{true, 1.2}, 1e8, 5e7, 20, 60)
+	insertDaily(t, ts, "gw", date, 17280, 288, sqlNull{true, 1.2}, 1e8, 5e7, 20, 60)
 
 	_, wItems := getWeekly(t, ts, "4")
 	_, aItems := getAvailability(t, ts, "?range=week&n=4")
@@ -127,15 +127,39 @@ func TestAvailabilityWeekIgualQueWeekly(t *testing.T) {
 	}
 }
 
-// TestAvailabilityDayActualNoPenaliza: el día de hoy con datos parciales se
-// normaliza por los minutos transcurridos, no por 1440.
+// insertRaw siembra muestras raw del router r: una al inicio de cada uno de
+// los primeros nBuckets buckets de 5 min del día UTC de hoy. El día en curso
+// se mide del raw (el daily llega con el rollup nocturno, #987).
+func insertRaw(t *testing.T, ts *testServer, routerID string, nBuckets int) {
+	t.Helper()
+	now := time.Now().UTC()
+	midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
+	for i := 0; i < nBuckets; i++ {
+		tsMs := midnight.Add(time.Duration(i) * 5 * time.Minute).UnixMilli()
+		_, err := ts.db.Exec(
+			"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES (?,?,?,?,?,?,?,?)",
+			routerID, tsMs, 20, 60, 40, 1.5, 1e6, 5e5)
+		if err != nil {
+			t.Fatalf("insert raw %s: %v", routerID, err)
+		}
+	}
+}
+
+// TestAvailabilityDayActualNoPenaliza: el día de hoy se mide del raw (el
+// daily llega con el rollup nocturno y marcaría el día como caído) y se
+// normaliza por los minutos transcurridos, no por 1440. Un router online
+// desde medianoche da ~100% hoy, sin downtime inventado (#987).
 func TestAvailabilityDayActualNoPenaliza(t *testing.T) {
 	ts := makeTestServer(t)
-	today := time.Now().UTC().Format("2006-01-02")
-	// 360 min de recolección hoy (medio día "de trabajo"). Si el divisor fuera
-	// 1440, daría 25% (parece caído). Con minutos transcurridos, refleja la
-	// cobertura real hasta ahora.
-	insertDaily(t, ts, "gw", today, 360*12, sqlNull{false, 0}, 0, 0, 20, 60) // 360 min = 4320 muestras
+	now := time.Now().UTC()
+	today := now.Format("2006-01-02")
+	nowMin := now.Hour()*60 + now.Minute()
+	if nowMin == 0 {
+		t.Skip("medianoche UTC: el día en curso aún no tiene minutos que medir")
+	}
+	// Cobertura continua desde medianoche hasta ahora: una muestra al inicio
+	// de cada bucket de 5 min transcurrido (un router online 24/7, #987).
+	insertRaw(t, ts, "gw", nowMin/5+1)
 
 	_, items := getAvailability(t, ts, "?range=day&n=5")
 	var today_ *availabilityEntry
@@ -147,22 +171,61 @@ func TestAvailabilityDayActualNoPenaliza(t *testing.T) {
 	if today_ == nil {
 		t.Fatalf("no se devolvió fila para hoy %q: %+v", today, items)
 	}
-	nowMin := time.Now().UTC().Hour()*60 + time.Now().UTC().Minute()
-	want := float64(today_.UpMin) / float64(nowMin) * 100
-	if nowMin == 0 {
-		want = 100 // evitar div/0 a medianoche
+	// Cobertura continua → upMin = minutos transcurridos (el bucket actual
+	// parcial se tope al divisor) y upPct = 100, no un día "caído". Margen de
+	// ±1 min por si el reloj cruza un minuto entre test y handler.
+	if today_.UpMin < int64(nowMin)-1 || today_.UpMin > int64(nowMin)+1 {
+		t.Fatalf("día actual upMin=%d, esperaba ~%d (minutos transcurridos)", today_.UpMin, nowMin)
+	}
+	if today_.UpPct < 99.9 || today_.UpPct > 100.1 {
+		t.Fatalf("día actual upPct=%v, esperaba ~100 (router online, #987)", today_.UpPct)
+	}
+}
+
+// TestAvailabilityAgenteOnlineNoInventaDowntime (#987): un router sondeado
+// cada 30 s (poll real de prod) o que reporta por agente tiene una n diaria
+// muy inferior a las 17280 muestras del poll de 5 s. La fórmula vieja
+// (n * 5 s) lo marcaba como caído el 83% del tiempo (17 días fantasma en 4
+// semanas). Con la semántica de buckets (up_count) una semana completa con
+// datos da ~100% y cero downtime inventado.
+func TestAvailabilityAgenteOnlineNoInventaDowntime(t *testing.T) {
+	ts := makeTestServer(t)
+	// 7 días completos la semana pasada con poll de 30 s: n = 2880 muestras
+	// (la fórmula vieja daba upMin = 240 → upPct 16,7%), up_count = 288
+	// buckets (día completo con datos).
+	monday := mondayOf(time.Now().UTC()).AddDate(0, 0, -7)
+	for i := 0; i < 7; i++ {
+		date := monday.AddDate(0, 0, i).Format("2006-01-02")
+		insertDaily(t, ts, "agent1", date, 2880, 288, sqlNull{true, 2.0}, 1e8, 5e7, 20, 60)
 	}
-	// El endpoint clamp a 100 (mismo tope que el report semanal, #207): si
-	// nowMin < upMin el ratio bruto excede 100 y el clamp lo lleva a 100.
-	if want > 100 {
-		want = 100
+
+	status, items := getAvailability(t, ts, "?range=week&n=4")
+	if status != http.StatusOK {
+		t.Fatalf("status %d, esperaba 200", status)
+	}
+	if len(items) != 1 {
+		t.Fatalf("items = %d, esperaba 1 (una semana): %+v", len(items), items)
+	}
+	if items[0].UpMin != 7*1440 {
+		t.Fatalf("upMin = %d, esperaba %d (semana completa con datos)", items[0].UpMin, 7*1440)
+	}
+	if items[0].UpPct < 99.9 {
+		t.Fatalf("upPct = %v, esperaba ~100: un router online no puede salir caído (#987)", items[0].UpPct)
+	}
+
+	// El endpoint weekly (API/CSV) aplica la misma semántica.
+	_, wItems := getWeekly(t, ts, "4")
+	var w *weeklyReportEntry
+	for i := range wItems {
+		if wItems[i].RouterID == "agent1" {
+			w = &wItems[i]
+		}
 	}
-	if today_.UpPct < want-0.5 || today_.UpPct > want+0.5 {
-		t.Fatalf("día actual upPct=%v, esperaba ~%.1f (upMin=%d / nowMin=%d)", today_.UpPct, want, today_.UpMin, nowMin)
+	if w == nil {
+		t.Fatalf("weekly sin fila para agent1: %+v", wItems)
 	}
-	// Y no debe verse como "caído": si ahora mismo hay cobertura, upPct cerca del 100%.
-	if today_.UpPct > 100.1 {
-		t.Fatalf("upPct > 100 sin tope: %v", today_.UpPct)
+	if w.UpPct < 99.9 {
+		t.Fatalf("weekly upPct = %v, esperaba ~100 (#987)", w.UpPct)
 	}
 }
 

+ 2 - 0
server-go/internal/httpapi/config.go

@@ -40,10 +40,12 @@ func (s *server) registerConfigRoutes(mux *http.ServeMux) {
 	mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
 	mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
 	mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
+	mux.Handle("POST /api/config/adguard/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectAdguard)))
 	mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
 	mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
 	mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
 	mux.Handle("POST /api/config/proxmox/test", auth.RequireAdmin(http.HandlerFunc(s.handleTestProxmoxConfig)))
+	mux.Handle("POST /api/config/proxmox/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectProxmox)))
 }
 
 // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).

+ 11 - 0
server-go/internal/httpapi/data.go

@@ -348,6 +348,17 @@ 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.
+func (s *server) handleAlertsClear(w http.ResponseWriter, _ *http.Request) {
+	s.adapter.AlertsEngine().DismissAll()
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
 // handleAlertsDismiss (POST): body {"ids":["a","b"]} → limpia alertas del
 // feed (issue #833). Las elimina del log y no reaparecen tras un reinicio;
 // si la condición se re-dispara, la alerta vuelve con el mismo ID.

+ 22 - 1
server-go/internal/httpapi/https_settings.go

@@ -176,11 +176,12 @@ func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Enabled  *bool   `json:"enabled"`
 		Mode     *string `json:"mode"`
+		Port     *int    `json:"port"`
 		Force    bool    `json:"force"`
 		Password string  `json:"password"`
 	}
 	if st := readJSONBody(w, r, &body); st != 0 {
-		writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "password" }`)
+		writeBodyError(w, st, "invalid_input", `expected { "enabled"?, "mode"?, "port"?, "password" }`)
 		return
 	}
 	// Counted as sign-in attempts: a stolen session must not be a way to
@@ -213,6 +214,26 @@ func (s *server) handleHTTPSChange(w http.ResponseWriter, r *http.Request) {
 			return
 		}
 	}
+	// Puerto HTTPS (#978): cambiarlo reconecta el listener al momento. Los
+	// agentes que ya reportan por HTTPS apuntan al puerto viejo y no tienen
+	// vuelta solos: mismo aviso que al desactivar, salvo force.
+	if body.Port != nil && *body.Port != s.tlsMgr.Status().Port {
+		httpsPort := *body.Port
+		if !body.Force && s.tlsMgr.Enabled() {
+			if moved := s.agentsByTransport(true); len(moved) > 0 {
+				writeJSON(w, http.StatusConflict, map[string]any{
+					"error":   "agents_on_https",
+					"message": "these agents report over HTTPS on the current port and would stop reporting",
+					"agents":  moved,
+				})
+				return
+			}
+		}
+		if err := s.tlsMgr.SetPort(httpsPort, by); err != nil {
+			writeHTTPSError(w, err)
+			return
+		}
+	}
 	resp := map[string]any{}
 	if body.Mode != nil {
 		mode, err := tlsmode.ParseMode(*body.Mode)

+ 6 - 2
server-go/internal/httpapi/mqtt_settings.go

@@ -46,7 +46,9 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
 			return
 		}
 		var body struct {
-			Enabled     bool   `json:"enabled"`
+			// Enabled es puntero (#968): un PUT parcial que solo toca otro
+			// campo (p.ej. host) NO debe apagar el publisher por accidente.
+			Enabled     *bool  `json:"enabled"`
 			Host        string `json:"host"`
 			Port        int    `json:"port"`
 			User        string `json:"user"`
@@ -58,7 +60,9 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager) {
 			return
 		}
 		cfg := mgr.Config()
-		cfg.Enabled = body.Enabled
+		if body.Enabled != nil {
+			cfg.Enabled = *body.Enabled
+		}
 		if body.Host != "" {
 			cfg.Host = body.Host
 		}

+ 39 - 0
server-go/internal/httpapi/presence.go

@@ -19,6 +19,11 @@ import (
 
 const presenceRetentionKey = "presence.retention_days"
 
+// historyLimitKey (#975): interruptor maestro de la poda del historial.
+// ON por defecto (ausente = limitar); OFF = retención ilimitada: el loop de
+// poda de main no borra nada aunque presence.retention_days tenga valor.
+const historyLimitKey = "history.limit_enabled"
+
 // handleDevicePresence devuelve los tramos de presencia de una MAC (dias
 // visibles, default 7, máx 30) más los eventos recientes y el nº de
 // conexiones en las últimas 24 h. En demo devuelve una muestra sintética
@@ -147,6 +152,40 @@ func PresenceRetentionDays(db *sql.DB) int {
 	return 30
 }
 
+// HistoryLimitEnabled lee el interruptor maestro de la poda (#975): default
+// ON (solo un "0" explícito lo desactiva). Lo usa el loop de poda de main.
+func HistoryLimitEnabled(db *sql.DB) bool {
+	return kvGet(db, historyLimitKey) != "0"
+}
+
+// handleHistoryLimitGet/Put exponen el interruptor maestro «Limitar
+// historial» (#975). OFF = sin poda de presencia/itinerancia (retención
+// ilimitada); el intervalo de ingesta (roam.collect.interval_sec) es
+// independiente y sigue aplicando con el límite desactivado.
+func (s *server) handleHistoryLimitGet(w http.ResponseWriter, _ *http.Request) {
+	writeJSON(w, http.StatusOK, map[string]any{"enabled": HistoryLimitEnabled(s.db.DB)})
+}
+
+func (s *server) handleHistoryLimitPut(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Enabled bool `json:"enabled"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	v := "1"
+	if !body.Enabled {
+		v = "0"
+	}
+	if _, err := s.db.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		historyLimitKey, v); err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"enabled": body.Enabled})
+}
+
 // presenceRetentionDays es la variante del server para el handler de settings.
 func (s *server) presenceRetentionDays() int {
 	return PresenceRetentionDays(s.db.DB)

+ 46 - 0
server-go/internal/httpapi/presence_api_test.go

@@ -9,6 +9,7 @@ import (
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
 )
 
 // TestDevicePresence devuelve los tramos fusionados de una MAC con eventos
@@ -104,6 +105,51 @@ func TestPresenceSettingsRoundtrip(t *testing.T) {
 	}
 }
 
+// TestHistoryLimitRoundtrip (#975): el interruptor maestro de la poda nace
+// ON (ausente = limitar), PUT false lo persiste y GET lo devuelve.
+func TestHistoryLimitRoundtrip(t *testing.T) {
+	ts := makeDeviceActionsTestServer(t, nil)
+	defer ts.Server.Close()
+
+	get := func() bool {
+		resp := deviceReq(t, "GET", ts.Server.URL, "/api/settings/history-limit", ts.cookie, "")
+		defer resp.Body.Close()
+		var body struct {
+			Enabled bool `json:"enabled"`
+		}
+		if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
+			t.Fatalf("decode: %v", err)
+		}
+		return body.Enabled
+	}
+	if !get() {
+		t.Fatal("history-limit debe nacer activado (default ON)")
+	}
+
+	resp := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/history-limit", ts.cookie, `{"enabled":false}`)
+	defer resp.Body.Close()
+	io.Copy(io.Discard, resp.Body)
+	if resp.StatusCode != 200 {
+		t.Fatalf("PUT history-limit: %d, want 200", resp.StatusCode)
+	}
+	if get() {
+		t.Fatal("history-limit debe quedar desactivado tras PUT enabled=false")
+	}
+	if httpapi.HistoryLimitEnabled(ts.db.DB) {
+		t.Fatal("HistoryLimitEnabled debe ser false con kv history.limit_enabled=0")
+	}
+
+	resp2 := deviceReq(t, "PUT", ts.Server.URL, "/api/settings/history-limit", ts.cookie, `{"enabled":true}`)
+	defer resp2.Body.Close()
+	io.Copy(io.Discard, resp2.Body)
+	if resp2.StatusCode != 200 {
+		t.Fatalf("PUT history-limit ON: %d, want 200", resp2.StatusCode)
+	}
+	if !get() {
+		t.Fatal("history-limit debe reactivarse tras PUT enabled=true")
+	}
+}
+
 // TestPresenceRoaming lista las MACs con más de un connect en 24 h.
 func TestPresenceRoaming(t *testing.T) {
 	ts := makeDeviceActionsTestServer(t, nil)

+ 143 - 0
server-go/internal/httpapi/proxmox_detect.go

@@ -0,0 +1,143 @@
+// proxmox_detect.go - POST /api/config/proxmox/detect (#967): descubrimiento
+// de hosts Proxmox VE en la /24 de los hosts configurados en `routers`.
+//
+// DOS FASES, y el orden importa: pveproxy LIMITA las conexiones simultaneas
+// por IP de origen, así que un barrido TLS paralelo mata TODAS las conexiones
+// (context deadline exceeded incluso contra hosts sanos). Por eso:
+//   - Fase 1: TCP connect masivo al :8006 (64 workers, 400ms) para filtrar
+//     los que aceptan el puerto (RST instantaneo o timeout ARP de 400ms).
+//   - Fase 2: confirmacion TLS GET /api2/json/version EN SERIE (5s), valida
+//     si el header Server es "pve-api-daemon" o el body contiene "pve".
+package httpapi
+
+import (
+	"context"
+	"crypto/tls"
+	"fmt"
+	"io"
+	"net"
+	"net/http"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// proxmoxDetectResponse es la forma JSON del detect: la lista de hosts
+// confirmados como PVE (puede estar vacia).
+type proxmoxDetectResponse struct {
+	Found bool     `json:"found"`
+	Hosts []string `json:"hosts"`
+}
+
+// Constantes del barrido (#967): los valores vienen de la validacion en vivo
+// (fase 1 ~1,6s por /24; fase 2 una conexion cada vez, siempre).
+const (
+	pveDetectPort        = 8006
+	pveDetectTCPWorkers  = 64
+	pveDetectTCPTimeout  = 400 * time.Millisecond
+	pveDetectTLSTimeout  = 5 * time.Second
+	pveDetectOverallCap  = 3 * time.Minute
+	pveDetectTLSMaxBytes = 8192
+)
+
+// Sondas inyectables en tests.
+var (
+	pveTCPProbe   = tcpAcceptsPVE
+	pveTLSConfirm = confirmPVEHost
+)
+
+// tcpAcceptsPVE: el host acepta TCP en el puerto (fase 1, barata y paralela).
+func tcpAcceptsPVE(host string, port int, timeout time.Duration) bool {
+	d := net.Dialer{Timeout: timeout}
+	conn, err := d.Dial("tcp", net.JoinHostPort(host, fmt.Sprintf("%d", port)))
+	if err != nil {
+		return false
+	}
+	_ = conn.Close()
+	return true
+}
+
+// confirmPVEHost: GET TLS /api2/json/version (fase 2, EN SERIE). Valido si
+// el header Server es "pve-api-daemon" o el body contiene "pve". El cert es
+// autofirmado en cualquier PVE real (mismo criterio que pve.NewClient).
+func confirmPVEHost(host string, port int, timeout time.Duration) bool {
+	tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} // #561
+	client := &http.Client{Transport: tr, Timeout: timeout}
+	res, err := client.Get(fmt.Sprintf("https://%s/api2/json/version", net.JoinHostPort(host, fmt.Sprintf("%d", port))))
+	if err != nil {
+		return false
+	}
+	defer res.Body.Close()
+	if strings.Contains(res.Header.Get("Server"), "pve-api-daemon") {
+		return true
+	}
+	body, err := io.ReadAll(io.LimitReader(res.Body, pveDetectTLSMaxBytes))
+	if err != nil {
+		return false
+	}
+	return strings.Contains(string(body), "pve")
+}
+
+// scanSubnetPVE: fase 1 - TCP connect masivo a toda la /24 en el puerto PVE.
+func scanSubnetPVE(subnet string) []string {
+	jobs := make(chan string)
+	var mu sync.Mutex
+	found := []string{}
+	var wg sync.WaitGroup
+	for w := 0; w < pveDetectTCPWorkers; w++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			for ip := range jobs {
+				if pveTCPProbe(ip, pveDetectPort, pveDetectTCPTimeout) {
+					mu.Lock()
+					found = append(found, ip)
+					mu.Unlock()
+				}
+			}
+		}()
+	}
+	for i := 1; i <= 254; i++ {
+		jobs <- fmt.Sprintf("%s.%d", subnet, i)
+	}
+	close(jobs)
+	wg.Wait()
+	sort.Strings(found)
+	return found
+}
+
+// handleDetectProxmox: escanea la /24 de cada host configurado en `routers`
+// y devuelve los hosts confirmados como Proxmox VE.
+func (s *server) handleDetectProxmox(w http.ResponseWriter, r *http.Request) {
+	ctx, cancel := context.WithTimeout(r.Context(), pveDetectOverallCap)
+	defer cancel()
+	subnets := map[string]bool{}
+	for _, rt := range routerstore.ListRouters(s.db.DB) {
+		ip := net.ParseIP(strings.TrimSpace(rt.Host))
+		if ip == nil || ip.To4() == nil {
+			continue
+		}
+		v4 := ip.To4()
+		subnets[fmt.Sprintf("%d.%d.%d", v4[0], v4[1], v4[2])] = true
+	}
+	confirmed := []string{}
+	for subnet := range subnets {
+		if ctx.Err() != nil {
+			break
+		}
+		for _, ip := range scanSubnetPVE(subnet) {
+			if ctx.Err() != nil {
+				break
+			}
+			// Fase 2 EN SERIE: pveproxy muere con TLS paralelo (ver cabecera).
+			if pveTLSConfirm(ip, pveDetectPort, pveDetectTLSTimeout) {
+				confirmed = append(confirmed, ip)
+			}
+		}
+	}
+	sort.Strings(confirmed)
+	writeJSON(w, http.StatusOK, proxmoxDetectResponse{Found: len(confirmed) > 0, Hosts: confirmed})
+}

+ 148 - 0
server-go/internal/httpapi/proxmox_detect_internal_test.go

@@ -0,0 +1,148 @@
+// proxmox_detect_internal_test.go - POST /api/config/proxmox/detect (#967):
+// barrido en dos fases (TCP masivo + confirmacion TLS EN SERIE) sobre la /24
+// de los hosts de `routers`, y validacion de la sonda TLS real.
+package httpapi
+
+import (
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"strconv"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// TestDetectProxmoxTwoPhase: fase 1 barre la /24 entera en TCP; fase 2
+// confirma TLS EN SERIE (concurrencia maxima 1, causa raiz del bug en vivo:
+// pveproxy limita conexiones simultaneas por IP).
+func TestDetectProxmoxTwoPhase(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	if _, err := routerstore.AddRouter(d.DB, routerstore.AddInput{Name: "gw", Host: "192.0.2.1", IsGateway: true}); err != nil {
+		t.Fatalf("AddRouter: %v", err)
+	}
+
+	var tcpCalls atomic.Int64
+	oldTCP := pveTCPProbe
+	t.Cleanup(func() { pveTCPProbe = oldTCP })
+	pveTCPProbe = func(host string, _ int, _ time.Duration) bool {
+		tcpCalls.Add(1)
+		// Dos candidatos abiertos en la /24: .100 (confirma) y .200 (no).
+		return host == "192.0.2.100" || host == "192.0.2.200"
+	}
+
+	var concurrent, maxConcurrent atomic.Int64
+	confirmed := []string{}
+	var mu sync.Mutex
+	oldTLS := pveTLSConfirm
+	t.Cleanup(func() { pveTLSConfirm = oldTLS })
+	pveTLSConfirm = func(host string, _ int, _ time.Duration) bool {
+		n := concurrent.Add(1)
+		for {
+			m := maxConcurrent.Load()
+			if n <= m || maxConcurrent.CompareAndSwap(m, n) {
+				break
+			}
+		}
+		defer concurrent.Add(-1)
+		time.Sleep(5 * time.Millisecond) // solape visible si hubiera paralelismo
+		mu.Lock()
+		confirmed = append(confirmed, host)
+		mu.Unlock()
+		return host == "192.0.2.100"
+	}
+
+	s := &server{db: d}
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest("POST", "/api/config/proxmox/detect", nil)
+	s.handleDetectProxmox(rec, req)
+	if rec.Code != 200 {
+		t.Fatalf("detect: status %d", rec.Code)
+	}
+	var out proxmoxDetectResponse
+	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+		t.Fatalf("detect json: %v", err)
+	}
+	if !out.Found || len(out.Hosts) != 1 || out.Hosts[0] != "192.0.2.100" {
+		t.Fatalf("respuesta: %+v", out)
+	}
+	if n := tcpCalls.Load(); n != 254 {
+		t.Fatalf("fase 1: %d sondeos TCP, esperado 254 (/24 completa)", n)
+	}
+	if m := maxConcurrent.Load(); m != 1 {
+		t.Fatalf("fase 2: concurrencia maxima %d, esperado 1 (serie estricta)", m)
+	}
+	if len(confirmed) != 2 {
+		t.Fatalf("fase 2: %d confirmaciones, esperado 2 candidatos", len(confirmed))
+	}
+}
+
+// TestConfirmPVEHost: la sonda TLS real acepta header Server pve-api-daemon
+// o un body con "pve", y rechaza cualquier otro servicio TLS en :8006.
+func TestConfirmPVEHost(t *testing.T) {
+	hostPort := func(t *testing.T, h http.Handler) (string, int) {
+		t.Helper()
+		srv := httptest.NewTLSServer(h)
+		t.Cleanup(srv.Close)
+		parts := strings.Split(strings.TrimPrefix(srv.URL, "https://"), ":")
+		port, err := strconv.Atoi(parts[1])
+		if err != nil {
+			t.Fatalf("port: %v", err)
+		}
+		return parts[0], port
+	}
+
+	// Body con "pve" (version API real).
+	h, p := hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		_, _ = w.Write([]byte(`{"data":{"version":"8.2.4","release":"pve","repoid":"2"}}`))
+	}))
+	if !confirmPVEHost(h, p, 3*time.Second) {
+		t.Fatal("body pve: no confirmado")
+	}
+
+	// Sin body pve pero con header Server pve-api-daemon.
+	h, p = hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		w.Header().Set("Server", "pve-api-daemon/3.10.8")
+		_, _ = w.Write([]byte(`{"data":null}`))
+	}))
+	if !confirmPVEHost(h, p, 3*time.Second) {
+		t.Fatal("header pve-api-daemon: no confirmado")
+	}
+
+	// Otro servicio TLS cualquiera: no es PVE.
+	h, p = hostPort(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		_, _ = w.Write([]byte(`<html>router admin</html>`))
+	}))
+	if confirmPVEHost(h, p, 3*time.Second) {
+		t.Fatal("servicio ajeno: confirmado como PVE")
+	}
+}
+
+// TestDetectProxmoxNoRouters: sin hosts IPv4 configurados, found=false.
+func TestDetectProxmoxNoRouters(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	s := &server{db: d}
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest("POST", "/api/config/proxmox/detect", nil)
+	s.handleDetectProxmox(rec, req)
+	var out proxmoxDetectResponse
+	if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+		t.Fatalf("detect json: %v", err)
+	}
+	if out.Found || len(out.Hosts) != 0 {
+		t.Fatalf("respuesta: %+v, esperado found=false", out)
+	}
+}

+ 201 - 66
server-go/internal/httpapi/reports.go

@@ -1,20 +1,28 @@
-// reports.go — GET /api/reports/weekly: informe de disponibilidad semanal.
-// Calculado de metrics_daily (rollup nocturno de Fase 8.3): un daily por
-// router y día con el nº de muestras recolectadas (n), medias de
-// latencia/cpu/ram y totales de tráfico. El corte temporal (semana ISO
-// lunes-domingo) se normaliza aquí para que el frontend no haga aritmética
-// de fechas.
+// reports.go - GET /api/reports/weekly y GET /api/reports/availability:
+// informes de disponibilidad por router.
 //
-// Semántica de disponibilidad (verificada contra datos reales de prod):
-//   - `n` = suma de muestras del día (poll de 5 s; día completo ≈ 17280).
-//   - minutos de recolección = n * 5 / 60.
-//   - upPct = minutos / (días con datos * 1440), clavado a 100 (issue #207):
-//     un bucket sobre-poblado (más muestras que minutos) no puede superar el
-//     100%, igual que availability. La semana en curso queda parcial y se
-//     normaliza solo sobre los días que tienen datos.
-//   - `up_count` del daily NO es fiable como base (es COUNT(*) de filas
-//     bucket, que en prod coincide con muestras porque el rollup no agrega);
-//     `up_min` del daily es MIN(min_ts) (timestamp), no minutos.
+// Calculados de metrics_daily (rollup nocturno de Fase 8.3) más el raw del
+// día en curso. El corte temporal (semana ISO lunes-domingo) se normaliza
+// aquí para que el frontend no haga aritmética de fechas.
+//
+// Semántica de disponibilidad (issue #987, verificada con datos reales de
+// prod):
+//   - Base: buckets de 5 min con al menos una muestra (metrics_daily.up_count;
+//     288 = día completo). Es agnóstica del intervalo de poll: la fórmula
+//     vieja (SUM(n) * 5 s) asumía poll de 5 s y, con el poll real de 30 s de
+//     prod, contaba el tiempo entre muestras como tiempo caído: 17 días
+//     fantasma en una ventana de 4 semanas en routers online 24/7.
+//   - upMin = buckets con datos * 5 (minutos con datos, resolución de 5 min).
+//   - El día en curso NO se lee del daily: el rollup es nocturno y llega con
+//     hasta 24 h de retraso, así que el daily de hoy está vacío o casi vacío
+//     y marcaría el día como caído. Se mide del raw (retención 7 días)
+//     contando buckets de 5 min distintos con muestras hoy.
+//   - Divisor: días con datos * 1440, pero el día en curso solo cuenta los
+//     minutos transcurridos (no penaliza). Clamp a 100 (#207): un bucket
+//     sobre-poblado no puede superar el 100%.
+//   - Lo medido es "minutos con datos recibidos": un hueco suele ser el
+//     router caído, pero también puede ser el monitor sin datos. La UI lo
+//     etiqueta como tal y nunca afirma más downtime que tiempo sin datos.
 package httpapi
 
 import (
@@ -22,17 +30,48 @@ import (
 	"encoding/csv"
 	"fmt"
 	"net/http"
+	"sort"
 	"strconv"
 	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
 )
 
+// minPerBucket: minutos que cubre un bucket de agregación (db.BucketMS).
+const minPerBucket = 5
+
+// todayBucketCoverage devuelve, por router, cuántos buckets de 5 min tienen
+// al menos una muestra raw desde medianoche UTC de hoy. El daily de hoy aún
+// no existe (rollup nocturno), así que el día en curso se mide del raw.
+func (s *server) todayBucketCoverage(midnightMS int64) (map[string]int64, error) {
+	rows, err := s.db.Query(`
+		SELECT router_id, COUNT(DISTINCT ts / ?)
+		FROM metrics
+		WHERE ts >= ?
+		GROUP BY router_id`, db.BucketMS, midnightMS)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := map[string]int64{}
+	for rows.Next() {
+		var id string
+		var n int64
+		if err := rows.Scan(&id, &n); err != nil {
+			continue
+		}
+		out[id] = n
+	}
+	return out, rows.Err()
+}
+
 // weeklyReportEntry es una fila del informe: un router durante una semana.
 type weeklyReportEntry struct {
 	RouterID string   `json:"routerId"`
 	Week     string   `json:"week"`   // semana ISO, formato "2026-W31" (lunes-domingo)
 	Days     int      `json:"days"`   // días con datos en esa semana (≤7)
-	UpMin    int64    `json:"upMin"`  // minutos de recolección en la semana
-	UpPct    float64  `json:"upPct"`  // % de disponibilidad sobre los días con datos
+	UpMin    int64    `json:"upMin"`  // minutos con datos en la semana (buckets de 5 min * 5)
+	UpPct    float64  `json:"upPct"`  // % de cobertura sobre los minutos medibles
 	LatAvg   *float64 `json:"latAvg"` // media de latencia (null si no hay datos)
 	RxTotal  float64  `json:"rxTotal"`
 	TxTotal  float64  `json:"txTotal"`
@@ -53,25 +92,27 @@ func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
 	}
 
 	// El daily se agrupa por día UTC (unixepoch en el rollup). La ventana se
-	// recorta con la fecha UTC de hoy; la semana en curso queda parcial y
-	// upPct se calcula solo sobre los días con datos (no penaliza).
-	since := time.Now().UTC().AddDate(0, 0, -7*weeks).Format("2006-01-02")
+	// recorta con la fecha UTC de hoy; el daily de hoy se EXCLUYE (rollup
+	// nocturno, llega con retraso) y se fusiona después desde el raw.
+	now := time.Now().UTC()
+	since := now.AddDate(0, 0, -7*weeks).Format("2006-01-02")
+	today := now.Format("2006-01-02")
+	nowMin := now.Hour()*60 + now.Minute()
 
 	rows, err := s.db.Query(`
 		SELECT
 			router_id,
 			strftime('%G-W%V', date) AS week,
 			COUNT(*),
-			SUM(n) * 5 / 60,
+			SUM(up_count) * ?,
 			AVG(lat_avg),
 			SUM(rx_total),
 			SUM(tx_total),
 			AVG(cpu_avg),
 			AVG(ram_avg)
 		FROM metrics_daily
-		WHERE date >= ?
-		GROUP BY router_id, strftime('%G-W%V', date)
-		ORDER BY week DESC, router_id`, since)
+		WHERE date >= ? AND date < ?
+		GROUP BY router_id, strftime('%G-W%V', date)`, minPerBucket, since, today)
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
@@ -79,30 +120,80 @@ func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
 	defer rows.Close()
 
 	out := []weeklyReportEntry{}
+	idx := map[string]int{} // routerId|week -> posición en out
+	hasToday := map[int]bool{}
 	for rows.Next() {
 		var e weeklyReportEntry
-		var upMin int64
 		var lat sql.NullFloat64
-		if err := rows.Scan(&e.RouterID, &e.Week, &e.Days, &upMin,
+		if err := rows.Scan(&e.RouterID, &e.Week, &e.Days, &e.UpMin,
 			&lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
 			continue
 		}
-		e.UpMin = upMin
 		if lat.Valid {
 			e.LatAvg = &lat.Float64
 		}
-		if e.Days > 0 {
-			e.UpPct = float64(upMin) / (float64(e.Days) * 24 * 60) * 100
-			if e.UpPct > 100 {
-				e.UpPct = 100
-			}
-		}
+		idx[e.RouterID+"|"+e.Week] = len(out)
 		out = append(out, e)
 	}
 	if err := rows.Err(); err != nil {
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
 	}
+
+	// Día en curso desde el raw (ver cabecera). A medianoche UTC exacta no hay
+	// minutos transcurridos que medir y se omite.
+	if nowMin > 0 {
+		midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).UnixMilli()
+		cov, err := s.todayBucketCoverage(midnight)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "db_error")
+			return
+		}
+		y, wn := now.ISOWeek()
+		todayWeek := fmt.Sprintf("%d-W%02d", y, wn)
+		for rid, buckets := range cov {
+			key := rid + "|" + todayWeek
+			if i, ok := idx[key]; ok {
+				out[i].Days++
+				out[i].UpMin += buckets * minPerBucket
+				hasToday[i] = true
+			} else {
+				idx[key] = len(out)
+				hasToday[len(out)] = true
+				out = append(out, weeklyReportEntry{
+					RouterID: rid, Week: todayWeek, Days: 1,
+					UpMin: buckets * minPerBucket,
+				})
+			}
+		}
+	}
+
+	// Divisor: días con datos * 1440; el día en curso solo los minutos
+	// transcurridos. UpMin se tope al divisor (el bucket actual parcial puede
+	// contarse entero) y upPct se clava a 100 (#207).
+	for i := range out {
+		divisor := float64(out[i].Days) * 1440
+		if hasToday[i] {
+			divisor = float64(out[i].Days-1)*1440 + float64(nowMin)
+		}
+		if divisor <= 0 {
+			continue
+		}
+		if float64(out[i].UpMin) > divisor {
+			out[i].UpMin = int64(divisor)
+		}
+		out[i].UpPct = float64(out[i].UpMin) / divisor * 100
+		if out[i].UpPct > 100 {
+			out[i].UpPct = 100
+		}
+	}
+	sort.Slice(out, func(i, j int) bool {
+		if out[i].Week != out[j].Week {
+			return out[i].Week > out[j].Week
+		}
+		return out[i].RouterID < out[j].RouterID
+	})
+
 	if r.URL.Query().Get("format") == "csv" {
 		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
 		w.Header().Set("Content-Disposition", "attachment; filename=netpulse-weekly.csv")
@@ -131,16 +222,15 @@ func (s *server) handleWeeklyReport(w http.ResponseWriter, r *http.Request) {
 //
 // Disponibilidad por router agregada por día, semana ISO o mes, sobre los
 // últimos N buckets (day: 30, week: 8, month: 12 por defecto). Reutiliza la
-// semántica de upMin/upPct del weekly. El día actual parcial se normaliza por
-// los minutos transcurridos (no penaliza); el mes en curso, por días con datos.
+// semántica de buckets del weekly (ver cabecera del fichero, #987).
 // ---------------------------------------------------------------------------
 
 type availabilityEntry struct {
 	RouterID string   `json:"routerId"`
 	Bucket   string   `json:"bucket"` // day "2026-08-07" | week "2026-W31" | month "2026-07"
 	Days     int      `json:"days"`   // días con datos en el bucket
-	UpMin    int64    `json:"upMin"`  // minutos de recolección en el bucket
-	UpPct    float64  `json:"upPct"`  // % de disponibilidad
+	UpMin    int64    `json:"upMin"`  // minutos con datos en el bucket (buckets de 5 min * 5)
+	UpPct    float64  `json:"upPct"`  // % de cobertura sobre los minutos medibles
 	LatAvg   *float64 `json:"latAvg"`
 	RxTotal  float64  `json:"rxTotal"`
 	TxTotal  float64  `json:"txTotal"`
@@ -196,69 +286,114 @@ func (s *server) handleAvailabilityReport(w http.ResponseWriter, r *http.Request
 	case "month":
 		since = now.AddDate(0, -n, 0).Format("2006-01-02")
 	}
+	today := now.Format("2006-01-02")
+	nowMin := now.Hour()*60 + now.Minute()
 
+	// Igual que el weekly: el daily de hoy se excluye y se fusiona del raw.
 	query := fmt.Sprintf(`
 		SELECT
 			router_id,
 			%s AS bucket,
 			COUNT(*),
-			SUM(n) * 5 / 60,
+			SUM(up_count) * ?,
 			AVG(lat_avg),
 			SUM(rx_total),
 			SUM(tx_total),
 			AVG(cpu_avg),
 			AVG(ram_avg)
 		FROM metrics_daily
-		WHERE date >= ?
-		GROUP BY router_id, %s
-		ORDER BY bucket DESC, router_id`, groupExpr, groupExpr)
+		WHERE date >= ? AND date < ?
+		GROUP BY router_id, %s`, groupExpr, groupExpr)
 
-	rows, err := s.db.Query(query, since)
+	rows, err := s.db.Query(query, minPerBucket, since, today)
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
 	}
 	defer rows.Close()
 
-	// Para el día actual parcial: divisor = minutos transcurridos del día UTC.
-	today := now.Format("2006-01-02")
-	nowMin := now.Hour()*60 + now.Minute()
-
 	out := []availabilityEntry{}
+	idx := map[string]int{} // routerId|bucket -> posición en out
+	hasToday := map[int]bool{}
 	for rows.Next() {
 		var e availabilityEntry
-		var upMin int64
 		var lat sql.NullFloat64
-		if err := rows.Scan(&e.RouterID, &e.Bucket, &e.Days, &upMin,
+		if err := rows.Scan(&e.RouterID, &e.Bucket, &e.Days, &e.UpMin,
 			&lat, &e.RxTotal, &e.TxTotal, &e.CPUAvg, &e.RAMAvg); err != nil {
 			continue
 		}
-		e.UpMin = upMin
 		if lat.Valid {
 			e.LatAvg = &lat.Float64
 		}
-		var divisor float64
-		if rangeParam == "day" {
-			if e.Bucket == today && nowMin > 0 {
-				divisor = float64(nowMin)
-			} else {
-				divisor = 1440
-			}
-		} else {
-			divisor = float64(e.Days) * 1440
-		}
-		if divisor > 0 {
-			e.UpPct = float64(upMin) / divisor * 100
-			if e.UpPct > 100 {
-				e.UpPct = 100
-			}
-		}
+		idx[e.RouterID+"|"+e.Bucket] = len(out)
 		out = append(out, e)
 	}
 	if err := rows.Err(); err != nil {
 		writeError(w, http.StatusInternalServerError, "db_error")
 		return
 	}
+
+	// Día en curso desde el raw; la etiqueta del grupo que contiene hoy
+	// depende del rango (día, semana ISO o mes).
+	if nowMin > 0 {
+		midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).UnixMilli()
+		cov, err := s.todayBucketCoverage(midnight)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "db_error")
+			return
+		}
+		var todayBucket string
+		switch rangeParam {
+		case "day":
+			todayBucket = today
+		case "week":
+			y, wn := now.ISOWeek()
+			todayBucket = fmt.Sprintf("%d-W%02d", y, wn)
+		case "month":
+			todayBucket = now.Format("2006-01")
+		}
+		for rid, buckets := range cov {
+			key := rid + "|" + todayBucket
+			if i, ok := idx[key]; ok {
+				out[i].Days++
+				out[i].UpMin += buckets * minPerBucket
+				hasToday[i] = true
+			} else {
+				idx[key] = len(out)
+				hasToday[len(out)] = true
+				out = append(out, availabilityEntry{
+					RouterID: rid, Bucket: todayBucket, Days: 1,
+					UpMin: buckets * minPerBucket,
+				})
+			}
+		}
+	}
+
+	// Divisor: días con datos * 1440; el día en curso solo los minutos
+	// transcurridos (mismo criterio que el weekly, #987).
+	for i := range out {
+		divisor := float64(out[i].Days) * 1440
+		if hasToday[i] {
+			divisor = float64(out[i].Days-1)*1440 + float64(nowMin)
+		}
+		if divisor <= 0 {
+			continue
+		}
+		if float64(out[i].UpMin) > divisor {
+			out[i].UpMin = int64(divisor)
+		}
+		out[i].UpPct = float64(out[i].UpMin) / divisor * 100
+		if out[i].UpPct > 100 {
+			out[i].UpPct = 100
+		}
+	}
+	sort.Slice(out, func(i, j int) bool {
+		if out[i].Bucket != out[j].Bucket {
+			return out[i].Bucket > out[j].Bucket
+		}
+		return out[i].RouterID < out[j].RouterID
+	})
+
 	if q.Get("format") == "csv" {
 		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
 		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=netpulse-availability-%s.csv", rangeParam))

+ 21 - 17
server-go/internal/httpapi/reports_test.go

@@ -13,8 +13,10 @@ import (
 )
 
 // insertDaily siembra un daily del router r para una fecha dada. nSamples es
-// el nº de muestras recolectadas (poll 5 s; día completo ≈ 17280 → 1440 min).
-func insertDaily(t *testing.T, ts *testServer, routerID, date string, nSamples int, lat sqlNull, rx, tx, cpu, ram float64) {
+// el nº de muestras recolectadas (informativo tras #987: la disponibilidad ya
+// no se deriva de n) y upCount el nº de buckets de 5 min con datos (288 = día
+// completo), que es la base de upMin/upPct.
+func insertDaily(t *testing.T, ts *testServer, routerID, date string, nSamples, upCount int, lat sqlNull, rx, tx, cpu, ram float64) {
 	t.Helper()
 	var latV any
 	if lat.valid {
@@ -22,7 +24,7 @@ func insertDaily(t *testing.T, ts *testServer, routerID, date string, nSamples i
 	}
 	_, err := ts.db.Exec(
 		"INSERT OR REPLACE INTO metrics_daily (router_id, date, n, cpu_avg, ram_avg, temp_avg, lat_avg, rx_avg, tx_avg, rx_total, tx_total, up_min, up_count) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
-		routerID, date, nSamples, cpu, ram, 40, latV, rx, tx, rx*float64(nSamples), tx*float64(nSamples), 0, nSamples)
+		routerID, date, nSamples, cpu, ram, 40, latV, rx, tx, rx*float64(nSamples), tx*float64(nSamples), 0, upCount)
 	if err != nil {
 		t.Fatalf("insert daily %s/%s: %v", routerID, date, err)
 	}
@@ -76,9 +78,11 @@ func TestWeeklyReportAgrupaPorRouterYSemana(t *testing.T) {
 	// Semanas relativas a HOY: el handler filtra por date >= now-7*weeks,
 	// así que usar semanas ISO fijas haría el test dependiente de la fecha
 	// (fallaba al avanzar la semana actual, CI rojo sin relación con cambios).
-	// Semana A = la actual (lunes), Semana B = la anterior.
+	// Además, desde #987 el daily del día en curso se excluye (se mide del
+	// raw), así que TODAS las fechas sembradas deben ser pasadas: semana A =
+	// la anterior, semana B = hace dos.
 	now := time.Now().UTC()
-	mondayA := mondayOf(now)
+	mondayA := mondayOf(now).AddDate(0, 0, -7)
 	mondayB := mondayA.AddDate(0, 0, -7)
 	weekA := isoWeek(mondayA)
 	weekB := isoWeek(mondayB)
@@ -86,14 +90,14 @@ func TestWeeklyReportAgrupaPorRouterYSemana(t *testing.T) {
 	dateA2 := mondayA.AddDate(0, 0, 1).Format("2006-01-02")
 	dateB := mondayB.Format("2006-01-02")
 
-	// Dos routers en la misma semana A. Día completo = 17280 muestras =
-	// 1440 min. latAvg null en prod real.
-	insertDaily(t, ts, "gw", dateA, 17280, sqlNull{true, 1.2}, 1e8, 5e7, 20, 60)
-	insertDaily(t, ts, "gw", dateA2, 17280, sqlNull{true, 1.4}, 1e8, 5e7, 22, 61)
-	insertDaily(t, ts, "ap2", dateA, 8640, sqlNull{false, 0}, 1e7, 1e7, 10, 40) // medio día, sin latencia
+	// Dos routers en la misma semana A. Día completo = 288 buckets de 5 min
+	// (upMin 1440). latAvg null en prod real.
+	insertDaily(t, ts, "gw", dateA, 17280, 288, sqlNull{true, 1.2}, 1e8, 5e7, 20, 60)
+	insertDaily(t, ts, "gw", dateA2, 17280, 288, sqlNull{true, 1.4}, 1e8, 5e7, 22, 61)
+	insertDaily(t, ts, "ap2", dateA, 8640, 144, sqlNull{false, 0}, 1e7, 1e7, 10, 40) // medio día, sin latencia
 
-	// Otra semana distinta (B, la anterior) para el mismo router.
-	insertDaily(t, ts, "gw", dateB, 17280, sqlNull{true, 1.0}, 9e7, 4e7, 19, 59)
+	// Otra semana distinta (B) para el mismo router.
+	insertDaily(t, ts, "gw", dateB, 17280, 288, sqlNull{true, 1.0}, 9e7, 4e7, 19, 59)
 
 	status, items := getWeekly(t, ts, "4")
 	if status != http.StatusOK {
@@ -174,12 +178,12 @@ func isoWeek(t time.Time) string {
 // clavaba y weekly no.
 func TestWeeklyReportUpPctClamp(t *testing.T) {
 	ts := makeTestServer(t)
-	// Fecha relativa a hoy (mismo patrón anti-dependencia de la fecha del
-	// test de agrupación): lunes de la semana actual.
-	dateA := mondayOf(time.Now().UTC()).Format("2006-01-02")
-	// Día completo = 17280 muestras = 1440 min. El doble (34560) da
+	// Fecha pasada (ayer): desde #987 el daily del día en curso se excluye y
+	// se mide del raw, así que el daily sembrado debe ser de un día cerrado.
+	dateA := time.Now().UTC().AddDate(0, 0, -1).Format("2006-01-02")
+	// Día completo = 288 buckets de 5 min = 1440 min. El doble (576) da
 	// upMin = 2880 sobre 1440 min → 200% sin el clamp.
-	insertDaily(t, ts, "gw", dateA, 34560, sqlNull{false, 0}, 0, 0, 20, 60)
+	insertDaily(t, ts, "gw", dateA, 34560, 576, sqlNull{false, 0}, 0, 0, 20, 60)
 
 	status, items := getWeekly(t, ts, "4")
 	if status != http.StatusOK {

+ 9 - 0
server-go/internal/httpapi/server.go

@@ -150,6 +150,10 @@ type server struct {
 	pollNow func()
 	started time.Time
 
+	// MQTT publisher (#838): lo usa también el endpoint de integraciones
+	// (#968) para el toggle enabled sin tocar el resto de la config.
+	mqtt *mqttpub.Manager
+
 	// SSE bidireccional para agentes (Fase 7.3).
 	agentHub *sse.AgentHub
 
@@ -270,6 +274,7 @@ func NewHandler(d Deps) http.Handler {
 		imageResolver:   d.FirmwareImage,
 		speedtest:       d.Speedtest,
 		alertEmitter:    d.AlertEmitter,
+		mqtt:            d.MQTT,
 	}
 	if s.imageResolver == nil {
 		s.imageResolver = firmware.NewImageResolver()
@@ -353,6 +358,9 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("GET /api/presence/roaming", s.handlePresenceRoaming)
 	mux.Handle("GET /api/settings/presence", auth.RequireAdmin(http.HandlerFunc(s.handlePresenceSettingsGet)))
 	mux.Handle("PUT /api/settings/presence", auth.RequireAdmin(http.HandlerFunc(s.handlePresenceSettingsPut)))
+	// Interruptor maestro de la poda del historial (#975).
+	mux.Handle("GET /api/settings/history-limit", auth.RequireAdmin(http.HandlerFunc(s.handleHistoryLimitGet)))
+	mux.Handle("PUT /api/settings/history-limit", auth.RequireAdmin(http.HandlerFunc(s.handleHistoryLimitPut)))
 	// Reserva DHCP y bloqueo de dispositivo (issue #439).
 	mux.Handle("GET /api/devices/{mac}/reservation", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationGet)))
 	mux.Handle("PUT /api/devices/{mac}/reservation", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationPut)))
@@ -366,6 +374,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("PUT /api/alerts/config", s.handleAlertsConfigPut)
 	mux.HandleFunc("POST /api/alerts/read", s.handleAlertsRead)
 	mux.HandleFunc("POST /api/alerts/read-all", s.handleAlertsReadAll)
+	mux.HandleFunc("POST /api/alerts/clear", s.handleAlertsClear)
 	mux.HandleFunc("POST /api/alerts/dismiss", s.handleAlertsDismiss)
 	mux.HandleFunc("POST /api/alerts/silence", s.handleAlertsSilence)
 	mux.HandleFunc("POST /api/alerts/unsilence", s.handleAlertsUnsilence)

+ 101 - 0
server-go/internal/httpapi/settings.go

@@ -13,11 +13,21 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 )
 
 // orchestrationKey es la clave kv que activa el menú de orquestación (#121).
 const orchestrationKey = "settings.orchestration_enabled"
 
+// integrationKeys: claves kv de los toggles de integraciones server-side
+// (#968). Ausente = activo (compat: instalaciones previas no tenían el flag).
+// MQTT no tiene clave propia aquí: reutiliza mqtt.enabled (#838).
+const (
+	integrationNtfyKey     = "settings.integrations.ntfy"
+	integrationTelegramKey = "settings.integrations.telegram"
+	integrationProxmoxKey  = "settings.integrations.proxmox"
+)
+
 // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
 // (compat: instalaciones previas no tenían este flag). Ajustes > Servicios.
 const adguardServiceKey = "settings.services.adguard"
@@ -49,6 +59,14 @@ func kvSetBool(db *sql.DB, key string, val bool) error {
 	return err
 }
 
+// kvSetStr escribe una cadena en el kv (UPSERT).
+func kvSetStr(db *sql.DB, key, val string) error {
+	_, err := db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		key, val)
+	return err
+}
+
 // kvGetDefaultOn lee un flag "1"/"0" con default TRUE cuando la clave está
 // ausente o vacía (a diferencia de kvGetBool, cuyo default es false). Se usa
 // para servicios que se monitorizan salvo que el usuario los desactive (#813).
@@ -119,6 +137,57 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 		writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
 	})))
 
+	// GET /api/settings/integrations - toggles server-side de integraciones
+	// (#968): ntfy/telegram/proxmox (ausente = activo) y mqtt (lee la clave
+	// existente mqtt.enabled via el manager, que ya fusiona env + kv).
+	mux.Handle("GET /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		writeJSON(w, http.StatusOK, s.integrationsView())
+	})))
+	// PUT /api/settings/integrations - parche parcial: SOLO se escriben las
+	// claves presentes en el body (un toggle no pisa el resto). Los gates
+	// leen la kv por evento, así que el cambio aplica sin reiniciar.
+	mux.Handle("PUT /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		var body struct {
+			Ntfy     *bool `json:"ntfy"`
+			Telegram *bool `json:"telegram"`
+			Proxmox  *bool `json:"proxmox"`
+			MQTT     *bool `json:"mqtt"`
+		}
+		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 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "at least one integration key is required")
+			return
+		}
+		for _, p := range []struct {
+			flag *bool
+			key  string
+		}{
+			{body.Ntfy, integrationNtfyKey},
+			{body.Telegram, integrationTelegramKey},
+			{body.Proxmox, integrationProxmoxKey},
+		} {
+			if p.flag == nil {
+				continue
+			}
+			// Formato "true"/"false" (como mqtt.enabled): los gates de
+			// main.go y del adapter leen "false" literal.
+			if err := kvSetStr(s.db.DB, p.key, strconv.FormatBool(*p.flag)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error")
+				return
+			}
+		}
+		if body.MQTT != nil {
+			if err := s.setMQTTEnabled(*body.MQTT); err != nil {
+				writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
+				return
+			}
+		}
+		writeJSON(w, http.StatusOK, s.integrationsView())
+	})))
+
 	// GET /api/settings/services — servicios monitorizados (#813). Ausente = activo.
 	mux.Handle("GET /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		writeJSON(w, http.StatusOK, map[string]bool{"adguard": kvGetDefaultOn(s.db.DB, adguardServiceKey)})
@@ -193,6 +262,38 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 	s.registerThresholdsRoutes(mux)
 }
 
+// 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 {
+	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,
+	}
+}
+
+// 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.
+func (s *server) setMQTTEnabled(enabled bool) error {
+	if s.mqtt == nil {
+		return kvSetStr(s.db.DB, "mqtt.enabled", strconv.FormatBool(enabled))
+	}
+	cfg := s.mqtt.Config()
+	cfg.Enabled = enabled
+	if err := mqttpub.SaveConfig(&dbKVAdapter{db: s.db.DB}, cfg); err != nil {
+		return err
+	}
+	s.mqtt.Apply(cfg)
+	return nil
+}
+
 // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
 type knownMacItem struct {
 	MAC  string `json:"mac"`

+ 76 - 0
server-go/internal/httpapi/settings_integrations_test.go

@@ -0,0 +1,76 @@
+// settings_integrations_test.go - GET/PUT /api/settings/integrations (#968):
+// toggles server-side de ntfy/telegram/proxmox (ausente = activo) y mqtt
+// (reutiliza la clave existente mqtt.enabled). El PUT es partial-safe: solo
+// se escriben las claves presentes en el body.
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+)
+
+func TestIntegrationsDefaultsOn(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if cookie == "" {
+		t.Fatal("login no devolvió cookie")
+	}
+
+	res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET: status %d, esperado 200", res.StatusCode)
+	}
+	for _, k := range []string{"ntfy", "telegram", "proxmox"} {
+		if body[k] != true {
+			t.Fatalf("%s default: %v, esperado true (ausente = activo)", k, body[k])
+		}
+	}
+	// MQTT por defecto apagado (la clave mqtt.enabled no existe aún).
+	if body["mqtt"] != false {
+		t.Fatalf("mqtt default: %v, esperado false", body["mqtt"])
+	}
+
+	// Sin sesión → 401.
+	res, _ = wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", "", "")
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("GET sin auth: status %d, esperado 401", res.StatusCode)
+	}
+}
+
+func TestIntegrationsPutIsPartialSafe(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if cookie == "" {
+		t.Fatal("login no devolvió cookie")
+	}
+
+	// Apagar ntfy no toca telegram ni proxmox.
+	res, body := wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"ntfy":false}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT ntfy=false: status %d (%v)", res.StatusCode, body)
+	}
+	if body["ntfy"] != false || body["telegram"] != true || body["proxmox"] != true {
+		t.Fatalf("echo tras PUT parcial: %v", body)
+	}
+
+	// Apagar telegram tampoco reactiva ntfy.
+	res, body = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"telegram":false}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT telegram=false: status %d (%v)", res.StatusCode, body)
+	}
+	if body["ntfy"] != false || body["telegram"] != false || body["proxmox"] != true {
+		t.Fatalf("echo tras segundo PUT parcial: %v", body)
+	}
+
+	// La vista persiste en kv (GET lo relee).
+	_, body = wanSpeedRequest(t, "GET", srv.URL, "/api/settings/integrations", cookie, "")
+	if body["ntfy"] != false || body["telegram"] != false || body["proxmox"] != true {
+		t.Fatalf("GET tras PUTs: %v", body)
+	}
+
+	// Body vacío → 400.
+	res, _ = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{}`)
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("PUT vacío: status %d, esperado 400", res.StatusCode)
+	}
+}

+ 1 - 1
server-go/internal/reinstall/reinstall.go

@@ -19,7 +19,7 @@ import (
 // so the agent token in the request header is not handed to whoever answers.
 // The binary's sha256 was always checked; this protects the token.
 type Trust struct {
-	ServerURL string // replaces the URL given to Script, e.g. https://host:3443
+	ServerURL string // replaces the URL given to Script, e.g. https://host:443
 	ServerFP  string // written as NETPULSE_SERVER_FP: what the agent pins
 	CAPEM     []byte // the root to verify downloads with
 }

+ 265 - 0
server-go/internal/speedtest/http_runner.go

@@ -0,0 +1,265 @@
+// http_runner.go - metodos de medicion por HTTP directo (#976): alternativas
+// reales al runner Ookla para lineas donde speedtest.net mide mal (peering
+// pobre con los servidores cercanos, CGNAT, etc.).
+//
+//   - cloudflare: speed.cloudflare.com, los endpoints publicos de su test
+//     web (__down?bytes=N para bajada, __up para subida).
+//   - librespeed: cualquier instancia LibreSpeed (autoalojada o publica);
+//     serverURL es la URL base de la instancia y se usan sus endpoints
+//     backend/garbage.php (bajada) y backend/empty.php (subida y ping).
+//   - custom (#1001): endpoint HTTP libre; serverURL es la URL completa y
+//     se usa tal cual para bajada (GET), subida (POST) y ping (GET).
+//     Cualquier respuesta 2xx vale.
+//
+// Ambos miden con bucles de chunks acotados por tiempo y por bytes para no
+// castigar lineas lentas ni subestimar las rapidas.
+package speedtest
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+)
+
+// Proveedores soportados en settings.speedtest.provider (#976). "" equivale
+// a ProviderOokla (instalaciones anteriores sin la clave kv).
+const (
+	ProviderOokla      = "ookla"      // speedtest.net via showwin/speedtest-go (default)
+	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
+)
+
+func validProvider(v string) bool {
+	return v == ProviderOokla || v == ProviderCloudflare || v == ProviderLibrespeed || v == ProviderCustom
+}
+
+// Limites de la medicion HTTP: al menos minDur midiendo (precision en
+// lineas rapidas) y como mucho maxBytes (techo en lineas lentas; el ctx del
+// scheduler -3 min- sigue siendo la ultima palabra).
+const (
+	httpDownMinDur   = 4 * time.Second
+	httpDownMaxBytes = 128 << 20 // 128 MiB
+	httpUpMinDur     = 3 * time.Second
+	httpUpMaxBytes   = 64 << 20 // 64 MiB
+	httpDownChunk    = 8 << 20  // 8 MiB por peticion de bajada
+	httpUpChunk      = 4 << 20  // 4 MiB por peticion de subida
+	httpPings        = 5
+)
+
+// statusOK valida la respuesta del endpoint: los proveedores conocidos
+// exigen 200 exacto; custom acepta cualquier 2xx (endpoint libre, #1001).
+func statusOK(provider string, code int) bool {
+	if provider == ProviderCustom {
+		return code >= 200 && code < 300
+	}
+	return code == http.StatusOK
+}
+
+// HTTPRunner ejecuta el test contra endpoints HTTP directos. Cumple la
+// interfaz Runner: para cloudflare el serverURL se ignora (endpoints
+// fijos); para librespeed es la URL base de la instancia; para custom es
+// la URL completa del endpoint.
+type HTTPRunner struct {
+	Provider string
+
+	// DownURL/UpURL/PingURL pisan los endpoints por defecto (tests con
+	// httptest); "" = los del proveedor.
+	DownURL string
+	UpURL   string
+	PingURL string
+
+	// Client opcional (tests); nil = uno con timeouts razonables.
+	Client *http.Client
+}
+
+func (r HTTPRunner) httpClient() *http.Client {
+	if r.Client != nil {
+		return r.Client
+	}
+	return &http.Client{Timeout: 60 * time.Second}
+}
+
+// endpoints resuelve las URLs de bajada, subida y ping del proveedor.
+func (r HTTPRunner) endpoints(serverURL string) (down, up, ping string, err error) {
+	switch r.Provider {
+	case ProviderCloudflare:
+		down, up, ping = "https://speed.cloudflare.com/__down", "https://speed.cloudflare.com/__up", "https://speed.cloudflare.com/__down?bytes=0"
+	case ProviderLibrespeed:
+		base := strings.TrimRight(strings.TrimSpace(serverURL), "/")
+		if base == "" {
+			return "", "", "", fmt.Errorf("librespeed exige la URL base de la instancia")
+		}
+		u, perr := url.Parse(base)
+		if perr != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+			return "", "", "", fmt.Errorf("URL de instancia librespeed invalida: %q", serverURL)
+		}
+		down, up, ping = base+"/backend/garbage.php", base+"/backend/empty.php", base+"/backend/empty.php"
+	case ProviderCustom:
+		// #1001: endpoint libre. La URL dada se usa TAL CUAL para bajada
+		// (GET), subida (POST) y ping (GET): el endpoint debe aceptar ambos
+		// metodos (estilo backend/empty.php de LibreSpeed o __down/__up de
+		// Cloudflare). Cualquier 2xx vale: no imponemos el contrato exacto
+		// de un proveedor concreto.
+		u := strings.TrimSpace(serverURL)
+		if u == "" {
+			return "", "", "", fmt.Errorf("custom exige la URL del endpoint de medicion")
+		}
+		parsed, perr := url.Parse(u)
+		if perr != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
+			return "", "", "", fmt.Errorf("URL de endpoint custom invalida: %q", serverURL)
+		}
+		down, up, ping = u, u, u
+	default:
+		return "", "", "", fmt.Errorf("proveedor HTTP desconocido %q", r.Provider)
+	}
+	if r.DownURL != "" {
+		down = r.DownURL
+	}
+	if r.UpURL != "" {
+		up = r.UpURL
+	}
+	if r.PingURL != "" {
+		ping = r.PingURL
+	}
+	return down, up, ping, nil
+}
+
+// Run mide ping, bajada y subida contra los endpoints del proveedor.
+func (r HTTPRunner) Run(ctx context.Context, serverURL string) (Result, error) {
+	down, up, ping, err := r.endpoints(serverURL)
+	if err != nil {
+		return Result{}, err
+	}
+	c := r.httpClient()
+
+	// Ping: minimo de N peticiones ligeras (como el runner Ookla, ping antes
+	// de las mediciones pesadas).
+	var best time.Duration
+	for i := 0; i < httpPings; i++ {
+		start := time.Now()
+		req, _ := http.NewRequestWithContext(ctx, http.MethodGet, ping, nil)
+		resp, perr := c.Do(req)
+		if perr != nil {
+			return Result{}, fmt.Errorf("ping: %w", perr)
+		}
+		_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1024))
+		resp.Body.Close()
+		if !statusOK(r.Provider, resp.StatusCode) {
+			return Result{}, fmt.Errorf("ping: HTTP %d", resp.StatusCode)
+		}
+		if d := time.Since(start); best == 0 || d < best {
+			best = d
+		}
+	}
+
+	downMbps, err := r.measureDown(ctx, c, down)
+	if err != nil {
+		return Result{}, fmt.Errorf("download: %w", err)
+	}
+	upMbps, err := r.measureUp(ctx, c, up)
+	if err != nil {
+		return Result{}, fmt.Errorf("upload: %w", err)
+	}
+
+	res := Result{
+		TS:       time.Now(),
+		DownMbps: downMbps,
+		UpMbps:   upMbps,
+	}
+	pingMs := float64(best.Microseconds()) / 1000.0
+	res.PingMs = &pingMs
+	if u, uerr := url.Parse(down); uerr == nil {
+		res.ServerName = u.Host
+		res.ServerID = r.Provider
+	}
+	return res, nil
+}
+
+// measureDown descarga chunks hasta cumplir la duracion minima o el techo de
+// bytes. Cloudflare acota por query (?bytes=N); librespeed por ckSize
+// (bloques de 1 KiB, max 1 MiB por peticion).
+func (r HTTPRunner) measureDown(ctx context.Context, c *http.Client, downURL string) (float64, error) {
+	var total int64
+	start := time.Now()
+	for total < httpDownMaxBytes {
+		u := downURL
+		switch r.Provider {
+		case ProviderLibrespeed:
+			u += "?ckSize=1024"
+		case ProviderCustom:
+			// #1001: la URL se usa tal cual, sin inventar parametros.
+		default:
+			if !strings.Contains(u, "bytes=") {
+				u = u + "?bytes=" + fmt.Sprint(httpDownChunk)
+			}
+		}
+		req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
+		resp, err := c.Do(req)
+		if err != nil {
+			return 0, err
+		}
+		var n int64
+		if r.Provider == ProviderCustom {
+			// Techo por peticion: un endpoint con stream infinito no debe
+			// bloquear el bucle (el ctx del scheduler sigue mandando).
+			n, err = io.Copy(io.Discard, io.LimitReader(resp.Body, httpDownChunk))
+		} else {
+			n, err = io.Copy(io.Discard, resp.Body)
+		}
+		resp.Body.Close()
+		if err != nil {
+			return 0, err
+		}
+		if !statusOK(r.Provider, resp.StatusCode) {
+			return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
+		}
+		if n == 0 {
+			return 0, fmt.Errorf("endpoint de bajada devolvio 0 bytes")
+		}
+		total += n
+		if time.Since(start) >= httpDownMinDur {
+			break
+		}
+	}
+	return mbps(total, time.Since(start)), nil
+}
+
+// measureUp sube chunks de ceros hasta cumplir la duracion minima o el
+// techo. Los cuerpos se reutilizan de un buffer unico (sin allocs por chunk).
+func (r HTTPRunner) measureUp(ctx context.Context, c *http.Client, upURL string) (float64, error) {
+	chunk := make([]byte, httpUpChunk)
+	var total int64
+	start := time.Now()
+	for total < httpUpMaxBytes {
+		req, _ := http.NewRequestWithContext(ctx, http.MethodPost, upURL, bytes.NewReader(chunk))
+		req.ContentLength = int64(len(chunk))
+		req.Header.Set("Content-Type", "application/octet-stream")
+		resp, err := c.Do(req)
+		if err != nil {
+			return 0, err
+		}
+		_, _ = io.Copy(io.Discard, resp.Body)
+		resp.Body.Close()
+		if !statusOK(r.Provider, resp.StatusCode) {
+			return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
+		}
+		total += int64(len(chunk))
+		if time.Since(start) >= httpUpMinDur {
+			break
+		}
+	}
+	return mbps(total, time.Since(start)), nil
+}
+
+func mbps(n int64, d time.Duration) float64 {
+	if d <= 0 {
+		return 0
+	}
+	return float64(n) * 8 / d.Seconds() / 1e6
+}

+ 253 - 0
server-go/internal/speedtest/http_runner_test.go

@@ -0,0 +1,253 @@
+// http_runner_test.go - contrato del runner HTTP (#976) con httptest: los
+// endpoints se sobreescriben con URLs locales y los handlers sirven bytes
+// conocidos para verificar el calculo de Mbps y el contrato Runner.
+package speedtest
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// fixedRunner devuelve el resultado indicado (para verificar que el
+// scheduler ejecuta el runner HTTP y no el Ookla).
+type fixedRunner struct{ down, up float64 }
+
+func (f fixedRunner) Run(context.Context, string) (Result, error) {
+	return Result{DownMbps: f.down, UpMbps: f.up, ServerName: "http-fake"}, nil
+}
+
+// speedHTTPServer imita los endpoints de Cloudflare/LibreSpeed: bajada
+// (bytes fijos), subida (200 sin cuerpo) y ping (200 minusculo).
+func speedHTTPServer(t *testing.T) *httptest.Server {
+	t.Helper()
+	payload := make([]byte, 1<<20) // 1 MiB por peticion
+	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch {
+		case r.Method == http.MethodPost:
+			w.WriteHeader(http.StatusOK)
+		case strings.Contains(r.URL.RawQuery, "bytes=0") || r.URL.Path == "/backend/empty.php":
+			w.WriteHeader(http.StatusOK)
+		default:
+			w.Header().Set("Content-Type", "application/octet-stream")
+			_, _ = w.Write(payload)
+		}
+	}))
+}
+
+func TestHTTPRunnerCloudflare(t *testing.T) {
+	srv := speedHTTPServer(t)
+	defer srv.Close()
+
+	r := HTTPRunner{
+		Provider: ProviderCloudflare,
+		DownURL:  srv.URL + "/__down",
+		UpURL:    srv.URL + "/__up",
+		PingURL:  srv.URL + "/__down?bytes=0",
+	}
+	res, err := r.Run(context.Background(), "")
+	if err != nil {
+		t.Fatalf("Run: %v", err)
+	}
+	if res.DownMbps <= 0 || res.UpMbps <= 0 {
+		t.Fatalf("mediciones no positivas: %+v", res)
+	}
+	if res.PingMs == nil || *res.PingMs <= 0 {
+		t.Fatalf("ping ausente: %+v", res)
+	}
+	if res.ServerID != ProviderCloudflare {
+		t.Fatalf("ServerID = %q, want %q", res.ServerID, ProviderCloudflare)
+	}
+	if res.TS.IsZero() {
+		t.Fatal("TS vacio")
+	}
+}
+
+func TestHTTPRunnerLibrespeedEndpoints(t *testing.T) {
+	srv := speedHTTPServer(t)
+	defer srv.Close()
+
+	// Sin overrides: las URLs se derivan de la URL base de la instancia.
+	r := HTTPRunner{Provider: ProviderLibrespeed}
+	down, up, ping, err := r.endpoints(srv.URL)
+	if err != nil {
+		t.Fatalf("endpoints: %v", err)
+	}
+	if down != srv.URL+"/backend/garbage.php" || up != srv.URL+"/backend/empty.php" || ping != srv.URL+"/backend/empty.php" {
+		t.Fatalf("endpoints derivados: %q %q %q", down, up, ping)
+	}
+
+	res, err := r.Run(context.Background(), srv.URL)
+	if err != nil {
+		t.Fatalf("Run: %v", err)
+	}
+	if res.DownMbps <= 0 || res.UpMbps <= 0 {
+		t.Fatalf("mediciones no positivas: %+v", res)
+	}
+}
+
+func TestHTTPRunnerCustom(t *testing.T) {
+	srv := speedHTTPServer(t)
+	defer srv.Close()
+
+	// #1001: la URL dada se usa TAL CUAL (sin derivar paths ni anadir
+	// query) para bajada, subida y ping.
+	r := HTTPRunner{Provider: ProviderCustom}
+	down, up, ping, err := r.endpoints(srv.URL + "/endpoint")
+	if err != nil {
+		t.Fatalf("endpoints: %v", err)
+	}
+	if down != srv.URL+"/endpoint" || up != down || ping != down {
+		t.Fatalf("endpoints custom: %q %q %q", down, up, ping)
+	}
+
+	res, err := r.Run(context.Background(), srv.URL+"/endpoint")
+	if err != nil {
+		t.Fatalf("Run: %v", err)
+	}
+	if res.DownMbps <= 0 || res.UpMbps <= 0 {
+		t.Fatalf("mediciones no positivas: %+v", res)
+	}
+	if res.ServerID != ProviderCustom {
+		t.Fatalf("ServerID = %q, want %q", res.ServerID, ProviderCustom)
+	}
+}
+
+func TestHTTPRunnerCustomErrores(t *testing.T) {
+	// Sin URL de endpoint.
+	if _, err := (HTTPRunner{Provider: ProviderCustom}).Run(context.Background(), ""); err == nil {
+		t.Fatal("custom sin URL aceptado")
+	}
+	// URL que no es http(s).
+	if _, err := (HTTPRunner{Provider: ProviderCustom}).Run(context.Background(), "ftp://x"); err == nil {
+		t.Fatal("custom con esquema no-http aceptado")
+	}
+	// 2xx distinto de 200 vale en custom (endpoint libre).
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.Method == http.MethodPost {
+			w.WriteHeader(http.StatusNoContent)
+			return
+		}
+		w.Header().Set("Content-Type", "application/octet-stream")
+		w.WriteHeader(http.StatusPartialContent)
+		_, _ = w.Write(make([]byte, 1<<20))
+	}))
+	defer srv.Close()
+	if _, err := (HTTPRunner{Provider: ProviderCustom}).Run(context.Background(), srv.URL); err != nil {
+		t.Fatalf("custom con 2xx no-200 rechazado: %v", err)
+	}
+}
+
+func TestHTTPRunnerErrores(t *testing.T) {
+	// Provider desconocido.
+	if _, err := (HTTPRunner{Provider: "nope"}).Run(context.Background(), ""); err == nil {
+		t.Fatal("provider desconocido aceptado")
+	}
+	// LibreSpeed sin URL base.
+	if _, err := (HTTPRunner{Provider: ProviderLibrespeed}).Run(context.Background(), ""); err == nil {
+		t.Fatal("librespeed sin URL base aceptado")
+	}
+	// LibreSpeed con URL que no es http(s).
+	if _, err := (HTTPRunner{Provider: ProviderLibrespeed}).Run(context.Background(), "ftp://x"); err == nil {
+		t.Fatal("librespeed con esquema no-http aceptado")
+	}
+	// Endpoint caido: error de bajada (no panic, no resultado basura).
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		w.WriteHeader(http.StatusBadGateway)
+	}))
+	defer srv.Close()
+	r := HTTPRunner{Provider: ProviderCloudflare, DownURL: srv.URL, UpURL: srv.URL, PingURL: srv.URL}
+	if _, err := r.Run(context.Background(), ""); err == nil {
+		t.Fatal("HTTP 502 del endpoint aceptado como medicion")
+	}
+}
+
+func TestSpeedtestProviderSettings(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	st, err := NewStore(d.DB)
+	if err != nil {
+		t.Fatalf("store: %v", err)
+	}
+	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)
+	}
+	// Roundtrip cloudflare.
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderCloudflare}); err != nil {
+		t.Fatalf("save cloudflare: %v", err)
+	}
+	if got := sched.LoadSettings(); got.Provider != ProviderCloudflare {
+		t.Fatalf("provider = %q, want cloudflare", got.Provider)
+	}
+	// Provider invalido rechazado.
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: "fast.com"}); err == nil {
+		t.Fatal("provider invalido aceptado")
+	}
+	// LibreSpeed exige la URL base.
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderLibrespeed}); err == nil {
+		t.Fatal("librespeed sin serverUrl aceptado")
+	}
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderLibrespeed, ServerURL: "https://speed.example.net"}); err != nil {
+		t.Fatalf("save librespeed: %v", err)
+	}
+	if got := sched.LoadSettings(); got.Provider != ProviderLibrespeed || got.ServerURL != "https://speed.example.net" {
+		t.Fatalf("roundtrip librespeed: %+v", got)
+	}
+	// Custom (#1001): exige la URL del endpoint y hace roundtrip.
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderCustom}); err == nil {
+		t.Fatal("custom sin serverUrl aceptado")
+	}
+	if err := sched.SaveSettings(Settings{IntervalHours: 12, Provider: ProviderCustom, ServerURL: "https://speed.lan/endpoint"}); err != nil {
+		t.Fatalf("save custom: %v", err)
+	}
+	if got := sched.LoadSettings(); got.Provider != ProviderCustom || got.ServerURL != "https://speed.lan/endpoint" {
+		t.Fatalf("roundtrip custom: %+v", got)
+	}
+}
+
+// TestExecuteUsaHTTPRunner: con provider != ookla el scheduler ejecuta el
+// runner HTTP inyectado, no el runner Ookla.
+func TestExecuteUsaHTTPRunner(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	st, err := NewStore(d.DB)
+	if err != nil {
+		t.Fatalf("store: %v", err)
+	}
+	sched := NewScheduler(st, d.DB, fakeRunner{})
+	sched.SetHTTPRunner(fixedRunner{down: 555, up: 111})
+
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 12, Provider: ProviderCloudflare}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	if err := sched.RunNow(); err != nil {
+		t.Fatalf("RunNow: %v", err)
+	}
+	// Espera activa corta al single-flight (RunNow ejecuta en goroutine).
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		last, _ := sched.Store().Latest()
+		if last != nil {
+			if last.DownMbps != 555 || last.UpMbps != 111 {
+				t.Fatalf("se uso el runner Ookla, no el HTTP: %+v", last)
+			}
+			return
+		}
+	time.Sleep(10 * time.Millisecond)
+	}
+	t.Fatal("el test manual no persistio resultado")
+}

+ 45 - 1
server-go/internal/speedtest/scheduler.go

@@ -50,6 +50,11 @@ type Settings struct {
 	IntervalHours int    `json:"intervalHours"`
 	ServerURL     string `json:"serverUrl"`
 	AlertPct      int    `json:"alertPct"`
+	// Provider (#976): metodo de medicion. ""/ookla = speedtest.net;
+	// cloudflare = speed.cloudflare.com por HTTP; librespeed = instancia
+	// LibreSpeed cuya URL base viaja en ServerURL; custom (#1001) =
+	// endpoint HTTP libre cuya URL completa viaja en ServerURL.
+	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).
@@ -65,6 +70,7 @@ const (
 	kvInterval  = "settings.speedtest.interval_h"
 	kvServerURL = "settings.speedtest.server_url"
 	kvAlertPct  = "settings.speedtest.alert_pct"
+	kvProvider  = "settings.speedtest.provider"
 	kvContractD = "settings.wan.speed_down" // del issue #151 (lectura)
 
 	kvScheduleKind = "settings.speedtest.schedule_kind"
@@ -86,6 +92,11 @@ type Scheduler struct {
 	runner Runner
 	emit   AlertEmitter
 
+	// httpRunner (#976) ejecuta los providers HTTP (cloudflare/librespeed/
+	// custom); nil = se construye un HTTPRunner por ejecucion. Inyectable
+	// en tests.
+	httpRunner 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)
@@ -111,6 +122,20 @@ func NewScheduler(store *Store, db *sql.DB, runner Runner) *Scheduler {
 // adapter live en main).
 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 }
+
+// runnerFor elige la implementacion segun el provider configurado.
+func (s *Scheduler) runnerFor(provider string) Runner {
+	if provider == "" || provider == ProviderOokla {
+		return s.runner
+	}
+	if s.httpRunner != nil {
+		return s.httpRunner
+	}
+	return HTTPRunner{Provider: provider}
+}
+
 // Store expone el store para las rutas de lectura (history/latest).
 func (s *Scheduler) Store() *Store { return s.store }
 
@@ -175,7 +200,7 @@ func (s *Scheduler) executeLocked(st Settings, origin string) error {
 
 	ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
 	defer cancel()
-	res, err := s.runner.Run(ctx, st.ServerURL)
+	res, err := s.runnerFor(st.Provider).Run(ctx, st.ServerURL)
 	if err != nil {
 		s.setLastError(err)
 		return err
@@ -293,6 +318,9 @@ func (s *Scheduler) LoadSettings() Settings {
 	if v := kvGet(s.db, kvServerURL); v != "" {
 		st.ServerURL = v
 	}
+	if v := kvGet(s.db, kvProvider); validProvider(v) {
+		st.Provider = v
+	}
 	if v, ok := kvInt(s.db, kvAlertPct); ok && v >= 0 && v <= 90 {
 		st.AlertPct = v
 	}
@@ -347,12 +375,28 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 		}
 		return errors.New("serverUrl debe ser una URL http(s) válida")
 	}
+	// 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).
+	if st.Provider == "" {
+		st.Provider = ProviderOokla
+	}
+	if !validProvider(st.Provider) {
+		return errors.New("provider debe ser ookla, cloudflare, librespeed o custom")
+	}
+	if st.Provider == ProviderLibrespeed && strings.TrimSpace(st.ServerURL) == "" {
+		return errors.New("librespeed exige serverUrl con la URL base de la instancia")
+	}
+	if st.Provider == ProviderCustom && strings.TrimSpace(st.ServerURL) == "" {
+		return errors.New("custom exige serverUrl con la URL del endpoint de medición")
+	}
 	if st.AlertPct < 0 || st.AlertPct > 90 {
 		return errors.New("alertPct debe estar entre 0 y 90 (0 = desactivada)")
 	}
 	kvSet(s.db, kvEnabled, boolStr(st.Enabled))
 	kvSet(s.db, kvInterval, fmt.Sprintf("%d", st.IntervalHours))
 	kvSet(s.db, kvServerURL, strings.TrimSpace(st.ServerURL))
+	kvSet(s.db, kvProvider, st.Provider)
 	kvSet(s.db, kvAlertPct, fmt.Sprintf("%d", st.AlertPct))
 	kvSet(s.db, kvScheduleKind, st.ScheduleKind)
 	kvSet(s.db, kvDayOfWeek, intPtrStr(st.DayOfWeek))

+ 83 - 5
server-go/internal/tlsmode/manager.go

@@ -4,7 +4,7 @@
 //
 // FORK: see docs/https.md. In short:
 //
-//   - Enabling HTTPS only adds a TLS listener (NETPULSE_TLS_PORT, 3443 by
+//   - Enabling HTTPS only adds a TLS listener (NETPULSE_TLS_PORT, 443 by
 //     default) served with a leaf of the private CA. Plain HTTP keeps working
 //     exactly as before (mode "full"), so enabling it cannot lock anyone out.
 //   - Mode "migrate" stops plain HTTP from carrying credentials - logins,
@@ -36,6 +36,7 @@ import (
 	"os"
 	"path/filepath"
 	"slices"
+	"strconv"
 	"strings"
 	"sync"
 	"sync/atomic"
@@ -66,6 +67,7 @@ func ParseMode(s string) (Mode, error) {
 const (
 	kvEnabled = "settings.https.enabled"
 	kvMode    = "settings.https.mode"
+	kvPort    = "settings.https.port" // #978: UI-chosen HTTPS port
 
 	// ConfirmWindow is how long a staged mode change waits for confirmation
 	// from an HTTPS page before it is dropped.
@@ -90,6 +92,11 @@ type Options struct {
 	// the private CA is on; EnvMode is non-empty when it fixes the mode.
 	EnvEnabled *bool
 	EnvMode    Mode
+	// EnvPort (#978) is true when NETPULSE_TLS_PORT fixes the port: the UI
+	// setting is locked, like the rest of the environment. PlainPort is the
+	// plain HTTP port, which the HTTPS listener cannot reuse.
+	EnvPort   bool
+	PlainPort int
 	// Unavailable, when not empty, says why this server's HTTPS is managed
 	// elsewhere (on-box, or a certificate of the admin's own), and the
 	// manager stays off.
@@ -112,6 +119,7 @@ type Manager struct {
 	mu       sync.Mutex
 	handler  http.Handler
 	enabled  bool
+	port     int // #978: mutable via SetPort (opts.Port is only the default)
 	ca       *tlscert.CA
 	srv      *http.Server
 	caStop   chan struct{}
@@ -155,6 +163,14 @@ func New(opts Options) *Manager {
 		mode = Full
 	}
 	m.mode.Store(mode)
+	// Puerto (#978): el entorno manda; si no, el kv guardado; si no, el
+	// default de Options.
+	m.port = opts.Port
+	if !opts.EnvPort {
+		if v := m.savedPort(); v != 0 {
+			m.port = v
+		}
+	}
 	return m
 }
 
@@ -222,7 +238,7 @@ func (m *Manager) startLocked() error {
 	if err := m.openCALocked(); err != nil {
 		return err
 	}
-	addr := fmt.Sprintf(":%d", m.opts.Port)
+	addr := fmt.Sprintf(":%d", m.port)
 	// Turning HTTPS off and on again quickly can find the previous listener
 	// still closing (stopLocked shuts it down in the background).
 	var ln net.Listener
@@ -245,7 +261,7 @@ func (m *Manager) startLocked() error {
 		}
 	}()
 	m.lastErr = ""
-	m.opts.Logf("[netpulse] HTTPS on :%d (private CA)", m.opts.Port)
+	m.opts.Logf("[netpulse] HTTPS on :%d (private CA)", m.port)
 	return nil
 }
 
@@ -321,6 +337,47 @@ func (m *Manager) SetEnabled(on bool, by string) error {
 	return nil
 }
 
+// SetPort changes the HTTPS listener's port, live (#978): with HTTPS on the
+// listener rebinds at once (no restart); with HTTPS off the new port applies
+// the next time it is turned on. Agents that pinned the old port keep
+// trying it - the API warns about them before calling this.
+func (m *Manager) SetPort(port int, by string) error {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.opts.Unavailable != "" || m.opts.EnvPort {
+		return ErrLocked
+	}
+	if port < 1 || port > 65535 {
+		return fmt.Errorf("the port must be between 1 and 65535")
+	}
+	if m.opts.PlainPort != 0 && port == m.opts.PlainPort {
+		return fmt.Errorf("the HTTPS port cannot be the plain HTTP port (%d)", m.opts.PlainPort)
+	}
+	if port == m.port {
+		return nil
+	}
+	old := m.port
+	m.port = port
+	if m.enabled {
+		m.stopLocked()
+		if err := m.startLocked(); err != nil {
+			// Roll back: better the old port than no HTTPS at all.
+			m.port = old
+			if err2 := m.startLocked(); err2 != nil {
+				m.enabled = false
+				m.mode.Store(Full)
+				m.lastErr = err2.Error()
+				return fmt.Errorf("HTTPS port %d failed (%v) and restoring %d failed too: %v", port, err, old, err2)
+			}
+			m.lastErr = err.Error()
+			return fmt.Errorf("HTTPS port %d: %w", port, err)
+		}
+	}
+	m.savePort(port)
+	m.opts.Logf("[netpulse] HTTPS port %d -> %d by %s", old, port, by)
+	return nil
+}
+
 // RequestMode changes what plain HTTP may do. Going back to full takes effect
 // at once; a stricter mode is staged and returns the code to confirm it with
 // from an HTTPS page (Confirm) before ConfirmWindow runs out.
@@ -412,6 +469,7 @@ type Status struct {
 	Mode          Mode      `json:"mode"`
 	ModeLocked    bool      `json:"modeLocked"`
 	Port          int       `json:"port"`
+	PortLocked    bool      `json:"portLocked"`
 	RootSHA256    string    `json:"rootSha256,omitempty"`
 	Fingerprint   string    `json:"fingerprint,omitempty"`
 	Names         []string  `json:"names,omitempty"`
@@ -433,7 +491,8 @@ func (m *Manager) Status() Status {
 		EnabledLocked: m.opts.Unavailable != "" || m.opts.EnvEnabled != nil,
 		Mode:          m.Mode(),
 		ModeLocked:    m.opts.Unavailable != "" || m.opts.EnvMode != "",
-		Port:          m.opts.Port,
+		Port:          m.port,
+		PortLocked:    m.opts.Unavailable != "" || m.opts.EnvPort,
 		Error:         m.lastErr,
 	}
 	if p := m.pending; p != nil && m.opts.Now().Before(p.expires) {
@@ -528,7 +587,7 @@ func (m *Manager) RedirectTarget(r *http.Request) (string, bool) {
 	}
 	u := url.URL{
 		Scheme:   "https",
-		Host:     net.JoinHostPort(host, fmt.Sprint(m.opts.Port)),
+		Host:     net.JoinHostPort(host, fmt.Sprint(m.port)),
 		Path:     r.URL.Path,
 		RawQuery: r.URL.RawQuery,
 	}
@@ -548,6 +607,19 @@ func (m *Manager) savedMode() Mode {
 	return Full
 }
 
+// savedPort (#978): the UI-chosen port, 0 when absent or invalid.
+func (m *Manager) savedPort() int {
+	v := m.kvGet(kvPort)
+	if v == "" {
+		return 0
+	}
+	n, err := strconv.Atoi(v)
+	if err != nil || n < 1 || n > 65535 {
+		return 0
+	}
+	return n
+}
+
 func (m *Manager) saveEnabled(on bool) {
 	v := "0"
 	if on {
@@ -562,6 +634,12 @@ func (m *Manager) saveMode(mode Mode) {
 	}
 }
 
+func (m *Manager) savePort(port int) {
+	if !m.opts.EnvPort {
+		m.kvSet(kvPort, strconv.Itoa(port))
+	}
+}
+
 func (m *Manager) kvGet(key string) string {
 	if m.opts.DB == nil {
 		return ""

+ 66 - 0
server-go/internal/tlsmode/manager_test.go

@@ -178,6 +178,72 @@ func TestTheEnvironmentWins(t *testing.T) {
 	}
 }
 
+// TestSetPortRebindsLive (#978): with HTTPS on, SetPort rebinds the listener
+// at once, persists the choice across a restart, and validates input.
+func TestSetPortRebindsLive(t *testing.T) {
+	r := newRig(t, nil)
+	if err := r.m.SetEnabled(true, "admin"); err != nil {
+		t.Fatalf("enable: %v", err)
+	}
+	if _, err := r.getTLS("/"); err != nil {
+		t.Fatalf("HTTPS on the original port: %v", err)
+	}
+
+	// Validation: range and the plain HTTP port.
+	if err := r.m.SetPort(0, "admin"); err == nil {
+		t.Fatal("port 0 accepted")
+	}
+	if err := r.m.SetPort(70000, "admin"); err == nil {
+		t.Fatal("port 70000 accepted")
+	}
+	// Same port: no-op, no error.
+	if err := r.m.SetPort(r.port, "admin"); err != nil {
+		t.Fatalf("same port should be a no-op: %v", err)
+	}
+
+	newPort := freePort(t)
+	if newPort == r.port {
+		newPort = freePort(t)
+	}
+	if err := r.m.SetPort(newPort, "admin"); err != nil {
+		t.Fatalf("SetPort: %v", err)
+	}
+	if got := r.m.Status().Port; got != newPort {
+		t.Fatalf("Status().Port = %d, want %d", got, newPort)
+	}
+	// The listener answers on the new port with the same root.
+	r.port = newPort
+	body, err := r.getTLS("/")
+	if err != nil || body != "tls=true" {
+		t.Fatalf("HTTPS did not rebind to the new port: %q %v", body, err)
+	}
+
+	// The choice survives a restart (kv), without the env fixing it.
+	r.m.Close()
+	again := New(r.m.opts)
+	if got := again.Status().Port; got != newPort {
+		t.Fatalf("after restart port = %d, want %d", got, newPort)
+	}
+	again.Close()
+}
+
+// TestSetPortLockedByEnv (#978): NETPULSE_TLS_PORT fixes the port, like the
+// rest of the environment.
+func TestSetPortLockedByEnv(t *testing.T) {
+	r := newRig(t, func(o *Options) { o.EnvPort = true; o.PlainPort = 8080 })
+	if err := r.m.SetPort(freePort(t), "admin"); !errors.Is(err, ErrLocked) {
+		t.Fatalf("changing a port fixed in the environment: %v, want ErrLocked", err)
+	}
+	if !r.m.Status().PortLocked {
+		t.Fatal("status does not show the port as locked")
+	}
+	// The plain HTTP port is rejected even without the env.
+	r2 := newRig(t, func(o *Options) { o.PlainPort = 8080 })
+	if err := r2.m.SetPort(8080, "admin"); err == nil {
+		t.Fatal("the plain HTTP port was accepted as HTTPS port")
+	}
+}
+
 func TestAStricterModeWaitsForConfirmationOverHTTPS(t *testing.T) {
 	r := newRig(t, nil)
 	if _, _, err := r.m.RequestMode(Migrate, "admin"); err == nil {

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff