Quellcode durchsuchen

feat: alert actions, NetGrip card in orchestration, about links, MQTT settings (#844)

* feat(alerts): dismiss action on every alert and auto-resolve agent-outdated

* feat(orchestration): experimental warning card recommending NetGrip

* feat(about): replace Ko-fi with GitHub star and add report-issue link

* feat(orchestration): redesign experimental banner with NetGrip CTA

* feat(orchestration): move experimental card below the orchestration UI

* feat(mqtt): settings card and propagation to NetGrip routers

* feat(mqtt): register the NetGrip executor token on agent startup

* feat(mqtt): exempt the executor-token route and show the publisher status in the card

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho vor 2 Monaten
Ursprung
Commit
2d48b0fa25

+ 24 - 3
app/public/locales/en/translation.json

@@ -246,7 +246,12 @@
         }
       }
     },
-    "viewDevice": "View device"
+    "viewDevice": "View device",
+    "actions": {
+      "identify": "Identify device",
+      "updateAgent": "Update agent",
+      "dismiss": "Clear alert"
+    }
   },
   "auth": {
     "checking": "Checking session",
@@ -1161,9 +1166,9 @@
     "about": {
       "changelog": "Changelog",
       "visitWeb": "Visit website",
-      "code": "Source code",
+      "starGithub": "Star us on GitHub",
+      "reportIssue": "Report a problem",
       "desc": "Network control panel for OpenWRT devices. Monitors routers and APs, and applies explicit admin actions (reservations, blocks, orchestration, firmware) with snapshot and rollback.",
-      "madeAtHome": "Support the project on Ko-fi",
       "privacy": "100% private · 0% cloud",
       "title": "About",
       "versionNote": "v1.0.0",
@@ -1899,6 +1904,22 @@
   "orchestration": {
     "title": "Orchestration",
     "subtitle": "Configure network services declaratively. Every change goes through a reviewable plan before applying.",
+    "experimental": {
+      "badge": "Experimental",
+      "title": "Experimental section",
+      "features": {
+        "panel": "Friendly panel on the router itself",
+        "wifi": "Guest and IoT WiFi with QR",
+        "vpn": "Guided WireGuard, SQM and DDNS",
+        "firewall": "Visual firewall and VLANs",
+        "snapshots": "Snapshots with undo",
+        "mqtt": "MQTT / Home Assistant integration"
+      },
+      "body": "This section writes to your routers over SSH through a reviewable plan before applying, with automatic snapshot and rollback if anything goes wrong. It is an experimental feature: always review the generated plan and work with a prior snapshot.",
+      "body2": "If your router runs OpenWrt, we recommend NetGrip: it runs on the router itself and also acts as a NetPulse agent; in that role it uses only about 10 MB of disk and 15 MB of RAM (measured on an ARM64 router), on top of offering much more functionality.",
+      "hook": "Your router can already do it all: NetGrip just makes it easy.",
+      "cta": "Discover NetGrip"
+    },
     "router": "Router",
     "gateway": "Gateway",
     "generatePlan": "Generate plan",

+ 24 - 3
app/public/locales/es/translation.json

@@ -246,7 +246,12 @@
         }
       }
     },
-    "viewDevice": "Ver dispositivo"
+    "viewDevice": "Ver dispositivo",
+    "actions": {
+      "identify": "Identificar dispositivo",
+      "updateAgent": "Actualizar agente",
+      "dismiss": "Limpiar alerta"
+    }
   },
   "auth": {
     "checking": "Comprobando sesión",
@@ -1161,9 +1166,9 @@
     "about": {
       "changelog": "Registro de cambios",
       "visitWeb": "Visitar web",
-      "code": "Código",
+      "starGithub": "Danos una estrella en GitHub",
+      "reportIssue": "Informar de un problema",
       "desc": "Panel de control de red para dispositivos OpenWRT. Monitoriza routers y APs y aplica acciones explícitas del admin (reservas, bloqueos, orquestación, firmware) con snapshot y rollback.",
-      "madeAtHome": "Apoya el proyecto en Ko-fi",
       "privacy": "100% privado · 0% nube",
       "title": "Acerca de",
       "versionNote": "v1.0.0",
@@ -1899,6 +1904,22 @@
   "orchestration": {
     "title": "Orquestación",
     "subtitle": "Configura servicios de red de forma declarativa. Cada cambio pasa por un plan revisable antes de aplicarse.",
+    "experimental": {
+      "badge": "Experimental",
+      "title": "Sección experimental",
+      "features": {
+        "panel": "Panel amable en el propio router",
+        "wifi": "WiFi de invitados e IoT con QR",
+        "vpn": "WireGuard, SQM y DDNS guiados",
+        "firewall": "Cortafuegos visual y VLANs",
+        "snapshots": "Snapshots con deshacer",
+        "mqtt": "Integración MQTT / Home Assistant"
+      },
+      "body": "Esta sección escribe en los routers por SSH a través de un plan revisable antes de aplicar, con snapshot automático y rollback si algo sale mal. Es una funcionalidad en fase experimental: revisa siempre el plan generado y trabaja con un snapshot previo.",
+      "body2": "Si tu router es OpenWrt, te recomendamos NetGrip: corre en el propio router y también actúa como agente de NetPulse; en ese papel consume solo unos 10 MB de disco y 15 MB de RAM (medidos en un router ARM64), además de ofrecer mucha más funcionalidad.",
+      "hook": "Tu router ya sabe hacerlo todo: NetGrip solo lo pone fácil.",
+      "cta": "Descubre NetGrip"
+    },
     "router": "Router",
     "gateway": "Puerta de enlace",
     "generatePlan": "Generar plan",

+ 31 - 1
app/src/data/DataProvider.tsx

@@ -172,6 +172,8 @@ export interface NetPulseApi extends NetPulseData {
   markAllAlertsRead: () => void
   /** POST /api/alerts/silence (live): silencia alertas con la misma dedup key. */
   silenceAlert: (id: string, duration: '1h' | '24h' | 'forever') => void
+  /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
+  dismissAlert: (id: string) => void
   /**
    * Fase 5 (Plan B): POST /api/agents/{slug}/rearm — reinicia el servicio
    * procd del agente en el router (vía SSH del servidor) y espera a que
@@ -925,6 +927,33 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     })()
   }, [])
 
+  /** Limpia una alerta del feed (issue #833): oculta la fila al instante y,
+   * en live, la persiste como dismiss en el backend (no reaparece tras un
+   * reinicio; si la condición se re-dispara, vuelve sola). */
+  const dismissAlert = useCallback((id: string) => {
+    setBundle((prev) => {
+      const alerts = prev.alerts.filter((a) => a.id !== id)
+      const unreadAlerts =
+        modeRef.current === 'live'
+          ? prev.unreadAlerts
+          : countUnreadAlerts(alerts, configRef.current)
+      return { ...prev, alerts, unreadAlerts }
+    })
+    if (modeRef.current !== 'live') return
+    void (async () => {
+      try {
+        const res = await fetch('/api/alerts/dismiss', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ ids: [id] }),
+        })
+        if (res.status === 401) redirectLogin()
+      } catch {
+        /* resync por snapshot */
+      }
+    })()
+  }, [])
+
   /**
    * Fase 5 (Plan B): rearme del servicio del agente en el router. El
    * backend ejecuta `init.d restart` por SSH y espera hasta 30 s el push de
@@ -1158,6 +1187,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       markAlertsRead,
       markAllAlertsRead,
       silenceAlert,
+      dismissAlert,
       rearmAgent,
       upgradeAgent,
       upgradeAllAgents,
@@ -1165,7 +1195,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       uninstallAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, silenceAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 53 - 2
app/src/pages/Alerts.tsx

@@ -10,6 +10,9 @@ import {
   CheckCheck,
   CheckCircle2,
   ChevronRight,
+  CircleArrowUp,
+  Eraser,
+  Fingerprint,
   Globe,
   Info,
   Laptop,
@@ -264,9 +267,11 @@ interface FeedRowProps {
   onToggle: () => void
   reduce: boolean
   onSilence?: (id: string, duration: '1h' | '24h' | 'forever') => void
+  onDismiss?: (id: string) => void
+  action?: { icon: LucideIcon; title: string; onClick: () => void }
 }
 
-function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence }: FeedRowProps) {
+function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence, onDismiss, action }: FeedRowProps) {
   const { t } = useTranslation()
   const sev = SEVERITY[ev.severity]
   const Icon = ev.icon ?? sev.icon
@@ -350,6 +355,28 @@ function FeedRow({ ev, index, read, expanded, onToggle, reduce, onSilence }: Fee
                   <BellOff className="h-3.5 w-3.5" strokeWidth={1.75} />
                 </button>
               )}
+              {/* #833: acción propia de la alerta (solo cuando aplica) y
+                  limpiar alerta, siempre; iconos con tooltip (title). */}
+              {action && (
+                <button
+                  type="button"
+                  onClick={(e) => { e.stopPropagation(); action.onClick() }}
+                  className="opacity-0 group-hover:opacity-100 transition-opacity text-text-muted hover:text-accent"
+                  title={action.title}
+                >
+                  <action.icon className="h-3.5 w-3.5" strokeWidth={1.75} />
+                </button>
+              )}
+              {onDismiss && (
+                <button
+                  type="button"
+                  onClick={(e) => { e.stopPropagation(); onDismiss(ev.id) }}
+                  className="opacity-0 group-hover:opacity-100 transition-opacity text-text-muted hover:text-text-primary"
+                  title={t('alerts.actions.dismiss')}
+                >
+                  <Eraser className="h-3.5 w-3.5" strokeWidth={1.75} />
+                </button>
+              )}
               <span className="font-mono text-caption text-text-muted">{alertRelTime(ev)}</span>
             </span>
           </div>
@@ -432,6 +459,7 @@ export default function Alerts() {
     markAlertsRead,
     markAllAlertsRead,
     silenceAlert,
+    dismissAlert,
   } = useNetPulse()
   // Feed: demo = diseño enriquecido del mockup; live = SOLO alertas reales
   const alertFeed = useMemo(
@@ -467,7 +495,8 @@ export default function Alerts() {
   const toggleEvent = (ev: FeedEvent) => {
     if (!ev.read) markAlertsRead([ev.id])
     // #827: la alerta de desconocido lleva directa al alta del dispositivo;
-    // el resto sigue desplegando el panel de contexto.
+    // el resto sigue desplegando el panel de contexto. La misma acción
+    // existe como icono en la fila (#833), junto a "limpiar alerta".
     const mac = intakeMacOf(ev)
     if (mac) {
       setExpandedId(null)
@@ -477,6 +506,26 @@ export default function Alerts() {
     setExpandedId((cur) => (cur === ev.id ? null : ev.id))
   }
 
+  // #833: acción contextual por tipo de alerta (icono + tooltip). Solo los
+  // tipos con una acción real la muestran; TODAS tienen "limpiar alerta".
+  const actionOf = (ev: FeedEvent): { icon: LucideIcon; title: string; onClick: () => void } | undefined => {
+    if (ev.type === 'unknown-device' && ev.vars?.mac) {
+      return {
+        icon: Fingerprint,
+        title: t('alerts.actions.identify'),
+        onClick: () => navigate(`/devices?intake=${encodeURIComponent(ev.vars?.mac ?? '')}`),
+      }
+    }
+    if (ev.type === 'agent-outdated') {
+      return {
+        icon: CircleArrowUp,
+        title: t('alerts.actions.updateAgent'),
+        onClick: () => navigate('/orchestration'),
+      }
+    }
+    return undefined
+  }
+
   const toggleCat = (cat: AlertCategory) => {
     setCats((prev) => {
       const next = new Set(prev)
@@ -878,6 +927,8 @@ export default function Alerts() {
                     onToggle={() => toggleEvent(ev)}
                     reduce={reduce}
                     onSilence={silenceAlert}
+                    onDismiss={dismissAlert}
+                    action={actionOf(ev)}
                   />
                 ))}
               </ul>

+ 55 - 1
app/src/pages/Orchestration.tsx

@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState, type ChangeEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion } from 'framer-motion'
-import { ChevronRight, CheckCircle2, AlertCircle, Loader2, Wand2, ShieldAlert, Plus, X } from 'lucide-react'
+import { ChevronRight, CheckCircle2, AlertCircle, ArrowUpRight, Loader2, Wand2, ShieldAlert, Plus, X, Sparkles } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 
@@ -91,6 +91,9 @@ export default function Orchestration() {
   const [usteerFtOverDs, setUsteerFtOverDs] = useState(false)
   const [usteerFtPskGenerateLocal, setUsteerFtPskGenerateLocal] = useState(true)
 
+  // #836: aviso "sección experimental + recomendación NetGrip". Siempre
+  // visible cada vez que se entra al menú (sin dismiss ni localStorage).
+
   // issue #120: todos los módulos son gateway-only por defecto. El toggle
   // "advanced" permite un router no-gateway (con warning + checks).
   const [allowNonGateway, setAllowNonGateway] = useState(false)
@@ -837,6 +840,57 @@ export default function Orchestration() {
           )}
         </motion.div>
       )}
+
+      {/* #836: esta sección ESCRIBE en los routers (fase experimental) y
+          NetGrip es la alternativa recomendada en OpenWrt. Siempre visible.
+          La tarjeta va al final de la página, debajo de toda la orquestación. */}
+      <motion.section
+        initial={{ opacity: 0, y: 10 }}
+        animate={{ opacity: 1, y: 0 }}
+        transition={{ duration: 0.3, ease: 'easeOut' }}
+        className="rounded-2xl border border-border bg-surface p-5 md:p-6"
+        aria-label={t('orchestration.experimental.title')}
+      >
+        <div className="flex items-start gap-3">
+          <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-accent-soft text-accent">
+            <Sparkles className="h-5 w-5" strokeWidth={1.75} />
+          </span>
+          <div className="min-w-0 flex-1">
+            <div className="flex flex-wrap items-center gap-2">
+              <h2 className="text-base font-semibold text-text-primary">{t('orchestration.experimental.title')}</h2>
+              <span className="rounded-full bg-warn/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-warn">
+                {t('orchestration.experimental.badge')}
+              </span>
+            </div>
+            <ul className="mt-3 grid gap-2 sm:grid-cols-2">
+              {(['panel', 'wifi', 'vpn', 'firewall', 'snapshots', 'mqtt'] as const).map((f) => (
+                <li key={f} className="flex items-start gap-2 text-sm text-text-secondary">
+                  <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-ok" strokeWidth={1.75} />
+                  {t(`orchestration.experimental.features.${f}`)}
+                </li>
+              ))}
+            </ul>
+            <p className="mt-4 text-sm leading-relaxed text-text-secondary">
+              {t('orchestration.experimental.body')}
+            </p>
+            <p className="mt-2 text-sm leading-relaxed text-text-secondary">
+              {t('orchestration.experimental.body2')}
+            </p>
+            <p className="mt-4 text-sm font-medium text-text-primary">
+              {t('orchestration.experimental.hook')}
+            </p>
+            <a
+              href="https://netgrip.cloudless.club"
+              target="_blank"
+              rel="noreferrer"
+              className="mt-3 inline-flex items-center gap-2 rounded-xl bg-accent px-5 py-2.5 text-sm font-semibold text-canvas shadow-sm transition-colors hover:bg-accent/90"
+            >
+              {t('orchestration.experimental.cta')}
+              <ArrowUpRight className="h-4 w-4" strokeWidth={2} />
+            </a>
+          </div>
+        </div>
+      </motion.section>
     </div>
   )
 }

+ 4 - 4
app/src/pages/Settings.tsx

@@ -8,6 +8,7 @@ import {
   BellRing,
   Check,
   ChevronDown,
+  CircleAlert,
   Copy,
   Database,
   Download,
@@ -17,9 +18,7 @@ import {
   FileText,
   FlaskConical,
   Gauge,
-  Github,
   HardDrive,
-  Heart,
   History,
   KeyRound,
   Loader2,
@@ -38,6 +37,7 @@ import {
    Server,
     Shield,
     ShieldCheck,
+   Star,
    Sun,
    Trash2,
    UserCog,
@@ -5287,9 +5287,9 @@ export default function Settings() {
 
                 <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2">
                   {[
-                    { icon: Github, label: t('settings.about.code'), href: 'https://github.com/gnacho/netpulse' },
+                    { icon: Star, label: t('settings.about.starGithub'), href: 'https://github.com/gnacho/netpulse' },
                     { icon: FileText, label: t('settings.about.visitWeb'), href: 'https://netpulse.cloudless.club' },
-                    { icon: Heart, label: t('settings.about.madeAtHome'), href: 'https://ko-fi.com/gnacho' },
+                    { icon: CircleAlert, label: t('settings.about.reportIssue'), href: 'https://github.com/gnacho/netpulse/issues' },
                     { icon: ShieldCheck, label: t('settings.about.privacy'), href: 'https://cloudless.club' },
                   ].map((item, i) => {
                     const cls = "flex items-center gap-2.5 rounded-xl border border-border px-3.5 py-2.5 text-sm text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent"

+ 17 - 11
server-go/internal/adapters/agent.go

@@ -771,19 +771,25 @@ func (l *Live) checkAgentVersion(cfg RouterConfig, p *probe.Payload) {
 			Vars:        map[string]string{"router": name, "version": p.Version, "kind": kindLabel, "latest": ref},
 			Time:        "ahora mismo", RouterID: cfg.ID,
 		})
-	} else if alerted {
+	} else if alerted || l.engine.Has(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID)) {
 		l.mu.Lock()
 		delete(l.agentOutdatedAlerted, cfg.ID)
 		l.mu.Unlock()
-		l.engine.Emit(AlertEvent{
-			ID:       fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
-			Category: alerts.CatSystem, Urgent: false,
-			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,
-		})
+		// #833: la alerta de desactualizado DESAPARECE del feed al
+		// actualizarse el agente (además del aviso ok de recuperación, que
+		// solo se emite cuando el flag en memoria estaba activo).
+		l.engine.Resolve(fmt.Sprintf("alert-agent-outdated-%s", cfg.ID))
+		if alerted {
+			l.engine.Emit(AlertEvent{
+				ID:       fmt.Sprintf("alert-agent-outdated-%s-ok-%d", cfg.ID, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false,
+				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,
+			})
+		}
 	}
 }

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

@@ -47,6 +47,7 @@ const (
 	configKey   = "alerts.config.v1"
 	readKey     = "alerts.read.v1"
 	silenceKey  = "alerts.silence.v1"
+	dismissKey  = "alerts.dismissed.v1"
 	MaxEvents   = 100
 	MaxReadIDs  = 200
 	DedupWindow = 5 * time.Minute
@@ -179,6 +180,10 @@ type Engine struct {
 	readSet map[string]bool
 	readOrd []string // FIFO de IDs (cap 200) para podar readSet
 	silenceMap map[string]int64 // dedup key → expiry (unix seconds); 0 = forever
+	// dismissed: IDs de alertas limpiadas por el usuario (issue #833). Se
+	// filtran del feed y del unread; si el mismo ID se vuelve a emitir (la
+	// condición se re-dispara), sale del conjunto y reaparece.
+	dismissed map[string]bool
 
 	// suppression: grafo de dependencias topológicas (issue #332).
 	// nil = sin supresión (tests o arranque sin topología).
@@ -212,6 +217,7 @@ func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
 		dedup:      map[string]int64{},
 		readSet:    map[string]bool{},
 		silenceMap: map[string]int64{},
+		dismissed:  map[string]bool{},
 		persistLog: persistLog,
 	}
 	if d != nil {
@@ -240,6 +246,16 @@ func newEngine(d *db.DB, n Notifier, persistLog bool) *Engine {
 		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", silenceKey).Scan(&raw); err == nil {
 			_ = json.Unmarshal([]byte(raw), &e.silenceMap)
 		}
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", dismissKey).Scan(&raw); err == nil {
+			ids := []string{}
+			if json.Unmarshal([]byte(raw), &ids) == nil {
+				for _, id := range ids {
+					if id != "" {
+						e.dismissed[id] = true
+					}
+				}
+			}
+		}
 		e.loadPersistedLocked()
 	}
 	return e
@@ -274,6 +290,10 @@ func (e *Engine) loadPersistedLocked() {
 			&ev.Title, &ev.Description, &hint, &routerID, &suppressedBy, &varsRaw, &read); err != nil {
 			return
 		}
+		// #833: una alerta limpiada no vuelve a aparecer tras un reinicio.
+		if e.dismissed[ev.ID] {
+			continue
+		}
 		ev.Type = typ
 		ev.Severity = sev
 		ev.Urgent = urgent != 0
@@ -395,6 +415,12 @@ func (e *Engine) insertaLocked(ev AlertEvent, now time.Time) bool {
 		return false
 	}
 	e.dedup[key] = now.UnixMilli()
+	// #833: si el ID estaba limpiado y la condición se re-dispara, la alerta
+	// vuelve al feed (dismissed solo oculta el histórico, no el presente).
+	if _, was := e.dismissed[ev.ID]; was {
+		delete(e.dismissed, ev.ID)
+		e.saveDismissedLocked()
+	}
 	if ev.Ts == 0 {
 		ev.Ts = now.Unix()
 	}
@@ -547,6 +573,9 @@ func (e *Engine) List() []AlertEvent {
 	e.pruneSilenceLocked()
 	out := make([]AlertEvent, 0, len(e.list))
 	for _, ev := range e.list {
+		if e.dismissed[ev.ID] {
+			continue
+		}
 		key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
 		if e.isSilencedLocked(key) {
 			continue
@@ -564,6 +593,9 @@ func (e *Engine) UnreadCount() int {
 	defer e.mu.Unlock()
 	n := 0
 	for _, ev := range e.list {
+		if e.dismissed[ev.ID] {
+			continue
+		}
 		key := ev.Category + "|" + ev.Title + "|" + ev.RouterID
 		if e.isSilencedLocked(key) {
 			continue
@@ -608,6 +640,91 @@ func (e *Engine) MarkAllRead() {
 	e.MarkRead(ids...)
 }
 
+// Dismiss limpia alertas del feed (issue #833, botón "limpiar alerta"): las
+// quita de la lista y del log persistido, las marca leídas y guarda el ID en
+// el conjunto dismissed (kv) para que no reaparezcan tras un reinicio. Si la
+// condición se re-dispara, el mismo ID se vuelve a emitir y sale del
+// conjunto (ver insertaLocked). IDs desconocidos se ignoran.
+func (e *Engine) Dismiss(ids ...string) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	changed := false
+	drop := map[string]bool{}
+	for _, id := range ids {
+		if id == "" {
+			continue
+		}
+		if !e.dismissed[id] {
+			e.dismissed[id] = true
+			changed = true
+		}
+		drop[id] = true
+		if !e.readSet[id] {
+			e.readSet[id] = true
+			e.readOrd = append(e.readOrd, id)
+		}
+		if e.db != nil {
+			_, _ = e.db.Exec("UPDATE alert_log SET read_flag = 1 WHERE id = ?", id)
+			_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
+		}
+	}
+	for len(e.readOrd) > MaxReadIDs {
+		delete(e.readSet, e.readOrd[0])
+		e.readOrd = e.readOrd[1:]
+	}
+	if changed {
+		e.saveDismissedLocked()
+		e.saveReadLocked()
+	}
+	kept := e.list[:0]
+	for _, ev := range e.list {
+		if !drop[ev.ID] {
+			kept = append(kept, ev)
+		}
+	}
+	e.list = kept
+}
+
+// Has informa si un ID de alerta está actualmente en la lista (persistida
+// incluida). Lo usa el agent-outdated check tras un reinicio, cuando el flag
+// en memoria (agentOutdatedAlerted) no sobrevive pero la alerta sí (#833).
+func (e *Engine) Has(id string) bool {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	for _, ev := range e.list {
+		if ev.ID == id {
+			return true
+		}
+	}
+	return false
+}
+
+// Resolve elimina una alerta cuya condición dejó de cumplirse (issue #833:
+// agent-outdated desaparece del feed cuando el agente se actualiza). A
+// diferencia de Dismiss NO guarda el ID en dismissed: si la condición vuelve,
+// la alerta se re-emite con normalidad. El dedup se conserva para no
+// re-notificar dentro de la ventana de 5 min.
+func (e *Engine) Resolve(id string) {
+	if id == "" {
+		return
+	}
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	for i, ev := range e.list {
+		if ev.ID == id {
+			e.list = append(e.list[:i], e.list[i+1:]...)
+			// La condición se resolvió: una reincidencia es un incidente
+			// nuevo y debe poder alertar de inmediato (sin esperar al
+			// expirar la ventana de dedup de 5 min).
+			delete(e.dedup, ev.Category+"|"+ev.Title+"|"+ev.RouterID)
+			break
+		}
+	}
+	if e.db != nil {
+		_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", id)
+	}
+}
+
 // Silence silences alerts matching the dedup key of the given alert ID for the
 // specified duration. Duration 0 means forever. Returns the dedup key that was
 // silenced, or empty string if the alert ID was not found.
@@ -716,6 +833,24 @@ func (e *Engine) saveSilenceLocked() {
 		silenceKey, string(raw))
 }
 
+func (e *Engine) saveDismissedLocked() {
+	if e.db == nil {
+		return
+	}
+	ids := make([]string, 0, len(e.dismissed))
+	for id := range e.dismissed {
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	raw, err := json.Marshal(ids)
+	if err != nil {
+		return
+	}
+	_, _ = e.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		dismissKey, string(raw))
+}
+
 func contains(list []string, v string) bool {
 	for _, x := range list {
 		if x == v {

+ 105 - 0
server-go/internal/alerts/dismiss_test.go

@@ -0,0 +1,105 @@
+// dismiss_test.go — issue #833: limpiar alerta (Dismiss) y auto-resolución
+// (Resolve) en el motor de alertas.
+package alerts
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func TestDismissRemovesFromFeedAndUnread(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(ev("a1", CatSystem, false))
+	e.Emit(ev("a2", CatSystem, false))
+	e.Dismiss("a1")
+	if got := len(e.List()); got != 1 {
+		t.Fatalf("lista tras dismiss: %d, esperaba 1", got)
+	}
+	for _, x := range e.List() {
+		if x.ID != "a2" {
+			t.Fatalf("alerta restante: %s", x.ID)
+		}
+	}
+	if got := e.UnreadCount(); got != 1 {
+		t.Fatalf("unread tras dismiss: %d, esperaba 1", got)
+	}
+	// Reaparece si la condición se re-dispara (fuera de la ventana de dedup).
+	e.SetClock(func() time.Time { return time.Now().Add(6 * time.Minute) })
+	e.Emit(ev("a1", CatSystem, false))
+	if got := len(e.List()); got != 2 {
+		t.Fatalf("lista tras re-emitir: %d, esperaba 2", got)
+	}
+}
+
+func TestDismissPersistsAcrossRestart(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	e := New(d, nil)
+	e.Emit(ev("a1", CatSystem, false))
+	e.Emit(ev("a2", CatSystem, false))
+	e.Dismiss("a1")
+
+	// Motor nuevo sobre la misma DB: la alerta limpiada NO vuelve.
+	e2 := New(d, nil)
+	for _, x := range e2.List() {
+		if x.ID == "a1" {
+			t.Fatal("a1 dismiss reapareció tras reinicio")
+		}
+	}
+	if got := len(e2.List()); got != 1 {
+		t.Fatalf("lista tras reinicio: %d, esperaba 1", got)
+	}
+}
+
+func TestResolveRemovesAndAllowsImmediateReEmit(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(ev("a1", CatSystem, false))
+	e.Resolve("a1")
+	if got := len(e.List()); got != 0 {
+		t.Fatalf("lista tras resolve: %d, esperaba 0", got)
+	}
+	// A diferencia del dedup, Resolve permite re-alertar de inmediato
+	// (la reincidencia es un incidente nuevo).
+	e.Emit(ev("a1", CatSystem, false))
+	if got := len(e.List()); got != 1 {
+		t.Fatalf("lista tras re-emitir: %d, esperaba 1", got)
+	}
+}
+
+func TestResolvePersistsAcrossRestart(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	e := New(d, nil)
+	e.Emit(ev("a1", CatSystem, false))
+	e.Resolve("a1")
+
+	e2 := New(d, nil)
+	if got := len(e2.List()); got != 0 {
+		t.Fatalf("lista tras reinicio: %d, esperaba 0", got)
+	}
+}
+
+func TestHas(t *testing.T) {
+	e := New(nil, nil)
+	if e.Has("a1") {
+		t.Fatal("Has con lista vacía")
+	}
+	e.Emit(ev("a1", CatSystem, false))
+	if !e.Has("a1") {
+		t.Fatal("Has tras emit")
+	}
+	e.Resolve("a1")
+	if e.Has("a1") {
+		t.Fatal("Has tras resolve")
+	}
+}

+ 37 - 2
server-go/internal/httpapi/alerts_api_test.go

@@ -184,10 +184,45 @@ func TestAlertsReadEndpoints(t *testing.T) {
 	}
 }
 
-// writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
-func TestAlertsNoTrailingNewline(t *testing.T) {
+// POST /api/alerts/dismiss (issue #833): limpia alertas del feed.
+func TestAlertsDismissEndpoint(t *testing.T) {
 	ts := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	// ids vacío → 400
+	res := doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":[]}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("dismiss ids vacío: %d, esperaba 400", res.StatusCode)
+	}
+	res.Body.Close()
+
+	res = doJSON(t, "POST", ts.URL, "/api/alerts/dismiss", cookie, `{"ids":["alert-temp-patio"]}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("dismiss: %d", res.StatusCode)
+	}
+	res.Body.Close()
+
+	items := alertItems(t, get(t, ts.URL, "/api/alerts", cookie))
+	for _, a := range items {
+		if a["id"] == "alert-temp-patio" {
+			t.Fatal("alert-temp-patio debía haber desaparecido del feed")
+		}
+	}
+	// unread baja: la alerta limpiada cuenta como leída y se elimina.
+	unread := 0
+	for _, a := range items {
+		if a["read"] != true {
+			unread++
+		}
+	}
+	if unread != 1 {
+		t.Fatalf("unread tras dismiss: %d, esperaba 1", unread)
+	}
+}
+
+// writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
+func TestAlertsNoTrailingNewline(t *testing.T) {	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	res := get(t, ts.URL, "/api/alerts/config", cookie)
 	defer res.Body.Close()
 	raw, _ := io.ReadAll(res.Body)

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

@@ -327,6 +327,25 @@ func (s *server) handleAlertsReadAll(w http.ResponseWriter, _ *http.Request) {
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
 }
 
+// handleAlertsDismiss (POST): body {"ids":["a","b"]} → limpia alertas del
+// feed (issue #833). Las elimina del log y no reaparecen tras un reinicio;
+// si la condición se re-dispara, la alerta vuelve con el mismo ID.
+func (s *server) handleAlertsDismiss(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		IDs []string `json:"ids"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if len(body.IDs) == 0 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "ids is required")
+		return
+	}
+	s.adapter.AlertsEngine().Dismiss(body.IDs...)
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
 // handleAlertsSilence (POST): body {"id":"...","duration":"1h|24h|forever"} →
 // silencia alertas con la misma dedup key (category|title|routerId).
 func (s *server) handleAlertsSilence(w http.ResponseWriter, r *http.Request) {

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

@@ -350,6 +350,7 @@ func NewHandler(d Deps) http.Handler {
 	mux.HandleFunc("PUT /api/alerts/config", s.handleAlertsConfigPut)
 	mux.HandleFunc("POST /api/alerts/read", s.handleAlertsRead)
 	mux.HandleFunc("POST /api/alerts/read-all", s.handleAlertsReadAll)
+	mux.HandleFunc("POST /api/alerts/dismiss", s.handleAlertsDismiss)
 	mux.HandleFunc("POST /api/alerts/silence", s.handleAlertsSilence)
 	mux.HandleFunc("POST /api/alerts/unsilence", s.handleAlertsUnsilence)
 	mux.HandleFunc("GET /api/alerts/silenced", s.handleAlertsSilenced)