Переглянути джерело

fix(overview): derive greeting alert count from the alert list, not the health score (#1710)

Nacho 1 місяць тому
батько
коміт
ff33f0db49

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Fixed
+
+- The greeting line on the Overview ("N important alerts") now counts the same alerts as the bell and the Alerts page (unread, level-filtered), instead of the health score breakdown. A health penalty without a visible alert, such as a down VPN peer with the vpn category set to "Nada", used to leave a phantom counter that could not be cleared from anywhere (#1707).
+
 ## [2.49.4] - 2026-10-30
 
 ### Added

+ 9 - 5
app/src/sections/HeroStrip.tsx

@@ -58,7 +58,7 @@ export function HeroStrip({ compact = false }: { compact?: boolean }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const { refreshKey } = useDashboard()
-  const { deviceTotals, health: healthScore, wan } = useNetPulse()
+  const { deviceTotals, health: healthScore, wan, unreadAlerts } = useNetPulse()
   const auth = useAuth()
   // SPEC-65 D65-5: saluda con displayName || username. En demo (sin backend)
   // el nombre vive en localStorage ('netpulse-displayname').
@@ -80,8 +80,12 @@ export function HeroStrip({ compact = false }: { compact?: boolean }) {
   const greeting = t(greetingKey()) + (name ? t('home.greetingName', { name }) : '')
   const words = greeting.split(' ')
 
-  const alerts = healthScore.breakdown?.length ?? 0
-  const statusLine = alerts > 0 ? t('home.importantAlerts', { count: alerts }) : t('home.noImportantAlerts')
+  // #1707: la línea de estado cuenta lo mismo que la campana y la lista de
+  // alertas (unreadAlerts: server truth con los filtros de nivel y de
+  // recuperación). Contar el breakdown del health score decía "N important
+  // alerts" sin ninguna alerta que quitar: una penalización de salud (peer
+  // VPN caído, temperatura...) no es una alerta del feed.
+  const statusLine = unreadAlerts > 0 ? t('home.importantAlerts', { count: unreadAlerts }) : 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.
@@ -147,7 +151,7 @@ export function HeroStrip({ compact = false }: { compact?: boolean }) {
                 animate={{ opacity: 1 }}
                 transition={{ delay: 0.25, duration: 0.4 }}
               >
-                {alerts > 0 ? (
+                {unreadAlerts > 0 ? (
                   <>
                     <AlertTriangle className="h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} />
                     {statusLine}
@@ -240,7 +244,7 @@ export function HeroStrip({ compact = false }: { compact?: boolean }) {
             animate={{ opacity: 1 }}
             transition={{ delay: 0.25, duration: 0.4 }}
           >
-            {alerts > 0 ? (
+            {unreadAlerts > 0 ? (
               <>
                 <AlertTriangle className="h-4 w-4 text-warn" strokeWidth={1.75} />
                 {statusLine}

+ 65 - 0
server-go/internal/adapters/overview_alert_count_test.go

@@ -0,0 +1,65 @@
+// overview_alert_count_test.go - la línea "N important alerts" de la Overview
+// debe contar lo mismo que la lista de alertas (#1707). Contaba el breakdown
+// del health score (computeHealth), así que una penalización de salud sin
+// alerta visible (p. ej. vpn en nivel "none", o el aviso ya resuelto con la
+// condición viva) dejaba un contador fantasma que no se podía quitar.
+package adapters
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// Repro del desajuste #1707: un peer urgente caído penaliza la salud
+// (breakdown con 1 entrada), pero con vpn en "none" el motor no registra la
+// alerta: la lista (List) y el contador de la campana (UnreadCount) están a
+// cero. La métrica vieja de la Overview decía "1 important alert" y la lista
+// no mostraba nada que resolver.
+func TestHealthPenaltyWithoutVisibleAlertIsThePhantomCount(t *testing.T) {
+	l := liveTestLive()
+	if err := l.engine.SetConfig(map[string]string{"vpn": "none"}); err != nil {
+		t.Fatal(err)
+	}
+	wg := &WireGuardStats{Interface: "wg0", Status: "active", Peers: []WGPeer{
+		{Key: "k1", Name: "Site B", Active: false, Urgent: true},
+	}}
+	h := computeHealth(nil, nil, wg)
+	if len(h.Breakdown) != 1 {
+		t.Fatalf("breakdown de salud: %d entradas, esperaba 1 (peer urgente caído): %+v", len(h.Breakdown), h.Breakdown)
+	}
+	// La emisión real del motor con la categoría en "none" no deja fila.
+	l.engine.Emit(alerts.AlertEvent{
+		ID: "alert-wgdown-site-b", Category: alerts.CatVPN, Urgent: true,
+		Severity: "critical", Title: "Site B down", RouterID: "flint2", Time: "just now",
+	})
+	if got := l.engine.List(); len(got) != 0 {
+		t.Fatalf("una categoría en none no debe asomar en la lista: %+v", got)
+	}
+	if got := l.engine.UnreadCount(); got != 0 {
+		t.Fatalf("unread con la categoría en none: %d, esperaba 0", got)
+	}
+}
+
+// El contador de la Overview vive en HeroStrip.tsx y debe usar unreadAlerts
+// (misma fuente que la campana: server truth con los mismos filtros que
+// List), nunca el breakdown del health score. Se comprueba sobre la fuente
+// porque la app no tiene tests de JS (patrón de frontend_defaults_test.go).
+func TestHeroStripImportantAlertsUseAlertListSemantics(t *testing.T) {
+	const rel = "../../../app/src/sections/HeroStrip.tsx"
+	raw, err := os.ReadFile(filepath.Join(rel))
+	if err != nil {
+		t.Fatalf("read %s: %v", rel, err)
+	}
+	src := string(raw)
+	if !strings.Contains(src, "unreadAlerts") {
+		t.Fatalf("%s: el contador de la Overview no usa unreadAlerts (debe compartir semántica con la lista de alertas)", rel)
+	}
+	const oldCount = "healthScore.breakdown?.length ?? 0"
+	if strings.Contains(src, oldCount) {
+		t.Fatalf("%s: el contador vuelve a derivarse del breakdown de salud (%q): reproduce el contador fantasma del #1707", rel, oldCount)
+	}
+}