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

fix(alerts): localize the alert feed in the user's language (#674)

Alert titles, descriptions and hints were server-generated Spanish literals,
so users running the app in English saw mixed-language alerts. Events now
carry the alert-type slug (Type) and interpolation vars; the frontend
translates by i18n key with the server literals as fallback. All 13 slugged
alert types are migrated (unknown-device, router offline, agent down/ssh,
agent outdated, firmware, wan-down, wan-slow, high temperature, weak signal,
port flapping, ghost port, degraded link), and unknown-device interpolates
the router's display name.

Closes #671

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

+ 6 - 0
CHANGELOG.md

@@ -5,6 +5,12 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
+## [Unreleased]
+
+### Fixed
+
+- **Las alertas se muestran en el idioma del usuario (#671)**: los textos del feed (título, descripción y sugerencia) los generaba el servidor en español y un usuario con la app en inglés los veía mezclados. Los eventos llevan ahora el slug de su tipo y sus variables, y el frontend los traduce por clave en el idioma activo (con los literales del servidor como respaldo). Migrados los 13 tipos con slug: dispositivo desconocido, router offline, agente caído (y su variante SSH), agente desactualizado, firmware, Internet caído, velocidad WAN lenta, temperatura alta, señal débil, port flapping, ghost port y enlace degradado. Las notificaciones push de las alertas urgentes siguen en español por ahora (seguimiento aparte).
+
 ## [2.28.18] - 2026-09-10
 
 ### Added

+ 61 - 2
app/public/locales/en/translation.json

@@ -78,14 +78,73 @@
     },
     "hints": {
       "agent-down": "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
+      "agent-down-ssh": "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
+      "agent-outdated": "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
+      "degraded-link": "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
+      "device-offline": "Verify the device power and network cable.",
+      "firmware-outdated": "NetPulse is read-only: update the firmware from LuCI.",
       "gateway-unreachable": "Check the connection between the gateway and the rest of the network.",
+      "ghost-port": "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
       "high-temperature": "Improve ventilation and keep the router away from heat sources.",
       "port-flapping": "Check the cable or switch port: an unstable link is usually the culprit.",
-      "device-offline": "Verify the device power and network cable.",
       "unknown-device": "If you do not recognize it, block it or mark it as trusted in Settings.",
-      "firmware-outdated": "NetPulse is read-only: update the firmware from LuCI.",
       "wan-down": "Check the modem/ONT and contact your ISP if the outage persists.",
+      "wan-slow": "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
       "wifi-weak": "Move the device closer to an access point or relocate the AP."
+    },
+    "types": {
+      "agent-down": {
+        "title": "Agent down on {{router}}",
+        "description": "No data from the agent on {{router}} for more than {{confirm}} — using cached data"
+      },
+      "agent-down-ssh": {
+        "title": "Agent down on {{router}} — falling back to SSH",
+        "description": "No data from the agent on {{router}} for more than {{confirm}} — SSH polling resumed"
+      },
+      "agent-outdated": {
+        "title": "Agent outdated on {{router}}",
+        "description": "{{router}} pushes version {{version}}; the latest available for the {{kind}} agent is {{latest}}"
+      },
+      "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"
+      },
+      "device-offline": {
+        "title": "{{router}} offline",
+        "description": "No response from {{host}}: {{error}}"
+      },
+      "firmware-outdated": {
+        "title": "Firmware outdated",
+        "description": "{{router}}: firmware \"{{firmware}}\" does not match the target \"{{target}}\""
+      },
+      "ghost-port": {
+        "title": "Ghost port: {{port}} went silent",
+        "description": "Port had traffic but zero bytes for {{polls}} consecutive polls"
+      },
+      "high-temperature": {
+        "title": "High temperature on {{router}}",
+        "description": "{{temp}} °C, above the threshold (65 °C)"
+      },
+      "port-flapping": {
+        "title": "Port flapping: {{port}} on {{router}}",
+        "description": "{{count}} transitions in {{window}}"
+      },
+      "unknown-device": {
+        "title": "Unknown device",
+        "description": "{{mac}} connected to {{router}}"
+      },
+      "wan-down": {
+        "title": "Internet down",
+        "description": "{{router}} responds but cannot reach the internet (100% packet loss)"
+      },
+      "wan-slow": {
+        "title": "WAN speed below plan",
+        "description": "Measured {{down}} Mbps down against {{plan}} Mbps contracted (less than {{pct}}% of the plan)"
+      },
+      "wifi-weak": {
+        "title": "Weak signal on {{device}}",
+        "description": "{{signal}} dBm on {{router}} — check coverage or move closer to an AP"
+      }
     }
   },
   "auth": {

+ 61 - 2
app/public/locales/es/translation.json

@@ -78,14 +78,73 @@
     },
     "hints": {
       "agent-down": "Comprueba la alimentación y la conexión del router; si no se recupera, reinstala el agente desde LuCI.",
+      "agent-down-ssh": "Comprueba la alimentación y la conexión del router; si no se recupera, reinstala el agente desde LuCI.",
+      "agent-outdated": "Actualiza el agente desde Ajustes, Agentes (botón Actualizar); si es un panel NetGrip, actualiza desde su propio panel.",
+      "degraded-link": "Revisa el cable y los conectores: un enlace degradado suele ser síntoma de cable dañado o conector flojo.",
+      "device-offline": "Verifica la alimentación y el cable de red del equipo.",
+      "firmware-outdated": "NetPulse es de solo lectura: actualiza el firmware desde LuCI.",
       "gateway-unreachable": "Comprueba la conexión entre la puerta de enlace y el resto de la red.",
+      "ghost-port": "Revisa el cable y el dispositivo conectado: un puerto activo que enmudece suele indicar un cable suelto o un equipo apagado.",
       "high-temperature": "Mejora la ventilación y aleja el router de fuentes de calor.",
       "port-flapping": "Revisa el cable o el puerto del switch: un enlace inestable suele ser el culpable.",
-      "device-offline": "Verifica la alimentación y el cable de red del equipo.",
       "unknown-device": "Si no lo reconoces, bloquéalo o márcalo como de confianza en Ajustes.",
-      "firmware-outdated": "NetPulse es de solo lectura: actualiza el firmware desde LuCI.",
       "wan-down": "Comprueba el módem/ONT y contacta con tu operador si la caída persiste.",
+      "wan-slow": "Reinicia el router y el módem/ONT y repite el test; si sigue bajo, contacta con tu operador (degrada la línea o hay saturación en tu área).",
       "wifi-weak": "Acerca el dispositivo a un punto de acceso o reubica el AP."
+    },
+    "types": {
+      "agent-down": {
+        "title": "Agente caído en {{router}}",
+        "description": "Sin datos del agente de {{router}} desde hace más de {{confirm}} — usando datos cacheados"
+      },
+      "agent-down-ssh": {
+        "title": "Agente caído en {{router}} — volviendo a SSH",
+        "description": "Sin datos del agente de {{router}} desde hace más de {{confirm}} — sondeo SSH reanudado"
+      },
+      "agent-outdated": {
+        "title": "Agente desactualizado en {{router}}",
+        "description": "{{router}} empuja la versión {{version}}; la última disponible del agente {{kind}} es {{latest}}"
+      },
+      "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"
+      },
+      "device-offline": {
+        "title": "{{router}} offline",
+        "description": "Sin respuesta de {{host}}: {{error}}"
+      },
+      "firmware-outdated": {
+        "title": "Firmware desactualizado",
+        "description": "{{router}}: firmware \"{{firmware}}\" no coincide con el target \"{{target}}\""
+      },
+      "ghost-port": {
+        "title": "Ghost port: {{port}} enmudeció",
+        "description": "El puerto tenía tráfico pero 0 bytes durante {{polls}} sondeos consecutivos"
+      },
+      "high-temperature": {
+        "title": "Temperatura alta en {{router}}",
+        "description": "{{temp}} °C, por encima del umbral (65 °C)"
+      },
+      "port-flapping": {
+        "title": "Port flapping: {{port}} en {{router}}",
+        "description": "{{count}} transiciones en {{window}}"
+      },
+      "unknown-device": {
+        "title": "Dispositivo desconocido",
+        "description": "{{mac}} se ha conectado a {{router}}"
+      },
+      "wan-down": {
+        "title": "Internet caído",
+        "description": "{{router}} responde pero no alcanza internet (100 % de pérdida)"
+      },
+      "wan-slow": {
+        "title": "Velocidad WAN por debajo del plan",
+        "description": "Medido {{down}} Mbps de bajada contra {{plan}} Mbps contratados (menos del {{pct}}% del plan)"
+      },
+      "wifi-weak": {
+        "title": "Señal débil en {{device}}",
+        "description": "{{signal}} dBm en {{router}} — revisa cobertura o acerca un AP"
+      }
     }
   },
   "auth": {

+ 8 - 4
app/src/components/AlertItem.tsx

@@ -1,7 +1,9 @@
 import { AlertTriangle, CheckCircle2, Info, OctagonX } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
 import { relTime } from '@/i18n'
 import type { AlertSeverity, AlertEvent } from '@/data/mock'
+import { alertDescription, alertHint, alertTitle } from '@/lib/alerts-i18n'
 import { cn } from '@/lib/utils'
 
 const SEVERITY: Record<AlertSeverity, { icon: LucideIcon; tile: string; dot: string; stripe: string }> = {
@@ -19,8 +21,10 @@ interface AlertItemProps {
 
 /** Ítem de alerta (design.md §10.6): tile de severidad, título, descripción, tiempo, dot no-leído. */
 export function AlertItem({ alert, onClick, className }: AlertItemProps) {
+  const { t } = useTranslation()
   const s = SEVERITY[alert.severity]
   const Icon = s.icon
+  const hint = alertHint(t, alert)
   return (
     <button
       type="button"
@@ -37,12 +41,12 @@ export function AlertItem({ alert, onClick, className }: AlertItemProps) {
       </div>
       <div className="min-w-0 flex-1">
         <div className="flex items-center justify-between gap-2">
-          <span className="truncate text-sm font-medium text-text-primary">{alert.title}</span>
+          <span className="truncate text-sm font-medium text-text-primary">{alertTitle(t, alert)}</span>
           <span className="shrink-0 text-caption text-text-muted">{relTime(alert.time)}</span>
         </div>
-        <p className="mt-0.5 truncate text-caption text-text-secondary">{alert.description}</p>
-        {alert.hint && (
-          <p className="mt-0.5 truncate text-caption italic text-text-muted">{alert.hint}</p>
+        <p className="mt-0.5 truncate text-caption text-text-secondary">{alertDescription(t, alert)}</p>
+        {hint && (
+          <p className="mt-0.5 truncate text-caption italic text-text-muted">{hint}</p>
         )}
       </div>
       {!alert.read && (

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

@@ -298,6 +298,11 @@ export interface AlertEvent {
   description: string
   /** Sugerencia accionable por tipo de alerta (issue #310). Ausente si no aplica. */
   hint?: string
+  /** Slug estable del tipo de alerta (issue #310): el frontend traduce
+   *  título/descripción/hint por clave i18n (#671). Ausente = literal. */
+  type?: string
+  /** Variables de interpolación para esas claves (router, mac, temp…). */
+  vars?: Record<string, string>
   /** LEGADO display: "hace 12 min" — fallback si `ts` no es válido */
   time: string
   /** Unix SEGUNDOS; el frontend calcula el tiempo relativo */

+ 32 - 0
app/src/lib/alerts-i18n.ts

@@ -0,0 +1,32 @@
+/**
+ * Traducción de alertas por clave i18n (#671).
+ *
+ * El motor de alertas del server genera los textos (título, descripción,
+ * hint) como literales, históricamente en español. Desde #671 el evento
+ * lleva además el slug estable del tipo (`type`, las claves del mapa Hints de
+ * #310) y las variables de interpolación (`vars`), y el frontend traduce por
+ * clave en el idioma del usuario: `alerts.types.<slug>.title|.description` y
+ * `alerts.hints.<slug>`.
+ *
+ * Fallback: si el evento no lleva `type` (servidores viejos, dataset demo,
+ * tipos aún sin migrar) o falta la clave, se muestra el literal del server.
+ */
+import type { TFunction } from 'i18next'
+import type { AlertEvent } from '@/data/types'
+
+export function alertTitle(t: TFunction, ev: AlertEvent): string {
+  if (!ev.type) return ev.title
+  return t(`alerts.types.${ev.type}.title`, { defaultValue: ev.title, ...(ev.vars ?? {}) })
+}
+
+export function alertDescription(t: TFunction, ev: AlertEvent): string {
+  if (!ev.type) return ev.description
+  return t(`alerts.types.${ev.type}.description`, { defaultValue: ev.description, ...(ev.vars ?? {}) })
+}
+
+/** Hint traducido; undefined cuando la alerta no lleva hint. */
+export function alertHint(t: TFunction, ev: AlertEvent): string | undefined {
+  if (!ev.hint) return undefined
+  if (!ev.type) return ev.hint
+  return t(`alerts.hints.${ev.type}`, { defaultValue: ev.hint })
+}

+ 5 - 4
app/src/pages/Alerts.tsx

@@ -26,6 +26,7 @@ import {
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { alertRelTime, relTime } from '@/i18n'
+import { alertDescription, alertHint, alertTitle } from '@/lib/alerts-i18n'
 import type { AlertCategory, AlertConfigLevel, AlertSeverity } from '@/data/types'
 import { ALERT_CATEGORIES } from '@/data/alertConfig'
 import { CountUp } from '@/components/CountUp'
@@ -302,7 +303,7 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence }: Fee
         <div className="min-w-0 flex-1">
           <div className="flex items-center justify-between gap-2">
             <span className="flex min-w-0 items-center gap-2">
-              <span className="truncate text-sm font-medium text-text-primary">{ev.title}</span>
+              <span className="truncate text-sm font-medium text-text-primary">{alertTitle(t, ev)}</span>
               {ev.urgent && (
                 <span className="shrink-0 rounded-md bg-danger/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-[0.05em] text-danger">
                   {t('alerts.urgentBadge')}
@@ -334,9 +335,9 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence }: Fee
               <span className="font-mono text-caption text-text-muted">{alertRelTime(ev)}</span>
             </span>
           </div>
-          <p className="mt-0.5 truncate text-caption text-text-secondary">{ev.description}</p>
-          {ev.hint && (
-            <p className="mt-0.5 truncate text-caption italic text-text-muted">{ev.hint}</p>
+          <p className="mt-0.5 truncate text-caption text-text-secondary">{alertDescription(t, ev)}</p>
+          {alertHint(t, ev) && (
+            <p className="mt-0.5 truncate text-caption italic text-text-muted">{alertHint(t, ev)}</p>
           )}
           {ev.suppressedBy && (
             <p className="mt-0.5 truncate text-caption text-text-muted" title={t('alertSuppression.suppressedHint')}>

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

@@ -400,6 +400,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 						Title:       fmt.Sprintf("Agente caído en %s", name),
 						Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — usando datos cacheados", name, confirm),
 						Hint:        alerts.HintFor(alerts.HintAgentDown),
+						Type:        alerts.HintAgentDown,
+						Vars:        map[string]string{"router": name, "confirm": confirm.String()},
 						Time:        "ahora mismo", RouterID: cfg.ID,
 					})
 				} else {
@@ -410,6 +412,8 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 						Title:       fmt.Sprintf("Agente caído en %s — volviendo a SSH", name),
 						Description: fmt.Sprintf("Sin datos del agente de %s desde hace más de %s — sondeo SSH reanudado", name, confirm),
 						Hint:        alerts.HintFor(alerts.HintAgentDown),
+						Type:        alerts.HintAgentDownSSH,
+						Vars:        map[string]string{"router": name, "confirm": confirm.String()},
 						Time:        "ahora mismo", RouterID: cfg.ID,
 					})
 				}
@@ -741,6 +745,8 @@ func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
 			Title:       "Agente desactualizado en " + name,
 			Description: fmt.Sprintf("%s empuja la versión %s; la última disponible del agente %s es %s", name, p.Version, kindLabel, ref),
 			Hint:        alerts.HintFor(alerts.HintAgentOutdated),
+			Type:        alerts.HintAgentOutdated,
+			Vars:        map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
 			Time:        "ahora mismo", RouterID: cfg.ID,
 		})
 	} else if alerted {

+ 39 - 0
server-go/internal/adapters/alerts_i18n_test.go

@@ -0,0 +1,39 @@
+// alerts_i18n_test.go — tipado de alertas para traducción client-side (#671).
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// TestUnknownDeviceAlertCarriesType: la alerta de dispositivo desconocido
+// lleva el slug del tipo y las vars (mac, router) para que el frontend
+// traduzca título/descripción/hint en el idioma del usuario.
+func TestUnknownDeviceAlertCarriesType(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "gateway", Name: "Flint 2", IsGateway: true},
+	}, nil)
+	l.emitUnknownDevice(Device{
+		ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "AA:BB:CC:DD:EE:FF",
+		RouterID: "gateway", Online: true,
+	})
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("esperado 1 alerta, got %d", len(list))
+	}
+	ev := list[0]
+	if ev.Type != alerts.HintUnknownDevice {
+		t.Fatalf("Type=%q (want %q)", ev.Type, alerts.HintUnknownDevice)
+	}
+	if ev.Vars["mac"] != "AA:BB:CC:DD:EE:FF" {
+		t.Fatalf("Vars mac=%q", ev.Vars["mac"])
+	}
+	if ev.Vars["router"] != "Flint 2" {
+		t.Fatalf("Vars router=%q (want nombre visible, no el id)", ev.Vars["router"])
+	}
+	// Los literales siguen viajando como fallback.
+	if ev.Title == "" || ev.Description == "" || ev.Hint == "" {
+		t.Fatalf("los literales de fallback no deben vaciarse: %+v", ev)
+	}
+}

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

@@ -1169,6 +1169,8 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 			Title:       "Firmware desactualizado",
 			Description: fmt.Sprintf("%s: firmware %q no coincide con el target %q", name, r.Firmware, p.cfg.FirmwareTarget),
 			Hint:        alerts.HintFor(alerts.HintFirmware),
+			Type:        alerts.HintFirmware,
+			Vars:        map[string]string{"router": name, "firmware": r.Firmware, "target": p.cfg.FirmwareTarget},
 			Time:        "ahora mismo", RouterID: p.cfg.ID,
 		})
 	}
@@ -1414,6 +1416,8 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 				Title:       name + " offline",
 				Description: fmt.Sprintf("Sin respuesta de %s: %v", res.cfg.Host, res.err),
 				Hint:        alerts.HintFor(alerts.HintDeviceOffline),
+				Type:        alerts.HintDeviceOffline,
+				Vars:        map[string]string{"router": name, "host": res.cfg.Host, "error": fmt.Sprint(res.err)},
 				Time:        "ahora mismo", RouterID: res.cfg.ID,
 			})
 		}
@@ -1485,6 +1489,8 @@ func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
 			Title:       "Internet caído",
 			Description: fmt.Sprintf("%s responde pero no alcanza internet (100 %% de pérdida)", name),
 			Hint:        alerts.HintFor(alerts.HintWanDown),
+			Type:        alerts.HintWanDown,
+			Vars:        map[string]string{"router": name},
 			Time:        "ahora mismo", RouterID: cfg.ID,
 		})
 	}
@@ -1572,6 +1578,18 @@ func (l *Live) persistUnknownAlerted(mac string) {
 	_, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unknown_alerted:"+mac)
 }
 
+// routerDisplayName: nombre visible de un router por id ("" si no está en la
+// flota). Usado por las alertas para interpolar la clave i18n {{router}}.
+// Debe llamarse con l.mu tomado.
+func (l *Live) routerDisplayName(id string) string {
+	for _, r := range l.routers {
+		if r.ID == id {
+			return r.Name
+		}
+	}
+	return id
+}
+
 // emitUnknownDevice: evento "dispositivo desconocido se conecta" (category
 // clients, warn, NO urgente — issue #196). "Desconocido" = sin nombre/alias:
 // device_attrib no guarda alias, así que la señal práctica es un cliente sin
@@ -1584,6 +1602,8 @@ func (l *Live) emitUnknownDevice(d Device) {
 		Title:       "Dispositivo desconocido",
 		Description: fmt.Sprintf("%s se ha conectado a %s", d.MAC, d.RouterID),
 		Hint:        alerts.HintFor(alerts.HintUnknownDevice),
+		Type:        alerts.HintUnknownDevice,
+		Vars:        map[string]string{"mac": d.MAC, "router": l.routerDisplayName(d.RouterID)},
 		Time:        "ahora mismo", RouterID: d.RouterID,
 	})
 }
@@ -2343,6 +2363,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 				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,
 			})
 		}
@@ -2394,6 +2416,8 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 					Severity: "warn", Title: "Señal débil en " + d.Name,
 					Description: fmt.Sprintf("%d dBm en %s — revisa cobertura o acerca un AP", *d.SignalDbm, d.RouterID),
 					Hint:        alerts.HintFor(alerts.HintWifiWeak),
+					Type:        alerts.HintWifiWeak,
+					Vars:        map[string]string{"device": d.Name, "signal": strconv.Itoa(*d.SignalDbm), "router": d.RouterID},
 					Time:        "ahora mismo", RouterID: d.RouterID,
 				})
 			}

+ 26 - 19
server-go/internal/adapters/portmonitor.go

@@ -2,6 +2,7 @@ package adapters
 
 import (
 	"fmt"
+	"strconv"
 	"sync"
 	"time"
 
@@ -9,13 +10,13 @@ import (
 )
 
 const (
-	flapWindow             = 10 * time.Minute
-	flapThreshold          = 5
-	ghostConsecutive       = 3
-	ghostMinHistory        = 12
-	snmpGhostMinDuration   = 5 * time.Minute
-	degradedConsec         = 3
-	degradedMinHistory     = 12
+	flapWindow           = 10 * time.Minute
+	flapThreshold        = 5
+	ghostConsecutive     = 3
+	ghostMinHistory      = 12
+	snmpGhostMinDuration = 5 * time.Minute
+	degradedConsec       = 3
+	degradedMinHistory   = 12
 )
 
 type portKey struct {
@@ -24,14 +25,14 @@ type portKey struct {
 }
 
 type portState struct {
-	up             bool
-	transitions    []time.Time
-	speedMbps      int
-	speedHistory   []int
-	trafficTotal   uint64
-	zeroStreak     int
-	hadTraffic     bool
-	lastTrafficAt  time.Time
+	up            bool
+	transitions   []time.Time
+	speedMbps     int
+	speedHistory  []int
+	trafficTotal  uint64
+	zeroStreak    int
+	hadTraffic    bool
+	lastTrafficAt time.Time
 	// Incidentes abiertos (issue #366): mientras la condición persiste hay
 	// UNA sola alerta viva por puerto (EmitOrUpdate la refresca in situ);
 	// la flag dispara la alerta de recuperación exactamente una vez.
@@ -41,10 +42,10 @@ type portState struct {
 }
 
 type PortMonitor struct {
-	mu               sync.Mutex
-	states           map[portKey]*portState
-	now              func() time.Time
-	ghostEnabled     bool
+	mu           sync.Mutex
+	states       map[portKey]*portState
+	now          func() time.Time
+	ghostEnabled bool
 }
 
 func NewPortMonitor(ghostEnabled bool) *PortMonitor {
@@ -123,6 +124,8 @@ func (pm *PortMonitor) checkFlapping(key portKey, st *portState, p EthPort, now
 			Title:       fmt.Sprintf("Port flapping: %s on %s", p.Label, key.routerID),
 			Description: fmt.Sprintf("%d transitions in %s", len(st.transitions), flapWindow),
 			Hint:        alerts.HintFor(alerts.HintPortFlapping),
+			Type:        alerts.HintPortFlapping,
+			Vars:        map[string]string{"port": p.Label, "router": key.routerID, "count": strconv.Itoa(len(st.transitions)), "window": flapWindow.String()},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})
@@ -191,6 +194,8 @@ func (pm *PortMonitor) checkGhost(key portKey, st *portState, p EthPort, now tim
 			Title:       fmt.Sprintf("Ghost port: %s went silent", p.Label),
 			Description: fmt.Sprintf("Port had traffic but zero bytes for %d consecutive polls", st.zeroStreak),
 			Hint:        alerts.HintFor(alerts.HintGhostPort),
+			Type:        alerts.HintGhostPort,
+			Vars:        map[string]string{"port": p.Label, "polls": strconv.Itoa(st.zeroStreak)},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})
@@ -235,6 +240,8 @@ func (pm *PortMonitor) checkDegraded(key portKey, st *portState, p EthPort, now
 			Title:       fmt.Sprintf("Degraded link: %s at %dMbps (was %dMbps)", p.Label, st.speedMbps, prev),
 			Description: fmt.Sprintf("Port negotiated speed dropped from %d to %d Mbps for %d consecutive polls", prev, st.speedMbps, degradedConsec),
 			Hint:        alerts.HintFor(alerts.HintDegradedLink),
+			Type:        alerts.HintDegradedLink,
+			Vars:        map[string]string{"port": p.Label, "speed": strconv.Itoa(st.speedMbps), "prev": strconv.Itoa(prev), "polls": strconv.Itoa(degradedConsec)},
 			Time:        "ahora mismo",
 			RouterID:    key.routerID,
 		})

+ 23 - 13
server-go/internal/alerts/alerts.go

@@ -67,6 +67,14 @@ type AlertEvent struct {
 	Ts       int64  `json:"ts"`   // unix SEGUNDOS; el frontend calcula el relativo
 	Read     bool   `json:"read"`
 	RouterID string `json:"routerId"`
+	// Type: slug estable del tipo de alerta (issue #310). Cuando viaja
+	// (#671), el frontend traduce título/descripción/hint por clave i18n
+	// (alerts.types.<slug>.title/.description y alerts.hints.<slug>) en el
+	// idioma del usuario; los literales Title/Description/Hint siguen en el
+	// evento como fallback (servidores viejos, demo, claves sin traducir).
+	Type string `json:"type,omitempty"`
+	// Vars: valores de interpolación para esas claves (router, mac, temp…).
+	Vars map[string]string `json:"vars,omitempty"`
 	// SuppressedBy is the routerId of the parent router whose offline alert
 	// is suppressing this one (issue #332). Empty when not suppressed.
 	SuppressedBy string `json:"suppressedBy,omitempty"`
@@ -74,25 +82,27 @@ type AlertEvent struct {
 
 // Stable alert-type slugs (issue #310): keys of the Hints map.
 const (
-	HintAgentDown      = "agent-down"
-	HintGatewayUnrch   = "gateway-unreachable"
-	HintHighTemp       = "high-temperature"
-	HintPortFlapping   = "port-flapping"
-	HintDeviceOffline  = "device-offline"
-	HintUnknownDevice  = "unknown-device"
-	HintFirmware       = "firmware-outdated"
-	HintWanDown        = "wan-down"
-	HintWifiWeak       = "wifi-weak"
-	HintGhostPort      = "ghost-port"
-	HintDegradedLink   = "degraded-link"
-	HintAgentOutdated  = "agent-outdated"
-	HintWanSlow        = "wan-slow"
+	HintAgentDown     = "agent-down"
+	HintAgentDownSSH  = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
+	HintGatewayUnrch  = "gateway-unreachable"
+	HintHighTemp      = "high-temperature"
+	HintPortFlapping  = "port-flapping"
+	HintDeviceOffline = "device-offline"
+	HintUnknownDevice = "unknown-device"
+	HintFirmware      = "firmware-outdated"
+	HintWanDown       = "wan-down"
+	HintWifiWeak      = "wifi-weak"
+	HintGhostPort     = "ghost-port"
+	HintDegradedLink  = "degraded-link"
+	HintAgentOutdated = "agent-outdated"
+	HintWanSlow       = "wan-slow"
 )
 
 // 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{
 	HintAgentDown:     "Comprueba la alimentación y la conexión del router; si no se recupera, reinstala el agente desde LuCI.",
+	HintAgentDownSSH:  "Comprueba la alimentación y la conexión del router; si no se recupera, reinstala el agente desde LuCI.",
 	HintGatewayUnrch:  "Comprueba la conexión entre el gateway y el resto de la red.",
 	HintHighTemp:      "Mejora la ventilación y aleja el router de fuentes de calor.",
 	HintPortFlapping:  "Revisa el cable o el puerto del switch: un enlace inestable suele ser el culpable.",

+ 7 - 4
server-go/internal/speedtest/scheduler.go

@@ -14,6 +14,7 @@ import (
 	"fmt"
 	"log"
 	"net/url"
+	"strconv"
 	"strings"
 	"sync"
 	"sync/atomic"
@@ -183,10 +184,10 @@ func (s *Scheduler) executeLocked(st Settings, origin string) error {
 
 // Status es la foto para GET /api/speedtest/status.
 type Status struct {
-	Running   bool     `json:"running"`
-	LastError string   `json:"lastError,omitempty"`
-	Last      *Result  `json:"last,omitempty"`
-	NextRun   *int64   `json:"nextRunMs,omitempty"` // unix ms; nil = sin programar
+	Running   bool    `json:"running"`
+	LastError string  `json:"lastError,omitempty"`
+	Last      *Result `json:"last,omitempty"`
+	NextRun   *int64  `json:"nextRunMs,omitempty"` // unix ms; nil = sin programar
 }
 
 // Status compone la foto actual (running, último error, último resultado y
@@ -241,6 +242,8 @@ func (s *Scheduler) maybeAlert(st Settings, res Result) {
 			"Medido %.0f Mbps de bajada contra %.0f Mbps contratados (menos del %d%% del plan)",
 			res.DownMbps, contract, st.AlertPct),
 		Hint: alerts.HintFor(alerts.HintWanSlow),
+		Type: alerts.HintWanSlow,
+		Vars: map[string]string{"down": fmt.Sprintf("%.0f", res.DownMbps), "plan": fmt.Sprintf("%.0f", contract), "pct": strconv.Itoa(st.AlertPct)},
 		Time: "ahora mismo", Ts: res.TS.Unix(),
 	})
 }