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

feat(router): per-router high-temperature threshold (#716) (#730)

The high-temperature alert used a single hardcoded 65 C threshold for
every router, so routers that run hotter forced raising it for all and
hiding real problems on the cooler ones. Routers now have an optional
temp_threshold column (NULL means the 65 C default) used by the alert
and the hot state, editable from the router dialog. The global slider,
which never governed the server alert, is removed.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
e6fb14d979

+ 2 - 0
CHANGELOG.md

@@ -13,6 +13,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- **El umbral de alerta por temperatura alta pasa a ser por router (#716)**: antes era un único valor fijo de 65 °C para todos, así que un router que corre más caliente obligaba a subir el umbral global y ocultaba problemas reales en los más frescos. Ahora cada router puede fijar el suyo (columna `temp_threshold` en `routers`, vacío = 65 °C por defecto); la alerta de temperatura y el estado "hot" del dashboard lo usan. En la UI se configura en Ajustes → Dispositivos, y se retira el slider global de "Datos y umbrales" que no gobernaba la alerta real.
+
 - **El panel WireGuard y la topología ya ven los peers de todos los túneles, no solo `wg0` (#713)**: el servidor sondeaba una única interfaz (`WG_INTERFACE`, por defecto `wg0`), así que un gateway con varios túneles solo mostraba los peers de `wg0`. Ahora `WG_INTERFACE` admite `auto` (nuevo default) o vacío para descubrir y agregar los peers de todas las interfaces del router (`wg show interfaces`), y un valor explícito (una interfaz o una lista separada por comas) sigue actuando como filtro, conservando el comportamiento del caso de un solo túnel.
 
 - **Detección y check de `owut` para upgrades de OpenWrt, Fase 1 (#695)**: el servidor puede detectar si un router tiene disponible `owut` (attended sysupgrade) y ejecutar `owut check` por SSH, exponiendo el resultado para revisión en la UI de Actualizaciones por router: si hay una actualización disponible y si la infraestructura ASU (sysupgrade.openwrt.org) puede construir la imagen. Es solo detección + check; `owut download`/`owut install` llegarán en una fase posterior con confirmación explícita. El flujo sysupgrade actual se mantiene intacto como fallback (owut requiere OpenWrt 24.10+; en 23.05 y anteriores no existe).

+ 4 - 1
app/public/locales/en/translation.json

@@ -844,7 +844,7 @@
     "sortBy": "Sort by {{column}}",
     "statusAria": "{{online}} routers online, {{warnings}} with warnings",
     "summary": "{{total}} routers · {{online}} online · {{warnings}} with warnings",
-    "tempThreshold": "Threshold: 65 °C",
+    "tempThreshold": "Threshold: {{value}} °C",
     "traffic24h": "Traffic 24 h",
     "trafficAria": "{{name}} traffic over the last 24 hours",
     "upgradingAll": "Updating…",
@@ -1152,6 +1152,7 @@
       "tempCaptionHot": "{{name}} is at {{temp}} °C → alert active",
       "tempCaptionOk": "{{name}} is at {{temp}} °C → within the limit",
       "tempLabel": "Warning temperature",
+      "tempNote": "The high-temperature threshold is set per router in \"Devices\" (65 °C by default).",
       "title": "Data & thresholds",
       "units": "Traffic units"
     },
@@ -1295,6 +1296,8 @@
       "snmpPollInterval": "Interval (s)",
       "sshPort": "SSH port",
       "sshPortHint": "SSH port of the router (default 22)",
+      "tempThreshold": "Temperature threshold (°C)",
+      "tempThresholdHint": "High-temperature alert threshold. Empty = 65 °C by default. A router that runs hotter can raise its own without hiding issues in cooler ones.",
       "openWrtBadge": "OpenWrt"
     },
     "overrides": {

+ 4 - 1
app/public/locales/es/translation.json

@@ -844,7 +844,7 @@
     "sortBy": "Ordenar por {{column}}",
     "statusAria": "{{online}} equipos online, {{warnings}} con aviso",
     "summary": "{{total}} equipos · {{online}} online · {{warnings}} con aviso",
-    "tempThreshold": "Umbral: 65 °C",
+    "tempThreshold": "Umbral: {{value}} °C",
     "traffic24h": "Tráfico 24 h",
     "trafficAria": "Tráfico de {{name}} en las últimas 24 horas",
     "upgradingAll": "Actualizando…",
@@ -1152,6 +1152,7 @@
       "tempCaptionHot": "{{name}} está a {{temp}} °C → aviso activo",
       "tempCaptionOk": "{{name}} está a {{temp}} °C → dentro del límite",
       "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"
     },
@@ -1295,6 +1296,8 @@
       "snmpPollInterval": "Intervalo (s)",
       "sshPort": "Puerto SSH",
       "sshPortHint": "Puerto SSH del router (22 por defecto)",
+      "tempThreshold": "Umbral de temperatura (°C)",
+      "tempThresholdHint": "Umbral de alerta por temperatura alta. Vacío = 65 °C por defecto. Un router que corre más caliente puede subir el suyo sin ocultar problemas en los más frescos.",
       "openWrtBadge": "OpenWrt"
     },
     "overrides": {

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

@@ -255,7 +255,7 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
                 value={`${router.temp} °C`}
                 pct={Math.min(100, ((router.temp ?? 0) / 90) * 100)}
                 hot={router.hotMetric === 'temp'}
-                title={router.hotMetric === 'temp' ? t('routers.tempThreshold') : undefined}
+                title={router.hotMetric === 'temp' ? t('routers.tempThreshold', { value: router.tempThreshold ?? 65 }) : undefined}
               />
             </>
           )}

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

@@ -69,7 +69,7 @@ function TempCell({ router }: { router: Router }) {
         'inline-flex rounded-md px-1.5 py-0.5 font-mono text-mono-sm',
         hot ? 'bg-warn/10 text-warn' : 'text-text-primary',
       )}
-      title={hot ? t('routers.tempThreshold') : undefined}
+      title={hot ? t('routers.tempThreshold', { value: router.tempThreshold ?? 65 }) : undefined}
     >
       {router.temp} °C
     </span>

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

@@ -69,6 +69,8 @@ export interface Router {
   bandSplit?: { band24: number; band5: number; band6: number; cable: number }
   /** Métrica en umbral (se pinta --warn), p. ej. 'temp' en Patio */
   hotMetric?: 'cpu' | 'ram' | 'temp'
+  /** Umbral efectivo de temperatura alta (°C) resuelto para este router (issue #716). */
+  tempThreshold?: number
   /**
    * Backhaul del AP (C1): 'wifi' = uplink inalámbrico (se dibuja dashed
    * ámbar); 'cable'/ausente = cableado o desconocido.

+ 24 - 18
app/src/pages/Settings.tsx

@@ -290,6 +290,7 @@ interface ConfigRouter {
   snmp_port: number
   snmp_poll_interval: number
   ssh_port?: number
+  temp_threshold?: number | null
 }
 
 interface DiscoverCandidate {
@@ -334,6 +335,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editSnmpPort, setEditSnmpPort] = useState(161)
   const [editSnmpPollInterval, setEditSnmpPollInterval] = useState(60)
   const [editSshPort, setEditSshPort] = useState(22)
+  const [editTempThreshold, setEditTempThreshold] = useState('')
   const [editSubmitting, setEditSubmitting] = useState(false)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [copied, setCopied] = useState(false)
@@ -517,6 +519,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditSnmpPort(r.snmp_port ?? 161)
     setEditSnmpPollInterval(r.snmp_poll_interval ?? 60)
     setEditSshPort(r.ssh_port ?? 22)
+    setEditTempThreshold(r.temp_threshold != null ? String(r.temp_threshold) : '')
     setError(null)
   }
 
@@ -541,6 +544,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           snmp_port: editSnmpPort,
           snmp_poll_interval: editSnmpPollInterval,
           ssh_port: editSshPort,
+          temp_threshold: editTempThreshold.trim() === '' ? 0 : Number(editTempThreshold),
         }),
       })
       if (res.status === 409) {
@@ -934,6 +938,23 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   className="rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
                 />
               </div>
+              <div>
+                <label htmlFor="temp-threshold" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                  {t('settings.routers.tempThreshold')}
+                </label>
+                <input
+                  id="temp-threshold"
+                  type="number"
+                  min={0}
+                  max={150}
+                  value={editTempThreshold}
+                  onChange={(e) => setEditTempThreshold(e.target.value)}
+                  placeholder="65"
+                  aria-label={t('settings.routers.tempThreshold')}
+                  className="w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                />
+                <p className="mt-1 text-caption leading-relaxed text-text-muted">{t('settings.routers.tempThresholdHint')}</p>
+              </div>
               <div className="flex flex-wrap items-center gap-3">
                 <SegmentedControl
                   options={[
@@ -3381,7 +3402,7 @@ function SettingsIndex({ items }: { items: SettingsIndexItem[] }) {
 export default function Settings() {
   const { t, i18n } = useTranslation()
   const reduce = useReducedMotion() ?? false
-  const { devices, routers, wan, isDemo, refresh: refreshOverview } = useNetPulse()
+  const { devices, wan, isDemo, refresh: refreshOverview } = useNetPulse()
   const auth = useAuth()
   // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
   const [services] = useServicesVisibility()
@@ -3626,17 +3647,14 @@ export default function Settings() {
   const [units, setUnits] = useStoredState<'mbps' | 'mbs'>('netpulse-units', 'mbps')
   const [decimalEs, setDecimalEs] = useStoredState('netpulse-decimal-es', true)
   const [refresh, setRefresh] = useStoredState<'3' | '5' | '10' | '0'>('netpulse-refresh', '3')
-  const [tempT, setTempT] = useStoredState('netpulse-th-temp', 65)
   const [signalT, setSignalT] = useStoredState('netpulse-th-signal', -70)
   const [latencyT, setLatencyT] = useStoredState('netpulse-th-latency', 50)
 
-  const patio = routers.find((r) => r.id === 'patio') ?? routers[routers.length - 1]
-  const tempHot = (patio?.temp ?? 0) > tempT
   const weakCount = devices.filter((d) => d.signalDbm !== null && d.signalDbm < signalT).length
   const latencyHot = wan.latencyMs > latencyT
   const previewScore = Math.max(
     40,
-    Math.min(100, 100 - (tempHot ? 8 : 0) - weakCount * 2 - (latencyHot ? 6 : 0)),
+    Math.min(100, 100 - weakCount * 2 - (latencyHot ? 6 : 0)),
   )
 
   // ——— Notificaciones visuales ———
@@ -3865,19 +3883,6 @@ export default function Settings() {
               <div className="space-y-5">
                 {(
                   [
-                    {
-                      key: 'temp',
-                      label: t('settings.data.tempLabel'),
-                      value: tempT,
-                      set: setTempT,
-                      min: 50,
-                      max: 85,
-                      format: (v: number) => `${v} °C`,
-                      caption: tempHot
-                        ? t('settings.data.tempCaptionHot', { name: patio?.name ?? '—', temp: patio?.temp ?? 0 })
-                        : t('settings.data.tempCaptionOk', { name: patio?.name ?? '—', temp: patio?.temp ?? 0 }),
-                      captionHot: tempHot,
-                    },
                     {
                       key: 'signal',
                       label: t('topology.weakSignal'),
@@ -3950,6 +3955,7 @@ export default function Settings() {
                   </div>
                 ))}
               </div>
+              <p className="mt-4 text-caption leading-relaxed text-text-muted">{t('settings.data.tempNote')}</p>
             </div>
 
             {/* divider: Velocidad WAN contratada (izq) | Test de velocidad periódico (der) */}

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

@@ -1076,6 +1076,8 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	l.mu.Lock()
 	gw := l.gatewayCfg
 	l.mu.Unlock()
+	// issue #716: umbral de temperatura alta del router (default 65 °C).
+	thr := p.cfg.TempThresholdValue()
 	model := p.cfg.Name
 	if model == "" {
 		model = p.cfg.Host
@@ -1098,7 +1100,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	}
 	if p.temp > 75 {
 		health -= 25
-	} else if p.temp > 65 {
+	} else if p.temp > thr {
 		health -= 12
 	}
 	if p.ram > 90 {
@@ -1115,7 +1117,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	}
 	isGw := gw != nil && p.cfg.ID == gw.ID
 	status := "online"
-	if p.temp > 65 || p.cpu > 85 {
+	if p.temp > thr || p.cpu > 85 {
 		status = "warn"
 	}
 	sparkline := make([]float64, 0, len(history))
@@ -1130,7 +1132,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 		IP: p.cfg.Host, Status: status, Health: health,
 		CPU: iptr(p.cpu), RAM: iptr(p.ram), Temp: iptr(p.temp),
 		Uptime: fmtUptime(p.uptimeSec), Clients: len(p.leases),
-		Sparkline: sparkline,
+		Sparkline: sparkline, TempThreshold: thr,
 	}
 	if noVitals {
 		r.VitalsAvailable = bptr(false)
@@ -1183,7 +1185,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 			Time:        "ahora mismo", RouterID: p.cfg.ID,
 		})
 	}
-	if p.temp > 65 {
+	if p.temp > thr {
 		r.HotMetric = "temp"
 	}
 	return r
@@ -2234,6 +2236,28 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	return devices
 }
 
+// emitTempAlert emite la alerta de temperatura alta UNA vez por proceso
+// (flag, como el JS), usando el umbral del router (issue #716; default 65).
+// Debe llamarse con l.mu tomado.
+func (l *Live) emitTempAlert(cfg RouterConfig, router Router) {
+	thr := cfg.TempThresholdValue()
+	if router.Temp == nil || *router.Temp <= thr || l.lastStatus[cfg.ID+":temp"] == "warn" {
+		return
+	}
+	l.lastStatus[cfg.ID+":temp"] = "warn"
+	l.engine.Emit(AlertEvent{
+		ID:       fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
+		Category: alerts.CatRouter, Urgent: true,
+		Severity:    "warn",
+		Title:       "Temperatura alta en " + router.Name,
+		Description: fmt.Sprintf("%d °C, por encima del umbral (%d °C)", *router.Temp, thr),
+		Hint:        alerts.HintFor(alerts.HintHighTemp),
+		Type:        alerts.HintHighTemp,
+		Vars:        map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp)},
+		Time:        "ahora mismo", RouterID: cfg.ID,
+	})
+}
+
 // computeHealth (index.js:462-486).
 func computeHealth(routers []Router, adguard *AdGuardStats) HealthScore {
 	score := 100
@@ -2248,10 +2272,16 @@ func computeHealth(routers []Router, adguard *AdGuardStats) HealthScore {
 			score -= 30
 			infraScore -= 40
 			breakdown = append(breakdown, HealthDelta{Label: r.Name + " offline", Delta: -30})
-		} else if r.Temp != nil && *r.Temp > 65 {
-			score -= 8
-			infraScore -= 10
-			breakdown = append(breakdown, HealthDelta{Label: "temp. " + r.Name, Delta: -8})
+		} else if r.Temp != nil {
+			thr := r.TempThreshold
+			if thr <= 0 {
+				thr = DefaultTempThreshold
+			}
+			if *r.Temp > thr {
+				score -= 8
+				infraScore -= 10
+				breakdown = append(breakdown, HealthDelta{Label: "temp. " + r.Name, Delta: -8})
+			}
 		}
 	}
 	if adguard != nil && adguard.Status != "active" {
@@ -2397,20 +2427,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		router := l.buildRouter(p, l.metricsHistory(cfg.ID, "24h"))
 		l.mu.Lock()
 		l.lastGood[cfg.ID] = &router
-		// Alerta de temperatura UNA vez por proceso (flag, como el JS)
-		if router.Temp != nil && *router.Temp > 65 && l.lastStatus[cfg.ID+":temp"] != "warn" {
-			l.lastStatus[cfg.ID+":temp"] = "warn"
-			l.engine.Emit(AlertEvent{
-				ID:       fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
-				Category: alerts.CatRouter, Urgent: true,
-				Severity: "warn", Title: "Temperatura alta en " + router.Name,
-				Description: fmt.Sprintf("%d °C, por encima del umbral (65 °C)", *router.Temp),
-				Hint:        alerts.HintFor(alerts.HintHighTemp),
-				Type:        alerts.HintHighTemp,
-				Vars:        map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp)},
-				Time:        "ahora mismo", RouterID: cfg.ID,
-			})
-		}
+		l.emitTempAlert(cfg, router)
 		l.mu.Unlock()
 		routerList = append(routerList, router)
 	}

+ 135 - 0
server-go/internal/adapters/live_temp_threshold_test.go

@@ -0,0 +1,135 @@
+// live_temp_threshold_test.go — issue #716: umbral de temperatura alta por
+// router. El umbral configurado se usa en el estado hot del router, en la
+// salud global y en el emisor de alerta, cayendo al default 65 cuando no hay.
+package adapters
+
+import (
+	"strings"
+	"testing"
+)
+
+func TestRouterConfigTempThresholdValue(t *testing.T) {
+	if got := (RouterConfig{}).TempThresholdValue(); got != DefaultTempThreshold {
+		t.Fatalf("sin umbral: %d, esperaba %d", got, DefaultTempThreshold)
+	}
+	if got := (RouterConfig{TempThreshold: iptr(70)}).TempThresholdValue(); got != 70 {
+		t.Fatalf("umbral 70: %d, esperaba 70", got)
+	}
+	if got := (RouterConfig{TempThreshold: iptr(0)}).TempThresholdValue(); got != DefaultTempThreshold {
+		t.Fatalf("umbral 0: %d, esperaba default %d", got, DefaultTempThreshold)
+	}
+}
+
+func TestBuildRouterUsesPerRouterTempThreshold(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+
+	// Umbral 70 y 68 °C → por debajo: online y sin hotMetric.
+	p := &routerPolled{
+		cfg:      RouterConfig{ID: "rt1", Name: "RT1", Host: "192.168.1.2", TempThreshold: iptr(70)},
+		temp:     68,
+		polledAt: 1000,
+	}
+	r := l.buildRouter(p, nil)
+	if r.Status != "online" {
+		t.Fatalf("68 °C con umbral 70: status=%q, esperaba online", r.Status)
+	}
+	if r.HotMetric != "" {
+		t.Fatalf("68 °C con umbral 70: hotMetric=%q, esperaba vacío", r.HotMetric)
+	}
+	if r.TempThreshold != 70 {
+		t.Fatalf("TempThreshold resuelto=%d, esperaba 70", r.TempThreshold)
+	}
+
+	// 72 °C supera el umbral 70 → warn + hotMetric.
+	p2 := &routerPolled{
+		cfg:      RouterConfig{ID: "rt1", Name: "RT1", Host: "192.168.1.2", TempThreshold: iptr(70)},
+		temp:     72,
+		polledAt: 1000,
+	}
+	r2 := l.buildRouter(p2, nil)
+	if r2.Status != "warn" {
+		t.Fatalf("72 °C con umbral 70: status=%q, esperaba warn", r2.Status)
+	}
+	if r2.HotMetric != "temp" {
+		t.Fatalf("72 °C con umbral 70: hotMetric=%q, esperaba temp", r2.HotMetric)
+	}
+}
+
+func TestBuildRouterTempThresholdFallsBackToDefault(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	// Sin umbral configurado → 65. 66 °C dispara warn (comportamiento previo).
+	p := &routerPolled{
+		cfg:      RouterConfig{ID: "rt1", Name: "RT1", Host: "192.168.1.2"},
+		temp:     66,
+		polledAt: 1000,
+	}
+	r := l.buildRouter(p, nil)
+	if r.Status != "warn" || r.HotMetric != "temp" {
+		t.Fatalf("66 °C sin umbral: status=%q hotMetric=%q, esperaba warn/temp", r.Status, r.HotMetric)
+	}
+	if r.TempThreshold != DefaultTempThreshold {
+		t.Fatalf("TempThreshold resuelto=%d, esperaba %d", r.TempThreshold, DefaultTempThreshold)
+	}
+}
+
+func TestEmitTempAlertUsesPerRouterThreshold(t *testing.T) {
+	l := liveTestLive()
+	cfg := RouterConfig{ID: "patio", Name: "Patio", TempThreshold: iptr(70)}
+	router := Router{Name: "Patio", Temp: iptr(72), TempThreshold: 70}
+
+	l.mu.Lock()
+	l.emitTempAlert(cfg, router)
+	l.mu.Unlock()
+
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("72 °C con umbral 70: %d alertas, esperaba 1", len(list))
+	}
+	if !strings.Contains(list[0].Description, "70 °C") {
+		t.Fatalf("la descripción no refleja el umbral del router: %q", list[0].Description)
+	}
+}
+
+func TestEmitTempAlertNoAlertBelowThreshold(t *testing.T) {
+	l := liveTestLive()
+	cfg := RouterConfig{ID: "patio", Name: "Patio", TempThreshold: iptr(70)}
+	router := Router{Name: "Patio", Temp: iptr(68), TempThreshold: 70}
+
+	l.mu.Lock()
+	l.emitTempAlert(cfg, router)
+	l.mu.Unlock()
+
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("68 °C con umbral 70: %d alertas, esperaba 0", n)
+	}
+}
+
+func TestEmitTempAlertFallsBackToDefault(t *testing.T) {
+	l := liveTestLive()
+	cfg := RouterConfig{ID: "patio", Name: "Patio"} // sin umbral → default 65
+	router := Router{Name: "Patio", Temp: iptr(66), TempThreshold: DefaultTempThreshold}
+
+	l.mu.Lock()
+	l.emitTempAlert(cfg, router)
+	l.mu.Unlock()
+
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("66 °C sin umbral: %d alertas, esperaba 1", len(list))
+	}
+	if !strings.Contains(list[0].Description, "65 °C") {
+		t.Fatalf("la descripción no usa el default 65: %q", list[0].Description)
+	}
+}
+
+func TestComputeHealthUsesPerRouterTempThreshold(t *testing.T) {
+	// 72 °C con umbral 70 penaliza (-8); 68 °C con umbral 70 no.
+	routers := []Router{
+		{Name: "hot", Status: "online", Temp: iptr(72), TempThreshold: 70},
+		{Name: "cool", Status: "online", Temp: iptr(68), TempThreshold: 70},
+	}
+	h := computeHealth(routers, nil)
+	if h.Score != 92 {
+		t.Fatalf("score=%d, esperaba 92", h.Score)
+	}
+}

+ 33 - 9
server-go/internal/adapters/types.go

@@ -179,23 +179,29 @@ type Router struct {
 	// reportar métricas de sistema (#441): switches sondeados por SNMP (#309)
 	// o pushers externos por beacon/scraper (#291). En ese caso CPU/RAM/Temp
 	// van a null y la UI no los pinta. Ausente = vitals disponibles.
-	VitalsAvailable *bool  `json:"vitalsAvailable,omitempty"`
+	VitalsAvailable *bool `json:"vitalsAvailable,omitempty"`
 	// SnmpEnabled: true si el router se sondea por SNMP (#309). Distingue un
 	// managed-switch sondeado por SNMP (que sí reporta contadores de bytes →
 	// la UI pinta bps) de un beacon/external que solo reporta tramas (fps)
 	// (#661). Ausente/false = no se sondea por SNMP.
-	SnmpEnabled bool `json:"snmpEnabled,omitempty"`
-	CPU             *int   `json:"cpu"`
-	RAM             *int   `json:"ram"`
-	Temp            *int   `json:"temp"`
-	Uptime          string `json:"uptime"` // "<d>d <h>h" | "—"
-	Clients         int    `json:"clients"`
+	SnmpEnabled bool   `json:"snmpEnabled,omitempty"`
+	CPU         *int   `json:"cpu"`
+	RAM         *int   `json:"ram"`
+	Temp        *int   `json:"temp"`
+	Uptime      string `json:"uptime"` // "<d>d <h>h" | "—"
+	Clients     int    `json:"clients"`
 	// BandSplit: clientes online por banda (2.4/5/6 GHz + cable) — issue #645.
 	// Misma fuente que Clients (mismo recuento), suma ≤ Clients (los clientes
 	// con banda desconocida "—" no caen en ninguna banda).
 	BandSplit *demoBandSplit `json:"bandSplit,omitempty"`
-	HotMetric string         `json:"hotMetric,omitempty"` // "temp" solo si temp>65
-	Sparkline []float64      `json:"sparkline"`
+	// HotMetric: métrica en umbral, p. ej. "temp" cuando supera el umbral
+	// de temperatura del router (issue #716).
+	HotMetric string `json:"hotMetric,omitempty"`
+	// TempThreshold: umbral efectivo de temperatura alta (°C) resuelto para
+	// este router (el configurado o DefaultTempThreshold). Lo usa computeHealth
+	// y la UI para pintar el umbral real en el tooltip (issue #716).
+	TempThreshold int       `json:"tempThreshold,omitempty"`
+	Sparkline     []float64 `json:"sparkline"`
 	// Backhaul: medio del uplink del router ("cable"|"wifi"). Ausente =
 	// cable/desconocido (router sin wifi o sonda no disponible).
 	Backhaul string `json:"backhaul,omitempty"`
@@ -798,6 +804,11 @@ type MetricsRow struct {
 	TxBps     *float64
 }
 
+// DefaultTempThreshold es el umbral de alerta por temperatura alta (°C)
+// cuando un router no lo configura (issue #716). Un router que corre más
+// caliente puede fijar el suyo sin ocultar problemas en los más frescos.
+const DefaultTempThreshold = 65
+
 // RouterConfig es una fila de la tabla routers (fuente de verdad; is_gateway
 // como booleano, orden is_gateway DESC, created_at ASC — SPEC §8.2).
 type RouterConfig struct {
@@ -821,6 +832,19 @@ type RouterConfig struct {
 	// SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
 	// estándar). 0/ausente → 22. Se usa en el pool, discovery e install.
 	SSHPort int `json:"ssh_port,omitempty"`
+	// TempThreshold (issue #716): umbral de alerta por temperatura alta (°C)
+	// de este router. NULL/ausente = DefaultTempThreshold (65). Un router que
+	// corre más caliente sube el suyo sin ocultar problemas en los más frescos.
+	TempThreshold *int `json:"temp_threshold,omitempty"`
+}
+
+// TempThresholdValue resuelve el umbral efectivo de temperatura alta (°C) de
+// este router: el configurado o DefaultTempThreshold si no lo hay (issue #716).
+func (c RouterConfig) TempThresholdValue() int {
+	if c.TempThreshold != nil && *c.TempThreshold > 0 {
+		return *c.TempThreshold
+	}
+	return DefaultTempThreshold
 }
 
 // SSHAddr devuelve el destino `host:port` para conectar por SSH, usando

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

@@ -466,6 +466,8 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "snmp_poll_interval", "ALTER TABLE routers ADD COLUMN snmp_poll_interval INTEGER NOT NULL DEFAULT 60")
 	// issue #605: puerto SSH por router (dropbear en puerto no estándar).
 	migrate(sqldb, "routers", "ssh_port", "ALTER TABLE routers ADD COLUMN ssh_port INTEGER NOT NULL DEFAULT 22")
+	// issue #716: umbral de alerta por temperatura alta (°C). NULL = 65 default.
+	migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
 	// issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
 	migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
 

+ 14 - 1
server-go/internal/httpapi/config.go

@@ -104,6 +104,9 @@ type routerInput struct {
 	// SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
 	// estándar). Ausente/0 → 22.
 	SSHPort *int `json:"ssh_port"`
+	// TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
+	// Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
+	TempThreshold *int `json:"temp_threshold"`
 }
 
 // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
@@ -338,12 +341,22 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		}
 		sshPort = &p
 	}
+	var tempThreshold *int
+	if in.TempThreshold != nil {
+		v := *in.TempThreshold
+		if v > 150 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
+			return
+		}
+		tempThreshold = &v
+	}
 	updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
 		Name: name, Host: host, Type: typ,
 		IsGateway: &gw, AgentOnly: &ao,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
-		SSHPort: sshPort,
+		SSHPort:       sshPort,
+		TempThreshold: tempThreshold,
 	})
 	if !ok {
 		writeError(w, http.StatusNotFound, "not_found")

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

@@ -320,6 +320,74 @@ func TestConfigRoutersFirmwareTarget(t *testing.T) {
 	}
 }
 
+// TestConfigRoutersTempThreshold cubre el umbral de temperatura por router
+// (issue #716): alta sin umbral (default 65), PUT que lo fija, persistencia en
+// la lista, reset a default con 0 y validación de rango.
+func TestConfigRoutersTempThreshold(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// POST sin umbral → 201 y el campo queda ausente (NULL = default 65).
+	res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"name":"rt1","host":"192.168.8.10","type":"openwrt"}`)
+	if res.StatusCode != 201 {
+		t.Fatalf("POST router: %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	router := body["router"].(map[string]any)
+	if _, ok := router["temp_threshold"]; ok {
+		t.Fatalf("temp_threshold tras alta debía estar ausente: %v", router)
+	}
+
+	// PUT fija el umbral → 200 y el campo cambia.
+	res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
+		`{"host":"192.168.8.10","temp_threshold":70}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT temp_threshold: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	rt := body["router"].(map[string]any)
+	if rt["temp_threshold"] != float64(70) {
+		t.Fatalf("temp_threshold tras PUT: %v", rt)
+	}
+
+	// GET persiste el valor en la lista.
+	res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("GET routers: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	var found float64 = -1
+	for _, r := range body["routers"].([]any) {
+		rm := r.(map[string]any)
+		if rm["id"] == "rt1" {
+			found, _ = rm["temp_threshold"].(float64)
+		}
+	}
+	if found != 70 {
+		t.Fatalf("temp_threshold persistido=%v, esperaba 70", found)
+	}
+
+	// PUT con 0 resetea a default (NULL) → campo ausente.
+	res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
+		`{"host":"192.168.8.10","temp_threshold":0}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT temp_threshold reset: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	rt = body["router"].(map[string]any)
+	if _, ok := rt["temp_threshold"]; ok {
+		t.Fatalf("temp_threshold tras reset debía estar ausente: %v", rt)
+	}
+
+	// Fuera de rango → 400 invalid_input.
+	res = doReq(t, "PUT", srv.URL+"/api/config/routers/rt1", cookie,
+		`{"host":"192.168.8.10","temp_threshold":200}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("temp_threshold fuera de rango: esperado 400, got %d", res.StatusCode)
+	}
+}
+
 // TestAdGuardConfigPort cubre PUT /api/config/adguard (#420):
 //   - guardar un puerto distinto de 3000 en modo standard
 //   - GET devuelve el puerto guardado, no 3000

+ 19 - 2
server-go/internal/routerstore/routerstore.go

@@ -27,7 +27,7 @@ const probeTimeout = 4 * time.Second
 // ListRouters devuelve la tabla routers ordenada is_gateway DESC,
 // created_at ASC, con is_gateway como booleano.
 func ListRouters(db *sql.DB) []adapters.RouterConfig {
-	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, temp_threshold FROM routers ORDER BY is_gateway DESC, created_at ASC")
 	if err != nil {
 		return []adapters.RouterConfig{}
 	}
@@ -37,7 +37,8 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 		var r adapters.RouterConfig
 		var gw, ao, snmpEn, snmpPort, snmpInterval, sshPort int
 		var name, ft, snmpComm sql.NullString
-		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort); err != nil {
+		var tt sql.NullInt64
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort, &tt); err != nil {
 			continue
 		}
 		r.Name = name.String
@@ -49,6 +50,10 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 		r.SnmpPort = snmpPort
 		r.SnmpPollInterval = snmpInterval
 		r.SSHPort = sshPort
+		if tt.Valid {
+			v := int(tt.Int64)
+			r.TempThreshold = &v
+		}
 		out = append(out, r)
 	}
 	return out
@@ -227,6 +232,9 @@ type UpdateInput struct {
 	SnmpPollInterval *int // issue #414
 	// SSHPort (issue #605): puerto SSH; nil = no tocar.
 	SSHPort *int
+	// TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
+	// nil = no tocar; <= 0 = reset a NULL (default 65); > 0 = fijar.
+	TempThreshold *int
 }
 
 // UpdateRouter actualiza un router existente por id. Si IsGateway pasa a true,
@@ -316,6 +324,15 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 		sets = append(sets, "ssh_port = ?")
 		args = append(args, v)
 	}
+	if in.TempThreshold != nil {
+		if *in.TempThreshold > 0 {
+			sets = append(sets, "temp_threshold = ?")
+			args = append(args, *in.TempThreshold)
+		} else {
+			// <= 0 = reset a default (NULL), misma convención que snmp_poll_interval.
+			sets = append(sets, "temp_threshold = NULL")
+		}
+	}
 	if len(sets) > 0 {
 		args = append(args, id)
 		if _, err := tx.Exec("UPDATE routers SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...); err != nil {