Explorar o código

Alerts: auto-resolve weak-signal episodes with hysteresis and consecutive samples (#1452) (#1453)

A weak-signal alert now closes itself when the client signal stays above
the threshold plus a hysteresis margin for N consecutive polls, instead of
lingering open until cleared by hand. Disappearing clients do not count as
recovered, roaming does not open or close anything on its own, and the
closed episode is kept in the log with its duration and recovery value.

Both the margin and the sample count live in kv (alerts.weak_signal_hysteresis_dbm,
alerts.weak_signal_resolve_samples, defaults 3 dBm / 3 samples) and are
editable from Settings - Data y umbrales alongside the threshold.
Nacho hai 1 mes
pai
achega
8f8aab0a42

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

@@ -297,6 +297,10 @@
       "firmware-downgrade-target": {
         "title": "Firmware downgrade target",
         "description": "{{router}}: the configured target \"{{target}}\" is older than the installed firmware \"{{firmware}}\""
+      },
+      "wifi-weak-recovered": {
+        "title": "Weak signal resolved on {{device}}",
+        "description": "Back to {{signal}} dBm on {{router}} after {{duration}}"
       }
     },
     "viewDevice": "View device",
@@ -1457,7 +1461,11 @@
       "presenceRetentionNote": "Connect/disconnect and AP-roaming events older than this are pruned hourly. The 7-day client timeline only needs a week.",
       "roamCollect": "Roaming events ingest interval",
       "roamCollectSecs": "s",
-      "roamCollectNote": "How often the server reads the router logs (logread) for WiFi roaming events. Applied without restart."
+      "roamCollectNote": "How often the server reads the router logs (logread) for WiFi roaming events. Applied without restart.",
+      "weakHystLabel": "Weak signal hysteresis",
+      "weakHystCaption": "Margin above the threshold that counts as recovered signal",
+      "weakSamplesLabel": "Samples to close the alert",
+      "weakSamplesCaption": "Consecutive cycles with good signal required to resolve the alert automatically"
     },
     "demo": {
       "caption": "Explore NetPulse with a sample network without touching your routers",

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

@@ -297,6 +297,10 @@
       "firmware-downgrade-target": {
         "title": "Target de firmware inferior",
         "description": "{{router}}: el target configurado \"{{target}}\" es más viejo que el firmware instalado \"{{firmware}}\""
+      },
+      "wifi-weak-recovered": {
+        "title": "Señal débil resuelta en {{device}}",
+        "description": "De vuelta a {{signal}} dBm en {{router}} tras {{duration}}"
       }
     },
     "viewDevice": "Ver dispositivo",
@@ -1457,7 +1461,11 @@
       "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.",
       "roamCollect": "Intervalo de ingesta de eventos de itinerancia",
       "roamCollectSecs": "s",
-      "roamCollectNote": "Cada cuánto el servidor lee los logs de los routers (logread) para los eventos de itinerancia. Se aplica sin reiniciar."
+      "roamCollectNote": "Cada cuánto el servidor lee los logs de los routers (logread) para los eventos de itinerancia. Se aplica sin reiniciar.",
+      "weakHystLabel": "Histéresis de señal débil",
+      "weakHystCaption": "Margen por encima del umbral que cuenta como señal recuperada",
+      "weakSamplesLabel": "Muestras para cerrar la alerta",
+      "weakSamplesCaption": "Ciclos consecutivos con buena señal necesarios para resolver la alerta automáticamente"
     },
     "demo": {
       "caption": "Explora NetPulse con una red de ejemplo sin tocar tus routers",

+ 96 - 0
app/src/pages/Settings.tsx

@@ -5386,6 +5386,12 @@ export default function Settings() {
   const [refresh, setRefresh] = useStoredState<'3' | '5' | '10' | '0'>('netpulse-refresh', '3')
   const [signalT, setSignalTState] = useState(-70)
   const [latencyT, setLatencyT] = useStoredState('netpulse-th-latency', 50)
+  // #1452: margen de histéresis y muestras consecutivas de la
+  // auto-resolución de la alerta de señal débil. Mismo ámbito server-wide
+  // que el umbral (kv via /api/settings/thresholds); en demo degradan a
+  // localStorage como el umbral.
+  const [weakHystT, setWeakHystTState] = useState(3)
+  const [weakSamplesT, setWeakSamplesTState] = useState(3)
 
   // #904: el umbral de señal es server-wide (kv alerts.weak_signal_dbm):
   // alimenta la alerta "Señal débil" y es el mismo para todos los clientes.
@@ -5434,6 +5440,74 @@ export default function Settings() {
     [isDemo],
   )
 
+  useEffect(() => {
+    if (isDemo) {
+      try {
+        const h = localStorage.getItem('netpulse-th-weak-hyst')
+        const hn = h !== null ? (JSON.parse(h) as number) : 3
+        if (Number.isFinite(hn)) setWeakHystTState(hn)
+        const s = localStorage.getItem('netpulse-th-weak-samples')
+        const sn = s !== null ? (JSON.parse(s) as number) : 3
+        if (Number.isFinite(sn)) setWeakSamplesTState(sn)
+      } catch {
+        /* valor por defecto */
+      }
+      return
+    }
+    let cancelled = false
+    fetch('/api/settings/thresholds')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((j) => {
+        if (cancelled || !j) return
+        if (typeof j.weakSignalHysteresisDbm === 'number') setWeakHystTState(j.weakSignalHysteresisDbm)
+        if (typeof j.weakSignalResolveSamples === 'number') setWeakSamplesTState(j.weakSignalResolveSamples)
+      })
+      .catch(() => {})
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+
+  const setWeakHyst = useCallback(
+    (v: number) => {
+      setWeakHystTState(v)
+      if (isDemo) {
+        try {
+          localStorage.setItem('netpulse-th-weak-hyst', JSON.stringify(v))
+        } catch {
+          /* modo privado */
+        }
+        return
+      }
+      void fetch('/api/settings/thresholds', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ weakSignalHysteresisDbm: v }),
+      }).catch(() => {})
+    },
+    [isDemo],
+  )
+
+  const setWeakSamples = useCallback(
+    (v: number) => {
+      setWeakSamplesTState(v)
+      if (isDemo) {
+        try {
+          localStorage.setItem('netpulse-th-weak-samples', JSON.stringify(v))
+        } catch {
+          /* modo privado */
+        }
+        return
+      }
+      void fetch('/api/settings/thresholds', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ weakSignalResolveSamples: v }),
+      }).catch(() => {})
+    },
+    [isDemo],
+  )
+
   const weakCount = devices.filter((d) => d.signalDbm !== null && d.signalDbm < signalT).length
   const latencyHot = wan.latencyMs > latencyT
   const previewScore = Math.max(
@@ -5706,6 +5780,28 @@ export default function Settings() {
                           : t('settings.data.signalCaption', { count: weakCount }),
                       captionHot: weakCount > 0,
                     },
+                    {
+                      key: 'weakHyst',
+                      label: t('settings.data.weakHystLabel'),
+                      value: weakHystT,
+                      set: setWeakHyst,
+                      min: 1,
+                      max: 10,
+                      format: (v: number) => `${v} dBm`,
+                      caption: t('settings.data.weakHystCaption'),
+                      captionHot: false,
+                    },
+                    {
+                      key: 'weakSamples',
+                      label: t('settings.data.weakSamplesLabel'),
+                      value: weakSamplesT,
+                      set: setWeakSamples,
+                      min: 1,
+                      max: 10,
+                      format: (v: number) => `${v}`,
+                      caption: t('settings.data.weakSamplesCaption'),
+                      captionHot: false,
+                    },
                     {
                       key: 'latency',
                       label: t('settings.data.latencyLabel'),

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

@@ -615,7 +615,7 @@ func TestDisabledUnitPaused(t *testing.T) {
 		offlineOpen:   map[string]bool{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakAlerted:   map[string]int64{},
+		weakStates:     map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}
@@ -664,7 +664,7 @@ func TestLiveGetOverviewConcurrent(t *testing.T) {
 		failCount:     map[string]int{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakAlerted:   map[string]int64{},
+		weakStates:     map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}
@@ -707,7 +707,7 @@ func TestLiveGetOverviewRecoversFromPanic(t *testing.T) {
 		failCount:     map[string]int{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakAlerted:   map[string]int64{},
+		weakStates:     map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}

+ 60 - 19
server-go/internal/adapters/live.go

@@ -321,9 +321,12 @@ type Live struct {
 	// wgUrgent (#1441): claves de peer (WGPeer.Key) marcadas como urgentes:
 	// sus caídas avisan (Urgent=true en la alerta), las del resto solo van al
 	// log. Persistido en kv (wgUrgentKey).
-	wgUrgent    map[string]bool
-	weakAlerted map[string]int64
-	onlineMacs  map[string]bool
+	wgUrgent map[string]bool
+	// weakStates (#1452): estado del ciclo de vida de la alerta de señal
+	// débil por MAC (antes sólo se guardaba el último disparo). La máquina
+	// pura vive en alerts.WeakSignalStep.
+	weakStates map[string]alerts.WeakSignalState
+	onlineMacs map[string]bool
 	// unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
 	// MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
 	// (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
@@ -485,7 +488,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		wgActive:             map[string]bool{},
 		wgActiveSince:        map[string]time.Time{},
 		wgUrgent:             map[string]bool{},
-		weakAlerted:          map[string]int64{},
+		weakStates:           map[string]alerts.WeakSignalState{},
 		onlineMacs:           map[string]bool{},
 		unknownGrace:         map[string]int{},
 		unknownAlerted:       map[string]bool{},
@@ -3450,26 +3453,34 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		l.suppression.SetTopology(parents)
 	}
 	l.mu.Unlock()
-	// Aviso de señal débil: una alerta por dispositivo y día. Umbral
-	// configurable (alerts.weak_signal_dbm, default -70; #904: antes era
-	// -70 hardcodeado y el ajuste de Ajustes no cableaba a nada).
+	// Aviso de señal débil con ciclo de vida completo (#1452): un episodio
+	// abierto por MAC, disparo con guarda de 24 h entre episodios y cierre
+	// automático cuando la señal se mantiene por encima del umbral + margen
+	// de histéresis durante N muestras consecutivas. Un cliente sin datos
+	// (offline o sin señal reportada) no cuenta como recuperado. La
+	// itinerancia no abre ni cierra nada: se juzga la señal del cliente.
 	var weakSignalDB *sql.DB
 	if l.db != nil {
 		weakSignalDB = l.db.DB
 	}
 	weakDbm := alerts.WeakSignalDbm(weakSignalDB)
-	for _, d := range devices {
-		if d.Online && d.SignalDbm != nil && *d.SignalDbm < weakDbm {
-			l.mu.Lock()
-			last := l.weakAlerted[d.MAC]
-			if time.Now().UnixMilli()-last > 24*3600e3 {
-				l.weakAlerted[d.MAC] = time.Now().UnixMilli()
-				routerName := l.routerDisplayName(d.RouterID)
-				if routerName == "" {
-					routerName = d.RouterID
-				}
+	weakHyst := alerts.WeakSignalHysteresisDbm(weakSignalDB)
+	weakSamples := alerts.WeakSignalResolveSamples(weakSignalDB)
+	weakNow := time.Now().UnixMilli()
+	for i := range devices {
+		d := &devices[i]
+		l.mu.Lock()
+		st := l.weakStates[d.MAC]
+		fireID, resolveID, episodeStart := alerts.WeakSignalStep(&st, d.MAC, d.SignalDbm, d.Online, weakDbm, weakHyst, weakSamples, weakNow)
+		l.weakStates[d.MAC] = st
+		if fireID != "" || resolveID != "" {
+			routerName := l.routerDisplayName(d.RouterID)
+			if routerName == "" {
+				routerName = d.RouterID
+			}
+			if fireID != "" {
 				l.engine.Emit(AlertEvent{
-					ID:       fmt.Sprintf("alert-weak-%s-%d", d.MAC, time.Now().UnixMilli()),
+					ID:       fireID,
 					Category: alerts.CatSignal, Urgent: false,
 					Severity: "warn", Title: "Weak signal on " + d.Name,
 					Description: fmt.Sprintf("%d dBm on %s - check coverage or move closer to an AP", *d.SignalDbm, routerName),
@@ -3479,8 +3490,38 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 					Time:        "just now", RouterID: d.RouterID,
 				})
 			}
-			l.mu.Unlock()
+			if resolveID != "" {
+				// El episodio cerrado se conserva en el log con su ts de
+				// cierre (#1349); el evento ok referencia qué cierra y lleva
+				// el valor de recuperación y la duración del episodio. Si el
+				// usuario desestimó la alerta a mano antes, no se emite el
+				// cierre (su ID ya no está en el feed).
+				wasOpen := l.engine.Has(resolveID)
+				l.engine.Resolve(resolveID)
+				if wasOpen {
+					recSignal := ""
+					if d.SignalDbm != nil {
+						recSignal = strconv.Itoa(*d.SignalDbm)
+					}
+					durMin := int((weakNow - episodeStart) / 60000)
+					dur := "<1 min"
+					if durMin >= 1 {
+						dur = fmt.Sprintf("%d min", durMin)
+					}
+					l.engine.Emit(AlertEvent{
+						ID:       fmt.Sprintf("alert-weak-%s-ok-%d", d.MAC, weakNow),
+						Category: alerts.CatSignal, Urgent: false,
+						Severity: "ok", Title: "Weak signal resolved on " + d.Name,
+						Description: fmt.Sprintf("back to %s dBm on %s after %s", recSignal, routerName, dur),
+						Type:        alerts.TypeWifiWeakRecovered,
+						Vars:        map[string]string{"device": d.Name, "signal": recSignal, "router": routerName, "duration": dur},
+						Resolves:    []string{resolveID},
+						Time:        "just now", RouterID: d.RouterID,
+					})
+				}
+			}
 		}
+		l.mu.Unlock()
 	}
 	// #1292: lápidas filtradas de la lista final (una estación stale del AP
 	// re-emite la MAC en cada ciclo sin pasar por device_seen).

+ 3 - 0
server-go/internal/alerts/alerts.go

@@ -151,6 +151,9 @@ const (
 	// and client device offline (opt-in, volatile).
 	TypeRouterOffline = "router-offline"
 	TypeDeviceOffline = "device-offline"
+	// #1452: cierre automático de la alerta de señal débil (episodio
+	// resuelto con valor de recuperación y duración).
+	TypeWifiWeakRecovered = "wifi-weak-recovered"
 )
 
 // Hints maps each alert-type slug to its actionable suggestion. Emitters copy

+ 119 - 1
server-go/internal/alerts/weak_signal.go

@@ -1,4 +1,5 @@
-// weak_signal.go - umbral configurable de la alerta de señal débil (#904).
+// weak_signal.go - umbral configurable de la alerta de señal débil (#904)
+// y su ciclo de vida completo (#1452).
 //
 // Hasta ahora la alerta "Señal débil" se disparaba con -70 dBm hardcodeado
 // y el ajuste "Weak signal" de Ajustes solo alimentaba un caption local del
@@ -6,21 +7,47 @@
 // umbral vive ahora en kv (alerts.weak_signal_dbm, default -70, clamp
 // -90..-50) para que sea server-wide (mismo valor para todos los clientes)
 // y pueda alimentar la alerta, la app móvil y el matrix filter.
+//
+// #1452: la alerta también se CIERRA sola. La resolución exige que la
+// señal se mantenga por encima del umbral + margen de histéresis durante
+// N muestras consecutivas (ambos kv, ajustables en "Datos y umbrales").
+// Un cliente sin datos (offline o sin señal reportada) NO cuenta como
+// recuperado: desaparecer es el caso "device offline", que tiene su
+// propia alerta. El itinerancia entre APs no abre ni cierra nada por sí
+// sola: se juzga la señal del cliente, no el AP al que cuelga.
 package alerts
 
 import (
 	"database/sql"
+	"fmt"
 	"strconv"
 )
 
 const KeyWeakSignalDbm = "alerts.weak_signal_dbm"
 
+const KeyWeakSignalHysteresisDbm = "alerts.weak_signal_hysteresis_dbm"
+
+const KeyWeakSignalResolveSamples = "alerts.weak_signal_resolve_samples"
+
 const (
 	DefaultWeakSignalDbm = -70
 	minWeakSignalDbm     = -90
 	maxWeakSignalDbm     = -50
 )
 
+// Margen de histéresis y muestras consecutivas para la auto-resolución
+// (#1452). El margen evita el flapping abierto/cerrado rodeando el umbral;
+// las muestras evitan cerrar por un único pico bueno. Defaults: 3 dBm y 3
+// muestras (el issue pedía 2-3 como default).
+const (
+	DefaultWeakSignalHysteresisDbm  = 3
+	minWeakSignalHysteresisDbm      = 1
+	maxWeakSignalHysteresisDbm      = 10
+	DefaultWeakSignalResolveSamples = 3
+	minWeakSignalResolveSamples     = 1
+	maxWeakSignalResolveSamples     = 10
+)
+
 // WeakSignalDbm devuelve el umbral efectivo (dBm). Valores corruptos o fuera
 // de rango devuelven el default.
 func WeakSignalDbm(db *sql.DB) int {
@@ -37,3 +64,94 @@ func WeakSignalDbm(db *sql.DB) int {
 	}
 	return n
 }
+
+func weakSignalInt(db *sql.DB, key string, def, min, max int) int {
+	if db == nil {
+		return def
+	}
+	var raw string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&raw); err != nil {
+		return def
+	}
+	n, err := strconv.Atoi(raw)
+	if err != nil || n < min || n > max {
+		return def
+	}
+	return n
+}
+
+// WeakSignalHysteresisDbm devuelve el margen de histéresis (dBm) por encima
+// del umbral a partir del cual una muestra cuenta como "buena".
+func WeakSignalHysteresisDbm(db *sql.DB) int {
+	return weakSignalInt(db, KeyWeakSignalHysteresisDbm, DefaultWeakSignalHysteresisDbm, minWeakSignalHysteresisDbm, maxWeakSignalHysteresisDbm)
+}
+
+// WeakSignalResolveSamples devuelve cuántas muestras buenas consecutivas
+// cierran una alerta de señal débil abierta.
+func WeakSignalResolveSamples(db *sql.DB) int {
+	return weakSignalInt(db, KeyWeakSignalResolveSamples, DefaultWeakSignalResolveSamples, minWeakSignalResolveSamples, maxWeakSignalResolveSamples)
+}
+
+// weakRefireGapMs es el guarda mínimo entre episodios: mientras una alerta
+// está abierta no hay re-disparo (una alerta = un episodio), y tras cerrarse
+// el throttle se reinicia para que un nuevo episodio real alerte de inmediato.
+const weakRefireGapMs = int64(24 * 3600 * 1000)
+
+// WeakSignalState es el estado del ciclo de vida por MAC.
+type WeakSignalState struct {
+	// OpenID es el ID de la alerta del episodio abierto ("" si ninguno).
+	OpenID string
+	// OpenTs es el instante (ms) en que se abrió el episodio: alimenta la
+	// duración que muestra el evento de cierre.
+	OpenTs int64
+	// Good es la racha de muestras buenas consecutivas.
+	Good int
+	// LastFire es el último disparo (ms) para el guarda entre episodios.
+	LastFire int64
+}
+
+// WeakSignalStep avanza la máquina de estados de una MAC un ciclo y devuelve
+// la acción a ejecutar: fireID != "" pide emitir una alerta nueva con ese
+// ID; resolveID != "" pide resolver la alerta con ese ID (episodeStartMs es
+// el ts de apertura del episodio cerrado, para la duración del cierre).
+// Pure (sin I/O): testeable. signal == nil o online == false significa "sin
+// datos" y NO cierra ni abre nada.
+func WeakSignalStep(st *WeakSignalState, mac string, signal *int, online bool, thr, hyst, samples int, nowMs int64) (fireID, resolveID string, episodeStartMs int64) {
+	if st == nil {
+		return "", "", 0
+	}
+	if !online || signal == nil {
+		return "", "", 0
+	}
+	switch {
+	case *signal < thr:
+		// Señal mala: la racha de buenas se rompe. Solo se dispara cuando
+		// no hay episodio abierto y pasó el guarda entre episodios (LastFire
+		// == 0 = nunca disparado).
+		st.Good = 0
+		if st.OpenID == "" && (st.LastFire == 0 || nowMs-st.LastFire > weakRefireGapMs) {
+			st.LastFire = nowMs
+			st.OpenTs = nowMs
+			st.OpenID = fmt.Sprintf("alert-weak-%s-%d", mac, nowMs)
+			return st.OpenID, "", 0
+		}
+		return "", "", 0
+	case *signal >= thr+hyst:
+		// Señal establemente buena (umbral + histéresis): cuenta muestra.
+		st.Good++
+		if st.OpenID != "" && st.Good >= samples {
+			id, start := st.OpenID, st.OpenTs
+			st.OpenID = ""
+			st.OpenTs = 0
+			st.Good = 0
+			st.LastFire = 0
+			return "", id, start
+		}
+		return "", "", 0
+	default:
+		// Zona muerta (entre umbral y umbral+histéresis): ni buena ni mala,
+		// rompe la racha de buenas sin cerrar nada.
+		st.Good = 0
+		return "", "", 0
+	}
+}

+ 122 - 0
server-go/internal/alerts/weak_signal_test.go

@@ -0,0 +1,122 @@
+// weak_signal_test.go - ciclo de vida de la alerta de señal débil (#1452).
+package alerts
+
+import "testing"
+
+func intPtr(v int) *int { return &v }
+
+func TestWeakSignalStepFiresOncePerEpisode(t *testing.T) {
+	var st WeakSignalState
+	thr, hyst, samples := -70, 3, 3
+
+	fire, resolve, _ := WeakSignalStep(&st, "aa", intPtr(-80), true, thr, hyst, samples, 1000)
+	if fire == "" {
+		t.Fatal("debe disparar con señal bajo el umbral")
+	}
+	if st.OpenID != fire {
+		t.Fatalf("el episodio abierto debe ser el disparado: %q vs %q", st.OpenID, fire)
+	}
+	// Segunda muestra mala: sin re-disparo (un episodio = una alerta).
+	fire, resolve, _ = WeakSignalStep(&st, "aa", intPtr(-78), true, thr, hyst, samples, 2000)
+	if fire != "" || resolve != "" {
+		t.Fatal("con el episodio abierto no hay ni disparo ni cierre")
+	}
+}
+
+func TestWeakSignalStepResolvesAfterNGoodSamples(t *testing.T) {
+	var st WeakSignalState
+	thr, hyst, samples := -70, 3, 3
+
+	fire, _, _ := WeakSignalStep(&st, "aa", intPtr(-80), true, thr, hyst, samples, 1000)
+	// -66 >= -70+3: buena. Dos muestras no cierran (N=3).
+	for i := 0; i < 2; i++ {
+		f, r, _ := WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, int64(2000+i))
+		if f != "" || r != "" {
+			t.Fatalf("muestra %d: no debe cerrar aún", i+1)
+		}
+	}
+	f, r, start := WeakSignalStep(&st, "aa", intPtr(-65), true, thr, hyst, samples, 3000)
+	if f != "" || r != fire {
+		t.Fatalf("la tercera muestra buena cierra el episodio: fire=%q resolve=%q", f, r)
+	}
+	if start != 1000 {
+		t.Fatalf("el ts de apertura del episodio es %d, quiero 1000", start)
+	}
+	if st.OpenID != "" || st.Good != 0 || st.LastFire != 0 {
+		t.Fatal("tras cerrar, el estado queda reiniciado (un nuevo episodio puede disparar ya)")
+	}
+}
+
+func TestWeakSignalStepDeadZoneBreaksStreak(t *testing.T) {
+	var st WeakSignalState
+	thr, hyst, samples := -70, 3, 3
+
+	fire, _, _ := WeakSignalStep(&st, "aa", intPtr(-80), true, thr, hyst, samples, 1000)
+	_ = fire
+	// Dos buenas, una en zona muerta (-69: >= thr pero < thr+hyst), una buena.
+	WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 2000)
+	WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 3000)
+	WeakSignalStep(&st, "aa", intPtr(-69), true, thr, hyst, samples, 4000)
+	f, r, _ := WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 5000)
+	if f != "" || r != "" {
+		t.Fatal("la zona muerta rompe la racha: una buena tras ella no cierra")
+	}
+	// Dos buenas más sí cierran (racha nueva de 3).
+	WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 6000)
+	f, r, _ = WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 7000)
+	if r == "" {
+		t.Fatal("tras recomponer la racha de 3 buenas, el episodio cierra")
+	}
+}
+
+func TestWeakSignalStepNoDataNeverResolves(t *testing.T) {
+	var st WeakSignalState
+	thr, hyst, samples := -70, 3, 2
+
+	fire, _, _ := WeakSignalStep(&st, "aa", intPtr(-80), true, thr, hyst, samples, 1000)
+	_ = fire
+	// Offline: no cierra ni rompe la racha de buenas acumulada.
+	WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 2000)
+	WeakSignalStep(&st, "aa", nil, false, thr, hyst, samples, 3000)
+	WeakSignalStep(&st, "aa", nil, true, thr, hyst, samples, 4000)
+	if st.Good != 1 {
+		t.Fatalf("sin datos no debe tocar la racha: good=%d", st.Good)
+	}
+	f, r, _ := WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 5000)
+	if f != "" || r != fire {
+		t.Fatal("la racha continúa tras el hueco sin datos y cierra en la 2ª buena")
+	}
+}
+
+func TestWeakSignalStepRefireGuard(t *testing.T) {
+	var st WeakSignalState
+	thr, hyst, samples := -70, 3, 1
+
+	f, _, _ := WeakSignalStep(&st, "aa", intPtr(-80), true, thr, hyst, samples, 1000)
+	if f == "" {
+		t.Fatal("primer episodio dispara")
+	}
+	// Cierra al instante (N=1).
+	_, r, _ := WeakSignalStep(&st, "aa", intPtr(-66), true, thr, hyst, samples, 2000)
+	if r == "" {
+		t.Fatal("cierra con una buena cuando N=1")
+	}
+	// Caída inmediata de nuevo: episodio nuevo SIN esperar 24 h (el guarda
+	// se reinicia al cerrar; un episodio real nuevo debe alertar ya).
+	f, _, _ = WeakSignalStep(&st, "aa", intPtr(-81), true, thr, hyst, samples, 3000)
+	if f == "" {
+		t.Fatal("tras cerrar, un nuevo episodio dispara de inmediato")
+	}
+}
+
+func TestWeakSignalStepDefaultGetters(t *testing.T) {
+	if got := WeakSignalHysteresisDbm(nil); got != DefaultWeakSignalHysteresisDbm {
+		t.Fatalf("default histéresis: %d", got)
+	}
+	if got := WeakSignalResolveSamples(nil); got != DefaultWeakSignalResolveSamples {
+		t.Fatalf("default muestras: %d", got)
+	}
+	if WeakSignalDbm(nil) != DefaultWeakSignalDbm {
+		t.Fatal("default dbm")
+	}
+}

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

@@ -16,15 +16,19 @@ func (s *server) registerThresholdsRoutes(mux *http.ServeMux) {
 	kv := &dbKVAdapter{db: s.db.DB}
 	mux.Handle("GET /api/settings/thresholds", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
 		writeJSON(w, http.StatusOK, map[string]any{
-			"weakSignalDbm":      alerts.WeakSignalDbm(s.db.DB),
-			"alertRetentionDays": alerts.RetentionDays(s.db.DB),
+			"weakSignalDbm":            alerts.WeakSignalDbm(s.db.DB),
+			"weakSignalHysteresisDbm":  alerts.WeakSignalHysteresisDbm(s.db.DB),
+			"weakSignalResolveSamples": alerts.WeakSignalResolveSamples(s.db.DB),
+			"alertRetentionDays":       alerts.RetentionDays(s.db.DB),
 		})
 	})))
 
 	mux.Handle("PUT /api/settings/thresholds", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		var body struct {
-			WeakSignalDbm      *int `json:"weakSignalDbm"`
-			AlertRetentionDays *int `json:"alertRetentionDays"`
+			WeakSignalDbm            *int `json:"weakSignalDbm"`
+			WeakSignalHysteresisDbm  *int `json:"weakSignalHysteresisDbm"`
+			WeakSignalResolveSamples *int `json:"weakSignalResolveSamples"`
+			AlertRetentionDays       *int `json:"alertRetentionDays"`
 		}
 		if st := readJSONBody(w, r, &body); st != 0 {
 			writeBodyError(w, st, "invalid_body", "body JSON inválido")
@@ -40,6 +44,28 @@ func (s *server) registerThresholdsRoutes(mux *http.ServeMux) {
 				return
 			}
 		}
+		// #1452: margen de histéresis y muestras consecutivas de la
+		// auto-resolución de la alerta de señal débil.
+		if body.WeakSignalHysteresisDbm != nil {
+			if *body.WeakSignalHysteresisDbm < 1 || *body.WeakSignalHysteresisDbm > 10 {
+				writeError(w, http.StatusBadRequest, "invalid_value", "weakSignalHysteresisDbm debe estar entre 1 y 10")
+				return
+			}
+			if err := kv.Set(alerts.KeyWeakSignalHysteresisDbm, strconv.Itoa(*body.WeakSignalHysteresisDbm)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error", err.Error())
+				return
+			}
+		}
+		if body.WeakSignalResolveSamples != nil {
+			if *body.WeakSignalResolveSamples < 1 || *body.WeakSignalResolveSamples > 10 {
+				writeError(w, http.StatusBadRequest, "invalid_value", "weakSignalResolveSamples debe estar entre 1 y 10")
+				return
+			}
+			if err := kv.Set(alerts.KeyWeakSignalResolveSamples, strconv.Itoa(*body.WeakSignalResolveSamples)); err != nil {
+				writeError(w, http.StatusInternalServerError, "kv_error", err.Error())
+				return
+			}
+		}
 		// #1034: retención del log de alertas en días (0 = poda temporal off;
 		// la cota de 500 filas sigue aplicando). Efecto sin reinicio: la poda
 		// horaria y la de arranque leen el kv en cada pasada.
@@ -54,8 +80,10 @@ func (s *server) registerThresholdsRoutes(mux *http.ServeMux) {
 			}
 		}
 		writeJSON(w, http.StatusOK, map[string]any{
-			"weakSignalDbm":      alerts.WeakSignalDbm(s.db.DB),
-			"alertRetentionDays": alerts.RetentionDays(s.db.DB),
+			"weakSignalDbm":            alerts.WeakSignalDbm(s.db.DB),
+			"weakSignalHysteresisDbm":  alerts.WeakSignalHysteresisDbm(s.db.DB),
+			"weakSignalResolveSamples": alerts.WeakSignalResolveSamples(s.db.DB),
+			"alertRetentionDays":       alerts.RetentionDays(s.db.DB),
 		})
 	})))
 }