Sfoglia il codice sorgente

Batch: alerts lifecycle, WireGuard transitions, health VPN, firmware release gating, FDB link speed, firmware UI (#1434 #1442 #1443 #1444 #1445 #1429 #1414) (#1461)

* Alerts: auto-resolve weak-signal episodes with hysteresis and consecutive samples (#1452)

A weak-signal alert now closes itself when the client signal stays above
the threshold plus a hysteresis margin for N consecutive polls, instead of
lingering open until cleared by hand. Disappearing clients do not count as
recovered, roaming does not open or close anything on its own, and the
closed episode is kept in the log with its duration and recovery value.

Both the margin and the sample count live in kv (alerts.weak_signal_hysteresis_dbm,
alerts.weak_signal_resolve_samples, defaults 3 dBm / 3 samples) and are
editable from Settings - Data y umbrales alongside the threshold.

* Alerts: broadcast feed state over SSE on clear, read, resolve and silence (#1434)

The poller only emits an overview snapshot when a polling cycle finishes,
which on a fleet with SNMP switches can take tens of seconds. Clearing or
marking alerts read updated the engine but no SSE event flowed until the
next cycle, so the overview (Resumen) and the badge kept the stale list
until something else forced a refresh.

The engine now notifies a SetOnChange callback after mutations that alter
the served feed (mark-read, dismiss, resolve, silence), and the server
broadcasts an 'alerts' event with the fresh list and unread count. The
web app applies it as a bundle patch, so every connected view converges
within milliseconds of the action.

* WireGuard: never lose connects of locally initiated tunnels and emit one connect per reconnection (#1443)

Three defects in the transition tracker, all visible on a fleet where a
site-to-site tunnel is initiated by the local unit:

- The warmup guard len(wgActive)>0 also swallowed the first real
  connection whenever the previous cycle had zero active peers (tunnel
  down). A dedicated wgPrimed flag now skips connects only on the first
  post-boot cycle.
- Connect and disconnect events carried constant titles, so the 5-minute
  dedup window swallowed reconnects within 5 minutes of a previous
  connect. Transitions are real incidents and now use EmitNoDedup.
- The tracker keyed peers by WGPeer.ID, which is derived from the dump
  index and can drift between polls, fabricating disconnect+connect
  pairs. It now keys by the stable pubkey (Key, #1441) with ID fallback.

* Health: factor WireGuard state into the health score (#1442)

A site-to-site tunnel down for hours used to leave the score at 100.
The VPN component penalizes a discovered-but-unresponsive WireGuard
interface (-10) and important (urgent-flagged, #1441) peers that are
down (-6 each, capped at -12 so one peer cannot dominate). Routers
without any WireGuard interface are not penalized (the 'inactive'
status also covers 'nothing to monitor', quirk #714), peers are not
counted while their interface is down (no double penalty), and every
delta shows up in the health breakdown so Resumen explains the drop.

* Firmware: periodic published-release check gates the outdated alert (#1444)

The outdated alert fired whenever the configured target differed from
the installed release, even if that target had never been released: a
typo became a permanent alert. A new daemon checks the official releases
index (downloads.openwrt.org, same source as the image resolver) on a
configurable cadence (default daily) and caches the list in kv.

- The outdated/downgrade alert only fires when the target exists
  upstream; an unknown target raises a distinct configuration warning
  (firmware-target-unknown) and does not mark the unit as outdated.
- Routers without WireGuard-style monitoring are untouched, and a fleet
  whose check never succeeded keeps the previous behavior (no gating).
- New admin endpoints: GET /api/firmware/releases, POST .../refresh,
  PUT .../settings (interval hours). The Firmware page shows the check
  state with a check-now button and the interval selector.

* WireGuard: edge cases of the per-peer urgency flag (#1445)

- Simultaneous urgent drops now all notify: the transition alerts use
  EmitNoDedup since #1443, so the 5-minute coalescing no longer hides a
  second peer dropping in the same window (test pins both notifications).
- Stale urgent keys are collected after 3 consecutive polls missing the
  peer from a non-empty dump. Empty or partial dumps count no misses, so
  a failed interface (#714) or a vanished dump cannot mass-delete flags;
  the diagnostic endpoint stops showing keys that no longer exist.
- A peer that vanishes from the wg dump in the same cycle it goes down
  keeps its disconnect urgent: the emitter falls back to the persisted
  urgency set when the sample no longer carries the peer.

* Topology: fill FDB-resolved unit link speed from the child end's port table (#1429)

On fleets whose inter-unit links resolve via FDB (SNMP switches contribute
no usable LLDP), the links table showed "-" even with both ports
identified (crowedavid on 2.44.0, #1325: sw1-ap1, sw2-ap2, sw1-sw2). The
FDB evidence already carries the childPort (the child's own uplink port,
learned from its own FDB); when the parent side reports no rate, the new
fill step reads the child's port table (an OpenWrt unit knows the
negotiated rate of its own uplink port). The parent's figure wins when
both ends report (same cable, direct measurement), a down child port
never asserts a rate, and no evidence still means an honest dash.

* Firmware UI: address the maintainer review on the method selector (#1414) (#1460)

- The owut step buttons (check, download, install image) are grouped in a
  bordered box, visually separated from the one-shot Upgrade now, and each
  button carries a tooltip explaining what it does.
- The Save button is hidden in owut mode: it persisted model and target
  for the classic URL flow, and owut sends the target in its own request,
  so it was a leftover there (it stays for auto/url/upload).
- Local upload gains an expected-SHA256 field: after the upload the
  server-computed checksum is compared against it, a mismatch shows a
  do-not-install warning, and uploading without a reference checksum
  surfaces an amber note advising to verify against the image release.

The standalone Backup config button needs a new agent-side snapshot
command and is tracked separately from this UI pass.
Nacho 1 mese fa
parent
commit
62e111f875

+ 26 - 1
app/public/locales/en/translation.json

@@ -301,6 +301,10 @@
       "wifi-weak-recovered": {
         "title": "Weak signal resolved on {{device}}",
         "description": "Back to {{signal}} dBm on {{router}} after {{duration}}"
+      },
+      "firmware-target-unknown": {
+        "title": "Firmware target not available",
+        "description": "{{router}}: the configured target \"{{target}}\" is not among the published OpenWrt releases (check the name in Firmware upgrades)"
       }
     },
     "viewDevice": "View device",
@@ -2313,7 +2317,28 @@
     "owutInstallImage": "Install downloaded image",
     "backupsTitle": "Config backups on the server",
     "backupsEmpty": "No backups yet. One is uploaded automatically before each flash.",
-    "backupsDownload": "Download"
+    "backupsDownload": "Download",
+    "releasesTitle": "Available releases check",
+    "releasesCaption": "NetPulse periodically queries the published OpenWrt releases so it only alerts when the configured target actually exists.",
+    "releasesLast": "Last check",
+    "releasesNever": "not successful yet",
+    "releasesVersions": "{{count}} published versions",
+    "releasesCheckNow": "Check now",
+    "releasesInterval": "Every",
+    "releasesHours": "h",
+    "uploadExpected": "Expected SHA256 (optional)",
+    "uploadExpectedPlaceholder": "from the image release",
+    "uploadChecksumMatch": "The SHA256 matches the one computed by the server.",
+    "uploadChecksumMismatch": "The SHA256 does NOT match the one computed by the server. Do not install this image.",
+    "uploadChecksumNote": "Without a reference SHA256 corruption cannot be ruled out: compare the computed value with the one from the image release before installing.",
+    "uploadComputed": "Computed SHA256",
+    "tipInstallOwut": "Installs the owut package (attended sysupgrade) on the unit via SSH",
+    "tipOwutDownload": "Builds and downloads the image on the unit with owut, without flashing, to review it before installing",
+    "tipOwutInstallImage": "Installs the image downloaded in the previous step on the unit",
+    "tipUpgradeOwut": "Flashes the target version now with owut (keeping current packages)",
+    "tipSchedule": "Schedule the upgrade for later or recurring",
+    "tipSave": "Saves model and target for the classic flow (URL/image)",
+    "owutStepsGroup": "owut steps"
   },
   "orchestration": {
     "title": "Orchestration",

+ 26 - 1
app/public/locales/es/translation.json

@@ -301,6 +301,10 @@
       "wifi-weak-recovered": {
         "title": "Señal débil resuelta en {{device}}",
         "description": "De vuelta a {{signal}} dBm en {{router}} tras {{duration}}"
+      },
+      "firmware-target-unknown": {
+        "title": "Target de firmware no disponible",
+        "description": "{{router}}: el target configurado \"{{target}}\" no figura entre los releases publicados de OpenWrt (revisa el nombre en Actualizaciones de firmware)"
       }
     },
     "viewDevice": "Ver dispositivo",
@@ -2313,7 +2317,28 @@
     "owutInstallImage": "Instalar imagen descargada",
     "backupsTitle": "Copias de configuración en el servidor",
     "backupsEmpty": "Todavía no hay copias. Se sube una automáticamente antes de cada flasheo.",
-    "backupsDownload": "Descargar"
+    "backupsDownload": "Descargar",
+    "releasesTitle": "Chequeo de releases disponibles",
+    "releasesCaption": "NetPulse consulta periódicamente los releases publicados de OpenWrt para avisar solo cuando el target configurado existe de verdad.",
+    "releasesLast": "Último chequeo",
+    "releasesNever": "todavía sin éxito",
+    "releasesVersions": "{{count}} versiones publicadas",
+    "releasesCheckNow": "Comprobar ahora",
+    "releasesInterval": "Cada",
+    "releasesHours": "h",
+    "uploadExpected": "SHA256 esperado (opcional)",
+    "uploadExpectedPlaceholder": "de la publicación de la imagen",
+    "uploadChecksumMatch": "El SHA256 coincide con el calculado por el servidor.",
+    "uploadChecksumMismatch": "El SHA256 NO coincide con el calculado por el servidor. No instales esta imagen.",
+    "uploadChecksumNote": "Sin SHA256 de referencia no se puede descartar una corrupción: contrasta el valor calculado con el de la publicación de la imagen antes de instalar.",
+    "uploadComputed": "SHA256 calculado",
+    "tipInstallOwut": "Instala el paquete owut (attended sysupgrade) en la unidad por SSH",
+    "tipOwutDownload": "Construye y descarga la imagen en la unidad con owut, sin flashear, para revisarla antes de instalar",
+    "tipOwutInstallImage": "Instala en la unidad la imagen descargada en el paso anterior",
+    "tipUpgradeOwut": "Flashea ahora la versión de destino con owut (con los paquetes actuales)",
+    "tipSchedule": "Programa la actualización para más tarde o de forma recurrente",
+    "tipSave": "Guarda modelo y target para el flujo clásico (URL/imagen)",
+    "owutStepsGroup": "Pasos owut"
   },
   "orchestration": {
     "title": "Orquestación",

+ 20 - 0
app/src/data/DataProvider.tsx

@@ -696,6 +696,26 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
           /* payload inválido: se ignora */
         }
       })
+      // #1434: resync del feed tras una mutación (clear/mark-read/dismiss/
+      // resolve/silence). El poller solo emite snapshot al terminar cada
+      // ciclo de sondeo; sin este evento Resumen y la campana se quedaban
+      // stale hasta el próximo ciclo. Se aplica como parche del bundle.
+      es.addEventListener('alerts', (ev) => {
+        try {
+          const data = JSON.parse((ev as MessageEvent).data as string) as {
+            alerts?: AlertEvent[]
+            unreadAlerts?: number
+          }
+          if (!Array.isArray(data.alerts)) return
+          setBundle((prev) => ({
+            ...prev,
+            alerts: data.alerts as AlertEvent[],
+            unreadAlerts: typeof data.unreadAlerts === 'number' ? data.unreadAlerts : prev.unreadAlerts,
+          }))
+        } catch {
+          /* payload inválido: se ignora */
+        }
+      })
       es.onopen = () => {
         backoffIdx = 0
         stopPolling()

+ 225 - 39
app/src/pages/FirmwareUpgrades.tsx

@@ -147,6 +147,10 @@ export default function FirmwareUpgrades() {
   const [owutDlOutput, setOwutDlOutput] = useState<Record<string, string>>({})
   const [uploadBusy, setUploadBusy] = useState<Record<string, boolean>>({})
   const [uploadInfo, setUploadInfo] = useState<Record<string, { name: string; size: number; checksum: string }>>({})
+  // #1414: SHA256 de referencia introducido por el admin para contrastarlo
+  // con el calculado por el server al subir la imagen.
+  const [uploadExpected, setUploadExpected] = useState<Record<string, string>>({})
+  const [uploadVerify, setUploadVerify] = useState<Record<string, 'match' | 'mismatch'>>({})
   // #1414: backups de config en el server (lista perezosa por tarjeta).
   const [fwBackups, setFwBackups] = useState<Record<string, { name: string; size: number; ts: number }[]>>({})
   const [fwBackupsLoaded, setFwBackupsLoaded] = useState<Record<string, boolean>>({})
@@ -492,6 +496,18 @@ export default function FirmwareUpgrades() {
       const body = await res.json().catch(() => ({}))
       if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
       setUploadInfo((prev) => ({ ...prev, [id]: { name: body.name ?? file.name, size: body.size ?? file.size, checksum: body.checksum ?? '' } }))
+      // #1414: contrasta con el SHA256 de referencia, si el admin lo dio.
+      const expected = (uploadExpected[id] ?? '').trim().toLowerCase()
+      const computed = (body.checksum ?? '').trim().toLowerCase()
+      if (expected && computed) {
+        setUploadVerify((prev) => ({ ...prev, [id]: expected === computed ? 'match' : 'mismatch' }))
+      } else {
+        setUploadVerify((prev) => {
+          const next = { ...prev }
+          delete next[id]
+          return next
+        })
+      }
       await fetchItems()
     } catch (err) {
       setError(String(err))
@@ -652,6 +668,9 @@ export default function FirmwareUpgrades() {
         </div>
       )}
 
+      {/* #1444: estado del chequeo periódico de releases (cadencia + último chequeo). */}
+      <ReleasesCheckCard />
+
       {error && (
         <div className="flex items-start gap-3 rounded-xl border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-600 dark:text-rose-400">
           <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
@@ -1040,6 +1059,32 @@ export default function FirmwareUpgrades() {
                 <div className="mt-3 rounded-lg border border-border bg-canvas px-3 py-2.5">
                   <p className="text-sm font-medium text-text-secondary">{t('firmwareUpgrades.uploadTitle')}</p>
                   <p className="mt-0.5 text-xs text-text-muted">{t('firmwareUpgrades.uploadHint')}</p>
+                  {/* #1414: SHA256 de referencia (de la publicación de la
+                      imagen) para contrastar con el calculado al subir. */}
+                  <label className="mt-2 flex flex-col gap-1">
+                    <span className="text-caption text-text-muted">{t('firmwareUpgrades.uploadExpected')}</span>
+                    <input
+                      type="text"
+                      value={uploadExpected[item.routerId] ?? ''}
+                      onChange={(ev) => {
+                        const v = ev.target.value
+                        setUploadExpected((prev) => ({ ...prev, [item.routerId]: v }))
+                        const computed = (uploaded?.checksum ?? '').trim().toLowerCase()
+                        const expected = v.trim().toLowerCase()
+                        setUploadVerify((prev) => {
+                          const next = { ...prev }
+                          if (expected && computed) next[item.routerId] = expected === computed ? 'match' : 'mismatch'
+                          else delete next[item.routerId]
+                          return next
+                        })
+                      }}
+                      disabled={!isAdmin}
+                      placeholder={t('firmwareUpgrades.uploadExpectedPlaceholder')}
+                      spellCheck={false}
+                      autoComplete="off"
+                      className="rounded-lg border border-border bg-surface px-3 py-2 font-mono text-xs text-text-primary disabled:opacity-60"
+                    />
+                  </label>
                   <div className="mt-2 flex flex-wrap items-center gap-2">
                     <input
                       type="file"
@@ -1055,11 +1100,31 @@ export default function FirmwareUpgrades() {
                     {uploadBusy[item.routerId] && <span className="text-xs text-text-muted">{t('firmwareUpgrades.uploadBusy')}</span>}
                   </div>
                   {hasUploadedImage && (
-                    <p className="mt-2 text-xs text-emerald-700 dark:text-emerald-300">
-                      {uploaded
-                        ? t('firmwareUpgrades.uploadedInfo', { name: uploaded.name, size: Math.round((uploaded.size / 1024 / 1024) * 10) / 10 })
-                        : t('firmwareUpgrades.uploadedSaved')}
-                    </p>
+                    <div className="mt-2 space-y-1 text-xs">
+                      <p className="text-emerald-700 dark:text-emerald-300">
+                        {uploaded
+                          ? t('firmwareUpgrades.uploadedInfo', { name: uploaded.name, size: Math.round((uploaded.size / 1024 / 1024) * 10) / 10 })
+                          : t('firmwareUpgrades.uploadedSaved')}
+                      </p>
+                      {uploaded?.checksum && (
+                        <p className="break-all font-mono text-text-muted">
+                          {t('firmwareUpgrades.uploadComputed')}: {uploaded.checksum}
+                        </p>
+                      )}
+                      {uploadVerify[item.routerId] === 'match' && (
+                        <p className="font-medium text-emerald-700 dark:text-emerald-300">{t('firmwareUpgrades.uploadChecksumMatch')}</p>
+                      )}
+                      {uploadVerify[item.routerId] === 'mismatch' && (
+                        <p className="rounded-md border border-rose-500/40 bg-rose-500/10 px-2 py-1 font-medium text-rose-600 dark:text-rose-400">
+                          {t('firmwareUpgrades.uploadChecksumMismatch')}
+                        </p>
+                      )}
+                      {uploaded?.checksum && !uploadVerify[item.routerId] && !(uploadExpected[item.routerId] ?? '').trim() && (
+                        <p className="rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-amber-700 dark:text-amber-300">
+                          {t('firmwareUpgrades.uploadChecksumNote')}
+                        </p>
+                      )}
+                    </div>
                   )}
                 </div>
               )}
@@ -1121,53 +1186,72 @@ export default function FirmwareUpgrades() {
                         type="button"
                         onClick={() => void installOwut(item.routerId)}
                         disabled={installBusy[item.routerId]}
+                        title={t('firmwareUpgrades.tipInstallOwut')}
                         className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                       >
                         <Download className={cn('h-4 w-4', installBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
                         {installBusy[item.routerId] ? t('firmwareUpgrades.installingOwut') : t('firmwareUpgrades.installOwut')}
                       </button>
                     )}
+                    {/* #1414 (feedback #1414): los tres pasos owut van juntos
+                        y en orden, separados del "Actualizar" a pelo. El
+                        grupo lleva tooltips que explican qué hace cada botón. */}
                     {(m === 'auto' || m === 'owut') && (
-                    <button
-                      type="button"
-                      onClick={() => void runOwutCheck(item.routerId)}
-                      disabled={owutBusy[item.routerId] || !owutAvail}
-                      title={!owutAvail ? t('firmwareUpgrades.owutUnavailable') : t('firmwareUpgrades.checkTooltip')}
-                      className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
-                    >
-                      <Terminal className={cn('h-4 w-4', owutBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
-                      {owutBusy[item.routerId] ? t('firmwareUpgrades.owutBusy') : t('firmwareUpgrades.check')}
-                    </button>
-                    )}
-                    {(m === 'auto' || m === 'owut') && owutAvail && (
-                      <>
-                        <button
-                          type="button"
-                          onClick={() => void runOwutDownload(item.routerId)}
-                          disabled={owutDlBusy[item.routerId] || !!active}
-                          className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
-                        >
-                          <Download className={cn('h-4 w-4', owutDlBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
-                          {owutDlBusy[item.routerId] ? t('firmwareUpgrades.owutDownloading') : t('firmwareUpgrades.owutDownload')}
-                        </button>
+                      <div
+                        className="flex flex-wrap items-center gap-2 rounded-xl border border-border bg-surface px-2.5 py-2"
+                        role="group"
+                        aria-label={t('firmwareUpgrades.owutStepsGroup')}
+                      >
                         <button
                           type="button"
-                          onClick={() => void runOwutInstallImage(item.routerId)}
-                          disabled={!!active || busy[item.routerId] === 'upgrade' || scheduled}
+                          onClick={() => void runOwutCheck(item.routerId)}
+                          disabled={owutBusy[item.routerId] || !owutAvail}
+                          title={!owutAvail ? t('firmwareUpgrades.owutUnavailable') : t('firmwareUpgrades.checkTooltip')}
                           className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                         >
-                          <Rocket className="h-4 w-4" strokeWidth={1.75} />
-                          {t('firmwareUpgrades.owutInstallImage')}
+                          <Terminal className={cn('h-4 w-4', owutBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
+                          {owutBusy[item.routerId] ? t('firmwareUpgrades.owutBusy') : t('firmwareUpgrades.check')}
                         </button>
-                      </>
+                        {owutAvail && (
+                          <>
+                            <button
+                              type="button"
+                              onClick={() => void runOwutDownload(item.routerId)}
+                              disabled={owutDlBusy[item.routerId] || !!active}
+                              title={t('firmwareUpgrades.tipOwutDownload')}
+                              className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
+                            >
+                              <Download className={cn('h-4 w-4', owutDlBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
+                              {owutDlBusy[item.routerId] ? t('firmwareUpgrades.owutDownloading') : t('firmwareUpgrades.owutDownload')}
+                            </button>
+                            <button
+                              type="button"
+                              onClick={() => void runOwutInstallImage(item.routerId)}
+                              disabled={!!active || busy[item.routerId] === 'upgrade' || scheduled}
+                              title={t('firmwareUpgrades.tipOwutInstallImage')}
+                              className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
+                            >
+                              <Rocket className="h-4 w-4" strokeWidth={1.75} />
+                              {t('firmwareUpgrades.owutInstallImage')}
+                            </button>
+                          </>
+                        )}
+                      </div>
+                    )}
+                    {/* #1414: en modo owut el "Guardar" no hace nada útil (el
+                        target viaja en el cuerpo de owut-upgrade; era
+                        heredado del flujo URL). Solo se muestra para los
+                        métodos que persisten target para el flujo clásico. */}
+                    {m !== 'owut' && (
+                      <button
+                        onClick={() => saveTarget(item.routerId)}
+                        disabled={busy[item.routerId] === 'save' || !e.targetVersion || !e.model}
+                        title={t('firmwareUpgrades.tipSave')}
+                        className="inline-flex h-9 items-center gap-2 rounded-lg bg-accent px-4 text-sm font-medium text-canvas transition-colors hover:bg-accent/90 disabled:opacity-50"
+                      >
+                        {busy[item.routerId] === 'save' ? t('common.loading') : t('common.save')}
+                      </button>
                     )}
-                    <button
-                      onClick={() => saveTarget(item.routerId)}
-                      disabled={busy[item.routerId] === 'save' || !e.targetVersion || !e.model}
-                      className="inline-flex h-9 items-center gap-2 rounded-lg bg-accent px-4 text-sm font-medium text-canvas transition-colors hover:bg-accent/90 disabled:opacity-50"
-                    >
-                      {busy[item.routerId] === 'save' ? t('common.loading') : t('common.save')}
-                    </button>
                     <button
                       onClick={() => {
                         if (owutAvail && (m === 'auto' || m === 'owut')) {
@@ -1181,6 +1265,7 @@ export default function FirmwareUpgrades() {
                         }
                       }}
                       disabled={active || busy[item.routerId] === 'upgrade' || scheduled || (!targetSel && !(m === 'upload' && hasUploadedImage))}
+                      title={owutAvail && (m === 'auto' || m === 'owut') ? t('firmwareUpgrades.tipUpgradeOwut') : undefined}
                       className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                     >
                       {active
@@ -1197,6 +1282,7 @@ export default function FirmwareUpgrades() {
                         setScheduleId(item.routerId)
                       }}
                       disabled={active}
+                      title={t('firmwareUpgrades.tipSchedule')}
                       className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                     >
                       <CalendarClock className="h-4 w-4 text-accent" strokeWidth={1.75} />
@@ -1508,3 +1594,103 @@ export default function FirmwareUpgrades() {
 function detectedVersionOf(item: FirmwareItem): string {
   return item.detectedVersion || item.currentVersion || ''
 }
+
+// #1444: tarjeta compacta del chequeo periódico de releases publicados:
+// cadencia configurable (igual de flexible que el test de velocidad WAN),
+// último chequeo y botón de comprobar ahora.
+function ReleasesCheckCard() {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const auth = useAuth()
+  const isAdmin = auth?.role === 'admin'
+  const [state, setState] = useState<{
+    versions: string[]
+    ts: number
+    available: boolean
+    intervalHours: number
+  } | null>(null)
+  const [busy, setBusy] = useState(false)
+
+  useEffect(() => {
+    if (isDemo) return
+    let cancelled = false
+    fetch('/api/firmware/releases')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((j) => {
+        if (!cancelled && j) setState(j)
+      })
+      .catch(() => {})
+    return () => {
+      cancelled = true
+    }
+  }, [isDemo])
+
+  if (isDemo) return null
+
+  const checkNow = () => {
+    setBusy(true)
+    fetch('/api/firmware/releases/refresh', { method: 'POST' })
+      .then((r) => (r.ok ? r.json() : null))
+      .then((j) => {
+        if (!j) return
+        setState((prev) => (prev ? { ...prev, ts: j.ts ?? 0, available: true } : prev))
+      })
+      .catch(() => {})
+      .finally(() => setBusy(false))
+  }
+  const changeInterval = (h: number) => {
+    setState((prev) => (prev ? { ...prev, intervalHours: h } : prev))
+    void fetch('/api/firmware/releases/settings', {
+      method: 'PUT',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ intervalHours: h }),
+    }).catch(() => {})
+  }
+
+  return (
+    <div className="rounded-2xl border border-border bg-surface p-4">
+      <div className="flex flex-wrap items-center gap-x-5 gap-y-2">
+        <div className="min-w-0 flex-1">
+          <div className="text-sm font-medium text-text-primary">{t('firmwareUpgrades.releasesTitle')}</div>
+          <div className="mt-0.5 text-caption text-text-muted">{t('firmwareUpgrades.releasesCaption')}</div>
+        </div>
+        <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-text-secondary">
+          <span>
+            {t('firmwareUpgrades.releasesLast')}:{' '}
+            <span className="text-text-primary">
+              {state && state.ts > 0
+                ? `${relTimeFromTs(state.ts)} · ${t('firmwareUpgrades.releasesVersions', { count: state.versions.length })}`
+                : t('firmwareUpgrades.releasesNever')}
+            </span>
+          </span>
+          <label className="flex items-center gap-1.5">
+            {t('firmwareUpgrades.releasesInterval')}
+            <select
+              value={state?.intervalHours ?? 24}
+              onChange={(ev) => changeInterval(Number(ev.target.value))}
+              disabled={!isAdmin}
+              className="h-8 rounded-lg border border-border bg-canvas px-2 text-sm text-text-primary disabled:opacity-60"
+              aria-label={t('firmwareUpgrades.releasesInterval')}
+            >
+              {[6, 12, 24, 48, 168].map((h) => (
+                <option key={h} value={h}>
+                  {h}
+                  {t('firmwareUpgrades.releasesHours')}
+                </option>
+              ))}
+            </select>
+          </label>
+          <button
+            type="button"
+            onClick={checkNow}
+            disabled={busy || !isAdmin}
+            className="inline-flex h-8 items-center gap-2 rounded-lg border border-border bg-canvas px-3 text-sm font-medium text-text-primary transition-colors hover:bg-elevated disabled:opacity-50"
+          >
+            <RefreshCw className={cn('h-4 w-4', busy && 'animate-spin')} strokeWidth={1.75} />
+            {t('firmwareUpgrades.releasesCheckNow')}
+          </button>
+        </div>
+      </div>
+    </div>
+  )
+}

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

@@ -497,6 +497,16 @@ func run() error {
 	// compartido (firmware.Engine) del flujo manual vía el AgentHub.
 	fwScheduler := firmware.NewScheduler(fwStore, firmware.NewEngine(fwStore, agentHub))
 
+	// Chequeo periódico de releases publicados (#1444): mantiene en kv la
+	// lista real de versiones OpenWrt (mismo host que el resolver de
+	// imágenes) y la publica en el adapter para el gating de la alerta de
+	// firmware. Demo: nil (las rutas responden 503).
+	var fwReleases *firmware.ReleasesRefresher
+	if live, ok := adapter.(*adapters.Live); ok {
+		fwReleases = firmware.NewReleasesRefresher(dbHandle.DB, firmware.DefaultImageBase)
+		fwReleases.SetSink(live.SetFirmwareReleases)
+	}
+
 	// Fase 9 R2/R3: TLS autofirmado + pairing token (on-box only).
 	// Se generan ANTES del handler para que serverFP esté disponible en Deps.
 	var (
@@ -762,6 +772,7 @@ func run() error {
 		PathAnalysis:    pathStore,
 		ConfigBackup:    cfgBackup,
 		Firmware:        fwStore,
+		FirmwareReleases: fwReleases,
 		Speedtest:       stScheduler,
 		AlertEmitter:    adapter.AlertsEngine(),
 		ChannelPlan:     chPlan,
@@ -837,6 +848,9 @@ func run() error {
 		mqttMgr.Start()
 		upd.Start()
 		go fwScheduler.Start()
+		if fwReleases != nil {
+			go fwReleases.Start()
+		}
 		if eventsCollector != nil {
 			eventsCollector.Start()
 		}
@@ -880,6 +894,9 @@ func run() error {
 		p.Stop()
 		upd.Stop()
 		fwScheduler.Stop()
+		if fwReleases != nil {
+			fwReleases.Stop()
+		}
 		if eventsCollector != nil {
 			eventsCollector.Stop()
 		}

+ 3 - 3
server-go/internal/adapters/adapters_test.go

@@ -615,7 +615,7 @@ func TestDisabledUnitPaused(t *testing.T) {
 		offlineOpen:   map[string]bool{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakStates:     map[string]alerts.WeakSignalState{},
+		weakStates:    map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}
@@ -664,7 +664,7 @@ func TestLiveGetOverviewConcurrent(t *testing.T) {
 		failCount:     map[string]int{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakStates:     map[string]alerts.WeakSignalState{},
+		weakStates:    map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}
@@ -707,7 +707,7 @@ func TestLiveGetOverviewRecoversFromPanic(t *testing.T) {
 		failCount:     map[string]int{},
 		wanDown:       map[string]int{},
 		onlineMacs:    map[string]bool{},
-		weakStates:     map[string]alerts.WeakSignalState{},
+		weakStates:    map[string]alerts.WeakSignalState{},
 		backhaulCache: map[string]backhaulCacheEntry{},
 		lldpCache:     map[string]lldpCacheEntry{},
 	}

+ 104 - 0
server-go/internal/adapters/health_vpn_test.go

@@ -0,0 +1,104 @@
+// health_vpn_test.go - componente VPN de la nota de salud (#1442).
+package adapters
+
+import (
+	"strings"
+	"testing"
+)
+
+// La interfaz caída (interfaces descubiertas pero ninguna responde, quirk
+// #714) resta y aparece en el breakdown.
+func TestComputeHealthWireGuardInterfaceDown(t *testing.T) {
+	h := computeHealth(nil, nil, &WireGuardStats{Interface: "wg0", Status: "inactive"})
+	if h.Score != 90 {
+		t.Fatalf("score: %d, want 90 (-10 interfaz caída)", h.Score)
+	}
+	found := false
+	for _, d := range h.Breakdown {
+		if d.Label == "WireGuard caído" && d.Delta == -10 {
+			found = true
+		}
+	}
+	if !found {
+		t.Fatalf("breakdown sin 'WireGuard caído -10': %+v", h.Breakdown)
+	}
+}
+
+// Sin interfaces WireGuard en el router (Interface vacío con estado
+// "inactive", quirk #714) NO penaliza: no hay VPN que vigilar.
+func TestComputeHealthNoWireGuardNoPenalty(t *testing.T) {
+	h := computeHealth(nil, nil, &WireGuardStats{Interface: "", Status: "inactive"})
+	if h.Score != 100 {
+		t.Fatalf("score: %d, want 100 (sin WG no hay penalización)", h.Score)
+	}
+	if len(h.Breakdown) != 0 {
+		t.Fatalf("breakdown vacío: %+v", h.Breakdown)
+	}
+}
+
+// Un peer urgente caído resta acotado y sale en el breakdown con su nombre.
+func TestComputeHealthUrgentPeerDown(t *testing.T) {
+	wg := &WireGuardStats{
+		Interface: "wg0", Status: "active",
+		Peers: []WGPeer{
+			{ID: "a", Name: "Site A", Active: true},
+			{ID: "b", Name: "Site B", Active: false, Urgent: true},
+		},
+	}
+	h := computeHealth(nil, nil, wg)
+	if h.Score != 94 {
+		t.Fatalf("score: %d, want 94 (-6 un peer urgente caído)", h.Score)
+	}
+	found := false
+	for _, d := range h.Breakdown {
+		if strings.Contains(d.Label, "Site B") && d.Delta == -6 {
+			found = true
+		}
+	}
+	if !found {
+		t.Fatalf("breakdown sin 'Site B -6': %+v", h.Breakdown)
+	}
+}
+
+// Varios urgentes caídos: el subtotal queda acotado (máx -12) para que un
+// enjambre de peers no domine la nota.
+func TestComputeHealthUrgentPeersCapped(t *testing.T) {
+	wg := &WireGuardStats{
+		Interface: "wg0", Status: "active",
+		Peers: []WGPeer{
+			{ID: "a", Name: "A", Active: false, Urgent: true},
+			{ID: "b", Name: "B", Active: false, Urgent: true},
+			{ID: "c", Name: "C", Active: false, Urgent: true},
+			{ID: "d", Name: "D", Active: false, Urgent: true},
+		},
+	}
+	h := computeHealth(nil, nil, wg)
+	if h.Score != 88 {
+		t.Fatalf("score: %d, want 88 (-12 acotado pese a 4 urgentes)", h.Score)
+	}
+}
+
+// Con la interfaz caída no se cuentan los peers urgentes: están caídos por
+// ella, no por sí mismos (sin doble penalización).
+func TestComputeHealthInterfaceDownSkipsPeers(t *testing.T) {
+	wg := &WireGuardStats{
+		Interface: "wg0", Status: "inactive",
+		Peers: []WGPeer{{ID: "b", Name: "Site B", Active: false, Urgent: true}},
+	}
+	h := computeHealth(nil, nil, wg)
+	if h.Score != 90 {
+		t.Fatalf("score: %d, want 90 (solo la interfaz, sin doble penalización)", h.Score)
+	}
+}
+
+// Los peers normales (no urgentes) caídos no tocan la nota.
+func TestComputeHealthNormalPeerDownIgnored(t *testing.T) {
+	wg := &WireGuardStats{
+		Interface: "wg0", Status: "active",
+		Peers: []WGPeer{{ID: "b", Name: "Laptop", Active: false}},
+	}
+	h := computeHealth(nil, nil, wg)
+	if h.Score != 100 {
+		t.Fatalf("score: %d, want 100 (peer normal caído no penaliza)", h.Score)
+	}
+}

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

@@ -285,6 +285,12 @@ type Live struct {
 	// cambia la versión o el target, y se resuelve al coincidir). Protegido
 	// por mu.
 	fwAlert map[string]fwAlertState
+	// #1444: lista cacheada de releases publicados de OpenWrt (la publica el
+	// ReleasesRefresher tras cada chequeo periódico) y episodios abiertos del
+	// aviso "target no disponible upstream" (routerID → target alertado).
+	fwReleases      []string
+	fwReleasesTs    int64
+	fwUnknownTarget map[string]string
 
 	// snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
 	// para loguear solo cuando el resultado cambia.
@@ -318,10 +324,19 @@ type Live struct {
 	engine        *alerts.Engine
 	wgActive      map[string]bool
 	wgActiveSince map[string]time.Time // when each active peer became active (disconnect duration)
+	// wgPrimed (#1443): la primera pasada tras el arranque NO emite connects
+	// (warmup: los peers activos al boot no son "conexiones"). Antes el
+	// warmup se deducía de len(wgActive)>0, que además tragaba la primera
+	// conexión real cuando el ciclo previo no tenía ningún peer activo
+	// (túnel iniciado por la unidad local tras estar caído).
+	wgPrimed bool
 	// wgUrgent (#1441): claves de peer (WGPeer.Key) marcadas como urgentes:
 	// sus caídas avisan (Urgent=true en la alerta), las del resto solo van al
 	// log. Persistido en kv (wgUrgentKey).
 	wgUrgent map[string]bool
+	// wgUrgentMiss (#1445): ausencias consecutivas del peer en el dump por
+	// clave urgente; a wgUrgentPruneMisses seguidas se recoge el flag.
+	wgUrgentMiss map[string]int
 	// weakStates (#1452): estado del ciclo de vida de la alerta de señal
 	// débil por MAC (antes sólo se guardaba el último disparo). La máquina
 	// pura vive en alerts.WeakSignalStep.
@@ -465,6 +480,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		lastGood:             map[string]*Router{},
 		lastStatus:           map[string]string{},
 		fwAlert:              map[string]fwAlertState{},
+		fwUnknownTarget:      map[string]string{},
 		boardCache:           map[string]*BoardInfo{},
 		layoutCache:          map[string][]PortLayout{},
 		extrasCache:          map[string]*extrasSnapshot{},
@@ -488,6 +504,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		wgActive:             map[string]bool{},
 		wgActiveSince:        map[string]time.Time{},
 		wgUrgent:             map[string]bool{},
+		wgUrgentMiss:         map[string]int{},
 		weakStates:           map[string]alerts.WeakSignalState{},
 		onlineMacs:           map[string]bool{},
 		unknownGrace:         map[string]int{},
@@ -1338,6 +1355,68 @@ func (l *Live) evalFirmwareAlert(routerID, name, installed, target string, cmp i
 	l.engine.EmitOrUpdate(ev)
 }
 
+// SetFirmwareReleases (#1444) publica la lista cacheada de releases
+// publicados (la alimenta el ReleasesRefresher tras cada chequeo periódico).
+func (l *Live) SetFirmwareReleases(v []string, ts int64) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	l.fwReleases = append([]string(nil), v...)
+	l.fwReleasesTs = ts
+}
+
+// firmwareTargetKnown (#1444): ¿figura el target entre los releases
+// publicados? Con la lista vacía (chequeo aún sin éxito) NO se gatea: se
+// conserva el comportamiento previo en flotas sin salida a
+// downloads.openwrt.org.
+func (l *Live) firmwareTargetKnown(target string) bool {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if len(l.fwReleases) == 0 {
+		return true
+	}
+	for _, v := range l.fwReleases {
+		if v == target {
+			return true
+		}
+	}
+	return false
+}
+
+// evalFirmwareUnknownTarget (#1444): episodio del aviso "el target no existe
+// upstream" (configuración, no firmware desactualizado). target == "" resuelve
+// el episodio (target corregido, retirado o vuelto conocido).
+func (l *Live) evalFirmwareUnknownTarget(routerID, name, target string) {
+	id := "alert-fw-target-unknown-" + routerID
+	l.mu.Lock()
+	if l.fwUnknownTarget == nil {
+		l.fwUnknownTarget = map[string]string{}
+	}
+	if target == "" {
+		_, active := l.fwUnknownTarget[routerID]
+		delete(l.fwUnknownTarget, routerID)
+		l.mu.Unlock()
+		if active {
+			l.engine.Resolve(id)
+		}
+		return
+	}
+	if prev, active := l.fwUnknownTarget[routerID]; active && prev == target {
+		l.mu.Unlock()
+		return
+	}
+	l.fwUnknownTarget[routerID] = target
+	l.mu.Unlock()
+	l.engine.EmitOrUpdate(AlertEvent{
+		ID: id, Category: alerts.CatSystem, Urgent: false,
+		Severity: "warn", RouterID: routerID,
+		Title:       "Firmware target not available",
+		Description: fmt.Sprintf("%s: configured target %q is not among the published OpenWrt releases", name, target),
+		Type:        alerts.HintFirmwareUnknownTarget,
+		Vars:        map[string]string{"router": name, "target": target},
+		Time:        "just now",
+	})
+}
+
 // buildRouter construye el Router del contrato (index.js:221-249).
 // countBand acumula un cliente en la banda del desglose (issue #645). La
 // banda "—" (desconocida) no cae en ninguna: suma ≤ total de clientes.
@@ -1506,6 +1585,7 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	// coincidir. El downgrade (target más viejo) alerta con wording propio.
 	if p.firmwareAvailable != "" {
 		r.FirmwareOutdated = true
+		l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
 		// Rama RouterOS (sondeo API): se conserva el aviso por ciclo como
 		// hasta #1411; la dedup de 5 min lo acota.
 		l.engine.Emit(AlertEvent{
@@ -1520,12 +1600,24 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 			Time:        "just now", RouterID: p.cfg.ID,
 		})
 	} else if p.cfg.FirmwareTarget != "" {
-		if fwCmp == fwNewer || fwCmp == fwAmbiguous {
-			r.FirmwareOutdated = true
-		}
-		if p.board != nil {
-			l.evalFirmwareAlert(p.cfg.ID, name, r.Firmware, p.cfg.FirmwareTarget, fwCmp)
+		// #1444: el target existe upstream → alerta normal de mismatch.
+		// Target desconocido upstream → aviso de configuración y SIN marca
+		// de desactualizado (un target inventado no es firmware viejo).
+		// Lista vacía (chequeo sin éxito aún) → comportamiento previo.
+		l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
+		if l.firmwareTargetKnown(p.cfg.FirmwareTarget) {
+			if fwCmp == fwNewer || fwCmp == fwAmbiguous {
+				r.FirmwareOutdated = true
+			}
+			if p.board != nil {
+				l.evalFirmwareAlert(p.cfg.ID, name, r.Firmware, p.cfg.FirmwareTarget, fwCmp)
+			}
+		} else {
+			l.evalFirmwareUnknownTarget(p.cfg.ID, name, p.cfg.FirmwareTarget)
 		}
+	} else {
+		// Sin target configurado: el aviso de target desconocido queda resuelto.
+		l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
 	}
 	if p.temp > thr {
 		r.HotMetric = "temp"
@@ -2583,23 +2675,89 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 	// Transitions run only on a successful poll: a failed poll would mark every
 	// previously active peer as spuriously disconnected.
 	l.applyWireGuardTransitions(stats, gw.ID)
+	// #1445: recoge los flags urgentes de peers que dejaron de existir.
+	l.pruneWGUrgent(stats.Peers)
 	return stats
 }
 
+// wgUrgentPruneMisses (#1445): ausencias consecutivas en el dump antes de
+// recoger un flag urgente. Un dump parcial (una interfaz no respondió, #714)
+// no borra flags de peers vivos; sólo desaparece del router de verdad quien
+// lleva varios sondeos seguidos sin aparecer.
+const wgUrgentPruneMisses = 3
+
+// pruneWGUrgent recoge las claves urgentes que llevan wgUrgentPruneMisses
+// sondeos seguidos sin casar con ningún peer configurado. Con dumps vacíos no
+// cuenta ausencias (no borra nada): sin peers no hay evidencia de nada.
+func (l *Live) pruneWGUrgent(peers []WGPeer) {
+	if len(peers) == 0 {
+		return
+	}
+	present := map[string]bool{}
+	for _, p := range peers {
+		k := p.Key
+		if k == "" {
+			k = p.ID
+		}
+		present[k] = true
+	}
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	changed := false
+	for k := range l.wgUrgent {
+		if present[k] {
+			if l.wgUrgentMiss[k] != 0 {
+				delete(l.wgUrgentMiss, k)
+				changed = true
+			}
+			continue
+		}
+		l.wgUrgentMiss[k]++
+		if l.wgUrgentMiss[k] >= wgUrgentPruneMisses {
+			delete(l.wgUrgent, k)
+			delete(l.wgUrgentMiss, k)
+			changed = true
+		}
+	}
+	if changed {
+		l.saveWGUrgentLocked()
+	}
+}
+
 // applyWireGuardTransitions emits connect (handshake) and disconnect alerts for
 // peers whose active state changed since the last successful poll, and keeps
 // wgActive/wgActiveSince in sync. A peer that was never active cannot emit a
 // disconnect; the first post-boot cycle never emits a connect (warmup).
 //
+// #1443: el tracker se indexa por Key (pubkey base64url estable, #1441) con
+// fallback a ID: WGPeer.ID puede cambiar entre sondeos ("peer-<idx>" según
+// la posición en el dump) y un cambio de identificador simulaba un
+// disconnect+connect fantasma. Los eventos de transición salen por
+// EmitNoDedup: cada uno es un incidente real (un connect y un disconnect
+// del mismo peer llevan el mismo título y el dedup de 5 min se comía los
+// flaps). El warmup es un flag propio (wgPrimed), no len(wgActive)>0: con
+// el guarda viejo, la primera conexión de un túnel iniciado por la unidad
+// local (ciclo previo con 0 peers activos) se perdía para siempre.
+//
 // #1441: la alerta de un peer URGENTE sale con Urgent=true (aviso push); la de
 // un peer normal con Urgent=false (solo queda en el log). La categoría y los
 // IDs no cambian: lo único que distingue a un site-to-site de un portátil es
 // el flag que puso el admin.
 func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
+	// wgTrackKey: identidad estable del peer para el tracker (#1443).
+	wgTrackKey := func(p WGPeer) string {
+		if p.Key != "" {
+			return p.Key
+		}
+		return p.ID
+	}
 	activeNow := map[string]bool{}
+	peerByKey := map[string]WGPeer{}
 	for _, p := range stats.Peers {
+		k := wgTrackKey(p)
+		peerByKey[k] = p
 		if p.Active {
-			activeNow[p.ID] = true
+			activeNow[k] = true
 		}
 	}
 	l.mu.Lock()
@@ -2608,26 +2766,28 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 	// el llamador construyó los WGPeer a mano, se cruza con el conjunto
 	// persistido por Key o por ID.
 	urgentNow := map[string]bool{}
-	for _, p := range stats.Peers {
-		urgentNow[p.ID] = p.Urgent || l.wgUrgent[p.Key] || l.wgUrgent[p.ID]
+	for k, p := range peerByKey {
+		urgentNow[k] = p.Urgent || l.wgUrgent[p.Key] || l.wgUrgent[p.ID]
 	}
 
 	// Disconnects: previously active peers no longer present in activeNow.
+	// #1445: si el peer desapareció del dump en el mismo ciclo de su caída,
+	// urgentNow no lo ve: se respalda con el conjunto persistido (la clave
+	// trackeada ES la Key, así que l.wgUrgent[id] devuelve su flag aunque el
+	// peer no esté en la muestra).
 	for id := range l.wgActive {
 		if activeNow[id] {
 			continue
 		}
 		name := id
-		for _, p := range stats.Peers {
-			if p.ID == id {
-				name = p.Name
-			}
+		if p, ok := peerByKey[id]; ok {
+			name = p.Name
 		}
 		dur := wgDuration(time.Since(l.wgActiveSince[id]))
-		l.engine.Emit(AlertEvent{
+		l.engine.EmitNoDedup(AlertEvent{
 			ID:          fmt.Sprintf("alert-wg-down-%s-%d", id, time.Now().UnixMilli()),
 			Category:    alerts.CatVPN,
-			Urgent:      urgentNow[id],
+			Urgent:      urgentNow[id] || l.wgUrgent[id],
 			Severity:    "info",
 			Title:       "WireGuard disconnect",
 			Description: fmt.Sprintf("%s disconnected after %s", name, dur),
@@ -2638,19 +2798,19 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 		})
 		delete(l.wgActiveSince, id)
 	}
-	// Connects: newly active peers, skipping the first post-boot cycle.
+	// Connects: newly active peers, skipping the first post-boot cycle
+	// (warmup, wgPrimed) y sin dedup de 5 min: cada reconexión es un
+	// incidente propio que el operador espera ver (#1443).
 	for id := range activeNow {
 		if l.wgActive[id] {
 			continue
 		}
-		if len(l.wgActive) > 0 {
+		if l.wgPrimed {
 			name := id
-			for _, p := range stats.Peers {
-				if p.ID == id {
-					name = p.Name
-				}
+			if p, ok := peerByKey[id]; ok {
+				name = p.Name
 			}
-			l.engine.Emit(AlertEvent{
+			l.engine.EmitNoDedup(AlertEvent{
 				ID:          fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
 				Category:    alerts.CatVPN,
 				Urgent:      urgentNow[id],
@@ -2666,6 +2826,7 @@ func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
 		l.wgActiveSince[id] = time.Now()
 	}
 	l.wgActive = activeNow
+	l.wgPrimed = true
 }
 
 // wgDuration humanizes a WireGuard session duration as "Xh Ym" (hours and
@@ -3240,7 +3401,7 @@ func (l *Live) emitTempAlert(cfg RouterConfig, router Router) {
 }
 
 // computeHealth (index.js:462-486).
-func computeHealth(routers []Router, adguard *AdGuardStats) HealthScore {
+func computeHealth(routers []Router, adguard *AdGuardStats, wg *WireGuardStats) HealthScore {
 	score := 100
 	breakdown := []HealthDelta{}
 	wanScore := 100
@@ -3270,6 +3431,38 @@ func computeHealth(routers []Router, adguard *AdGuardStats) HealthScore {
 		svcScore -= 20
 		breakdown = append(breakdown, HealthDelta{Label: "AdGuard inactivo", Delta: -5})
 	}
+	// #1442: VPN en la nota de salud. "inactive" con interfaces descubiertas
+	// = túnel caído (quirk #714: sin interfaces WireGuard en el router el
+	// estado también es "inactive", pero Interface queda vacío y NO se
+	// penaliza: no hay nada que vigilar). Con la interfaz caída no se
+	// cuentan peers: están caídos por ella, no por sí mismos (no doble
+	// penalización). Cada peer importante (urgente, #1441) caído resta
+	// acotado para que uno solo no domine la nota.
+	if wg != nil && wg.Status != "active" && wg.Interface != "" {
+		score -= 10
+		svcScore -= 15
+		breakdown = append(breakdown, HealthDelta{Label: "WireGuard caído", Delta: -10})
+	} else if wg != nil {
+		urgentDown := []string{}
+		for _, p := range wg.Peers {
+			if p.Urgent && !p.Active {
+				urgentDown = append(urgentDown, p.Name)
+			}
+		}
+		if len(urgentDown) > 0 {
+			delta := 6 * len(urgentDown)
+			if delta > 12 {
+				delta = 12
+			}
+			score -= delta
+			svcScore -= delta + 3
+			if len(urgentDown) == 1 {
+				breakdown = append(breakdown, HealthDelta{Label: "peer WireGuard " + urgentDown[0] + " caído", Delta: -delta})
+			} else {
+				breakdown = append(breakdown, HealthDelta{Label: fmt.Sprintf("%d peers WireGuard importantes caídos", len(urgentDown)), Delta: -delta})
+			}
+		}
+	}
 	if score < 0 {
 		score = 0
 	}
@@ -3633,9 +3826,10 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		distNodes = filtered
 	}
 	fillUplinkSpeeds(polled, distNodes, topo.Links)
-	fillWiredSpeeds(polled, distNodes, topo.Links) // #1384
+	fillWiredSpeeds(polled, distNodes, topo.Links)             // #1384
+	fillUplinkSpeedsFromChild(polled, fdbEvidence, topo.Links) // #1429
 	return &Overview{
-		Health:  computeHealth(routerList, adguard),
+		Health:  computeHealth(routerList, adguard, wireguard),
 		WAN:     wan,
 		Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
 		Adguard: ag, Wireguard: wgStats, Routers: routerList,

+ 1 - 1
server-go/internal/adapters/live_temp_threshold_test.go

@@ -131,7 +131,7 @@ func TestComputeHealthUsesPerRouterTempThreshold(t *testing.T) {
 		{Name: "hot", Status: "online", Temp: iptr(72), TempThreshold: 70},
 		{Name: "cool", Status: "online", Temp: iptr(68), TempThreshold: 70},
 	}
-	h := computeHealth(routers, nil)
+	h := computeHealth(routers, nil, nil)
 	if h.Score != 92 {
 		t.Fatalf("score=%d, esperaba 92", h.Score)
 	}

+ 36 - 0
server-go/internal/adapters/topology.go

@@ -883,3 +883,39 @@ func fillWiredSpeeds(polled map[string]*routerPolled, dists []DistributionNode,
 		}
 	}
 }
+
+// fillUplinkSpeedsFromChild (#1429): los enlaces entre unidades resueltos
+// por FDB (los switches SNMP no aportan LLDP útil) ya identifican la boca en
+// AMBOS extremos (la evidencia FDB guarda también el childPort: la boca del
+// hijo hacia el padre, aprendida del propio FDB del hijo). Cuando el lado
+// del padre no dio velocidad, se mira la tabla de puertos del HIJO: un
+// OpenWrt sabe la velocidad negociada de su propia boca de uplink. El padre
+// manda cuando ambos extremos reportan: son el mismo cable y el dato del
+// lado que sondea el enlace es el directo.
+func fillUplinkSpeedsFromChild(polled map[string]*routerPolled, evidence map[string]topoParent, links []TopoLink) {
+	if len(links) == 0 {
+		return
+	}
+	for i := range links {
+		l := &links[i]
+		if l.Kind != "uplink" || l.SpeedMbps > 0 {
+			continue
+		}
+		ev, ok := evidence[l.To]
+		if !ok || ev.childPort == "" {
+			continue
+		}
+		p := polled[l.To]
+		if p == nil {
+			continue
+		}
+		for _, ep := range p.ports {
+			if ep.Up && (ep.ID == ev.childPort || stripLANPrefix(ep.ID) == stripLANPrefix(ev.childPort)) {
+				if mbps := parseSpeedMbps(ep.Speed); mbps > 0 {
+					l.SpeedMbps = mbps
+				}
+				break
+			}
+		}
+	}
+}

+ 77 - 0
server-go/internal/adapters/topology_child_speed_test.go

@@ -0,0 +1,77 @@
+// topology_child_speed_test.go - velocidad del enlace desde la boca del hijo
+// (#1429).
+package adapters
+
+import "testing"
+
+// El caso de crowedavid: enlace FDB sw1↔ap1 sin velocidad en el lado del
+// padre (la boca del switch no reporta o no casa); el HIJO (OpenWrt) sabe la
+// velocidad negociada de su propia boca de uplink (childPort de la evidencia
+// FDB).
+func TestFillUplinkSpeedsFromChild(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"ap1": {ports: []EthPort{
+			{ID: "lan1", Up: true, Speed: "1 Gbps"},
+			{ID: "wan", Up: true, Speed: "1 Gbps"},
+		}},
+		"ap2": {ports: []EthPort{
+			{ID: "lan1", Up: true, Speed: "2.5 Gbps"},
+		}},
+	}
+	evidence := map[string]topoParent{
+		"ap1": {parent: "sw1", port: "1/0/5", childPort: "wan"},
+		"ap2": {parent: "sw1", port: "1/0/7", childPort: "lan1"},
+	}
+	links := []TopoLink{
+		{From: "sw1", To: "ap1", Kind: "uplink", Port: "1/0/5"}, // el padre no aportó velocidad
+		{From: "sw1", To: "ap2", Kind: "uplink", Port: "1/0/7"},
+	}
+	fillUplinkSpeedsFromChild(polled, evidence, links)
+	if links[0].SpeedMbps != 1000 {
+		t.Fatalf("sw1-ap1 desde la boca del hijo (wan 1G): %d, want 1000", links[0].SpeedMbps)
+	}
+	if links[1].SpeedMbps != 2500 {
+		t.Fatalf("sw1-ap2 desde la boca del hijo (lan1 2.5G): %d, want 2500", links[1].SpeedMbps)
+	}
+}
+
+// El lado del padre manda cuando ambos extremos reportan (son el mismo
+// cable; el dato del lado que sondea el enlace es el directo).
+func TestFillUplinkSpeedsFromChildKeepsParent(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"ap1": {ports: []EthPort{{ID: "wan", Up: true, Speed: "100 Mbps"}}},
+	}
+	evidence := map[string]topoParent{"ap1": {parent: "sw1", port: "1/0/5", childPort: "wan"}}
+	links := []TopoLink{{From: "sw1", To: "ap1", Kind: "uplink", Port: "1/0/5", SpeedMbps: 1000}}
+	fillUplinkSpeedsFromChild(polled, evidence, links)
+	if links[0].SpeedMbps != 1000 {
+		t.Fatalf("el lado del padre no se pisa: %d, want 1000", links[0].SpeedMbps)
+	}
+}
+
+// Sin childPort en la evidencia (uplink resuelto por otro camino) no hay
+// nada que mirar en el hijo: la "—" honesta se respeta.
+func TestFillUplinkSpeedsFromChildNoEvidence(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"ap1": {ports: []EthPort{{ID: "wan", Up: true, Speed: "1 Gbps"}}},
+	}
+	links := []TopoLink{{From: "sw1", To: "ap1", Kind: "uplink", Port: "1/0/5"}}
+	fillUplinkSpeedsFromChild(polled, nil, links)
+	if links[0].SpeedMbps != 0 {
+		t.Fatalf("sin evidencia no se inventa: %d, want 0", links[0].SpeedMbps)
+	}
+}
+
+// Boca del hijo caída (Down): no afirma velocidad sobre un puerto que no
+// está levantado, aunque la tabla guarde un valor.
+func TestFillUplinkSpeedsFromChildDownPort(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"ap1": {ports: []EthPort{{ID: "wan", Up: false, Speed: "1 Gbps"}}},
+	}
+	evidence := map[string]topoParent{"ap1": {parent: "sw1", port: "1/0/5", childPort: "wan"}}
+	links := []TopoLink{{From: "sw1", To: "ap1", Kind: "uplink", Port: "1/0/5"}}
+	fillUplinkSpeedsFromChild(polled, evidence, links)
+	if links[0].SpeedMbps != 0 {
+		t.Fatalf("boca del hijo caída: %d, want 0", links[0].SpeedMbps)
+	}
+}

+ 116 - 0
server-go/internal/adapters/wireguard_connect_test.go

@@ -0,0 +1,116 @@
+// wireguard_connect_test.go - connects de túneles iniciados por la unidad
+// local y flaps (#1443).
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func wgHandshakes(l *Live, peer string) []alerts.AlertEvent {
+	out := []alerts.AlertEvent{}
+	for _, ev := range l.engine.List() {
+		if ev.Type == alerts.TypeWireguardHandshake && (peer == "" || ev.Vars["peer"] == peer) {
+			out = append(out, ev)
+		}
+	}
+	return out
+}
+
+// El escenario reportado: el túnel lo inicia la unidad local. El ciclo
+// previo no tenía NINGÚN peer activo (túnel caído), así que con el guarda
+// viejo len(wgActive)>0 el connect se perdía para siempre.
+func TestWireGuardLocalInitiatedConnectNotLost(t *testing.T) {
+	l := wgAlertLive(t)
+	key := WGPeerKey(realPubkey(31))
+
+	// Ciclo 1 (post-boot): el túnel está caído; el peer aparece en el dump
+	// pero inactivo. Warmup: nada suena.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "site-a", Key: key, Name: "Site A", Active: false},
+	}}, "gw")
+	if got := wgHandshakes(l, "Site A"); len(got) != 0 {
+		t.Fatalf("warmup: 0 handshakes, hay %d", len(got))
+	}
+
+	// Ciclo 2: la unidad local inicia el túnel; el handshake aparece en el
+	// dump. El connect DEBE sonar aunque el ciclo previo no tuviera activos.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "site-a", Key: key, Name: "Site A", Active: true},
+	}}, "gw")
+	if got := wgHandshakes(l, "Site A"); len(got) != 1 {
+		t.Fatalf("connect del túnel local: 1 handshake, hay %d", len(got))
+	}
+}
+
+// Flaps repetidos: cada reconexión emite SU connect. Con el dedup de 5 min
+// (mismo título "WireGuard handshake") los flaps rápidos se tragaban. Los
+// ciclos van separados unos ms para que los IDs (timestamp) no colisionen:
+// en producción los flaps están separados por segundos como mínimo.
+func TestWireGuardFlapsEachEmitConnect(t *testing.T) {
+	l := wgAlertLive(t)
+	key := WGPeerKey(realPubkey(32))
+	peer := WGPeer{ID: "site-b", Key: key, Name: "Site B", Active: false}
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw") // warmup: túnel caído
+	peer.Active = true
+	time.Sleep(5 * time.Millisecond)
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw") // connect 1
+	peer.Active = false
+	time.Sleep(5 * time.Millisecond)
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw") // disconnect
+	peer.Active = true
+	time.Sleep(5 * time.Millisecond)
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw") // connect 2 (reconexión)
+
+	if got := wgHandshakes(l, "Site B"); len(got) != 2 {
+		t.Fatalf("dos flaps: 2 handshakes, hay %d", len(got))
+	}
+	if got := wgDisconnects(l); len(got) != 1 {
+		t.Fatalf("un disconnect, hay %d", len(got))
+	}
+}
+
+// El tracker se indexa por Key estable: si el ID derivado del dump cambia
+// ("peer-0" pasa a ser "peer-1" al reordenarse los peers), NO debe emitirse
+// un disconnect+connect fantasma para el mismo peer. La única activación del
+// peer quedó consumida por el warmup: el total de eventos debe ser cero.
+func TestWireGuardTrackerKeyedByStableKey(t *testing.T) {
+	l := wgAlertLive(t)
+	key := WGPeerKey(realPubkey(33))
+
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peer-0", Key: key, Name: "Site C", Active: true},
+	}}, "gw") // warmup: activación consumida sin connect
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peer-0", Key: key, Name: "Site C", Active: true},
+	}}, "gw") // estable, sin eventos
+	// Reorden del dump: mismo peer (misma Key), distinto índice de ID.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "peer-1", Key: key, Name: "Site C", Active: true},
+	}}, "gw")
+
+	if got := wgHandshakes(l, "Site C"); len(got) != 0 {
+		t.Fatalf("sin connects por cambio de ID: 0, hay %d", len(got))
+	}
+	if got := wgDisconnects(l); len(got) != 0 {
+		t.Fatalf("sin disconnects por cambio de ID: 0, hay %d", len(got))
+	}
+}
+
+// Tras un reinicio (wgPrimed a false) con los túneles ya activos, el warmup
+// sigue sin emitir connects: no hay tormenta de alertas en el arranque.
+func TestWireGuardBootWarmupStillSkipsConnects(t *testing.T) {
+	l := wgAlertLive(t)
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "site-d", Key: WGPeerKey(realPubkey(34)), Name: "Site D", Active: true},
+	}}, "gw")
+	if got := wgHandshakes(l, ""); len(got) != 0 {
+		t.Fatalf("warmup post-boot: 0 handshakes, hay %d", len(got))
+	}
+	if !l.wgPrimed {
+		t.Error("wgPrimed debe quedar true tras el primer ciclo")
+	}
+}

+ 1 - 0
server-go/internal/adapters/wireguard_disconnect_test.go

@@ -157,6 +157,7 @@ func TestWireGuardHandshakeStillEmitted(t *testing.T) {
 	l := wgAlertLive(t)
 	l.wgActive = map[string]bool{"peerB": true}
 	l.wgActiveSince = map[string]time.Time{"peerB": time.Now().Add(-5 * time.Minute)}
+	l.wgPrimed = true // estado post-warmup: el connect de peerA debe sonar
 
 	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
 		{ID: "peerA", Name: "Alice", Active: true},

+ 136 - 0
server-go/internal/adapters/wireguard_urgent_edges_test.go

@@ -0,0 +1,136 @@
+// wireguard_urgent_edges_test.go - aristas del flag urgente (#1445).
+package adapters
+
+import (
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+type notifySpy struct{ got []alerts.AlertEvent }
+
+func (n *notifySpy) Notify(ev alerts.AlertEvent) { n.got = append(n.got, ev) }
+
+// 1) Coalescing: dos urgentes cayendo en el MISMO ciclo producen DOS
+// alertas y DOS notificaciones. Antes (#1443 era Emit con dedup de 5 min)
+// la segunda caída se tragaba: el operador no se enteraba del segundo peer.
+func TestWireGuardUrgentSimultaneousDropsAllNotify(t *testing.T) {
+	spy := &notifySpy{}
+	l := wgAlertLive(t)
+	l.engine.SetNotifier(spy)
+	ka, kb := WGPeerKey(realPubkey(41)), WGPeerKey(realPubkey(42))
+	if err := l.SetWireGuardPeerUrgent(ka, true); err != nil {
+		t.Fatalf("urgente A: %v", err)
+	}
+	if err := l.SetWireGuardPeerUrgent(kb, true); err != nil {
+		t.Fatalf("urgente B: %v", err)
+	}
+	l.wgActive = map[string]bool{ka: true, kb: true}
+	l.wgActiveSince = map[string]time.Time{ka: time.Now().Add(-time.Hour), kb: time.Now().Add(-time.Hour)}
+	l.wgPrimed = true
+
+	// Ambos caen en el mismo ciclo: el dump los sigue listando, inactivos.
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
+		{ID: "a", Key: ka, Name: "Site A", Active: false},
+		{ID: "b", Key: kb, Name: "Site B", Active: false},
+	}}, "gw")
+
+	if got := wgDisconnects(l); len(got) != 2 {
+		t.Fatalf("alertas de caída: 2, hay %d", len(got))
+	}
+	urgentNotifies := 0
+	for _, ev := range spy.got {
+		if ev.Type == alerts.TypeWireguardDisconnect && ev.Urgent {
+			urgentNotifies++
+		}
+	}
+	if urgentNotifies != 2 {
+		t.Fatalf("notificaciones urgentes: 2, hay %d (coalescing)", urgentNotifies)
+	}
+}
+
+// 2) Clave urgente huérfana: el flag sobrevive ausencias sueltas (dump
+// parcial #714) y se recoge tras wgUrgentPruneMisses sondeos seguidos.
+func TestWireGuardUrgentPruneAfterMisses(t *testing.T) {
+	l := wgAlertLive(t)
+	ka := WGPeerKey(realPubkey(43))
+	if err := l.SetWireGuardPeerUrgent(ka, true); err != nil {
+		t.Fatalf("urgente: %v", err)
+	}
+	other := WGPeer{ID: "x", Key: WGPeerKey(realPubkey(44)), Name: "X", Active: true}
+
+	// Dump sin el peer A: dos sondeos no bastan.
+	l.pruneWGUrgent([]WGPeer{other})
+	l.pruneWGUrgent([]WGPeer{other})
+	if !l.WireGuardPeerUrgent(ka) {
+		t.Fatal("el flag no debe recogerse con 2 ausencias")
+	}
+	// Tercera ausencia consecutiva: se recoge.
+	l.pruneWGUrgent([]WGPeer{other})
+	if l.WireGuardPeerUrgent(ka) {
+		t.Fatal("tras 3 ausencias seguidas el flag huérfano se recoge")
+	}
+	if got := l.WireGuardUrgentPeers(); len(got) != 0 {
+		t.Fatalf("diagnóstico sin claves huérfanas: %v", got)
+	}
+}
+
+// 2b) Un dump vacío NO cuenta ausencias: sin peers no hay evidencia.
+func TestWireGuardUrgentPruneSkipsEmptyDump(t *testing.T) {
+	l := wgAlertLive(t)
+	ka := WGPeerKey(realPubkey(45))
+	if err := l.SetWireGuardPeerUrgent(ka, true); err != nil {
+		t.Fatalf("urgente: %v", err)
+	}
+	for i := 0; i < 10; i++ {
+		l.pruneWGUrgent(nil)
+	}
+	if !l.WireGuardPeerUrgent(ka) {
+		t.Fatal("dump vacío no debe recoger flags")
+	}
+}
+
+// 2c) Si el peer reaparece, el contador de ausencias se reinicia.
+func TestWireGuardUrgentPruneMissCounterResets(t *testing.T) {
+	l := wgAlertLive(t)
+	ka := WGPeerKey(realPubkey(46))
+	if err := l.SetWireGuardPeerUrgent(ka, true); err != nil {
+		t.Fatalf("urgente: %v", err)
+	}
+	other := WGPeer{ID: "x", Key: WGPeerKey(realPubkey(47)), Name: "X", Active: true}
+	l.pruneWGUrgent([]WGPeer{other})
+	l.pruneWGUrgent([]WGPeer{other})
+	l.pruneWGUrgent([]WGPeer{ // reaparece: reinicio
+		other, {ID: "a", Key: ka, Name: "A", Active: true},
+	})
+	l.pruneWGUrgent([]WGPeer{other})
+	l.pruneWGUrgent([]WGPeer{other})
+	if !l.WireGuardPeerUrgent(ka) {
+		t.Fatal("la reaparición reinicia el contador: con 2 ausencias nuevas no se recoge")
+	}
+}
+
+// 3) Peer urgente que DESAPARECE del dump en el ciclo de su caída: la
+// alerta de caída conserva Urgent=true (respaldo del conjunto persistido).
+func TestWireGuardUrgentDropAbsentFromDumpStaysUrgent(t *testing.T) {
+	l := wgAlertLive(t)
+	ka := WGPeerKey(realPubkey(48))
+	if err := l.SetWireGuardPeerUrgent(ka, true); err != nil {
+		t.Fatalf("urgente: %v", err)
+	}
+	l.wgActive = map[string]bool{ka: true}
+	l.wgActiveSince = map[string]time.Time{ka: time.Now().Add(-time.Hour)}
+	l.wgPrimed = true
+
+	// El dump ya NO lista al peer (el router lo borró al caer).
+	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{}}, "gw")
+
+	got := wgDisconnects(l)
+	if len(got) != 1 {
+		t.Fatalf("caída: 1 alerta, hay %d", len(got))
+	}
+	if !got[0].Urgent {
+		t.Error("la caída de un peer urgente ausente del dump sigue siendo Urgent=true")
+	}
+}

+ 11 - 6
server-go/internal/adapters/wireguard_urgent_test.go

@@ -150,8 +150,12 @@ func TestLoadWGUrgentIgnoresGarbage(t *testing.T) {
 func dropOnePeer(t *testing.T, peer WGPeer) AlertEvent {
 	t.Helper()
 	l, _ := newUrgentLive(t)
-	l.wgActive = map[string]bool{peer.ID: true}
-	l.wgActiveSince = map[string]time.Time{peer.ID: time.Now().Add(-2 * time.Hour)}
+	k := peer.Key
+	if k == "" {
+		k = peer.ID
+	}
+	l.wgActive = map[string]bool{k: true}
+	l.wgActiveSince = map[string]time.Time{k: time.Now().Add(-2 * time.Hour)}
 	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{peer}}, "gw")
 	for _, ev := range l.engine.List() {
 		if ev.Type == alerts.TypeWireguardDisconnect {
@@ -170,8 +174,8 @@ func TestWireGuardDisconnectUrgencyFollowsFlag(t *testing.T) {
 	if err := l.SetWireGuardPeerUrgent(urgent.Key, true); err != nil {
 		t.Fatalf("marcar urgente: %v", err)
 	}
-	l.wgActive = map[string]bool{urgent.ID: true}
-	l.wgActiveSince = map[string]time.Time{urgent.ID: time.Now().Add(-2 * time.Hour)}
+	l.wgActive = map[string]bool{urgent.Key: true}
+	l.wgActiveSince = map[string]time.Time{urgent.Key: time.Now().Add(-2 * time.Hour)}
 	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{urgent}}, "gw")
 
 	byPeer := map[string]AlertEvent{}
@@ -210,8 +214,9 @@ func TestWireGuardHandshakeUrgencyFollowsFlag(t *testing.T) {
 	if err := l.SetWireGuardPeerUrgent(urgentKey, true); err != nil {
 		t.Fatalf("marcar urgente: %v", err)
 	}
-	l.wgActive = map[string]bool{"otro": true}
-	l.wgActiveSince = map[string]time.Time{"otro": time.Now()}
+	l.wgActive = map[string]bool{WGPeerKey(realPubkey(22)): true}
+	l.wgActiveSince = map[string]time.Time{WGPeerKey(realPubkey(22)): time.Now()}
+	l.wgPrimed = true // estado post-warmup: el connect de site-a debe sonar
 	l.applyWireGuardTransitions(&WireGuardStats{Peers: []WGPeer{
 		{ID: "site-a", Key: urgentKey, Name: "Site A", Active: true},
 		{ID: "otro", Key: WGPeerKey(realPubkey(22)), Name: "Otro", Active: true},

+ 66 - 5
server-go/internal/alerts/alerts.go

@@ -111,6 +111,10 @@ const (
 	// #1412: el target configurado es MÁS VIEJO que lo instalado (posible
 	// downgrade, casi siempre un target mal puesto).
 	HintFirmwareDowngrade = "firmware-downgrade-target"
+	// #1444: el target configurado NO figura entre los releases publicados
+	// de OpenWrt (chequeo periódico contra downloads.openwrt.org). Es un
+	// aviso de configuración, no una alerta de firmware desactualizado.
+	HintFirmwareUnknownTarget = "firmware-target-unknown"
 	HintWanDown           = "wan-down"
 	HintWifiWeak          = "wifi-weak"
 	HintGhostPort         = "ghost-port"
@@ -241,6 +245,12 @@ type Engine struct {
 	// (issue #798). false solo en el dataset demo, que es sintético y se
 	// regenera en cada arranque (cargar/re-guardar duplicaría las semillas).
 	persistLog bool
+
+	// onChange (#1434): callback invocado SIN e.mu tras una mutación que
+	// altera la lista servida o el read-state (mark-read, dismiss, resolve,
+	// silence). El server lo usa para reemitir el estado del feed por SSE
+	// al instante; el poller ya no es el único camino de actualización.
+	onChange func()
 }
 
 // PersistMaxEvents es la cota de filas del log persistido (issue #798): la
@@ -426,6 +436,16 @@ func (e *Engine) SetSuppression(g *SuppressionGraph) {
 	e.suppression = g
 }
 
+// SetOnChange (#1434) fija el callback de mutación del feed. Se invoca DESPUÉS
+// de soltar e.mu, así que el receptor puede leer el engine (List/UnreadCount)
+// sin riesgo de deadlock; solo hay que evitar mutar el engine desde dentro
+// (recursión de notificaciones).
+func (e *Engine) SetOnChange(f func()) {
+	e.mu.Lock()
+	defer e.mu.Unlock()
+	e.onChange = f
+}
+
 // Config devuelve una copia de la config efectiva (siempre las 6 claves).
 func (e *Engine) Config() map[string]string {
 	e.mu.Lock()
@@ -828,13 +848,21 @@ func (e *Engine) UnreadCount() int {
 
 // MarkRead marca IDs como leídos (persiste; cap 200 FIFO sobre los IDs que
 // ya NO son visibles; una alerta visible leída nunca vuelve a no-leída).
+// #1434: si algo cambió, avisa a OnChange (el server re-emite el estado del
+// feed por SSE para que Resumen/campana se actualicen al instante).
 func (e *Engine) MarkRead(ids ...string) {
 	e.mu.Lock()
-	defer e.mu.Unlock()
+	changed := false
 	for _, id := range ids {
 		if id == "" || e.readSet[id] {
 			continue
 		}
+		// La notificación solo cuenta cuando la alerta existe en el feed:
+		// marcar leído un ID ajeno (o de un episodio ya cerrado) persiste
+		// el leído como siempre, pero no cambia nada visible que reemitir.
+		if e.idInListLocked(id) {
+			changed = true
+		}
 		e.readSet[id] = true
 		e.readOrd = append(e.readOrd, id)
 		// Espejo en alert_log para restaurar el leído tras un reinicio (#798).
@@ -844,6 +872,11 @@ func (e *Engine) MarkRead(ids ...string) {
 	}
 	e.pruneReadOrdLocked()
 	e.saveReadLocked()
+	cb := e.onChange
+	e.mu.Unlock()
+	if changed && cb != nil {
+		cb()
+	}
 }
 
 // pruneReadOrdLocked poda el FIFO del read-set, PERO sin expulsar IDs que
@@ -907,13 +940,14 @@ func (e *Engine) MarkAllRead() {
 // conjunto (ver insertaLocked). IDs desconocidos se ignoran.
 func (e *Engine) Dismiss(ids ...string) {
 	e.mu.Lock()
-	defer e.mu.Unlock()
 	changed := false
+	seen := false
 	drop := map[string]bool{}
 	for _, id := range ids {
 		if id == "" {
 			continue
 		}
+		seen = true
 		if !e.dismissed[id] {
 			e.dismissed[id] = true
 			changed = true
@@ -934,12 +968,21 @@ func (e *Engine) Dismiss(ids ...string) {
 		e.saveReadLocked()
 	}
 	kept := e.list[:0]
+	droppedAny := false
 	for _, ev := range e.list {
 		if !drop[ev.ID] {
 			kept = append(kept, ev)
+		} else {
+			droppedAny = true
 		}
 	}
 	e.list = kept
+	cb := e.onChange
+	e.mu.Unlock()
+	// #1434: el feed cambió -> el server re-emite el estado por SSE.
+	if seen && (changed || droppedAny) && cb != nil {
+		cb()
+	}
 }
 
 // DismissAll limpia TODAS las alertas del feed: equivale a Dismiss sobre
@@ -984,7 +1027,7 @@ func (e *Engine) Resolve(id string) {
 		return
 	}
 	e.mu.Lock()
-	defer e.mu.Unlock()
+	found := false
 	for i, ev := range e.list {
 		if ev.ID == id {
 			e.list = append(e.list[:i], e.list[i+1:]...)
@@ -992,6 +1035,7 @@ func (e *Engine) Resolve(id string) {
 			// 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)
+			found = true
 			break
 		}
 	}
@@ -1019,6 +1063,13 @@ func (e *Engine) Resolve(id string) {
 		// viejo de la fila conservada (#1107 sigue valiendo).
 		_, _ = e.db.Exec("UPDATE alert_log SET resolved_ts = ?, read_flag = 0 WHERE id = ?", time.Now().Unix(), id)
 	}
+	cb := e.onChange
+	e.mu.Unlock()
+	// #1434: la lista del feed cambió -> el server re-emite el estado por
+	// SSE para que Resumen/campana se actualicen al instante.
+	if found && cb != nil {
+		cb()
+	}
 }
 
 // Remove elimina eventos por ID: los retira de la lista en memoria, de su
@@ -1064,7 +1115,6 @@ func (e *Engine) Remove(ids ...string) {
 // silenced, or empty string if the alert ID was not found.
 func (e *Engine) Silence(id string, dur time.Duration) string {
 	e.mu.Lock()
-	defer e.mu.Unlock()
 	var dedupKey string
 	for _, ev := range e.list {
 		if ev.ID == id {
@@ -1073,6 +1123,7 @@ func (e *Engine) Silence(id string, dur time.Duration) string {
 		}
 	}
 	if dedupKey == "" {
+		e.mu.Unlock()
 		return ""
 	}
 	var expiry int64
@@ -1081,15 +1132,25 @@ func (e *Engine) Silence(id string, dur time.Duration) string {
 	}
 	e.silenceMap[dedupKey] = expiry
 	e.saveSilenceLocked()
+	cb := e.onChange
+	e.mu.Unlock()
+	// #1434: la lista servida cambia (la alerta queda filtrada).
+	if cb != nil {
+		cb()
+	}
 	return dedupKey
 }
 
 // Unsilence removes the silence for a dedup key.
 func (e *Engine) Unsilence(dedupKey string) {
 	e.mu.Lock()
-	defer e.mu.Unlock()
 	delete(e.silenceMap, dedupKey)
 	e.saveSilenceLocked()
+	cb := e.onChange
+	e.mu.Unlock()
+	if cb != nil {
+		cb()
+	}
 }
 
 // Silenced returns all currently silenced dedup keys with their expiry times.

+ 115 - 0
server-go/internal/alerts/onchange_test.go

@@ -0,0 +1,115 @@
+// onchange_test.go - notificación de mutaciones del feed (#1434).
+package alerts
+
+import "testing"
+
+func testEvent(id string) AlertEvent {
+	return AlertEvent{
+		ID:       id,
+		Category: CatClients,
+		Severity: "warn",
+		Title:    "t " + id,
+		Time:     "just now",
+	}
+}
+
+func TestOnChangeMarkReadFiresOnlyOnChange(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	calls := 0
+	e.SetOnChange(func() { calls++ })
+
+	e.MarkRead("a")
+	if calls != 1 {
+		t.Fatalf("mark-read nuevo: 1 llamada, hay %d", calls)
+	}
+	e.MarkRead("a")
+	if calls != 1 {
+		t.Fatalf("mark-read idempotente no re-dispara: hay %d", calls)
+	}
+	e.MarkRead("inexistente")
+	if calls != 1 {
+		t.Fatalf("mark-read de ID ajeno no dispara: hay %d", calls)
+	}
+}
+
+func TestOnChangeDismiss(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	calls := 0
+	e.SetOnChange(func() { calls++ })
+
+	e.Dismiss("a")
+	if calls != 1 {
+		t.Fatalf("dismiss de alerta visible: 1 llamada, hay %d", calls)
+	}
+	e.Dismiss("a")
+	if calls != 1 {
+		t.Fatalf("dismiss repetido no re-dispara: hay %d", calls)
+	}
+}
+
+func TestOnChangeDismissAll(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	e.Emit(testEvent("b"))
+	calls := 0
+	e.SetOnChange(func() { calls++ })
+
+	e.DismissAll()
+	if calls == 0 {
+		t.Fatal("dismiss-all dispara al menos una notificación")
+	}
+}
+
+func TestOnChangeResolveOnlyWhenFound(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	calls := 0
+	e.SetOnChange(func() { calls++ })
+
+	e.Resolve("inexistente")
+	if calls != 0 {
+		t.Fatalf("resolve de ID ausente no dispara: hay %d", calls)
+	}
+	e.Resolve("a")
+	if calls != 1 {
+		t.Fatalf("resolve de alerta visible dispara: hay %d", calls)
+	}
+}
+
+func TestOnChangeSilenceUnsilence(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	calls := 0
+	e.SetOnChange(func() { calls++ })
+
+	if e.Silence("inexistente", 0) != "" {
+		t.Fatal("silence de ID ausente devuelve vacío")
+	}
+	if calls != 0 {
+		t.Fatalf("silence de ID ausente no dispara: hay %d", calls)
+	}
+	if e.Silence("a", 0) == "" {
+		t.Fatal("silence de alerta visible devuelve la dedup key")
+	}
+	e.Unsilence("cat|t|")
+	if calls != 2 {
+		t.Fatalf("silence+unsilence disparan 2: hay %d", calls)
+	}
+}
+
+// TestOnChangeCallbackMayReadEngine: el callback se invoca sin e.mu tomado,
+// así que el receptor puede leer el engine (es lo que hace el server para
+// reemitir el feed por SSE). Sin esta garantía habría deadlock.
+func TestOnChangeCallbackMayReadEngine(t *testing.T) {
+	e := New(nil, nil)
+	e.Emit(testEvent("a"))
+	e.SetOnChange(func() {
+		_ = e.List()
+		_ = e.UnreadCount()
+	})
+	e.MarkRead("a")
+	e.Resolve("a")
+	e.Dismiss("a")
+}

+ 341 - 0
server-go/internal/firmware/releases.go

@@ -0,0 +1,341 @@
+// releases.go - disponibilidad real de releases OpenWrt (#1444).
+//
+// La alerta de firmware desactualizado se dispara cuando el target
+// configurado difiere del instalado (#1412), pero nada comprobaba que ese
+// target existiera de verdad: un target inventado se convertía en alerta
+// permanente. Este módulo consulta periódicamente el índice oficial
+// (downloads.openwrt.org/releases/, la misma fuente que ya usa el resolver
+// de imágenes) y guarda la lista en kv; el sondeo sólo alerta "outdated"
+// cuando el target figura en ella. Un target desconocido es un aviso de
+// configuración distinto (firmware-target-unknown), no una alerta de
+// firmware. La periodicidad es configurable (default: una vez al día).
+package firmware
+
+import (
+	"context"
+	"database/sql"
+	"encoding/json"
+	"fmt"
+	"log"
+	"net/http"
+	"regexp"
+	"sort"
+	"strconv"
+	"strings"
+	"sync"
+	"time"
+)
+
+const (
+	releasesKey         = "firmware.releases.v1"
+	releasesIntervalKey = "firmware.releases.intervalHours"
+
+	DefaultReleasesIntervalHours = 24
+	minReleasesIntervalHours     = 1
+	maxReleasesIntervalHours     = 168
+
+	// releasesURL: índice HTML de releases oficiales (mismo host que el
+	// resolver de imágenes, DefaultImageBase). No es ASU: el servicio ASU
+	// no es necesario para saber QUÉ versiones existen.
+	releasesPath = "/releases/"
+)
+
+// ReleasesState es la lista cacheada de versiones publicadas.
+type ReleasesState struct {
+	// Ts es el instante (segundos unix) de la última consulta exitosa.
+	Ts int64 `json:"ts"`
+	// Versions son las versiones ordenadas de más nueva a más vieja.
+	Versions []string `json:"versions"`
+}
+
+var releaseDirRe = regexp.MustCompile(`<a href="([0-9]+\.[0-9]+(\.[0-9]+)?(-rc[0-9]+)?)/"`)
+
+// ParseReleasesIndex extrae las versiones del índice HTML de
+// downloads.openwrt.org/releases/ (enlaces a directorios "X.Y.Z/").
+// Descarta entradas ajenas (snapshots, fa.html, ../). Ordena de más nueva
+// a más vieja. Pure: testeable sin red.
+func ParseReleasesIndex(html string) []string {
+	seen := map[string]bool{}
+	out := []string{}
+	for _, m := range releaseDirRe.FindAllStringSubmatch(html, -1) {
+		v := m[1]
+		if !seen[v] {
+			seen[v] = true
+			out = append(out, v)
+		}
+	}
+	sort.SliceStable(out, func(i, j int) bool { return releaseVersionLess(out[j], out[i]) })
+	return out
+}
+
+// releaseVersionLess compara "X.Y.Z" / "X.Y.Z-rcN" (a < b). Las rc de una
+// versión ordenan ANTES del final de esa versión. Formatos raros no
+// parseables ordenan al final (menos que todo lo demás).
+func releaseVersionLess(a, b string) bool {
+	pa, ra, oka := splitReleaseVersion(a)
+	pb, rb, okb := splitReleaseVersion(b)
+	if oka != okb {
+		return !oka // no parseable → al final
+	}
+	if !oka {
+		return a < b
+	}
+	for i := 0; i < 3; i++ {
+		if pa[i] != pb[i] {
+			return pa[i] < pb[i]
+		}
+	}
+	if ra != rb {
+		// sin rc (0) es posterior a cualquier rc
+		if ra == 0 {
+			return false
+		}
+		if rb == 0 {
+			return true
+		}
+		return ra < rb
+	}
+	return false
+}
+
+func splitReleaseVersion(v string) ([3]int, int, bool) {
+	var out [3]int
+	rc := 0
+	base := v
+	if i := strings.Index(v, "-rc"); i >= 0 {
+		if n, err := strconv.Atoi(v[i+3:]); err == nil {
+			rc = n
+			base = v[:i]
+		}
+	}
+	parts := strings.Split(base, ".")
+	if len(parts) < 2 || len(parts) > 3 {
+		return out, 0, false
+	}
+	for i := 0; i < len(parts); i++ {
+		n, err := strconv.Atoi(parts[i])
+		if err != nil || n < 0 {
+			return out, 0, false
+		}
+		out[i] = n
+	}
+	return out, rc, true
+}
+
+// FetchReleases descarga y parsea el índice de releases. base sigue el
+// contrato de ImageResolver.BaseURL (sin barra final).
+func FetchReleases(ctx context.Context, client *http.Client, base string) ([]string, error) {
+	if client == nil {
+		client = &http.Client{Timeout: 15 * time.Second}
+	}
+	url := strings.TrimRight(base, "/") + releasesPath
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+	if err != nil {
+		return nil, err
+	}
+	resp, err := client.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("releases index: HTTP %d", resp.StatusCode)
+	}
+	buf := new(strings.Builder)
+	tmp := make([]byte, 8192)
+	for {
+		n, err := resp.Body.Read(tmp)
+		buf.Write(tmp[:n])
+		if err != nil {
+			break
+		}
+	}
+	versions := ParseReleasesIndex(buf.String())
+	if len(versions) == 0 {
+		return nil, fmt.Errorf("releases index: no version entries parsed")
+	}
+	return versions, nil
+}
+
+// LoadReleases lee la lista cacheada de kv. ok=false si nunca se guardó.
+func LoadReleases(db *sql.DB) (ReleasesState, bool) {
+	var st ReleasesState
+	if db == nil {
+		return st, false
+	}
+	var raw string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", releasesKey).Scan(&raw); err != nil {
+		return st, false
+	}
+	if err := json.Unmarshal([]byte(raw), &st); err != nil || len(st.Versions) == 0 {
+		return ReleasesState{}, false
+	}
+	return st, true
+}
+
+// SaveReleases persiste la lista cacheada en kv.
+func SaveReleases(db *sql.DB, st ReleasesState) error {
+	if db == nil {
+		return nil
+	}
+	raw, err := json.Marshal(st)
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		releasesKey, string(raw))
+	return err
+}
+
+// ReleasesIntervalHours devuelve la cadencia configurada del chequeo
+// (default una vez al día). Valores corruptos o fuera de rango devuelven el
+// default.
+func ReleasesIntervalHours(db *sql.DB) int {
+	if db == nil {
+		return DefaultReleasesIntervalHours
+	}
+	var raw string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", releasesIntervalKey).Scan(&raw); err != nil {
+		return DefaultReleasesIntervalHours
+	}
+	n, err := strconv.Atoi(raw)
+	if err != nil || n < minReleasesIntervalHours || n > maxReleasesIntervalHours {
+		return DefaultReleasesIntervalHours
+	}
+	return n
+}
+
+// SetReleasesIntervalHours valida y persiste la cadencia (horas).
+func SetReleasesIntervalHours(db *sql.DB, h int) error {
+	if h < minReleasesIntervalHours || h > maxReleasesIntervalHours {
+		return fmt.Errorf("intervalHours debe estar entre %d y %d", minReleasesIntervalHours, maxReleasesIntervalHours)
+	}
+	if db == nil {
+		return nil
+	}
+	_, err := db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		releasesIntervalKey, strconv.Itoa(h))
+	return err
+}
+
+// ReleasesRefresher es el daemon que mantiene la lista al día: tick corto
+// (como los demás schedulers) y refresco cuando la caché supera la
+// cadencia configurada. El sink publica la lista en el adapter (para el
+// gating de la alerta) sin depender de la API.
+type ReleasesRefresher struct {
+	db     *sql.DB
+	client *http.Client
+	base   string
+
+	mu     sync.Mutex
+	sink   func([]string, int64)
+	flying bool // single-flight del refresco
+
+	stop chan struct{}
+	wg   sync.WaitGroup
+
+	now  func() time.Time
+	logf func(format string, args ...any)
+}
+
+// NewReleasesRefresher construye el daemon. base sigue el contrato de
+// ImageResolver.BaseURL.
+func NewReleasesRefresher(db *sql.DB, base string) *ReleasesRefresher {
+	return &ReleasesRefresher{
+		db:     db,
+		client: &http.Client{Timeout: 15 * time.Second},
+		base:   base,
+		stop:   make(chan struct{}),
+		now:    time.Now,
+		logf:   func(f string, a ...any) { log.Printf("[firmware] "+f, a...) },
+	}
+}
+
+// SetSink fija el publicador de la lista en el adapter (lo llama tras cada
+// refresco exitoso y al arrancar si ya hay caché).
+func (r *ReleasesRefresher) SetSink(fn func([]string, int64)) {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	r.sink = fn
+}
+
+func (r *ReleasesRefresher) emitSink(v []string, ts int64) {
+	r.mu.Lock()
+	fn := r.sink
+	r.mu.Unlock()
+	if fn != nil {
+		fn(v, ts)
+	}
+}
+
+const releasesTick = 30 * time.Second
+
+// Start lanza el bucle periódico (daemon; no retorna hasta Stop).
+func (r *ReleasesRefresher) Start() {
+	r.wg.Add(1)
+	defer r.wg.Done()
+	// Al arrancar, publica la caché existente: el gating funciona desde el
+	// primer ciclo aunque el refresco todavía no haya tocado.
+	if st, ok := LoadReleases(r.db); ok {
+		r.emitSink(st.Versions, st.Ts)
+	}
+	ticker := time.NewTicker(releasesTick)
+	defer ticker.Stop()
+	for {
+		select {
+		case <-r.stop:
+			return
+		case <-ticker.C:
+			r.tick()
+		}
+	}
+}
+
+// Stop detiene el bucle y espera al tick en curso.
+func (r *ReleasesRefresher) Stop() {
+	close(r.stop)
+	r.wg.Wait()
+}
+
+func (r *ReleasesRefresher) tick() {
+	interval := time.Duration(ReleasesIntervalHours(r.db)) * time.Hour
+	if st, ok := LoadReleases(r.db); ok {
+		if r.now().Sub(time.Unix(st.Ts, 0)) < interval {
+			return // caché fresca
+		}
+	}
+	if err := r.RunNow(context.Background()); err != nil {
+		r.logf("releases: refresco falló: %v", err)
+	}
+}
+
+// RunNow fuerza un refresco (endpoint "comprobar ahora" y arranque). Es
+// single-flight: una segunda llamada durante un refresco en curso espera
+// pacíficamente sin lanzar otra descarga.
+func (r *ReleasesRefresher) RunNow(ctx context.Context) error {
+	r.mu.Lock()
+	if r.flying {
+		r.mu.Unlock()
+		return nil
+	}
+	r.flying = true
+	r.mu.Unlock()
+	defer func() {
+		r.mu.Lock()
+		r.flying = false
+		r.mu.Unlock()
+	}()
+
+	versions, err := FetchReleases(ctx, r.client, r.base)
+	if err != nil {
+		return err
+	}
+	st := ReleasesState{Ts: r.now().Unix(), Versions: versions}
+	if err := SaveReleases(r.db, st); err != nil {
+		return err
+	}
+	r.emitSink(versions, st.Ts)
+	return nil
+}

+ 171 - 0
server-go/internal/firmware/releases_test.go

@@ -0,0 +1,171 @@
+// releases_test.go - disponibilidad de releases OpenWrt (#1444).
+package firmware
+
+import (
+	"context"
+	"database/sql"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func testDB(t *testing.T) *sql.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d.DB
+}
+
+func TestParseReleasesIndex(t *testing.T) {
+	html := `<!DOCTYPE html><html><body>
+<a href="../">../</a>
+<a href="21.02.7/">21.02.7/</a>
+<a href="24.10.0/">24.10.0/</a>
+<a href="23.05.5/">23.05.5/</a>
+<a href="24.10.1/">24.10.1/</a>
+<a href="25.12.0-rc1/">25.12.0-rc1/</a>
+<a href="snapshots/">snapshots/</a>
+<a href="fa.html">Free software</a>
+</body></html>`
+	got := ParseReleasesIndex(html)
+	want := []string{"25.12.0-rc1", "24.10.1", "24.10.0", "23.05.5", "21.02.7"}
+	if strings.Join(got, ",") != strings.Join(want, ",") {
+		t.Fatalf("parse: %v, want %v", got, want)
+	}
+}
+
+func TestParseReleasesIndexRCOrdersBeforeFinal(t *testing.T) {
+	got := ParseReleasesIndex(`<a href="24.10.0/">24.10.0/</a><a href="24.10.0-rc3/">24.10.0-rc3/</a>`)
+	if len(got) != 2 || got[0] != "24.10.0" || got[1] != "24.10.0-rc3" {
+		t.Fatalf("orden rc: %v", got)
+	}
+}
+
+func TestParseReleasesIndexEmpty(t *testing.T) {
+	if got := ParseReleasesIndex("<html>nada</html>"); len(got) != 0 {
+		t.Fatalf("sin entradas: %v", got)
+	}
+}
+
+func TestFetchReleasesOK(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		fmt.Fprint(w, `<a href="24.10.1/">24.10.1/</a><a href="23.05.5/">23.05.5/</a>`)
+	}))
+	defer srv.Close()
+	got, err := FetchReleases(context.Background(), srv.Client(), srv.URL)
+	if err != nil {
+		t.Fatalf("fetch: %v", err)
+	}
+	if len(got) != 2 || got[0] != "24.10.1" {
+		t.Fatalf("versions: %v", got)
+	}
+}
+
+func TestFetchReleasesHTTPError(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		w.WriteHeader(http.StatusBadGateway)
+	}))
+	defer srv.Close()
+	if _, err := FetchReleases(context.Background(), srv.Client(), srv.URL); err == nil {
+		t.Fatal("debe fallar con HTTP != 200")
+	}
+}
+
+func TestFetchReleasesEmptyParseFails(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		fmt.Fprint(w, "<html>vacio</html>")
+	}))
+	defer srv.Close()
+	if _, err := FetchReleases(context.Background(), srv.Client(), srv.URL); err == nil {
+		t.Fatal("índice sin versiones debe fallar (no pisar la caché buena)")
+	}
+}
+
+func TestReleasesIntervalDefaultAndSet(t *testing.T) {
+	if got := ReleasesIntervalHours(nil); got != DefaultReleasesIntervalHours {
+		t.Fatalf("default: %d", got)
+	}
+	if err := SetReleasesIntervalHours(nil, 0); err == nil {
+		t.Fatal("rango inválido debe dar error")
+	}
+	if err := SetReleasesIntervalHours(nil, 24); err != nil {
+		t.Fatalf("set nil-db: %v", err)
+	}
+}
+
+func TestReleasesRefresherPublishesCacheOnStart(t *testing.T) {
+	db := testDB(t)
+	if err := SaveReleases(db, ReleasesState{Ts: time.Now().Unix(), Versions: []string{"24.10.1"}}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		fmt.Fprint(w, `<a href="24.10.1/">24.10.1/</a><a href="24.10.0/">24.10.0/</a>`)
+	}))
+	defer srv.Close()
+	r := NewReleasesRefresher(db, srv.URL)
+	got := make(chan []string, 1)
+	r.SetSink(func(v []string, _ int64) { got <- v })
+	if st, ok := LoadReleases(db); ok {
+		r.emitSink(st.Versions, st.Ts)
+	}
+	v := <-got
+	if len(v) != 1 || v[0] != "24.10.1" {
+		t.Fatalf("caché publicada al arranque: %v", v)
+	}
+}
+
+func TestReleasesRefresherRunNowSingleFlight(t *testing.T) {
+	db := testDB(t)
+	calls := 0
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		calls++
+		fmt.Fprint(w, `<a href="24.10.1/">24.10.1/</a>`)
+	}))
+	defer srv.Close()
+	r := NewReleasesRefresher(db, srv.URL)
+	if err := r.RunNow(context.Background()); err != nil {
+		t.Fatalf("runnow: %v", err)
+	}
+	if calls != 1 {
+		t.Fatalf("llamadas HTTP: %d, want 1", calls)
+	}
+	st, ok := LoadReleases(db)
+	if !ok || len(st.Versions) != 1 || st.Versions[0] != "24.10.1" {
+		t.Fatalf("caché guardada: %+v (ok=%v)", st, ok)
+	}
+	// Caché fresca: un tick no dispara otra descarga.
+	r.tick()
+	if calls != 1 {
+		t.Fatalf("tick con caché fresca no debe descargar: %d llamadas", calls)
+	}
+}
+
+func TestReleasesRefresherTickRefreshesStaleCache(t *testing.T) {
+	db := testDB(t)
+	if err := SaveReleases(db, ReleasesState{Ts: time.Now().Add(-48 * time.Hour).Unix(), Versions: []string{"23.05.5"}}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	calls := 0
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		calls++
+		fmt.Fprint(w, `<a href="24.10.1/">24.10.1/</a>`)
+	}))
+	defer srv.Close()
+	r := NewReleasesRefresher(db, srv.URL)
+	r.tick()
+	if calls != 1 {
+		t.Fatalf("caché vieja debe refrescarse: %d llamadas", calls)
+	}
+	st, _ := LoadReleases(db)
+	if st.Versions[0] != "24.10.1" {
+		t.Fatalf("versiones tras refresco: %v", st.Versions)
+	}
+}

+ 3 - 0
server-go/internal/httpapi/firmware.go

@@ -55,6 +55,9 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 	s.registerFirmwareUploadRoutes(mux)
 	// Backups de config en el server (#1414).
 	s.registerFirmwareBackupRoutes(mux)
+	// Disponibilidad real de releases (#1444): lista cacheada, chequeo
+	// forzado y cadencia configurables.
+	s.registerFirmwareReleasesRoutes(mux)
 
 	mux.Handle("GET /api/firmware-upgrades", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if s.db == nil {

+ 75 - 0
server-go/internal/httpapi/firmware_releases.go

@@ -0,0 +1,75 @@
+// firmware_releases.go - endpoints de disponibilidad de releases (#1444).
+//
+// GET /api/firmware/releases: lista cacheada de versiones publicadas (la
+// misma fuente que alimenta el gating de la alerta y, en unidades sin owut,
+// el desplegable de target).
+// POST /api/firmware/releases/refresh: fuerza el chequeo ahora.
+// PUT /api/firmware/releases/settings: cadencia del chequeo (horas).
+package httpapi
+
+import (
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/firmware"
+)
+
+func (s *server) registerFirmwareReleasesRoutes(mux *http.ServeMux) {
+	if s.fwReleases == nil {
+		return
+	}
+
+	mux.Handle("GET /api/firmware/releases", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		st, ok := firmware.LoadReleases(s.db.DB)
+		versions := []string{}
+		if ok {
+			versions = st.Versions
+		}
+		writeJSON(w, http.StatusOK, map[string]any{
+			"versions":      versions,
+			"ts":            st.Ts,
+			"available":     ok,
+			"intervalHours": firmware.ReleasesIntervalHours(s.db.DB),
+		})
+	})))
+
+	mux.Handle("POST /api/firmware/releases/refresh", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		if err := s.fwReleases.RunNow(r.Context()); err != nil {
+			writeError(w, http.StatusBadGateway, "fetch_failed", err.Error())
+			return
+		}
+		st, _ := firmware.LoadReleases(s.db.DB)
+		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "versions": len(st.Versions), "ts": st.Ts})
+	})))
+
+	mux.Handle("PUT /api/firmware/releases/settings", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		var body struct {
+			IntervalHours *int `json:"intervalHours"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "body JSON inválido")
+			return
+		}
+		if body.IntervalHours != nil {
+			if err := firmware.SetReleasesIntervalHours(s.db.DB, *body.IntervalHours); err != nil {
+				writeError(w, http.StatusBadRequest, "invalid_value", err.Error())
+				return
+			}
+		}
+		writeJSON(w, http.StatusOK, map[string]any{
+			"intervalHours": firmware.ReleasesIntervalHours(s.db.DB),
+		})
+	})))
+}

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

@@ -126,6 +126,9 @@ type Deps struct {
 	ConfigBackup *configbackup.Store
 	// Firmware: targets y upgrades de firmware (#453).
 	Firmware *firmware.Store
+	// FirmwareReleases refresca la lista de releases publicados (#1444).
+	// nil → las rutas /api/firmware/releases responden 503 (demo).
+	FirmwareReleases *firmware.ReleasesRefresher
 	// FirmwareImage resuelve la imagen de un router desde el índice de
 	// descargas (downloads.openwrt.org). nil → se construye el por defecto.
 	FirmwareImage *firmware.ImageResolver
@@ -245,6 +248,8 @@ type server struct {
 
 	// Firmware: targets y upgrades de firmware (#453).
 	firmware *firmware.Store
+	// FirmwareReleases: daemon del chequeo periódico de releases (#1444).
+	fwReleases *firmware.ReleasesRefresher
 	// imageResolver resuelve la imagen de un router (downloads.openwrt.org).
 	imageResolver *firmware.ImageResolver
 	// FirmwareEngine: motor compartido de upgrades (manual + programados #494).
@@ -281,6 +286,7 @@ func NewHandler(d Deps) http.Handler {
 		firmware:        d.Firmware,
 		firmwareEngine:  firmware.NewEngine(d.Firmware, d.AgentHub),
 		imageResolver:   d.FirmwareImage,
+		fwReleases:      d.FirmwareReleases,
 		speedtest:       d.Speedtest,
 		alertEmitter:    d.AlertEmitter,
 		mqtt:            d.MQTT,
@@ -288,6 +294,22 @@ func NewHandler(d Deps) http.Handler {
 	if s.imageResolver == nil {
 		s.imageResolver = firmware.NewImageResolver()
 	}
+	// #1434: las mutaciones del feed (mark-read, dismiss, resolve, silence)
+	// re-emiten el estado por SSE al instante. El poller solo broadcastea el
+	// snapshot al terminar cada ciclo de sondeo (decenas de segundos con
+	// SNMP): sin esto, Resumen y la campana se quedaban stale hasta el
+	// próximo ciclo o una reconexión. El evento "alerts" lleva la lista y el
+	// unread actualizados; el front lo aplica como parche del bundle.
+	if d.Adapter != nil && s.hub != nil {
+		if eng := d.Adapter.AlertsEngine(); eng != nil {
+			eng.SetOnChange(func() {
+				s.hub.Broadcast("alerts", map[string]any{
+					"alerts":       eng.List(),
+					"unreadAlerts": eng.UnreadCount(),
+				})
+			})
+		}
+	}
 	if s.boardVersionFn == nil {
 		s.boardVersionFn = s.detectedFirmwareVersion
 	}