Преглед изворни кода

fix(alerts): hide categories set to none from the feed, bell and log (#1660)

* fix(alerts): hide categories set to none from the feed, bell and log (#1659)

* docs(changelog): record the alerts none level fix (#1659)
Nacho пре 1 месец
родитељ
комит
8570a30bfd

+ 3 - 2
ARCHITECTURE.md

@@ -148,8 +148,9 @@ del Resumen, ≠ username; columna `users.display_name` migrada como
 
 Eventos con `Category` (router|internet|clients|signal|vpn|system), `Urgent`
 y `Ts`. El motor aplica **config por categoría de 3 niveles** (`urgent` / `all`
-/ `none`, en `kv alerts.config.v1`) EN CREACIÓN: `none` descarta, `urgent` solo
-deja pasar los urgentes, `all` pasa todo. Dedup 5 min por
+/ `none`, en `kv alerts.config.v1`): `none` oculta la categoría por completo (no
+entra al feed, no cuenta en la campana ni se persiste, #1659); `urgent` registra
+todo y solo notifica los urgentes; `all` registra y notifica todo (#1413). Dedup 5 min por
 (categoría,título,router), cap 100. Read-state en servidor (`kv
 alerts.read.v1`, FIFO 200) — la campana usa `overview.unreadAlerts` (server
 truth). Fuentes live: router offline (2 fallos seguidos) y recuperado, WAN

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Fixed
+
+- **El nivel "Nada" de una categoría la oculta del historial y de la campana (#1659)**: antes el nivel solo decidía qué se notificaba, así que una categoría en "Nada" seguía guardando eventos, apareciendo en el historial y sumando en la campana. Ahora "Nada" no registra el evento, no lo persiste y oculta los ya guardados sin reiniciar, mientras "Solo urgentes" sigue registrando todo y avisando solo de lo urgente. El contador del servidor y el del frontend usan el mismo criterio.
+
 ## [2.48.2] - 2026-10-29
 
 ### Added

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

@@ -59,7 +59,7 @@
     "resolvesTitle_other": "Resolves {{count}} events",
     "configButton": "Configure alerts",
     "configTitle": "Alert settings",
-    "configDescription": "Every event is kept in your history and counted on the bell. Choose what notifies you, per category.",
+    "configDescription": "Choose what gets recorded and what notifies you, per category. On \"Nothing\" the category disappears from the history and the bell.",
     "configSaved": "Saved",
     "configSaveError": "Could not save — please try again",
     "categories": {

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

@@ -59,7 +59,7 @@
     "resolvesTitle_other": "Resuelve {{count}} eventos",
     "configButton": "Configurar alertas",
     "configTitle": "Configuración de alertas",
-    "configDescription": "Todos los eventos quedan en tu historial y cuentan en la campana. Elige qué te notifica, por categoría.",
+    "configDescription": "Elige qué se registra y qué te notifica, por categoría. En \"Nada\" la categoría desaparece del historial y de la campana.",
     "configSaved": "Guardado",
     "configSaveError": "No se pudo guardar — inténtalo de nuevo",
     "categories": {

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

@@ -57,6 +57,7 @@ import {
 import i18n from '@/i18n'
 import {
   countUnreadAlerts,
+  isHiddenByLevel,
   loadDemoAlertsConfig,
   normalizeAlertsConfig,
   saveDemoAlertsConfig,
@@ -679,6 +680,10 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       es.addEventListener('alert', (ev) => {
         try {
           const alert = JSON.parse((ev as MessageEvent).data as string) as AlertEvent
+          // #1659: un nivel "none" oculta la categoría por completo. El
+          // servidor ya no la emite; esto cubre el modo demo y una config
+          // recién cambiada antes del siguiente snapshot.
+          if (isHiddenByLevel(alert, configRef.current)) return
           setBundle((prev) => {
             // #891: dedupe por ID — un alert con ID ya presente NO se vuelve
             // a anteponer (duplicaba filas y sumaba al badge). Se reemplaza

+ 12 - 3
app/src/data/alertConfig.ts

@@ -77,7 +77,16 @@ export function passesAlertConfig(ev: Pick<AlertEvent, 'category' | 'urgent'>, c
   return true
 }
 
-/** No leídas que pasan la config — el contador de la campana en demo. */
-export function countUnreadAlerts(alerts: Pick<AlertEvent, 'category' | 'urgent' | 'read'>[], cfg: AlertsConfig): number {
-  return alerts.filter((a) => !a.read && passesAlertConfig(a, cfg)).length
+/**
+ * Nivel "none" = la categoría no existe para el operador: el servidor no la
+ * registra ni la sirve (#1659). Es distinto de "urgent", que solo limita los
+ * avisos y deja el evento en el historial (#1413).
+ */
+export function isHiddenByLevel(ev: Pick<AlertEvent, 'category'>, cfg: AlertsConfig): boolean {
+  return (cfg[ev.category] ?? 'all') === 'none'
+}
+
+/** No leídas que el motor sirve — el contador de la campana. */
+export function countUnreadAlerts(alerts: Pick<AlertEvent, 'category' | 'read'>[], cfg: AlertsConfig): number {
+  return alerts.filter((a) => !a.read && !isHiddenByLevel(a, cfg)).length
 }

+ 3 - 3
docs/manual.en.md

@@ -293,7 +293,7 @@ The map is built from the bridge FDB (for wired clients), LLDP when available (t
 ### What it shows
 
 - **Summary**: three counters (unread warnings, alerts today, critical) with a per-cause breakdown.
-- **Alert configuration**: per category, the notification level (Urgent only / All / None) and a custom rules manager. Every event is always kept in the log regardless of the level; the level only controls what notifies you.
+- **Alert configuration**: per category, the level (Urgent only / All / None) and a custom rules manager. "None" hides the category from the log and the bell; "Urgent only" and "All" decide only what notifies, and events are always recorded.
 - **Filters**: by severity, by kind, by category and "Unread only".
 - **Timeline feed** grouped by day, with severity by color and expandable context (a sparkline with a threshold line, or the WireGuard peer / affected device data).
 
@@ -310,14 +310,14 @@ Alerts are generated by the server from what it already monitors: temperature, a
 
 ### Design decisions
 
-- Configuration is **per category and per level**, not per alert: the level is a notification policy (None / Urgent only / All). Events below the level are still recorded in the log and the feed; use the feed's category filters to hide them visually.
+- Configuration is **per category and per level**, not per alert. **None** hides the category: its events do not enter the log, do not count on the bell and do not notify. **Urgent only** and **All** are notification policy: everything is recorded and the level decides what notifies.
 - You can **silence** a specific alert for 1 hour, 24 hours or forever.
 - The **feed uses simulated infinite scroll**: reaching the bottom shows the end of history.
 
 ### Procedure: configure which alerts you want
 
 1. Open **Alerts** and click **Configuration**.
-2. For each category (Router, Internet, Clients, Signal, VPN, System) choose the notification level: **Urgent only**, **All** or **None**. All events are kept in the log and counted on the bell either way; the level only decides what pushes a notification.
+2. For each category (Router, Internet, Clients, Signal, VPN, System) choose the level: **Urgent only**, **All** or **None**. With **None** the category disappears from the log and the bell; with the other two everything is recorded and the level only decides what notifies.
 3. If you need custom rules (custom thresholds), use the **rules** manager at the bottom of the panel.
 4. Changes save instantly (you will see the confirmation).
 

+ 3 - 3
docs/manual.es.md

@@ -293,7 +293,7 @@ El mapa se construye con el bridge FDB (para clientes por cable), LLDP cuando es
 ### Qué muestra
 
 - **Resumen**: tres contadores (avisos sin leer, alertas de hoy, críticos) con un desglose por causa.
-- **Configuración de alertas**: por categoría, el nivel de notificación (Solo urgentes / Todo / Nada) y un gestor de reglas personalizadas. Todos los eventos se guardan siempre en el registro, con cualquier nivel; el nivel solo controla qué te notifica.
+- **Configuración de alertas**: por categoría, el nivel (Solo urgentes / Todo / Nada) y un gestor de reglas personalizadas. "Nada" oculta la categoría del registro y de la campana; "Solo urgentes" y "Todo" deciden solo qué notifica, y los eventos se registran siempre.
 - **Filtros**: por severidad, por tipo, por categoría y "Solo no leídas".
 - **Feed en línea de tiempo** agrupado por día, con severidad por color y contexto expandible (minigráfica con umbral, datos del peer WireGuard o del dispositivo afectado).
 
@@ -310,14 +310,14 @@ Las alertas las genera el servidor a partir de lo que ya monitoriza: temperatura
 
 ### Decisiones de diseño
 
-- La configuración es **por categoría y por nivel**, no alerta a alerta: el nivel es una política de notificación (Nada / Solo urgentes / Todo). Los eventos por debajo del nivel siguen registrándose en el log y el feed; para ocultarlos visualmente usa los filtros de categoría del feed.
+- La configuración es **por categoría y por nivel**, no alerta a alerta. **Nada** oculta la categoría: sus eventos no entran al registro, no cuentan en la campana y no notifican. **Solo urgentes** y **Todo** son política de notificación: todo se registra y el nivel decide qué avisa.
 - Puedes **silenciar** una alerta concreta 1 hora, 24 horas o para siempre.
 - El **feed usa scroll infinito simulado**: al llegar abajo se muestra el fin del historial.
 
 ### Procedimiento: configurar qué alertas quieres
 
 1. Abre **Alertas** y pulsa **Configuración**.
-2. Para cada categoría (Router, Internet, Clientes, Señal, VPN, Sistema) elige el nivel de notificación: **Solo urgentes**, **Todo** o **Nada**. Con cualquier nivel todos los eventos quedan en el registro y cuentan en la campana; el nivel solo decide cuál envía notificación.
+2. Para cada categoría (Router, Internet, Clientes, Señal, VPN, Sistema) elige el nivel: **Solo urgentes**, **Todo** o **Nada**. Con **Nada** la categoría desaparece del registro y de la campana; con las otras dos todo se registra y el nivel solo decide cuál envía notificación.
 3. Si necesitas reglas propias (umbrales a medida), usa el gestor de **reglas** al final del panel.
 4. Los cambios se guardan al instante (verás la confirmación).
 

+ 5 - 0
server-go/internal/adapters/weak_recovered_test.go

@@ -13,6 +13,11 @@ import (
 
 func TestEmitWeakRecoveredCollapsesPerDevice(t *testing.T) {
 	eng := alerts.New(nil, nil)
+	// #1659: signal arranca en "none" (la categoría no entra al feed), este
+	// test trabaja con cierres de señal.
+	if err := eng.SetConfig(map[string]string{alerts.CatSignal: alerts.LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 	l := &Live{engine: eng}
 
 	sig := -58

+ 31 - 2
server-go/internal/alerts/alerts.go

@@ -99,6 +99,10 @@ type AlertEvent struct {
 	// condicion se resuelve (engine.Remove). Uso: caida de agente, cuya
 	// semantica es "viva por router", no un historico de incidentes.
 	Volatile bool `json:"-"`
+	// seeded: fixture del dataset demo (Seed). No lo somete el filtro de
+	// nivel "none" (#1659): la historia canónica del demo se sirve completa
+	// aunque su config deje la categoría en "none".
+	seeded bool
 }
 
 // ResolvedEvent (#1466): datos mínimos del evento que un cierre resolvió.
@@ -542,6 +546,15 @@ func (e *Engine) notificaLocked(ev AlertEvent) bool {
 	return true
 }
 
+// hiddenByLevelLocked: una categoría en nivel "none" no existe para el
+// operador. No entra al feed, no cuenta en la campana y no se persiste
+// (issue #1659). El nivel "urgent" sigue siendo solo política de
+// notificación (#1413): sus eventos se registran y solo silencian el aviso.
+// Los fixtures del demo (Seed) quedan exentos para servir el canon completo.
+func (e *Engine) hiddenByLevelLocked(ev AlertEvent) bool {
+	return !ev.seeded && e.cfg[ev.Category] == LevelNone
+}
+
 // insertaLocked inserta un evento nuevo al frente con dedup y cap.
 // Requiere e.mu ya tomado. Devuelve true si se guardó. skipDedup omite la
 // ventana de dedup de 5 min (issue #846: los incidentes con estado propio,
@@ -552,6 +565,11 @@ func (e *Engine) insertaLocked(ev AlertEvent, now time.Time, skipDedup bool) boo
 	if e.isSilencedLocked(key) {
 		return false
 	}
+	// #1659: el nivel "none" oculta la categoría por completo (feed, campana
+	// y alert_log). Se descarta antes del dedup para no consumir la ventana.
+	if e.hiddenByLevelLocked(ev) {
+		return false
+	}
 	if !skipDedup {
 		if last, ok := e.dedup[key]; ok && now.UnixMilli()-last < DedupWindow.Milliseconds() {
 			return false
@@ -621,8 +639,9 @@ func (e *Engine) persistLocked(ev AlertEvent) {
 }
 
 // Emit aplica el dedup de 5 min y el cap de 100; devuelve true si el evento
-// se guardó. TODO evento se guarda (issue #1413): el nivel none/urgent/all de
-// su categoría ya no filtra la ingesta, solo gobierna si dispara el Notifier.
+// se guardó. El nivel de la categoría gobierna qué se registra: "none" no
+// entra al feed ni se persiste (#1659), "urgent" sí se registra y solo
+// silencia el aviso (#1413).
 // El filtro por URGENCIA fino vive en cada canal (#874): cada transporte
 // decide si lleva solo urgentes (default) o todo.
 // Supresión topológica (#332): si el router tiene un padre offline en el
@@ -842,6 +861,8 @@ func (e *Engine) Seed(ev AlertEvent) bool {
 		ev.Time = "just now"
 	}
 	ev.Read = false
+	// #1659: fixture de demo, exento del filtro de nivel.
+	ev.seeded = true
 	e.list = append([]AlertEvent{ev}, e.list...)
 	if len(e.list) > MaxEvents {
 		e.list = e.list[:MaxEvents]
@@ -868,6 +889,11 @@ func (e *Engine) List() []AlertEvent {
 		if e.dismissed[ev.ID] {
 			continue
 		}
+		// #1659: los eventos de una categoría en nivel "none" no se sirven,
+		// aunque estuvieran ya persistidos de antes del cambio de nivel.
+		if e.hiddenByLevelLocked(ev) {
+			continue
+		}
 		key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
 		if e.isSilencedLocked(key) {
 			continue
@@ -906,6 +932,9 @@ func (e *Engine) UnreadCount() int {
 		if e.dismissed[ev.ID] {
 			continue
 		}
+		if e.hiddenByLevelLocked(ev) {
+			continue
+		}
 		key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
 		if e.isSilencedLocked(key) {
 			continue

+ 21 - 11
server-go/internal/alerts/alerts_test.go

@@ -64,16 +64,23 @@ func TestSetConfigPartialAndValidation(t *testing.T) {
 	}
 }
 
-// TestEmitFiltering cubre la semántica #1413: la config de categoría NO filtra
-// la ingesta (todo se guarda en el log y el feed); solo gobierna el Notifier
-// (none = nunca, urgent = solo Urgent, all = siempre).
+// TestEmitFiltering cubre la semántica de niveles: "none" oculta la categoría
+// por completo (#1659: no entra al feed, no cuenta en la campana, no se
+// persiste); "urgent" solo gobierna el Notifier (#1413) y "all" lo deja pasar
+// todo.
 func TestEmitFiltering(t *testing.T) {
 	e := New(nil, nil)
 	spy := &spyNotifier{}
 	e.SetNotifier(spy)
-	// none → se guarda pero NO notifica (signal por defecto)
-	if !e.Emit(ev("s1", CatSignal, true)) {
-		t.Fatal("signal:none debía guardar (la ingesta ya no se filtra)")
+	// none → no se guarda ni notifica (signal por defecto)
+	if e.Emit(ev("s1", CatSignal, true)) {
+		t.Fatal("signal:none no debía guardar el evento")
+	}
+	if got := len(e.List()); got != 0 {
+		t.Fatalf("signal:none no debía aparecer en el feed, hay %d", got)
+	}
+	if got := e.UnreadCount(); got != 0 {
+		t.Fatalf("signal:none no debía contar en la campana, hay %d", got)
 	}
 	if len(spy.got) != 0 {
 		t.Fatalf("signal:none no debía notificar, notificó %d", len(spy.got))
@@ -101,10 +108,11 @@ func TestEmitFiltering(t *testing.T) {
 	if len(spy.got) != 4 {
 		t.Fatalf("notificados: %d, esperaba 4 (todo salvo signal:none y el no-urgente de router)", len(spy.got))
 	}
-	if got := len(e.List()); got != 6 {
-		t.Fatalf("lista: %d, esperaba 6 (nada se descarta)", got)
+	// #1659: el evento de signal:none no está en el feed (5 de 6 emitidos).
+	if got := len(e.List()); got != 5 {
+		t.Fatalf("lista: %d, esperaba 5 (signal:none se descarta)", got)
 	}
-	// Cambio de nivel reconfigura SOLO la notificación
+	// Cambio de nivel a "all" hace visible y notificable la categoría
 	if err := e.SetConfig(map[string]string{"signal": "all"}); err != nil {
 		t.Fatal(err)
 	}
@@ -284,15 +292,17 @@ func TestNotifierSuppressedNeverNotifies(t *testing.T) {
 
 func TestSeedSkipsConfigButKeepsDedup(t *testing.T) {
 	e := New(nil, nil)
-	// Seed ignora el filtro (vpn:none) — historia del demo (SPEC §5)
+	// Seed ignora el filtro de nivel al insertar — historia del demo (SPEC §5)
 	if !e.Seed(ev("h1", CatVPN, false)) {
 		t.Fatal("Seed debía guardar pese a vpn:none")
 	}
 	if e.Seed(AlertEvent{ID: "h2", Category: CatVPN, Title: "t-h1", RouterID: "r1"}) {
 		t.Fatal("Seed debía respetar dedup")
 	}
+	// #1659: los fixtures sembrados quedan exentos del nivel "none" del demo,
+	// así que se sirven aunque vpn esté en "none".
 	if got := len(e.List()); got != 1 {
-		t.Fatalf("lista: %d", got)
+		t.Fatalf("el fixture sembrado debía servirse, hay %d", got)
 	}
 }
 

+ 7 - 0
server-go/internal/alerts/hide_recovery_test.go

@@ -34,6 +34,10 @@ func TestHideRecoveryFiltersFeedAndUnread(t *testing.T) {
 	}
 	t.Cleanup(func() { _ = d.Close() })
 	e := New(d, nil)
+	// #1659: signal arranca en "none" (oculta la categoría), este test la usa.
+	if err := e.SetConfig(map[string]string{CatSignal: LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 
 	now := time.Now().Unix()
 	e.Emit(AlertEvent{ID: "w1", Category: CatSignal, Severity: "warn", Title: "Weak signal on dev-a", Ts: now})
@@ -129,6 +133,9 @@ func TestPurgeSupersededWeakClosures(t *testing.T) {
 	}
 
 	e2 := New(d, nil)
+	if err := e2.SetConfig(map[string]string{CatSignal: LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 	got := map[string]bool{}
 	for _, ev := range e2.List() {
 		got[ev.ID] = true

+ 11 - 0
server-go/internal/alerts/resolved_details_test.go

@@ -10,6 +10,10 @@ import (
 
 func TestListAttachesResolvedDetails(t *testing.T) {
 	e := New(nil, nil)
+	// #1659: signal arranca en "none" (oculta la categoría), este test la usa.
+	if err := e.SetConfig(map[string]string{CatSignal: LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 	clock := time.Unix(1_700_000_000, 0)
 	e.SetClock(func() time.Time { return clock })
 
@@ -66,6 +70,10 @@ func TestListAttachesResolvedDetails(t *testing.T) {
 // referencia desnuda con el ID.
 func TestListResolvedUnknownID(t *testing.T) {
 	e := New(nil, nil)
+	// #1659: signal arranca en "none" (oculta la categoría), este test la usa.
+	if err := e.SetConfig(map[string]string{CatSignal: LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 	if !e.Emit(AlertEvent{
 		ID: "close-x", Category: CatSignal, Severity: "ok", Title: "cierre",
 		RouterID: "rt4", Resolves: []string{"alert-que-ya-no-esta"},
@@ -90,6 +98,9 @@ func TestListResolvedUnknownID(t *testing.T) {
 func TestResolvesSurviveRestart(t *testing.T) {
 	dir := t.TempDir()
 	e1 := newPersistTestEngine(t, dir, false)
+	if err := e1.SetConfig(map[string]string{CatSignal: LevelAll}); err != nil {
+		t.Fatalf("SetConfig: %v", err)
+	}
 	orig := AlertEvent{
 		ID: "alert-weak-x", Category: CatSignal, Severity: "warn",
 		Title: "Señal débil", Type: "wifi-weak", RouterID: "rt4",