Răsfoiți Sursa

fix(alerts): localize the remaining alert types via type/vars (#712) (#723)

#671 moved the alert feed to translate from a stable type slug plus
vars, but only 13 emitters were migrated; the rest still sent Spanish
literals. The remaining 20 emitters (agent/SSH recovery, WireGuard
handshake, port monitor recoveries, beacon loop/port/link/SFP/reboot
and rearm/reinstall) now carry a type slug and their vars, with the
ES/EN keys added to the catalogs. The literals stay as fallback and
dedup/silence are untouched.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 luni în urmă
părinte
comite
23deb11a7c

+ 1 - 0
CHANGELOG.md

@@ -21,6 +21,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- **El feed de alertas ya no muestra español para los tipos que faltaban por migrar (#712)**: los emisores que seguían generando literales sin `type`/`vars` (recuperaciones de agente, router y puerto, acceso SSH perdido/recuperado, handshake de WireGuard, los eventos del beacon del switch, el diagnóstico SFP y el auto-rearme) llevan ahora su slug estable y sus variables, y el frontend traduce el título y la descripción en el idioma del usuario. Los literales se mantienen como respaldo y el dedup/silence (que usan el título) no cambian.
 - **Los clientes cableados y callados de un AP puente ya no vuelven a colgarse del router principal (#694)**: la clasificación de los puertos de subida (uplink) se calculaba cada tick solo con las MACs de bridge presentes en ese sondeo, así que un cliente callado cuya brMac ya no estaba en el FDB del gateway acababa atribuido al principal por dos vías transitorias (el FDB del gateway y el fallback ARP, que gana por orden alfabético). Ahora el servidor recuerda los puertos que alguna vez aprendieron la MAC de bridge de otro router (la clasificación de uplink persiste entre ticks y sobrevive a sondeos fallidos), el gateway no pisa la memoria de boca de un satélite en un puerto de uplink, y la memoria de puerto se refresca mientras el dispositivo siga online por ARP/lease aunque no hable por FDB. Además, `GetBridgeFdb` devuelve `nil` ante un fallo de sonda para no sustituir la caché anti-parpadeo por un FDB vacío.
 - **Las notificaciones push de alertas se traducen al idioma del dispositivo (#689)**: el payload viajaba con los literales en español, así que un usuario con la app en inglés recibía los avisos en español. Ahora el server añade el slug del tipo y sus variables (`type`/`vars`) y el service worker traduce con el catálogo de la app (`alerts.types.*` / `alerts.hints.*`) según el idioma del navegador, manteniendo los literales como fallback.
 - **Los nombres de la topología ya no se montan sobre los iconos (#692)**: los labels de los APs se dibujaban a los lados y chocaban con el abanico de clientes cableados (que sale al oeste) y con los chips wifi; los de los peers WireGuard se montaban sobre su propio icono y el del peer vecino. Ahora ambos van centrados bajo el nodo: el modelo ya excluye el ángulo del label al repartir los chips wifi, así que ese sector queda libre por construcción.

+ 80 - 0
app/public/locales/en/translation.json

@@ -105,6 +105,26 @@
         "title": "Agent outdated on {{router}}",
         "description": "{{router}} pushes version {{version}}; the latest available for the {{kind}} agent is {{latest}}"
       },
+      "agent-rearmed": {
+        "title": "Agent rearmed on {{router}}",
+        "description": "Agent service restarted from the server - the agent is pushing again"
+      },
+      "agent-recovered": {
+        "title": "Agent recovered on {{router}}",
+        "description": "The agent on {{router}} is pushing data again - native polling resumed"
+      },
+      "agent-reinstalled": {
+        "title": "Agent reinstalled on {{router}}",
+        "description": "Full reinstall from the server (binary, config, init and watchdog) - the agent is pushing again"
+      },
+      "agent-updated": {
+        "title": "Agent updated on {{router}}",
+        "description": "{{router}} now pushes version {{version}} of {{kind}}"
+      },
+      "auto-rearm-failed": {
+        "title": "Auto-rearm without recovery on {{router}}",
+        "description": "The supervisor restarted netpulse-agent on {{router}} but the agent has not pushed again; next attempt in {{cooldown}} s"
+      },
       "degraded-link": {
         "title": "Degraded link: {{port}} at {{speed}}Mbps (was {{prev}}Mbps)",
         "description": "Negotiated speed dropped from {{prev}} to {{speed}} Mbps for {{polls}} consecutive polls"
@@ -121,14 +141,70 @@
         "title": "Ghost port: {{port}} went silent",
         "description": "Port had traffic but zero bytes for {{polls}} consecutive polls"
       },
+      "ghost-port-recovered": {
+        "title": "Ghost port recovered: {{port}} on {{router}}",
+        "description": "Port is moving traffic again"
+      },
       "high-temperature": {
         "title": "High temperature on {{router}}",
         "description": "{{temp}} °C, above the threshold (65 °C)"
       },
+      "link-down": {
+        "title": "Link down on {{port}}",
+        "description": "The switch beacon reports a link loss"
+      },
+      "link-recovered": {
+        "title": "Link speed recovered: {{port}} on {{router}}",
+        "description": "Port negotiated speed is back to {{speed}} Mbps"
+      },
+      "link-up": {
+        "title": "Link restored on {{port}}",
+        "description": "The switch beacon reports an active link"
+      },
+      "port-disabled": {
+        "title": "Port disabled: {{port}}",
+        "description": "Disabled by the loop guard; will retry in 5 min (max 3 times)"
+      },
       "port-flapping": {
         "title": "Port flapping: {{port}} on {{router}}",
         "description": "{{count}} transitions in {{window}}"
       },
+      "port-recovered": {
+        "title": "Port re-enabled: {{port}}",
+        "description": "The loop guard re-enabled the port"
+      },
+      "port-stable": {
+        "title": "Port stable again: {{port}} on {{router}}",
+        "description": "Flapping stopped, fewer than {{threshold}} transitions in {{window}}"
+      },
+      "router-recovered": {
+        "title": "{{router}} recovered",
+        "description": "{{router}} is responding again"
+      },
+      "sfp-rx-low": {
+        "title": "SFP RX low on {{port}}",
+        "description": "RX power {{rx}} dBm (threshold {{threshold}} dBm)"
+      },
+      "sfp-temp-high": {
+        "title": "SFP hot on {{port}}",
+        "description": "Temperature {{temp}} °C (threshold {{threshold}} °C)"
+      },
+      "ssh-access-lost": {
+        "title": "SSH access lost on {{router}}",
+        "description": "{{router}} does not accept the SSH key, but its agent keeps sending data. Check authorized_keys after a firmware upgrade."
+      },
+      "ssh-access-recovered": {
+        "title": "SSH access recovered on {{router}}",
+        "description": "SSH access to {{router}} is working again"
+      },
+      "switch-loop": {
+        "title": "Loop detected on {{port}}",
+        "description": "The switch guard detected MAC {{mac}} on two ports and disabled {{port}}"
+      },
+      "switch-rebooted": {
+        "title": "Switch rebooted",
+        "description": "The beacon counter of {{router}} restarted (seq {{seq}} after {{prev}}): the switch booted again"
+      },
       "unknown-device": {
         "title": "Unknown device",
         "description": "{{mac}} connected to {{router}}"
@@ -144,6 +220,10 @@
       "wifi-weak": {
         "title": "Weak signal on {{device}}",
         "description": "{{signal}} dBm on {{router}} — check coverage or move closer to an AP"
+      },
+      "wireguard-handshake": {
+        "title": "WireGuard handshake",
+        "description": "{{peer}} connected"
       }
     }
   },

+ 80 - 0
app/public/locales/es/translation.json

@@ -105,6 +105,26 @@
         "title": "Agente desactualizado en {{router}}",
         "description": "{{router}} empuja la versión {{version}}; la última disponible del agente {{kind}} es {{latest}}"
       },
+      "agent-rearmed": {
+        "title": "Agente rearmado en {{router}}",
+        "description": "Reinicio del servicio del agente desde el servidor - el agente vuelve a empujar"
+      },
+      "agent-recovered": {
+        "title": "Agente recuperado en {{router}}",
+        "description": "El agente de {{router}} vuelve a empujar datos - sondeo nativo reanudado"
+      },
+      "agent-reinstalled": {
+        "title": "Agente reinstalado en {{router}}",
+        "description": "Reinstalación completa desde el servidor (binario, config, init y watchdog) - el agente vuelve a empujar"
+      },
+      "agent-updated": {
+        "title": "Agente actualizado en {{router}}",
+        "description": "{{router}} ya empuja la versión {{version}} de {{kind}}"
+      },
+      "auto-rearm-failed": {
+        "title": "Auto-rearme sin recuperación en {{router}}",
+        "description": "El supervisor reinició netpulse-agent en {{router}} pero el agente no ha vuelto a empujar; próximo intento en {{cooldown}} s"
+      },
       "degraded-link": {
         "title": "Enlace degradado: {{port}} a {{speed}} Mbps (antes {{prev}} Mbps)",
         "description": "La velocidad negociada cayó de {{prev}} a {{speed}} Mbps durante {{polls}} sondeos consecutivos"
@@ -121,14 +141,70 @@
         "title": "Ghost port: {{port}} enmudeció",
         "description": "El puerto tenía tráfico pero 0 bytes durante {{polls}} sondeos consecutivos"
       },
+      "ghost-port-recovered": {
+        "title": "Puerto fantasma recuperado: {{port}} en {{router}}",
+        "description": "El puerto vuelve a mover tráfico"
+      },
       "high-temperature": {
         "title": "Temperatura alta en {{router}}",
         "description": "{{temp}} °C, por encima del umbral (65 °C)"
       },
+      "link-down": {
+        "title": "Link caído en {{port}}",
+        "description": "El beacon del switch reporta pérdida de link"
+      },
+      "link-recovered": {
+        "title": "Velocidad del enlace recuperada: {{port}} en {{router}}",
+        "description": "La velocidad negociada del puerto vuelve a {{speed}} Mbps"
+      },
+      "link-up": {
+        "title": "Link restablecido en {{port}}",
+        "description": "El beacon del switch reporta link activo"
+      },
+      "port-disabled": {
+        "title": "Boca deshabilitada: {{port}}",
+        "description": "Desactivada por la guardia de bucles; se reintentará en 5 min (máx. 3 veces)"
+      },
       "port-flapping": {
         "title": "Port flapping: {{port}} en {{router}}",
         "description": "{{count}} transiciones en {{window}}"
       },
+      "port-recovered": {
+        "title": "Boca re-habilitada: {{port}}",
+        "description": "La guardia de bucles ha vuelto a habilitar la boca"
+      },
+      "port-stable": {
+        "title": "Puerto estable de nuevo: {{port}} en {{router}}",
+        "description": "El flapping se detuvo, menos de {{threshold}} transiciones en {{window}}"
+      },
+      "router-recovered": {
+        "title": "{{router}} recuperado",
+        "description": "{{router}} vuelve a responder"
+      },
+      "sfp-rx-low": {
+        "title": "SFP RX bajo en {{port}}",
+        "description": "Potencia RX {{rx}} dBm (umbral {{threshold}} dBm)"
+      },
+      "sfp-temp-high": {
+        "title": "SFP caliente en {{port}}",
+        "description": "Temperatura {{temp}} °C (umbral {{threshold}} °C)"
+      },
+      "ssh-access-lost": {
+        "title": "Acceso SSH perdido en {{router}}",
+        "description": "{{router}} no acepta la clave SSH, pero su agente sigue enviando datos. Revisa authorized_keys tras un firmware upgrade."
+      },
+      "ssh-access-recovered": {
+        "title": "Acceso SSH recuperado en {{router}}",
+        "description": "El acceso SSH a {{router}} funciona de nuevo"
+      },
+      "switch-loop": {
+        "title": "Bucle detectado en {{port}}",
+        "description": "La guardia del switch ha detectado la MAC {{mac}} en dos bocas y ha deshabilitado {{port}}"
+      },
+      "switch-rebooted": {
+        "title": "Switch reiniciado",
+        "description": "El contador de beacons de {{router}} volvió a empezar (seq {{seq}} tras {{prev}}): el switch ha arrancado de nuevo"
+      },
       "unknown-device": {
         "title": "Dispositivo desconocido",
         "description": "{{mac}} se ha conectado a {{router}}"
@@ -144,6 +220,10 @@
       "wifi-weak": {
         "title": "Señal débil en {{device}}",
         "description": "{{signal}} dBm en {{router}} — revisa cobertura o acerca un AP"
+      },
+      "wireguard-handshake": {
+        "title": "Handshake WireGuard",
+        "description": "{{peer}} conectado"
       }
     }
   },

+ 8 - 0
server-go/internal/adapters/agent.go

@@ -344,6 +344,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 				Severity:    "ok",
 				Title:       "Agente recuperado en " + name,
 				Description: fmt.Sprintf("El agente de %s vuelve a empujar datos — sondeo nativo reanudado", name),
+				Type:        alerts.TypeAgentRecovered,
+				Vars:        map[string]string{"router": name},
 				Time:        "ahora mismo", RouterID: cfg.ID,
 			})
 		}
@@ -359,6 +361,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 					Severity:    "warn",
 					Title:       "Acceso SSH perdido en " + name,
 					Description: fmt.Sprintf("%s no acepta la clave SSH, pero su agente sigue enviando datos. Revisa authorized_keys tras un firmware upgrade.", name),
+					Type:        alerts.TypeSSHAccessLost,
+					Vars:        map[string]string{"router": name},
 					Time:        "ahora mismo", RouterID: cfg.ID,
 				})
 			}
@@ -371,6 +375,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 				Severity:    "ok",
 				Title:       "Acceso SSH recuperado en " + name,
 				Description: fmt.Sprintf("El acceso SSH a %s funciona de nuevo", name),
+				Type:        alerts.TypeSSHAccessRecovered,
+				Vars:        map[string]string{"router": name},
 				Time:        "ahora mismo", RouterID: cfg.ID,
 			})
 		}
@@ -759,6 +765,8 @@ func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
 			Severity:    "ok",
 			Title:       "Agente actualizado en " + name,
 			Description: fmt.Sprintf("%s ya empuja la versión %s de %s", name, p.Version, kindLabel),
+			Type:        alerts.TypeAgentUpdated,
+			Vars:        map[string]string{"router": name, "version": p.Version, "kind": kindLabel},
 			Time:        "ahora mismo", RouterID: cfg.ID,
 		})
 	}

+ 4 - 0
server-go/internal/adapters/live.go

@@ -1451,6 +1451,8 @@ func (l *Live) emitRouterRecovered(routerID, name string) {
 		Severity:    "ok",
 		Title:       name + " recuperado",
 		Description: fmt.Sprintf("%s vuelve a responder", name),
+		Type:        alerts.TypeRouterRecovered,
+		Vars:        map[string]string{"router": name},
 		Time:        "ahora mismo", RouterID: routerID,
 	})
 }
@@ -1823,6 +1825,8 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 				Category: alerts.CatVPN, Urgent: false,
 				Severity: "info", Title: "Handshake WireGuard",
 				Description: name + " conectado",
+				Type:        alerts.TypeWireguardHandshake,
+				Vars:        map[string]string{"peer": name},
 				Time:        "ahora mismo", RouterID: gw.ID,
 			})
 		}

+ 6 - 0
server-go/internal/adapters/portmonitor.go

@@ -138,6 +138,8 @@ func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now
 			Severity:    "ok",
 			Title:       fmt.Sprintf("Port stable again: %s on %s", p.Label, key.routerID),
 			Description: fmt.Sprintf("Flapping stopped, fewer than %d transitions in %s", flapThreshold, flapWindow),
+			Type:        alerts.TypePortStable,
+			Vars:        map[string]string{"port": p.Label, "router": key.routerID, "threshold": strconv.Itoa(flapThreshold), "window": flapWindow.String()},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})
@@ -208,6 +210,8 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now tim
 			Severity:    "ok",
 			Title:       fmt.Sprintf("Ghost port recovered: %s on %s", p.Label, key.routerID),
 			Description: "Port is moving traffic again",
+			Type:        alerts.TypeGhostPortRecovered,
+			Vars:        map[string]string{"port": p.Label, "router": key.routerID},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})
@@ -254,6 +258,8 @@ func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, now
 			Severity:    "ok",
 			Title:       fmt.Sprintf("Link speed recovered: %s on %s", p.Label, key.routerID),
 			Description: fmt.Sprintf("Port negotiated speed is back to %d Mbps", st.speedMbps),
+			Type:        alerts.TypeLinkRecovered,
+			Vars:        map[string]string{"port": p.Label, "router": key.routerID, "speed": strconv.Itoa(st.speedMbps)},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})

+ 8 - 1
server-go/internal/adapters/portmonitor_test.go

@@ -335,9 +335,16 @@ func TestPortMonitorGhostRecovery(t *testing.T) {
 			pm.Observe("r1", []EthPort{port}, engine)
 		}
 	}
-	if n, _ := findAlerts(engine, "Ghost port recovered: LAN1 on r1"); n != 1 {
+	n, last := findAlerts(engine, "Ghost port recovered: LAN1 on r1")
+	if n != 1 {
 		t.Fatalf("recovery alerts = %d, want 1", n)
 	}
+	if last.Type != alerts.TypeGhostPortRecovered {
+		t.Fatalf("Type=%q, want %q", last.Type, alerts.TypeGhostPortRecovered)
+	}
+	if last.Vars["port"] != "LAN1" || last.Vars["router"] != "r1" {
+		t.Fatalf("Vars=%v", last.Vars)
+	}
 }
 
 // issue #419: cuando ghost port esta desactivado, no se emiten alertas de

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

@@ -98,6 +98,31 @@ const (
 	HintWanSlow       = "wan-slow"
 )
 
+// Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
+// types emitted without Type/Vars in #671. They carry no hint.
+const (
+	TypeAgentRecovered     = "agent-recovered"
+	TypeSSHAccessLost      = "ssh-access-lost"
+	TypeSSHAccessRecovered = "ssh-access-recovered"
+	TypeAgentUpdated       = "agent-updated"
+	TypeRouterRecovered    = "router-recovered"
+	TypeWireguardHandshake = "wireguard-handshake"
+	TypePortStable         = "port-stable"
+	TypeGhostPortRecovered = "ghost-port-recovered"
+	TypeLinkRecovered      = "link-recovered"
+	TypeSwitchLoop         = "switch-loop"
+	TypePortDisabled       = "port-disabled"
+	TypePortRecovered      = "port-recovered"
+	TypeLinkDown           = "link-down"
+	TypeLinkUp             = "link-up"
+	TypeSfpRxLow           = "sfp-rx-low"
+	TypeSfpTempHigh        = "sfp-temp-high"
+	TypeSwitchRebooted     = "switch-rebooted"
+	TypeAgentRearmed       = "agent-rearmed"
+	TypeAgentReinstalled   = "agent-reinstalled"
+	TypeAutoRearmFailed    = "auto-rearm-failed"
+)
+
 // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
 // the value into AlertEvent.Hint; the feed and push render it as a helper line.
 var Hints = map[string]string{

+ 91 - 0
server-go/internal/alerts/alerts_i18n_test.go

@@ -0,0 +1,91 @@
+// alerts_i18n_test.go — contrato de slugs de alertas con sus claves i18n (#712).
+package alerts
+
+import (
+	"encoding/json"
+	"os"
+	"path/filepath"
+	"regexp"
+	"strings"
+	"testing"
+)
+
+// newTypeSlugs: slugs añadidos en #712 para los emisores que seguían sin
+// Type/Vars (recuperaciones, beacon, rearme, SFP, WireGuard...).
+var newTypeSlugs = []string{
+	TypeAgentRecovered, TypeSSHAccessLost, TypeSSHAccessRecovered,
+	TypeAgentUpdated, TypeRouterRecovered, TypeWireguardHandshake,
+	TypePortStable, TypeGhostPortRecovered, TypeLinkRecovered,
+	TypeSwitchLoop, TypePortDisabled, TypePortRecovered,
+	TypeLinkDown, TypeLinkUp, TypeSfpRxLow, TypeSfpTempHigh,
+	TypeSwitchRebooted, TypeAgentRearmed, TypeAgentReinstalled,
+	TypeAutoRearmFailed,
+}
+
+// hintSlugs: slugs ya existentes en #310/#671 (con hint) para detectar colisiones.
+var hintSlugs = []string{
+	HintAgentDown, HintAgentDownSSH, HintGatewayUnrch, HintHighTemp,
+	HintPortFlapping, HintDeviceOffline, HintUnknownDevice, HintFirmware,
+	HintWanDown, HintWifiWeak, HintGhostPort, HintDegradedLink,
+	HintAgentOutdated, HintWanSlow,
+}
+
+var kebabRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
+
+// TestNewTypeSlugsAreKebabCaseAndUnique: los slugs nuevos son kebab-case y no
+// colisionan con los existentes.
+func TestNewTypeSlugsAreKebabCaseAndUnique(t *testing.T) {
+	seen := map[string]bool{}
+	for _, h := range hintSlugs {
+		seen[h] = true
+	}
+	for _, slug := range newTypeSlugs {
+		if !kebabRe.MatchString(slug) {
+			t.Errorf("slug %q no es kebab-case", slug)
+		}
+		if seen[slug] {
+			t.Errorf("slug %q colisiona con un hint/slug existente", slug)
+		}
+		seen[slug] = true
+	}
+	if len(newTypeSlugs) != 20 {
+		t.Errorf("se esperan 20 slugs nuevos, hay %d", len(newTypeSlugs))
+	}
+}
+
+// TestAlertTypeSlugsHaveI18nKeys: cada slug nuevo tiene title y description
+// en ES y EN. Lee los catálogos de la app (contrato server <-> frontend).
+func TestAlertTypeSlugsHaveI18nKeys(t *testing.T) {
+	root := filepath.Join("..", "..", "..") // server-go/internal/alerts -> repo root
+	for _, lang := range []string{"es", "en"} {
+		path := filepath.Join(root, "app", "public", "locales", lang, "translation.json")
+		data, err := os.ReadFile(path)
+		if err != nil {
+			t.Fatalf("no se pudo leer %s: %v", path, err)
+		}
+		var tree map[string]interface{}
+		if err := json.Unmarshal(data, &tree); err != nil {
+			t.Fatalf("json inválido en %s: %v", path, err)
+		}
+		alertsNode, ok := tree["alerts"].(map[string]interface{})
+		if !ok {
+			t.Fatalf("%s: falta alerts", lang)
+		}
+		types, ok := alertsNode["types"].(map[string]interface{})
+		if !ok {
+			t.Fatalf("%s: falta alerts.types", lang)
+		}
+		for _, slug := range newTypeSlugs {
+			entry, ok := types[slug].(map[string]interface{})
+			if !ok {
+				t.Errorf("%s: falta alerts.types.%s", lang, slug)
+				continue
+			}
+			for _, key := range []string{"title", "description"} {
+				if v, ok := entry[key].(string); !ok || strings.TrimSpace(v) == "" {
+					t.Errorf("%s: alerts.types.%s.%s vacío o ausente", lang, slug, key)
+				}
+			}
+		}
+	}
+}

+ 20 - 0
server-go/internal/httpapi/beacon.go

@@ -301,20 +301,30 @@ func (s *server) handleBeaconEvent(p beaconPacket) {
 		ev.Description = fmt.Sprintf(
 			"La guardia del switch ha detectado la MAC %s en dos bocas y ha deshabilitado %s",
 			p.Mac, portName)
+		ev.Type = alerts.TypeSwitchLoop
+		ev.Vars = map[string]string{"port": portName, "mac": p.Mac}
 	case "port_disabled":
 		ev.Title = "Boca deshabilitada: " + portName
 		ev.Description = "Desactivada por la guardia de bucles; se reintentará en 5 min (máx. 3 veces)"
+		ev.Type = alerts.TypePortDisabled
+		ev.Vars = map[string]string{"port": portName}
 	case "port_recovered":
 		ev.Severity = "ok"
 		ev.Title = "Boca re-habilitada: " + portName
 		ev.Description = "La guardia de bucles ha vuelto a habilitar la boca"
+		ev.Type = alerts.TypePortRecovered
+		ev.Vars = map[string]string{"port": portName}
 	case "port_down":
 		ev.Title = "Link caído en " + portName
 		ev.Description = "El beacon del switch reporta pérdida de link"
+		ev.Type = alerts.TypeLinkDown
+		ev.Vars = map[string]string{"port": portName}
 	case "port_up":
 		ev.Severity = "ok"
 		ev.Title = "Link restablecido en " + portName
 		ev.Description = "El beacon del switch reporta link activo"
+		ev.Type = alerts.TypeLinkUp
+		ev.Vars = map[string]string{"port": portName}
 	default:
 		log.Printf("[netpulse:beacon] evento desconocido %q de %s", p.Ev, p.Slug)
 		return
@@ -340,6 +350,8 @@ func (s *server) emitPortLinkChange(slug, label string, up bool) {
 			Category: alerts.CatSystem, Severity: "ok", Time: "ahora mismo",
 			RouterID: slug, Title: "Link restablecido en " + name,
 			Description: "Detectado por el cambio entre beacons",
+			Type:        alerts.TypeLinkUp,
+			Vars:        map[string]string{"port": name},
 		}
 	} else {
 		ev = alerts.AlertEvent{
@@ -347,6 +359,8 @@ func (s *server) emitPortLinkChange(slug, label string, up bool) {
 			Category: alerts.CatSystem, Severity: "warn", Time: "ahora mismo",
 			RouterID: slug, Title: "Link caído en " + name,
 			Description: "Detectado por el cambio entre beacons",
+			Type:        alerts.TypeLinkDown,
+			Vars:        map[string]string{"port": name},
 		}
 	}
 	eng.Emit(ev)
@@ -378,6 +392,8 @@ func (s *server) emitSFPAlerts(slug string, labels map[string]string, sfpByPort
 				Severity: "warn", Time: "ahora mismo", RouterID: slug,
 				Title:       fmt.Sprintf("SFP RX bajo en %s", portName),
 				Description: fmt.Sprintf("Potencia RX %.1f dBm (umbral %.0f dBm)", sfp.RxPower, sfpAlertRxLow),
+				Type:        alerts.TypeSfpRxLow,
+				Vars:        map[string]string{"port": portName, "rx": fmt.Sprintf("%.1f", sfp.RxPower), "threshold": fmt.Sprintf("%.0f", sfpAlertRxLow)},
 			})
 		}
 		if sfp.Temperature > sfpAlertTempHigh {
@@ -387,6 +403,8 @@ func (s *server) emitSFPAlerts(slug string, labels map[string]string, sfpByPort
 				Severity: "warn", Time: "ahora mismo", RouterID: slug,
 				Title:       fmt.Sprintf("SFP caliente en %s", portName),
 				Description: fmt.Sprintf("Temperatura %.1f °C (umbral %.0f °C)", sfp.Temperature, sfpAlertTempHigh),
+				Type:        alerts.TypeSfpTempHigh,
+				Vars:        map[string]string{"port": portName, "temp": fmt.Sprintf("%.1f", sfp.Temperature), "threshold": fmt.Sprintf("%.0f", sfpAlertTempHigh)},
 			})
 		}
 	}
@@ -493,6 +511,8 @@ func (s *server) beaconSeqNote(slug string, seq uint32) {
 				Category: alerts.CatSystem, Severity: "info", Time: "ahora mismo",
 				RouterID: slug, Title: "Switch reiniciado",
 				Description: fmt.Sprintf("El contador de beacons de %s volvió a empezar (seq %d tras %d): el switch ha arrancado de nuevo", slug, seq, old),
+				Type:        alerts.TypeSwitchRebooted,
+				Vars:        map[string]string{"router": slug, "seq": fmt.Sprintf("%d", seq), "prev": fmt.Sprintf("%d", old)},
 			})
 		}
 	}

+ 25 - 1
server-go/internal/httpapi/beacon_test.go

@@ -241,6 +241,12 @@ func TestBeaconLoopEventEmitsUrgentAlert(t *testing.T) {
 	if !strings.Contains(a.Title, "boca 2") {
 		t.Fatalf("título sin la boca: %q", a.Title)
 	}
+	if a.Type != alerts.TypeSwitchLoop {
+		t.Fatalf("Type=%q, want %q", a.Type, alerts.TypeSwitchLoop)
+	}
+	if a.Vars["mac"] != "AABBCCDDEEFF" || a.Vars["port"] != "boca 2" {
+		t.Fatalf("Vars=%v", a.Vars)
+	}
 }
 
 // El fallback por delta: dos beacons seguidos con un link cambiado generan
@@ -258,7 +264,13 @@ func TestBeaconDeltaFallbackEmitsLinkChange(t *testing.T) {
 	waitFresh(t, s, "switch16")
 	down := fmt.Sprintf(`{"v":1,"seq":2,"slug":"switch16","token":"%s","ports":[{"n":2,"l":0,"tx":1,"rx":1}]}`, token)
 	sendUDP(t, addr, down)
-	waitForAlert(t, s, "Link caído")
+	a := waitForAlert(t, s, "Link caído")
+	if a.Type != alerts.TypeLinkDown {
+		t.Fatalf("Type=%q, want %q", a.Type, alerts.TypeLinkDown)
+	}
+	if a.Vars["port"] == "" {
+		t.Fatalf("Vars port vacío: %v", a.Vars)
+	}
 }
 
 // Datagrama FDB (v1.2): sustituye la tabla MAC conservando las bocas del
@@ -343,6 +355,12 @@ func TestBeaconSeqResetEmitsRebootAlert(t *testing.T) {
 	if a.Severity != "info" || a.RouterID != "switch16" {
 		t.Fatalf("alerta de reboot mal: %+v", a)
 	}
+	if a.Type != alerts.TypeSwitchRebooted {
+		t.Fatalf("Type=%q, want %q", a.Type, alerts.TypeSwitchRebooted)
+	}
+	if a.Vars["router"] != "switch16" || a.Vars["seq"] == "" || a.Vars["prev"] == "" {
+		t.Fatalf("Vars=%v", a.Vars)
+	}
 }
 
 // Beacon con campo sfp: los datos DDM/DOM se inyectan en la EthPort
@@ -384,4 +402,10 @@ func TestBeaconSFPDataAndAlert(t *testing.T) {
 	if a.Severity != "warn" || a.Category != "system" {
 		t.Fatalf("alerta SFP RX mal: %+v", a)
 	}
+	if a.Type != alerts.TypeSfpRxLow {
+		t.Fatalf("Type=%q, want %q", a.Type, alerts.TypeSfpRxLow)
+	}
+	if a.Vars["rx"] == "" || a.Vars["threshold"] == "" {
+		t.Fatalf("Vars=%v", a.Vars)
+	}
 }

+ 6 - 0
server-go/internal/rearmer/rearmer.go

@@ -311,6 +311,8 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 				Category: alerts.CatSystem, Urgent: false, Severity: "info",
 				Title:       fmt.Sprintf("Agente rearmado en %s", slug),
 				Description: "Reinicio del servicio del agente desde el servidor — el agente vuelve a empujar",
+				Type:        alerts.TypeAgentRearmed,
+				Vars:        map[string]string{"router": slug},
 				Time:        "ahora mismo", RouterID: slug,
 			})
 		}
@@ -386,6 +388,8 @@ func (r *Rearmer) Reinstall(slug, publicURL string) (Result, error) {
 				Category: alerts.CatSystem, Urgent: false, Severity: "info",
 				Title:       fmt.Sprintf("Agente reinstalado en %s", slug),
 				Description: "Reinstalación completa desde el servidor (binario, config, init y watchdog) — el agente vuelve a empujar",
+				Type:        alerts.TypeAgentReinstalled,
+				Vars:        map[string]string{"router": slug},
 				Time:        "ahora mismo", RouterID: slug,
 			})
 		}
@@ -605,6 +609,8 @@ func (s *Supervisor) emitFail(slug string) {
 		Category: alerts.CatSystem, Urgent: false, Severity: "warn",
 		Title:       fmt.Sprintf("Auto-rearme sin recuperación en %s", slug),
 		Description: fmt.Sprintf("El supervisor reinició netpulse-agent en %s pero el agente no ha vuelto a empujar; próximo intento en %d s", slug, int(s.cooldown.Seconds())),
+		Type:        alerts.TypeAutoRearmFailed,
+		Vars:        map[string]string{"router": slug, "cooldown": fmt.Sprintf("%d", int(s.cooldown.Seconds()))},
 		Time:        "ahora mismo", RouterID: slug,
 	})
 }