Sfoglia il codice sorgente

fix(alerts): keep mark-all-read state sticky across in-flight snapshots (#892)

* fix(alerts): keep mark-all-read state sticky across in-flight snapshots

The optimistic read state could be overwritten by a snapshot taken
before the POST landed, bouncing unread back until the next snapshot.
Re-apply the read state when the POST resolves, and dedupe SSE alert
events by id so a duplicate event no longer reintroduces unread rows.

Ref #891

* feat(alerts): server default language for push notifications

Alert titles and descriptions are composed in Spanish and translated by
the web UI per user, but ntfy/telegram/webhook published the raw Spanish
literals, so an English UI showed console alerts in English and pushes
in Spanish. Localize server-side at dispatch time reusing the same
embedded app catalogs (alerts.types.<slug> keys), with a new server-wide
alerts.lang setting (default en) exposed at GET/PUT
/api/settings/alerts-lang and a Settings card.

Closes #888
Ref #889

* fix(routers): soften agent-down banner during server startup grace

Right after a netpulse-server restart every agent looks down until its
first push, so all router cards immediately showed the drastic
"Agent down - reinstall it" banner even though the agents recover on
their own seconds later. The overview now carries serverUptimeSec and
the card shows a neutral "Waiting for agents to reconnect" banner for
the first 90 s after server start, keeping the drastic banner for a
persistent failure afterwards.

Closes #887
Nacho 2 mesi fa
parent
commit
dc24ec9dbf

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

@@ -906,7 +906,8 @@
       "stepVerifying": "Verifying integrity",
       "stepVerifying": "Verifying integrity",
       "timelineSummary": "· {{count}} steps · {{secs}} s",
       "timelineSummary": "· {{count}} steps · {{secs}} s",
       "netgripBadge": "NetGrip",
       "netgripBadge": "NetGrip",
-      "netgripFreshTip": "NetGrip v{{version}} · embedded agent"
+      "netgripFreshTip": "NetGrip v{{version}} · embedded agent",
+      "warmingBanner": "Waiting for agents to reconnect…"
     },
     },
     "colClients": "Clients",
     "colClients": "Clients",
     "colCpu": "CPU",
     "colCpu": "CPU",
@@ -1690,6 +1691,11 @@
       "propagateEmpty": "There are no NetGrip routers in the fleet to propagate to.",
       "propagateEmpty": "There are no NetGrip routers in the fleet to propagate to.",
       "running": "publishing",
       "running": "publishing",
       "notRunning": "stopped"
       "notRunning": "stopped"
+    },
+    "alertsLang": {
+      "title": "Notification language",
+      "description": "Language used for ntfy, Telegram and webhook alerts (alerts are composed in Spanish and translated when published).",
+      "label": "Alert language"
     }
     }
   },
   },
   "statcard": {
   "statcard": {
@@ -2211,4 +2217,4 @@
     "link": "See more",
     "link": "See more",
     "dismiss": "Dismiss announcement"
     "dismiss": "Dismiss announcement"
   }
   }
-}
+}

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

@@ -906,7 +906,8 @@
       "stepVerifying": "Comprobando integridad",
       "stepVerifying": "Comprobando integridad",
       "timelineSummary": "· {{count}} pasos · {{secs}} s",
       "timelineSummary": "· {{count}} pasos · {{secs}} s",
       "netgripBadge": "NetGrip",
       "netgripBadge": "NetGrip",
-      "netgripFreshTip": "NetGrip v{{version}} · agente embebido"
+      "netgripFreshTip": "NetGrip v{{version}} · agente embebido",
+      "warmingBanner": "Esperando a que los agentes se reconecten…"
     },
     },
     "colClients": "Clientes",
     "colClients": "Clientes",
     "colCpu": "CPU",
     "colCpu": "CPU",
@@ -1690,6 +1691,11 @@
       "propagateEmpty": "No hay routers NetGrip en la flota a los que propagar.",
       "propagateEmpty": "No hay routers NetGrip en la flota a los que propagar.",
       "running": "publicando",
       "running": "publicando",
       "notRunning": "detenido"
       "notRunning": "detenido"
+    },
+    "alertsLang": {
+      "title": "Idioma de las notificaciones",
+      "description": "Idioma en que se envían los avisos de ntfy, Telegram y webhook (las alertas se componen en español y se traducen al publicar).",
+      "label": "Idioma de los avisos"
     }
     }
   },
   },
   "statcard": {
   "statcard": {
@@ -2211,4 +2217,4 @@
     "link": "Ver más",
     "link": "Ver más",
     "dismiss": "Descartar aviso"
     "dismiss": "Descartar aviso"
   }
   }
-}
+}

+ 20 - 4
app/src/components/routers/FleetCard.tsx

@@ -1,5 +1,5 @@
 import { Link } from 'react-router'
 import { Link } from 'react-router'
-import { AlertTriangle, Cable, Cpu, MemoryStick, Router as RouterIcon, Thermometer, Users, Wifi } from 'lucide-react'
+import { AlertTriangle, Cable, Clock, Cpu, MemoryStick, Router as RouterIcon, Thermometer, Users, Wifi } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { motion, useReducedMotion } from 'framer-motion'
 import { motion, useReducedMotion } from 'framer-motion'
 import { Area, AreaChart, ResponsiveContainer, Tooltip } from 'recharts'
 import { Area, AreaChart, ResponsiveContainer, Tooltip } from 'recharts'
@@ -81,9 +81,15 @@ function TrafficTooltip({
 /** FleetCard grande de /routers (routers.md §②) */
 /** FleetCard grande de /routers (routers.md §②) */
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
   const { t } = useTranslation()
   const { t } = useTranslation()
-  const { isDemo } = useNetPulse()
+  const { isDemo, serverUptimeSec } = useNetPulse()
   const [tempUnit] = useTempUnit()
   const [tempUnit] = useTempUnit()
   const agent = useAgentFor(router.id)
   const agent = useAgentFor(router.id)
+  // #887: período de gracia post-arranque del server. Justo tras un reinicio
+  // los agentes aún no han vuelto a empujar (push cada 15 s + reconexión SSE)
+  // y no es honesto gritar "agente caído / reinstalar": se muestra un aviso
+  // suave de espera. Pasado el grace, el banner drástico de siempre.
+  const STARTUP_GRACE_SEC = 90
+  const inStartupGrace = (serverUptimeSec ?? Number.MAX_SAFE_INTEGER) < STARTUP_GRACE_SEC
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
   const warn = router.status === 'warn'
   const isOpenWrt = router.type === undefined || router.type === '' || router.type === 'glinet' || router.type === 'openwrt'
   const isOpenWrt = router.type === undefined || router.type === '' || router.type === 'glinet' || router.type === 'openwrt'
@@ -136,8 +142,18 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
           </div>
           </div>
         )}
         )}
 
 
-        {/* Banner de agente caído (el router tiene agente registrado pero no responde) */}
-        {agentDown && (
+        {/* Banner de agente caído (el router tiene agente registrado pero no
+            responde). Durante la gracia post-arranque (#887) se suaviza: es
+            normal que los agentes aún no hayan vuelto a empujar. */}
+        {agentDown && inStartupGrace && (
+          <div className="mb-4 -mx-6 -mt-6 flex items-center gap-2 border-b border-border bg-elevated px-6 py-2.5">
+            <Clock className="h-4 w-4 shrink-0 animate-pulse text-text-muted" strokeWidth={1.75} />
+            <span className="text-caption font-semibold text-text-muted">
+              {t('routers.agent.warmingBanner')}
+            </span>
+          </div>
+        )}
+        {agentDown && !inStartupGrace && (
           <div className="mb-4 -mx-6 -mt-6 flex items-center gap-2 border-b border-warn/30 bg-warn/10 px-6 py-2.5">
           <div className="mb-4 -mx-6 -mt-6 flex items-center gap-2 border-b border-warn/30 bg-warn/10 px-6 py-2.5">
             <AlertTriangle className="h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} />
             <AlertTriangle className="h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} />
             <span className="text-caption font-semibold text-warn">{t('routers.agent.downBanner')}</span>
             <span className="text-caption font-semibold text-warn">{t('routers.agent.downBanner')}</span>

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

@@ -130,6 +130,8 @@ export interface NetPulseData {
   dawnDeprecated?: boolean
   dawnDeprecated?: boolean
   /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
   /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
   orchestration?: boolean
   orchestration?: boolean
+  /** Segundos desde el arranque del server (#887); ausente = sin gracia. */
+  serverUptimeSec?: number
 }
 }
 
 
 export interface NetPulseApi extends NetPulseData {
 export interface NetPulseApi extends NetPulseData {
@@ -538,6 +540,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       roamingDaemon: o.roamingDaemon,
       roamingDaemon: o.roamingDaemon,
       dawnDeprecated: o.dawnDeprecated,
       dawnDeprecated: o.dawnDeprecated,
       orchestration: o.orchestration,
       orchestration: o.orchestration,
+      serverUptimeSec: o.serverUptimeSec,
       ...(o.devices ? { devices: o.devices } : {}),
       ...(o.devices ? { devices: o.devices } : {}),
     }))
     }))
   }, [])
   }, [])
@@ -618,11 +621,26 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       es.addEventListener('alert', (ev) => {
       es.addEventListener('alert', (ev) => {
         try {
         try {
           const alert = JSON.parse((ev as MessageEvent).data as string) as AlertEvent
           const alert = JSON.parse((ev as MessageEvent).data as string) as AlertEvent
-          setBundle((prev) => ({
-            ...prev,
-            alerts: [alert, ...prev.alerts],
-            unreadAlerts: prev.unreadAlerts + (alert.read ? 0 : 1),
-          }))
+          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
+            // en sitio: es la versión más reciente del mismo evento, y su
+            // flag read viene de la verdad del servidor (engine.List).
+            const idx = prev.alerts.findIndex((a) => a.id === alert.id)
+            const existing = idx >= 0 ? prev.alerts[idx] : undefined
+            if (existing) {
+              const alerts = [...prev.alerts]
+              alerts[idx] = alert
+              const hadUnread = existing.read ? 0 : 1
+              const hasUnread = alert.read ? 0 : 1
+              return { ...prev, alerts, unreadAlerts: Math.max(0, prev.unreadAlerts - hadUnread + hasUnread) }
+            }
+            return {
+              ...prev,
+              alerts: [alert, ...prev.alerts],
+              unreadAlerts: prev.unreadAlerts + (alert.read ? 0 : 1),
+            }
+          })
         } catch {
         } catch {
           /* payload inválido: se ignora */
           /* payload inválido: se ignora */
         }
         }
@@ -872,6 +890,14 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
           body: JSON.stringify({ ids }),
           body: JSON.stringify({ ids }),
         })
         })
         if (res.status === 401) redirectLogin()
         if (res.status === 401) redirectLogin()
+        // #891: igual que en read-all — re-aplica el leído si un snapshot
+        // pre-POST pisó el estado optimista mientras el POST estaba en vuelo.
+        if (res.ok) {
+          setBundle((prev) => ({
+            ...prev,
+            alerts: prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a)),
+          }))
+        }
       } catch {
       } catch {
         /* el próximo snapshot/SSE resincroniza el read state */
         /* el próximo snapshot/SSE resincroniza el read state */
       }
       }
@@ -889,6 +915,17 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       try {
       try {
         const res = await fetch('/api/alerts/read-all', { method: 'POST' })
         const res = await fetch('/api/alerts/read-all', { method: 'POST' })
         if (res.status === 401) redirectLogin()
         if (res.status === 401) redirectLogin()
+        // #891: un snapshot tomado ANTES de que el POST llegara al servidor
+        // puede haber pisado el estado optimista con read=false. Al resolver
+        // el POST, la verdad del servidor YA incluye el read-all, así que se
+        // re-aplica el estado leído por si llegó ese snapshot enrarecido.
+        if (res.ok) {
+          setBundle((prev) => ({
+            ...prev,
+            alerts: prev.alerts.map((a) => ({ ...a, read: true })),
+            unreadAlerts: 0,
+          }))
+        }
       } catch {
       } catch {
         /* idem: resync por snapshot */
         /* idem: resync por snapshot */
       }
       }

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

@@ -413,6 +413,11 @@ export interface OverviewBundle {
    * colector o primera pasada): el mapa cuelga los cableados del router.
    * colector o primera pasada): el mapa cuelga los cableados del router.
    */
    */
   distributionNodes?: DistributionNode[]
   distributionNodes?: DistributionNode[]
+  /**
+   * Segundos desde el arranque del proceso server (#887). Ausente en
+   * servidores viejos → el frontend no aplica la gracia post-arranque.
+   */
+  serverUptimeSec?: number
   /**
   /**
    * Versión del view-model (SPEC-65 D65-4). Siempre presente en servidores
    * Versión del view-model (SPEC-65 D65-4). Siempre presente en servidores
    * nuevos; ausente en servidores viejos (se asume VM_SUPPORTED).
    * nuevos; ausente en servidores viejos (se asume VM_SUPPORTED).

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

@@ -81,6 +81,66 @@ import pkg from '../../package.json'
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
 /** Estado persistido en localStorage (settings.md §Interactions) */
 /** Estado persistido en localStorage (settings.md §Interactions) */
+// Idioma de las notificaciones push (#889): ajuste server-wide (kv
+// alerts.lang). Los pushes ntfy/telegram/webhook se traducen server-side con
+// los mismos catálogos de la app (#888).
+function AlertsLangControl({ onSaved }: { onSaved: () => void }) {
+  const { t } = useTranslation()
+  const [lang, setLang] = useState('')
+  const [supported, setSupported] = useState<string[]>([])
+  const [saving, setSaving] = useState(false)
+
+  useEffect(() => {
+    void (async () => {
+      try {
+        const res = await fetch('/api/settings/alerts-lang')
+        if (!res.ok) return
+        const body = (await res.json()) as { lang: string; supported: string[] }
+        setLang(body.lang)
+        setSupported(body.supported)
+      } catch {
+        /* se queda el estado vacío; el select queda deshabilitado */
+      }
+    })()
+  }, [])
+
+  const change = async (next: string) => {
+    setLang(next)
+    setSaving(true)
+    try {
+      const res = await fetch('/api/settings/alerts-lang', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ lang: next }),
+      })
+      if (res.ok) onSaved()
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <div className="flex items-center gap-3">
+      <label className="text-sm text-text-secondary" htmlFor="alerts-lang">
+        {t('settings.alertsLang.label')}
+      </label>
+      <select
+        id="alerts-lang"
+        value={lang}
+        disabled={saving || supported.length === 0}
+        onChange={(e) => void change(e.target.value)}
+        className="rounded-lg border border-border bg-elevated px-2.5 py-1.5 text-sm text-text-primary disabled:opacity-50"
+      >
+        {supported.map((l) => (
+          <option key={l} value={l}>
+            {l}
+          </option>
+        ))}
+      </select>
+    </div>
+  )
+}
+
 function useStoredState<T>(key: string, initial: T): [T, (v: T) => void] {
 function useStoredState<T>(key: string, initial: T): [T, (v: T) => void] {
   const [state, setState] = useState<T>(() => {
   const [state, setState] = useState<T>(() => {
     try {
     try {
@@ -4869,6 +4929,15 @@ export default function Settings() {
           </Card>
           </Card>
         </div>
         </div>
 
 
+        {/* Idioma de las notificaciones push (#889): server-wide */}
+        {!isDemo && (
+          <div className="order-69">
+            <Card title={t('settings.alertsLang.title')} caption={t('settings.alertsLang.description')} index={4} reduce={reduce}>
+              <AlertsLangControl onSaved={notify} />
+            </Card>
+          </div>
+        )}
+
         {/* Telegram (#326): notificaciones directas al bot — sección Notificaciones */}
         {/* Telegram (#326): notificaciones directas al bot — sección Notificaciones */}
         {!isDemo && (
         {!isDemo && (
           <div className="order-70">
           <div className="order-70">

+ 17 - 2
server-go/cmd/netpulse/main.go

@@ -56,6 +56,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+	"github.com/gnacho/netpulse/server-go/internal/alertlang"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
 	"github.com/gnacho/netpulse/server-go/internal/telegram"
 	"github.com/gnacho/netpulse/server-go/internal/telegram"
 	"github.com/gnacho/netpulse/server-go/internal/telemetry"
 	"github.com/gnacho/netpulse/server-go/internal/telemetry"
@@ -129,6 +130,7 @@ func main() {
 }
 }
 
 
 func run() error {
 func run() error {
+	serverStarted := time.Now()
 	serverRoot, err := os.Getwd()
 	serverRoot, err := os.Getwd()
 	if err != nil {
 	if err != nil {
 		return err
 		return err
@@ -370,6 +372,7 @@ func run() error {
 	// la cadena lo empaqueta en la interfaz con tipo pero valor nil → la
 	// la cadena lo empaqueta en la interfaz con tipo pero valor nil → la
 	// interfaz NO es nil y `if n != nil` de notifierChain no lo filtra →
 	// interfaz NO es nil y `if n != nil` de notifierChain no lo filtra →
 	// panic al Notify. Filtrar ANTES de empaquetar.
 	// panic al Notify. Filtrar ANTES de empaquetar.
+	var notifyChain alerts.Notifier
 	if pushNotifier != nil || webhookNotifier != nil || telegramNotifier != nil || ntfyNotifier != nil {
 	if pushNotifier != nil || webhookNotifier != nil || telegramNotifier != nil || ntfyNotifier != nil {
 		// #874: el filtro de urgencia vive en cada canal (default: solo
 		// #874: el filtro de urgencia vive en cada canal (default: solo
 		// urgentes, comportamiento de siempre). El engine dispara todo lo que
 		// urgentes, comportamiento de siempre). El engine dispara todo lo que
@@ -388,7 +391,7 @@ func run() error {
 		if ntfyNotifier != nil {
 		if ntfyNotifier != nil {
 			chain = append(chain, urgencyGate{n: ntfyNotifier, kv: kv, key: "ntfy.urgent_only"})
 			chain = append(chain, urgencyGate{n: ntfyNotifier, kv: kv, key: "ntfy.urgent_only"})
 		}
 		}
-		adapter.AlertsEngine().SetNotifier(chain)
+		notifyChain = chain
 	}
 	}
 
 
 	// Dependencia sse↔poller resuelta con un holder (como index.js:40-45).
 	// Dependencia sse↔poller resuelta con un holder (como index.js:40-45).
@@ -408,6 +411,15 @@ func run() error {
 	}
 	}
 	static := staticspa.New(staticDir)
 	static := staticspa.New(staticDir)
 
 
+	// #888/#889: los pushes (ntfy/telegram/webhook/push) salen traducidos al
+	// idioma del ajuste alerts.lang, con los catálogos embebidos del dist.
+	// El wrap debe hacerse DESPUÉS de construir la cadena y de tener el FS.
+	if notifyChain != nil {
+		mainKV := &mainKVAdapter{db: dbHandle.DB}
+		alertlang.SetLocalesFS(staticspa.LocalesFS())
+		adapter.AlertsEngine().SetNotifier(alertlang.Notifier(mainKV, notifyChain))
+	}
+
 	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53).
 	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53).
 	// La versión embebida (httpapi.Version) se usa para comparar contra el
 	// La versión embebida (httpapi.Version) se usa para comparar contra el
 	// último release tag en modo estable (layout install.sh). ConDataDir
 	// último release tag en modo estable (layout install.sh). ConDataDir
@@ -552,6 +564,9 @@ func run() error {
 		// primer evento pisaría los campos en la UI.
 		// primer evento pisaría los campos en la UI.
 		p.SetEnrich(func(ov *adapters.Overview) {
 		p.SetEnrich(func(ov *adapters.Overview) {
 			httpapi.EnrichOverview(dbHandle.DB, stScheduler, ov)
 			httpapi.EnrichOverview(dbHandle.DB, stScheduler, ov)
+			// #887: el snapshot SSE también lleva el uptime para la gracia
+			// post-arranque en el frontend.
+			ov.ServerUptimeSec = int64(time.Since(serverStarted).Seconds())
 		})
 		})
 		go stScheduler.Start()
 		go stScheduler.Start()
 	}
 	}
@@ -629,7 +644,7 @@ func run() error {
 			return p.LastOverview()
 			return p.LastOverview()
 		},
 		},
 		PollNow: p.PollNow,
 		PollNow: p.PollNow,
-		Started: time.Now(),
+		Started: serverStarted,
 	})
 	})
 
 
 	// Envolver el handler con GET /fingerprint (sin auth) si on-box.
 	// Envolver el handler con GET /fingerprint (sin auth) si on-box.

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

@@ -418,6 +418,11 @@ type Overview struct {
 	TopDevices   []Device       `json:"topDevices"` // 5 por trafficMbps desc
 	TopDevices   []Device       `json:"topDevices"` // 5 por trafficMbps desc
 	Alerts       []AlertEvent   `json:"alerts"`
 	Alerts       []AlertEvent   `json:"alerts"`
 	UnreadAlerts int            `json:"unreadAlerts"`
 	UnreadAlerts int            `json:"unreadAlerts"`
+	// ServerUptimeSec: segundos desde el arranque del proceso server. Lo usa
+	// el frontend para el período de gracia post-arranque (#887): justo tras
+	// un reinicio los agentes aún no han vuelto a empujar y no debe saltar
+	// el banner drástico de "agente caído / reinstalar".
+	ServerUptimeSec int64 `json:"serverUptimeSec,omitempty"`
 	// DistributionNodes: switches/hipervisores inferidos del FDB (topología
 	// DistributionNodes: switches/hipervisores inferidos del FDB (topología
 	// v5). Vacío/ausente si aún no hay datos FDB: el mapa cuelga los
 	// v5). Vacío/ausente si aún no hay datos FDB: el mapa cuelga los
 	// cableados del router (degradación amable).
 	// cableados del router (degradación amable).

+ 191 - 0
server-go/internal/alertlang/alertlang.go

@@ -0,0 +1,191 @@
+// Package alertlang traduce server-side las alertas para los canales de
+// notificación externa (#888 / #889).
+//
+// El motor de alertas compone título/descripción con literales en español y
+// la web los traduce en render (#671). Los canales ntfy/telegram/webhook
+// usaban los literales crudos, así que un usuario con la UI en inglés veía
+// consola EN pero push ES. Web Push ya lo resolvía client-side (#689); este
+// paquete hace lo equivalente server-side reutilizando los MISMOS catálogos
+// de la app embebidos en el binario (dist/locales/<lang>/translation.json,
+// claves alerts.types.<slug>.title|.description|.results.* y alerts.hints.*),
+// sin duplicar textos.
+//
+// El idioma es un ajuste GLOBAL del servidor (kv "alerts.lang", default "en"):
+// las alertas no llevan usuario emisor, son server-wide.
+package alertlang
+
+import (
+	"encoding/json"
+	"io/fs"
+	"log"
+	"strings"
+	"sync"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// KV es el mínimo de store que necesita el paquete (mismo contrato que usan
+// ntfy/telegram: Get(key) (string, bool)).
+type KV interface {
+	Get(key string) (string, bool)
+}
+
+const (
+	// KeyLang: idioma de las notificaciones push del servidor.
+	KeyLang = "alerts.lang"
+	// DefaultLang: un usuario que no toca nada recibe pushes en inglés (el
+	// reporte de #888 pedía exactamente eso; la UI sigue auto-detectando).
+	DefaultLang = "en"
+)
+
+var (
+	localesFS fs.FS
+	mu        sync.Mutex
+	cache     = map[string]*catalog{} // lang → catálogo parseado
+	supported = map[string]bool{}     // idiomas presentes en el dist
+)
+
+type typeEntry struct {
+	Title           string            `json:"title"`
+	Description     string            `json:"description"`
+	DescriptionUnit string            `json:"descriptionUnit"`
+	Results         map[string]string `json:"results"`
+}
+
+type catalog struct {
+	Alerts struct {
+		Types map[string]typeEntry `json:"types"`
+		Hints map[string]string    `json:"hints"`
+	} `json:"alerts"`
+}
+
+// SetLocalesFS fija el FS de catálogos ("<lang>/translation.json"). Se llama
+// una vez al arrancar (staticspa.LocalesFS).
+func SetLocalesFS(f fs.FS) {
+	localesFS = f
+	entries, err := fs.ReadDir(f, ".")
+	if err != nil {
+		log.Printf("[netpulse] alertlang: no se pudo listar locales: %v", err)
+		return
+	}
+	for _, e := range entries {
+		if e.IsDir() {
+			supported[e.Name()] = true
+		}
+	}
+	log.Printf("[netpulse] alertlang: idiomas disponibles para push: %v", keys(supported))
+}
+
+func keys(m map[string]bool) []string {
+	out := make([]string, 0, len(m))
+	for k := range m {
+		out = append(out, k)
+	}
+	return out
+}
+
+// Supported devuelve los idiomas disponibles (los del dist).
+func Supported() []string { return keys(supported) }
+
+func load(lang string) *catalog {
+	mu.Lock()
+	defer mu.Unlock()
+	if c, ok := cache[lang]; ok {
+		return c
+	}
+	if localesFS == nil {
+		return nil
+	}
+	raw, err := fs.ReadFile(localesFS, lang+"/translation.json")
+	if err != nil {
+		log.Printf("[netpulse] alertlang: catálogo no encontrado: lang=%s (%v)", lang, err)
+		return nil
+	}
+	var c catalog
+	if err := json.Unmarshal(raw, &c); err != nil {
+		log.Printf("[netpulse] alertlang: catálogo inválido: lang=%s (%v)", lang, err)
+		return nil
+	}
+	cache[lang] = &c
+	return &c
+}
+
+// Lang devuelve el idioma efectivo de las notificaciones (kv alerts.lang,
+// validado contra los disponibles; default en).
+func Lang(kv KV) string {
+	if kv != nil {
+		if v, ok := kv.Get(KeyLang); ok && supported[v] {
+			return v
+		}
+	}
+	return DefaultLang
+}
+
+// interpolate replica el formato de i18next usado por la app ({{var}}).
+func interpolate(tpl string, vars map[string]string) string {
+	if vars == nil {
+		return tpl
+	}
+	return strings.NewReplacer(pairs(vars)...).Replace(tpl)
+}
+
+func pairs(vars map[string]string) []string {
+	out := make([]string, 0, len(vars)*2)
+	for k, v := range vars {
+		out = append(out, "{{"+k+"}}", v)
+	}
+	return out
+}
+
+// Localize devuelve una copia del evento con title/description/hint
+// traducidos al idioma efectivo. Cae a los literales del server (español) si
+// el evento no tiene type, falta la clave o no hay catálogo: nunca peor que
+// antes.
+func Localize(ev alerts.AlertEvent, kv KV) alerts.AlertEvent {
+	if ev.Type == "" {
+		return ev
+	}
+	c := load(Lang(kv))
+	if c == nil {
+		return ev
+	}
+	entry, ok := c.Alerts.Types[ev.Type]
+	if !ok {
+		return ev
+	}
+	out := ev
+	if entry.Title != "" {
+		out.Title = interpolate(entry.Title, ev.Vars)
+	}
+	body := entry.Description
+	if r := ev.Vars["result"]; r != "" && entry.Results != nil && entry.Results[r] != "" {
+		body = entry.Results[r]
+	}
+	if body != "" {
+		out.Description = interpolate(body, ev.Vars)
+	}
+	if ev.Hint != "" {
+		if h := c.Alerts.Hints[ev.Type]; h != "" {
+			out.Hint = h
+		}
+	}
+	return out
+}
+
+// notifier traduce cada evento antes de pasarlo a la cadena real.
+type notifier struct {
+	kv   KV
+	next alerts.Notifier
+}
+
+// Notifier envuelve la cadena ntfy/telegram/webhook/push para que los pushes
+// salgan en el idioma del ajuste alerts.lang (#888, núcleo de #889).
+func Notifier(kv KV, next alerts.Notifier) alerts.Notifier {
+	return notifier{kv: kv, next: next}
+}
+
+func (n notifier) Notify(ev alerts.AlertEvent) {
+	if n.next != nil {
+		n.next.Notify(Localize(ev, n.kv))
+	}
+}

+ 102 - 0
server-go/internal/alertlang/alertlang_test.go

@@ -0,0 +1,102 @@
+// alertlang_test.go - traducción server-side de pushes (#888/#889) contra los
+// catálogos reales de la app (mismo enfoque que alerts_i18n_test.go).
+package alertlang
+
+import (
+	"os"
+	"strings"
+	"path/filepath"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+type mapKV map[string]string
+
+func (m mapKV) Get(key string) (string, bool) { v, ok := m[key]; return v, ok }
+
+func localesFromApp(t *testing.T) {
+	t.Helper()
+	root, err := filepath.Abs("../../..")
+	if err != nil {
+		t.Fatal(err)
+	}
+	SetLocalesFS(os.DirFS(filepath.Join(root, "app", "dist", "locales")))
+	if len(Supported()) == 0 {
+		t.Fatal("no se detectaron idiomas (¿falta npm run build en app/?)")
+	}
+}
+
+func agentDownEv() alerts.AlertEvent {
+	return alerts.AlertEvent{
+		ID:          "alert-agent-down-gateway",
+		Category:    alerts.CatRouter,
+		Type:        "agent-down",
+		Title:       "Agente caído en gateway",
+		Description: "Sin datos del agente de gateway desde hace más de 5m — usando datos cacheados",
+		Vars:        map[string]string{"router": "gateway", "confirm": "5m"},
+	}
+}
+
+func TestLocalizeEnglish(t *testing.T) {
+	localesFromApp(t)
+	out := Localize(agentDownEv(), mapKV{KeyLang: "en"})
+	if out.Title != "Agent down on gateway" {
+		t.Fatalf("title = %q", out.Title)
+	}
+	if out.Description == "" || containsES(out.Description) {
+		t.Fatalf("description parece sin traducir: %q", out.Description)
+	}
+}
+
+func containsES(s string) bool {
+	return strings.Contains(s, "Agente") || strings.Contains(s, "caído") || strings.Contains(s, "Sin datos")
+}
+
+func TestLocalizeSpanishExplicit(t *testing.T) {
+	localesFromApp(t)
+	out := Localize(agentDownEv(), mapKV{KeyLang: "es"})
+	if out.Title != "Agente caído en gateway" {
+		t.Fatalf("title = %q", out.Title)
+	}
+}
+
+func TestLocalizeFallbacks(t *testing.T) {
+	localesFromApp(t)
+	// Sin type → sin tocar.
+	ev := agentDownEv()
+	ev.Type = ""
+	if out := Localize(ev, mapKV{KeyLang: "en"}); out.Title != ev.Title {
+		t.Fatal("un evento sin type no debe cambiar")
+	}
+	// Type desconocido → sin tocar.
+	ev = agentDownEv()
+	ev.Type = "no-existe-este-slug"
+	if out := Localize(ev, mapKV{KeyLang: "en"}); out.Title != ev.Title {
+		t.Fatal("un type sin clave i18n no debe cambiar")
+	}
+	// Idioma no configurado → default en.
+	if got := Lang(mapKV{}); got != DefaultLang {
+		t.Fatalf("Lang default = %q", got)
+	}
+	// Idioma inválido en kv → default en.
+	if got := Lang(mapKV{KeyLang: "xx"}); got != DefaultLang {
+		t.Fatalf("Lang inválido = %q", got)
+	}
+}
+
+func TestNotifierWrapsNext(t *testing.T) {
+	localesFromApp(t)
+	var got alerts.AlertEvent
+	n := Notifier(mapKV{KeyLang: "en"}, notifierFunc(func(ev alerts.AlertEvent) { got = ev }))
+	n.Notify(agentDownEv())
+	if got.Title != "Agent down on gateway" {
+		t.Fatalf("el notifier no tradujo: %q", got.Title)
+	}
+	// next nil no debe explotar.
+	Notifier(mapKV{}, nil).Notify(agentDownEv())
+}
+
+type notifierFunc func(alerts.AlertEvent)
+
+func (f notifierFunc) Notify(ev alerts.AlertEvent) { f(ev) }

+ 49 - 0
server-go/internal/httpapi/alerts_lang.go

@@ -0,0 +1,49 @@
+// alerts_lang.go - ajuste del idioma de las notificaciones push (#889).
+// GET devuelve el idioma efectivo + los soportados (los del dist embebido);
+// PUT valida contra los soportados y persiste en kv "alerts.lang".
+package httpapi
+
+import (
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/alertlang"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+func (s *server) registerAlertsLangRoutes(mux *http.ServeMux) {
+	kv := &dbKVAdapter{db: s.db.DB}
+	mux.Handle("GET /api/settings/alerts-lang", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		writeJSON(w, http.StatusOK, map[string]any{
+			"lang":      alertlang.Lang(kv),
+			"supported": alertlang.Supported(),
+			"default":   alertlang.DefaultLang,
+		})
+	})))
+
+	mux.Handle("PUT /api/settings/alerts-lang", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		var body struct {
+			Lang string `json:"lang"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "body JSON inválido")
+			return
+		}
+		supported := map[string]bool{}
+		for _, l := range alertlang.Supported() {
+			supported[l] = true
+		}
+		if body.Lang != "" && !supported[body.Lang] {
+			writeError(w, http.StatusBadRequest, "invalid_lang", "idioma no soportado")
+			return
+		}
+		lang := body.Lang
+		if lang == "" {
+			lang = alertlang.DefaultLang
+		}
+		if err := kv.Set(alertlang.KeyLang, lang); err != nil {
+			writeError(w, http.StatusInternalServerError, "kv_error", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"lang": lang})
+	})))
+}

+ 1 - 0
server-go/internal/httpapi/data.go

@@ -120,6 +120,7 @@ func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
 	engine := s.adapter.AlertsEngine()
 	engine := s.adapter.AlertsEngine()
 	out.Alerts = engine.List()
 	out.Alerts = engine.List()
 	out.UnreadAlerts = engine.UnreadCount()
 	out.UnreadAlerts = engine.UnreadCount()
+	out.ServerUptimeSec = int64(time.Since(s.started).Seconds())
 	EnrichOverview(s.db.DB, s.speedtest, &out)
 	EnrichOverview(s.db.DB, s.speedtest, &out)
 	writeJSON(w, http.StatusOK, &out)
 	writeJSON(w, http.StatusOK, &out)
 }
 }

+ 1 - 0
server-go/internal/httpapi/settings.go

@@ -188,6 +188,7 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 	s.registerKnownMacsRoutes(mux)
 	s.registerKnownMacsRoutes(mux)
 	s.registerTelegramRoutes(mux)
 	s.registerTelegramRoutes(mux)
 	s.registerNtfyRoutes(mux)
 	s.registerNtfyRoutes(mux)
+	s.registerAlertsLangRoutes(mux)
 }
 }
 
 
 // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
 // knownMacItem es la forma JSON de una entrada de la allowlist (#196).

+ 11 - 0
server-go/internal/staticspa/staticspa.go

@@ -58,6 +58,17 @@ func New(staticDir string) *Handler {
 	return h
 	return h
 }
 }
 
 
+// LocalesFS expone el FS con los catálogos de idioma del dist
+// ("<lang>/translation.json"), embebidos en el binario. Lo usa el paquete
+// alertlang para traducir las notificaciones push server-side (#888/#889).
+func LocalesFS() fs.FS {
+	sub, err := fs.Sub(embeddedDist, "dist/locales")
+	if err != nil {
+		return embeddedDist
+	}
+	return sub
+}
+
 // serveFile sirve el fichero `name` si existe y no es directorio.
 // serveFile sirve el fichero `name` si existe y no es directorio.
 func (h *Handler) serveFile(w http.ResponseWriter, r *http.Request, name string) bool {
 func (h *Handler) serveFile(w http.ResponseWriter, r *http.Request, name string) bool {
 	if !fs.ValidPath(name) {
 	if !fs.ValidPath(name) {