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

feat: opt-in alert when a marked device goes offline (#1354)

Closes #1354. Opt-in per-device offline alerting: notify_offline override + editor switch, volatile self-resolving alert with 3-cycle grace and warmup guard. Router-offline slug split with idempotent log migration.
Nacho 1 месяц назад
Родитель
Сommit
2ea6c8bccc

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

@@ -81,6 +81,7 @@
       "agent-outdated": "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
       "degraded-link": "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
       "device-offline": "Verify the unit's power and network cable.",
+      "router-offline": "Verify the unit's power and network cable.",
       "firmware-outdated": "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
       "gateway-unreachable": "Check the connection between the gateway and the rest of the network.",
       "ghost-port": "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
@@ -131,6 +132,10 @@
         "description": "Negotiated speed dropped from {{prev}} to {{speed}} Mbps for {{polls}} consecutive polls"
       },
       "device-offline": {
+        "title": "Device offline: {{device}}",
+        "description": "{{device}} went offline on {{router}}"
+      },
+      "router-offline": {
         "title": "{{router}} offline",
         "description": "No response from {{host}}: {{error}}"
       },
@@ -429,6 +434,7 @@
       "nameHint": "Empty = automatic name (DHCP hostname)",
       "type": "Type",
       "icon": "Icon",
+      "notifyOffline": "Notify when offline",
       "auto": "Auto",
       "save": "Save",
       "saved": "Device updated",

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

@@ -81,6 +81,7 @@
       "agent-outdated": "Actualiza el agente desde Ajustes, Agentes (botón Actualizar); si es un panel NetGrip, actualiza desde su propio panel.",
       "degraded-link": "Revisa el cable y los conectores: un enlace degradado suele ser síntoma de cable dañado o conector flojo.",
       "device-offline": "Verifica la alimentación y el cable de red del equipo.",
+      "router-offline": "Verifica la alimentación y el cable de red del equipo.",
       "firmware-outdated": "Tu router tiene firmware más reciente disponible; revisa Actualizaciones de firmware (Laboratorio) o LuCI.",
       "gateway-unreachable": "Comprueba la conexión entre la puerta de enlace y el resto de la red.",
       "ghost-port": "Revisa el cable y el dispositivo conectado: un puerto activo que enmudece suele indicar un cable suelto o un equipo apagado.",
@@ -131,6 +132,10 @@
         "description": "La velocidad negociada cayó de {{prev}} a {{speed}} Mbps durante {{polls}} sondeos consecutivos"
       },
       "device-offline": {
+        "title": "Dispositivo desconectado: {{device}}",
+        "description": "{{device}} se ha desconectado de {{router}}"
+      },
+      "router-offline": {
         "title": "{{router}} offline",
         "description": "Sin respuesta de {{host}}: {{error}}"
       },
@@ -429,6 +434,7 @@
       "nameHint": "Vacío = nombre automático (hostname DHCP)",
       "type": "Tipo",
       "icon": "Icono",
+      "notifyOffline": "Avisar si se desconecta",
       "auto": "Auto",
       "save": "Guardar",
       "saved": "Dispositivo actualizado",

+ 17 - 3
app/src/components/DeviceEditSheet.tsx

@@ -17,6 +17,7 @@ import {
   SheetHeader,
   SheetTitle,
 } from '@/components/ui/sheet'
+import { Switch } from '@/components/ui/switch'
 import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
 import { cn, fetchJson } from '@/lib/utils'
 import { useNetPulse } from '@/data/DataProvider'
@@ -35,7 +36,7 @@ export interface DeviceEditSheetProps {
   saving?: boolean
   onClose: () => void
   /** Patch absoluto: '' en un campo = volver al valor automático (#797). */
-  onSave: (device: ClientDevice, patch: { icon: string; name: string; type: string }) => void
+  onSave: (device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean }) => void
   /** #1145: tras borrar el cliente del registro (el padre cierra y refresca). */
   onDeleted?: () => void
   /** #1151: resto de clientes (para el selector de enlace). */
@@ -69,6 +70,7 @@ export function DeviceEditSheet({
   const [linkTarget, setLinkTarget] = useState('')
   const [linkBusy, setLinkBusy] = useState(false)
   const [icon, setIcon] = useState(device?.iconOverride ?? '')
+  const [notifyOffline, setNotifyOffline] = useState(device?.notifyOffline ?? false)
 
   const otherClients = (clients ?? []).filter(
     (c) => c.mac && c.mac !== device?.mac && c.mac !== device?.id && !(device?.aliasMacs ?? []).includes(c.mac),
@@ -139,8 +141,9 @@ export function DeviceEditSheet({
     setIcon(device?.iconOverride ?? '')
     setName(device?.nameOverride ?? '')
     setDevType(device?.typeOverride ?? '')
+    setNotifyOffline(device?.notifyOffline ?? false)
     setReserveDraft(device?.ip ?? '')
-  }, [device?.id, device?.iconOverride, device?.nameOverride, device?.typeOverride, device?.ip])
+  }, [device?.id, device?.iconOverride, device?.nameOverride, device?.typeOverride, device?.notifyOffline, device?.ip])
 
   useEffect(() => {
     if (!device || isDemo) return
@@ -171,7 +174,7 @@ export function DeviceEditSheet({
 
   const handleSave = () => {
     if (!device) return
-    onSave(device, { icon, name: name.trim(), type: devType })
+    onSave(device, { icon, name: name.trim(), type: devType, notifyOffline })
   }
 
   // #800: hostname DNS derivado del nombre visible (input del sheet o nombre
@@ -272,6 +275,17 @@ export function DeviceEditSheet({
               </div>
             </div>
 
+            {/* #1354: alerta opt-in cuando el dispositivo se desconecta */}
+            <div className="flex items-center justify-between rounded-xl border border-border bg-elevated/40 p-3">
+              <label className="text-label uppercase text-text-muted">{t('devices.edit.notifyOffline')}</label>
+              <Switch
+                checked={notifyOffline}
+                onCheckedChange={setNotifyOffline}
+                disabled={saving}
+                aria-label={t('devices.edit.notifyOffline')}
+              />
+            </div>
+
             {/* #1096: Save/Cancel junto a la zona que editan (nombre, tipo,
                 icono); abajo quedaban lejos, tras Reserva/Bloqueo, que son
                 acciones independientes con sus propios botones. */}

+ 5 - 3
app/src/components/routers/RouterClients.tsx

@@ -26,6 +26,7 @@ interface LocalOverride {
   icon?: string
   name?: string
   type?: string
+  notifyOffline?: boolean
 }
 
 /** ⑦ Clientes de este router (router-detail.md §⑦). */
@@ -61,6 +62,7 @@ export function RouterClients({ router }: { router: Router }) {
           type: (ov.type || d.type) as ClientDevice['type'],
           nameOverride: ov.name || d.nameOverride,
           typeOverride: ov.type || d.typeOverride,
+          notifyOffline: ov.notifyOffline ?? d.notifyOffline,
         }
       })
     // #827: los sin identificar (nombre = MAC) son los accionables: se
@@ -92,9 +94,9 @@ export function RouterClients({ router }: { router: Router }) {
   const toggleSort = (key: SortKey) =>
     setSort((prev) => (prev.key === key ? { key, dir: prev.dir === 1 ? -1 : 1 } : { key, dir: 1 }))
 
-  const handleEditSave = async (device: ClientDevice, patch: { icon: string; name: string; type: string }) => {
+  const handleEditSave = async (device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean }) => {
     if (isDemo) {
-      setOverrides((prev) => ({ ...prev, [device.id]: { icon: patch.icon, name: patch.name, type: patch.type } }))
+      setOverrides((prev) => ({ ...prev, [device.id]: { icon: patch.icon, name: patch.name, type: patch.type, notifyOffline: patch.notifyOffline } }))
       setEditingId(null)
       setToast(t('devices.edit.saved'))
       return
@@ -103,7 +105,7 @@ export function RouterClients({ router }: { router: Router }) {
     const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/override`, {
       method: 'PUT',
       headers: { 'Content-Type': 'application/json' },
-      body: JSON.stringify({ icon: patch.icon, name: patch.name, type: patch.type }),
+      body: JSON.stringify({ icon: patch.icon, name: patch.name, type: patch.type, notifyOffline: patch.notifyOffline }),
     })
     setSaving(false)
     if (!res.ok) {

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

@@ -253,6 +253,8 @@ export interface Device {
   nameOverride?: string
   /** Override manual del tipo (#797). El efectivo viaja en `type`. */
   typeOverride?: string
+  /** #1354: avisar cuando este dispositivo se desconecta (opt-in). */
+  notifyOffline?: boolean
   /**
    * Epoch ms de la primera/última vez que el server vio online al cliente
    * (#954, tabla device_seen). Ausente/0 = desconocido; la app formatea el

+ 9 - 6
app/src/pages/Devices.tsx

@@ -1422,10 +1422,10 @@ export default function Devices() {
       // fallo silencioso: la sugerencia sigue para reintentar
     }
   }
-  const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string }>>(() => {
+  const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean }>>(() => {
     try {
       const raw = localStorage.getItem('netpulse-device-overrides')
-      return raw ? (JSON.parse(raw) as Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string }>) : {}
+      return raw ? (JSON.parse(raw) as Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean }>) : {}
     } catch {
       return {}
     }
@@ -1447,6 +1447,7 @@ export default function Devices() {
         type: (ov?.typeOverride || d.type) as ClientDevice['type'],
         nameOverride: ov?.nameOverride || d.nameOverride,
         typeOverride: ov?.typeOverride || d.typeOverride,
+        notifyOffline: ov?.notifyOffline ?? d.notifyOffline,
       }
     })
     const hosts = new Set(
@@ -1753,14 +1754,15 @@ export default function Devices() {
   const [savingOverride, setSavingOverride] = useState(false)
 
   const persistOverride = useCallback(
-    (id: string, patch: { iconOverride: string; nameOverride: string; typeOverride: string } | null) => {
+    (id: string, patch: { iconOverride: string; nameOverride: string; typeOverride: string; notifyOffline: boolean } | null) => {
       setDeviceOverrides((prev) => {
         const next = { ...prev }
-        if (patch && (patch.iconOverride || patch.nameOverride || patch.typeOverride)) {
+        if (patch && (patch.iconOverride || patch.nameOverride || patch.typeOverride || patch.notifyOffline)) {
           next[id] = {
             iconOverride: patch.iconOverride,
             nameOverride: patch.nameOverride,
             typeOverride: patch.typeOverride,
+            notifyOffline: patch.notifyOffline,
           }
         } else {
           delete next[id]
@@ -1780,11 +1782,12 @@ export default function Devices() {
   // return de "sin cambios" impedía limpiar un override (p. ej. volver al
   // icono Auto).
   const handleEditSave = useCallback(
-    async (device: ClientDevice, patch: { icon: string; name: string; type: string }) => {
+    async (device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean }) => {
       persistOverride(device.id, {
         iconOverride: patch.icon,
         nameOverride: patch.name,
         typeOverride: patch.type,
+        notifyOffline: patch.notifyOffline,
       })
 
       if (!isDemo) {
@@ -1792,7 +1795,7 @@ export default function Devices() {
         const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/override`, {
           method: 'PUT',
           headers: { 'Content-Type': 'application/json' },
-          body: JSON.stringify({ icon: patch.icon, name: patch.name, type: patch.type }),
+          body: JSON.stringify({ icon: patch.icon, name: patch.name, type: patch.type, notifyOffline: patch.notifyOffline }),
         })
         setSavingOverride(false)
         if (!res.ok) {

+ 4 - 4
server-go/internal/adapters/alerts_live_test.go

@@ -242,12 +242,12 @@ func TestLiveRouterReconcileRemovesOrphan(t *testing.T) {
 	// y una de OTRO router que no responde en este ciclo.
 	l.engine.Emit(alerts.AlertEvent{
 		ID: "alert-offline-patio-111", Category: alerts.CatRouter, Urgent: true,
-		Severity: "critical", Title: "Patio offline", Type: alerts.HintDeviceOffline,
+		Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
 		RouterID: "patio",
 	})
 	l.engine.Emit(alerts.AlertEvent{
 		ID: "alert-offline-living-222", Category: alerts.CatRouter, Urgent: true,
-		Severity: "critical", Title: "Living offline", Type: alerts.HintDeviceOffline,
+		Severity: "critical", Title: "Living offline", Type: alerts.TypeRouterOffline,
 		RouterID: "living",
 	})
 	if n := len(l.engine.List()); n != 2 {
@@ -285,14 +285,14 @@ func TestLiveRouterOfflineOpenReplacesOrphans(t *testing.T) {
 	}
 	l.engine.Emit(alerts.AlertEvent{
 		ID: "alert-offline-patio-111", Category: alerts.CatRouter, Urgent: true,
-		Severity: "critical", Title: "Patio offline", Type: alerts.HintDeviceOffline,
+		Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
 		RouterID: "patio",
 	})
 	// Segunda huérfana con la misma key de dedup: solo entra sin dedup (es el
 	// shape real tras reinicios seguidos durante una caída larga).
 	l.engine.EmitNoDedup(alerts.AlertEvent{
 		ID: "alert-offline-patio-222", Category: alerts.CatRouter, Urgent: true,
-		Severity: "critical", Title: "Patio offline", Type: alerts.HintDeviceOffline,
+		Severity: "critical", Title: "Patio offline", Type: alerts.TypeRouterOffline,
 		RouterID: "patio",
 	})
 	cfg := &RouterConfig{ID: "patio", Name: "Patio", Host: "10.0.0.1"}

+ 126 - 0
server-go/internal/adapters/device_offline_alert_test.go

@@ -0,0 +1,126 @@
+// device_offline_alert_test.go - issue #1354: alerta opt-in cuando un
+// dispositivo marcado se desconecta (volátil, ID estable, gracia de 3 ticks).
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+func offlineAlertTestLive() *Live {
+	return &Live{
+		engine:          alerts.New(nil, nil),
+		routers:         []RouterConfig{{ID: "rt1", Name: "Salón"}},
+		offlineOnline:   map[string]bool{},
+		offlineMisses:   map[string]int{},
+		offlineAlerted:  map[string]bool{},
+		offlineAlertNum: 3,
+	}
+}
+
+func offlineMarkedDevice() Device {
+	return Device{MAC: "AA:BB:CC:DD:EE:01", Name: "TV Salón", RouterID: "rt1", NotifyOffline: true, Online: true}
+}
+
+// (a) Dispositivo marcado offline N ciclos: una única emisión con ID estable.
+func TestTrackOfflineDevicesEmitsOnceAfterGrace(t *testing.T) {
+	l := offlineAlertTestLive()
+	d := offlineMarkedDevice()
+	l.trackOfflineDevices([]Device{d}) // línea base online
+	d.Online = false
+	l.trackOfflineDevices([]Device{d}) // miss 1
+	l.trackOfflineDevices([]Device{d}) // miss 2
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("aún en gracia: %d alertas", n)
+	}
+	l.trackOfflineDevices([]Device{d}) // miss 3: emite
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("esperaba 1 alerta, got %d", len(list))
+	}
+	ev := list[0]
+	if ev.ID != "alert-device-offline-"+d.MAC {
+		t.Fatalf("ID=%q", ev.ID)
+	}
+	if ev.Type != alerts.TypeDeviceOffline {
+		t.Fatalf("Type=%q (want %q)", ev.Type, alerts.TypeDeviceOffline)
+	}
+	if ev.Category != alerts.CatClients || !ev.Urgent || ev.Severity != "warn" {
+		t.Fatalf("taxonomía: (%s,%v,%s)", ev.Category, ev.Urgent, ev.Severity)
+	}
+	if ev.Vars["device"] != "TV Salón" || ev.Vars["router"] != "Salón" {
+		t.Fatalf("Vars=%+v", ev.Vars)
+	}
+	// Un tick más offline: el ID estable no re-emite (sigue 1 entrada).
+	l.trackOfflineDevices([]Device{d})
+	if len(l.engine.List()) != 1 {
+		t.Fatalf("re-emitió: %d alertas", len(l.engine.List()))
+	}
+}
+
+// (b) Vuelve online: la entrada volátil desaparece del feed.
+func TestTrackOfflineDevicesResolvesOnRecovery(t *testing.T) {
+	l := offlineAlertTestLive()
+	d := offlineMarkedDevice()
+	l.trackOfflineDevices([]Device{d})
+	d.Online = false
+	l.trackOfflineDevices([]Device{d})
+	l.trackOfflineDevices([]Device{d})
+	l.trackOfflineDevices([]Device{d})
+	if len(l.engine.List()) != 1 {
+		t.Fatalf("previo: %d alertas", len(l.engine.List()))
+	}
+	d.Online = true
+	l.trackOfflineDevices([]Device{d})
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("la alerta debió retirarse al volver online, quedaron %d: %+v", n, l.engine.List())
+	}
+}
+
+// (c) Dispositivo SIN marca: ninguna emisión.
+func TestTrackOfflineDevicesUnmarkedNeverEmits(t *testing.T) {
+	l := offlineAlertTestLive()
+	d := offlineMarkedDevice()
+	d.NotifyOffline = false
+	l.trackOfflineDevices([]Device{d})
+	d.Online = false
+	for i := 0; i < 6; i++ {
+		l.trackOfflineDevices([]Device{d})
+	}
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("sin marca no debía emitir: %+v", l.engine.List())
+	}
+}
+
+// (d) Ya offline al arrancar: sin transición online->offline, nada.
+func TestTrackOfflineDevicesAlreadyOfflineAtBootNeverEmits(t *testing.T) {
+	l := offlineAlertTestLive()
+	d := offlineMarkedDevice()
+	d.Online = false
+	for i := 0; i < 6; i++ {
+		l.trackOfflineDevices([]Device{d})
+	}
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("una MAC offline desde el arranque no debía emitir: %+v", l.engine.List())
+	}
+}
+
+// (e) Offline 2 ciclos y vuelve (dentro de la gracia): nada.
+func TestTrackOfflineDevicesFlapWithinGraceNoEmit(t *testing.T) {
+	l := offlineAlertTestLive()
+	d := offlineMarkedDevice()
+	l.trackOfflineDevices([]Device{d}) // línea base online
+	d.Online = false
+	l.trackOfflineDevices([]Device{d}) // miss 1
+	l.trackOfflineDevices([]Device{d}) // miss 2
+	d.Online = true
+	l.trackOfflineDevices([]Device{d}) // vuelve dentro de la gracia
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("un flap dentro de la gracia no debía emitir: %+v", l.engine.List())
+	}
+	l.trackOfflineDevices([]Device{d})
+	if n := len(l.engine.List()); n != 0 {
+		t.Fatalf("restos tras la recuperación: %+v", l.engine.List())
+	}
+}

+ 86 - 8
server-go/internal/adapters/live.go

@@ -324,6 +324,15 @@ type Live struct {
 	// presencePruneAfter: ticks sin verse que eliminan la MAC de los mapas
 	// (dispositivo que se fue para siempre; ~2h a 5s/tick, issue #206).
 	presencePruneAfter int
+	// offlineAlert (#1354): seguimiento opt-in de desconexión de dispositivos
+	// marcados (notify_offline). offlineOnline marca qué MACs se vieron online
+	// alguna vez (línea base del arranque); offlineMisses cuenta ticks offline
+	// seguidos antes de confirmar; offlineAlerted evita re-emitir mientras el
+	// incidente sigue abierto.
+	offlineOnline   map[string]bool
+	offlineMisses   map[string]int
+	offlineAlerted  map[string]bool
+	offlineAlertNum int // ticks offline seguidos antes de emitir (default 3)
 	// usteerAvailable: cache de "¿hay usteer en algún router?" para el flag del
 	// overview (entrada /roaming). Refrescado asíncronamente (TTL 30s, 1 SSH
 	// al gateway) por usteerAvailableCached para no bloquear buildOverview.
@@ -455,6 +464,10 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		presenceMisses:       map[string]int{},
 		presenceOfflineAfter: 3,
 		presencePruneAfter:   2000,
+		offlineOnline:        map[string]bool{},
+		offlineMisses:        map[string]int{},
+		offlineAlerted:       map[string]bool{},
+		offlineAlertNum:      3,
 		wanDown:              map[string]int{},
 		uplinkWatch:          map[string]*uplinkWatch{},
 		backhaulCache:        map[string]backhaulCacheEntry{},
@@ -1747,7 +1760,7 @@ func (l *Live) trackRouterOffline(cfg *RouterConfig, err error, fails int) {
 		Title:       name + " offline",
 		Description: fmt.Sprintf("No response from %s: %v", cfg.Host, err),
 		Hint:        alerts.HintFor(alerts.HintDeviceOffline),
-		Type:        alerts.HintDeviceOffline,
+		Type:        alerts.TypeRouterOffline,
 		Vars:        map[string]string{"router": name, "host": cfg.Host, "error": fmt.Sprint(err)},
 		Time:        "just now", RouterID: cfg.ID,
 	}
@@ -2240,6 +2253,64 @@ func (l *Live) trackDevicePresence(devices []Device, nowMs int64) {
 	l.presenceSeen = true
 }
 
+// trackOfflineDevices (#1354): alerta volátil opt-in cuando un dispositivo
+// marcado (override notify_offline) cae de la red. La transición
+// online->offline se CONFIRMA tras offlineAlertNum (default 3) ticks offline
+// seguidos, espejo de trackDevicePresence; un flap corto dentro de la gracia
+// no emite nada. Anti-arranque: solo alerta para MACs vistas online alguna vez
+// (una MAC ya offline al arrancar nunca "se desconecta"). Al volver online se
+// retira la entrada volátil (engine.Remove), de modo que el feed se
+// auto-resuelve. Toma l.mu internamente.
+func (l *Live) trackOfflineDevices(devices []Device) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	for _, d := range devices {
+		if !d.NotifyOffline {
+			continue
+		}
+		if d.Online {
+			l.offlineOnline[d.MAC] = true
+			if l.offlineAlerted[d.MAC] {
+				l.offlineAlerted[d.MAC] = false
+				l.engine.Remove("alert-device-offline-" + d.MAC)
+			}
+			l.offlineMisses[d.MAC] = 0
+			continue
+		}
+		// Solo transiciones reales: MACs que ya vimos online en un ciclo previo.
+		if !l.offlineOnline[d.MAC] {
+			continue
+		}
+		l.offlineMisses[d.MAC]++
+		if l.offlineMisses[d.MAC] >= l.offlineAlertNum && !l.offlineAlerted[d.MAC] {
+			l.offlineAlerted[d.MAC] = true
+			l.emitDeviceOffline(d)
+		}
+	}
+}
+
+// emitDeviceOffline emite la alerta volátil de desconexión (category clients,
+// warn, urgente). ID estable por MAC: un incidente = una entrada del feed.
+// Debe llamarse con l.mu tomado.
+func (l *Live) emitDeviceOffline(d Device) {
+	name := d.Name
+	if name == "" {
+		name = d.MAC
+	}
+	router := l.routerDisplayName(d.RouterID)
+	l.engine.EmitVolatile(AlertEvent{
+		ID:       "alert-device-offline-" + d.MAC,
+		Category: alerts.CatClients, Urgent: true,
+		Severity:    "warn",
+		Title:       fmt.Sprintf("Device offline: %s", name),
+		Description: fmt.Sprintf("%s went offline on %s", name, router),
+		Hint:        alerts.HintFor(alerts.HintDeviceOffline),
+		Type:        alerts.TypeDeviceOffline,
+		Vars:        map[string]string{"device": name, "router": router},
+		Time:        "just now", RouterID: d.RouterID,
+	})
+}
+
 // insertDeviceEvent persiste una transición de presencia. Con db nil
 // (demo/tests sin BD) es no-op. Debe llamarse con l.mu tomado.
 func (l *Live) insertDeviceEvent(mac, routerID, state string, signalDbm *int, nowMs int64) {
@@ -2725,22 +2796,24 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	// issue #437/#797: overrides manuales de dispositivo (icono, nombre
 	// visible y tipo) sobre el dispositivo auto-descubierto.
 	type overrideInfo struct {
-		Icon        string
-		Name        string
-		DeviceType  string
-		BannedBands string
+		Icon          string
+		Name          string
+		DeviceType    string
+		BannedBands   string
+		NotifyOffline bool
 	}
 	deviceOverrides := map[string]overrideInfo{}
 	if l.db != nil {
-		if rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands FROM device_overrides"); err == nil {
+		if rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands, notify_offline FROM device_overrides"); err == nil {
 			for rows.Next() {
 				var mac, name, deviceType, bannedBands string
 				var icon sql.NullString
-				if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands); err == nil {
+				var notifyOffline bool
+				if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, &notifyOffline); err == nil {
 					// Clave en minúsculas: las MACs de los sondeos pueden
 					// llegar en cualquier caso y el lookup debe ser robusto
 					// (#797: icon overrides que "desaparecían" por caso).
-					deviceOverrides[strings.ToLower(mac)] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands}
+					deviceOverrides[strings.ToLower(mac)] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
 				}
 			}
 			rows.Close()
@@ -2875,6 +2948,10 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			d.Type = ov.DeviceType
 			d.TypeOverride = ov.DeviceType
 		}
+		// #1354: flag opt-in de alerta por desconexión (override persistido).
+		if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
+			d.NotifyOffline = ov.NotifyOffline
+		}
 		if isSeen {
 			d.RouterID = s.routerID
 			d.Band = s.band
@@ -3211,6 +3288,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	// re-emite la MAC en cada ciclo sin pasar por device_seen).
 	devices = l.filterTombstoned(devices)
 	l.trackUnknownDevices(devices, distNodes)
+	l.trackOfflineDevices(devices)
 	l.trackDevicePresence(devices, time.Now().UnixMilli())
 	// #954: first/last seen persistente de TODOS los clientes online.
 	l.noteDevicesSeen(devices, time.Now().UnixMilli())

+ 19 - 16
server-go/internal/adapters/types.go

@@ -265,7 +265,7 @@ type Device struct {
 	SpeedMbps int `json:"speedMbps,omitempty"`
 	// Infra: rol de infraestructura sellado server-side (Fase 4). La app NO
 	// infiere: pinta badge si viene. "hypervisor" (host Proxmox/VMware/…),
- 
+
 	// "ct" (contenedor anidado bajo hipervisor), "vm" (máquina virtual, que
 	// solo el inventario del hipervisor distingue de un contenedor),
 	// "managed-switch" (switch con gestión identificado por LLDP — hoy
@@ -289,6 +289,9 @@ type Device struct {
 	// el override crudo para que la UI de edición pueda mostrarlo y limpiarlo.
 	NameOverride string `json:"nameOverride,omitempty"`
 	TypeOverride string `json:"typeOverride,omitempty"`
+	// NotifyOffline (#1354): opt-in del usuario para alertar cuando este
+	// dispositivo se desconecta (override persistido notify_offline).
+	NotifyOffline bool `json:"notifyOffline,omitempty"`
 	// --- extras demo (omitempty = ausentes en live) ---
 	Hostname  string `json:"hostname,omitempty"`
 	DHCPLease string `json:"dhcpLease,omitempty"`
@@ -296,17 +299,17 @@ type Device struct {
 	// vio al cliente (#954; persistidos en la tabla device_seen). 0/ausente =
 	// desconocido. La app formatea en relativo con el locale del usuario; el
 	// server NO pre-formatea (lección #899).
-	FirstSeenMs  int64  `json:"firstSeenMs,omitempty"`
-	LastSeenMs   int64  `json:"lastSeenMs,omitempty"`
+	FirstSeenMs int64 `json:"firstSeenMs,omitempty"`
+	LastSeenMs  int64 `json:"lastSeenMs,omitempty"`
 	// AliasMacs: MACs enlazadas a este cliente (#1151, mismo dispositivo con
 	// varias MACs - p. ej. una por SSID). Solo viaja en el canónico.
-	AliasMacs []string `json:"aliasMacs,omitempty"`
-	Traffic24hRx string `json:"traffic24hRx,omitempty"`
-	Traffic24hTx string `json:"traffic24hTx,omitempty"`
-	Adguard      *bool  `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)
-	Group        string `json:"group,omitempty"`
-	IsNew        bool   `json:"isNew,omitempty"`
-	NewThisWeek  bool   `json:"newThisWeek,omitempty"`
+	AliasMacs    []string `json:"aliasMacs,omitempty"`
+	Traffic24hRx string   `json:"traffic24hRx,omitempty"`
+	Traffic24hTx string   `json:"traffic24hTx,omitempty"`
+	Adguard      *bool    `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)
+	Group        string   `json:"group,omitempty"`
+	IsNew        bool     `json:"isNew,omitempty"`
+	NewThisWeek  bool     `json:"newThisWeek,omitempty"`
 }
 
 // LldpInfo identifica un vecino que se anuncia por LLDP (switch gestionado,
@@ -566,11 +569,11 @@ type SfpInfo struct {
 // vecino en el detalle: connectedTo/deviceMac/detail, SPEC §7.8 + contadores
 // por puerto #305: iface física, bytes/errores acumulados y rates + SFP #313).
 type EthPort struct {
-	ID          string   `json:"id"`
-	Label       string   `json:"label"`
-	Up          bool     `json:"up"`
-	Speed       string   `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
-	Iface       string   `json:"iface,omitempty"` // iface física (/proc/net/dev)
+	ID    string `json:"id"`
+	Label string `json:"label"`
+	Up    bool   `json:"up"`
+	Speed string `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
+	Iface string `json:"iface,omitempty"` // iface física (/proc/net/dev)
 	// #1125: familia para interfaces NO físicas ("lag"|"vlan"|"bridge"|
 	// "tunnel"|"virtual"); vacío/ausente = boca física. El frontend las
 	// agrupa en la sección colapsada de la tarjeta de puertos.
@@ -593,7 +596,7 @@ type EthPort struct {
 	// cual (nombre/IP/alias). Valores: "router-link", "router-link-lldp",
 	// "ap-wifi", "curated", "inferred-switch".
 	PeerKind string `json:"peerKind,omitempty"`
-	Detail      string   `json:"detail,omitempty"`
+	Detail   string `json:"detail,omitempty"`
 	// Snmp indica que el puerto proviene de un switch gestionado por SNMP
 	// (issue #414). Se usa para aplicar histeresis temporal en ghost-port.
 	Snmp bool `json:"-"`

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

@@ -131,6 +131,10 @@ const (
 	TypeAutoRearmFailed    = "auto-rearm-failed"
 	TypeUplinkRestored     = "uplink-restored"
 	TypeSnmpRecovered      = "snmp-recovered"
+	// #1354: router offline (was reused from HintDeviceOffline, now its own slug)
+	// and client device offline (opt-in, volatile).
+	TypeRouterOffline = "router-offline"
+	TypeDeviceOffline = "device-offline"
 )
 
 // Hints maps each alert-type slug to its actionable suggestion. Emitters copy
@@ -191,7 +195,7 @@ type Engine struct {
 	// startedAt vienen de una sesión previa: si se re-emiten (update), es
 	// un episodio nuevo tras el reinicio y vuelven a no-leídas (#1094).
 	startedAt time.Time
-	now      func() time.Time
+	now       func() time.Time
 
 	cfg        map[string]string
 	list       []AlertEvent

+ 3 - 2
server-go/internal/alerts/alerts_i18n_test.go

@@ -20,6 +20,7 @@ var newTypeSlugs = []string{
 	TypeLinkDown, TypeLinkUp, TypeSfpRxLow, TypeSfpTempHigh,
 	TypeSwitchRebooted, TypeAgentRearmed, TypeAgentReinstalled,
 	TypeAutoRearmFailed, TypeUplinkRestored, TypeSnmpRecovered,
+	TypeRouterOffline,
 }
 
 // hintSlugs: slugs ya existentes en #310/#671 (con hint) para detectar colisiones.
@@ -48,8 +49,8 @@ func TestNewTypeSlugsAreKebabCaseAndUnique(t *testing.T) {
 		}
 		seen[slug] = true
 	}
-	if len(newTypeSlugs) != 22 {
-		t.Errorf("se esperan 22 slugs nuevos, hay %d", len(newTypeSlugs))
+	if len(newTypeSlugs) != 23 {
+		t.Errorf("se esperan 23 slugs nuevos, hay %d", len(newTypeSlugs))
 	}
 }
 

+ 18 - 7
server-go/internal/db/db.go

@@ -275,13 +275,14 @@ CREATE INDEX IF NOT EXISTS idx_update_history_ts ON update_history(ts DESC);
 -- bloqueo por banda. La clave es la MAC normalizada (minúsculas, ':').
 -- #797: name (nombre visible) y device_type (override del tipo clasificado).
 CREATE TABLE IF NOT EXISTS device_overrides (
-  mac         TEXT PRIMARY KEY,
-  icon        TEXT,
-  name        TEXT NOT NULL DEFAULT '',
-  device_type TEXT NOT NULL DEFAULT '',
-  banned_bands TEXT NOT NULL DEFAULT '', -- lista separada por comas: '2.4,5,6'
-  created_at  INTEGER NOT NULL,
-  updated_at  INTEGER NOT NULL
+  mac            TEXT PRIMARY KEY,
+  icon           TEXT,
+  name           TEXT NOT NULL DEFAULT '',
+  device_type    TEXT NOT NULL DEFAULT '',
+  banned_bands   TEXT NOT NULL DEFAULT '', -- lista separada por comas: '2.4,5,6'
+  notify_offline INTEGER NOT NULL DEFAULT 0, -- issue #1354: alert opt-in cuando se desconecta
+  created_at     INTEGER NOT NULL,
+  updated_at     INTEGER NOT NULL
 );
 
 -- Per-port time series (issue #302): raw (7d) -> 5m (1y) -> daily (forever).
@@ -617,6 +618,16 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	// issue #797: nombre visible y tipo de dispositivo sobreescritos a mano.
 	migrate(sqldb, "device_overrides", "name", "ALTER TABLE device_overrides ADD COLUMN name TEXT NOT NULL DEFAULT ''")
 	migrate(sqldb, "device_overrides", "device_type", "ALTER TABLE device_overrides ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
+	// issue #1354: opt-in alert when a marked device goes offline (0 = off).
+	migrate(sqldb, "device_overrides", "notify_offline", "ALTER TABLE device_overrides ADD COLUMN notify_offline INTEGER NOT NULL DEFAULT 0")
+
+	// #1354: las filas de alert_log tipadas "device-offline" son eventos de
+	// ROUTER offline (ese slug lo emitía trackRouterOffline antes de partirlo
+	// en router-offline). Discriminador idempotente: las filas del router
+	// llevan "host" en vars; las de cliente nuevas, no (vars = device/router).
+	if _, err := sqldb.Exec(`UPDATE alert_log SET type = 'router-offline' WHERE type = 'device-offline' AND vars LIKE '%"host"%'`); err != nil {
+		log.Printf("[netpulse] aviso: no se pudo migrar el tipo de alertas router-offline: %v", err)
+	}
 
 	// #817: port_series_raw tenía dos índices idénticos a su PK, creados por
 	// error en db.go y portseries.go. Se eliminan de forma idempotente (no se

+ 27 - 17
server-go/internal/httpapi/device_overrides.go

@@ -70,9 +70,10 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 		return
 	}
 	var body struct {
-		Icon *string `json:"icon"`
-		Name *string `json:"name"`
-		Type *string `json:"type"`
+		Icon          *string `json:"icon"`
+		Name          *string `json:"name"`
+		Type          *string `json:"type"`
+		NotifyOffline *bool   `json:"notifyOffline"`
 	}
 	if st := readJSONBody(w, r, &body); st != 0 {
 		writeBodyError(w, st, "invalid_body", "body JSON inválido")
@@ -101,8 +102,9 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	// Valores actuales (los campos ausentes conservan lo persistido).
 	var curIcon sql.NullString
 	var curName, curType string
-	row := s.db.QueryRow("SELECT icon, name, device_type FROM device_overrides WHERE mac = ?", mac)
-	switch err := row.Scan(&curIcon, &curName, &curType); err {
+	var curNotifyOffline bool
+	row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline FROM device_overrides WHERE mac = ?", mac)
+	switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline); err {
 	case nil:
 	case sql.ErrNoRows:
 	default:
@@ -111,6 +113,7 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	}
 	nextIcon := curIcon.String
 	nextName, nextType := curName, curType
+	nextNotifyOffline := curNotifyOffline
 	if body.Icon != nil {
 		nextIcon = *body.Icon
 	}
@@ -120,17 +123,21 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	if body.Type != nil {
 		nextType = *body.Type
 	}
+	if body.NotifyOffline != nil {
+		nextNotifyOffline = *body.NotifyOffline
+	}
 
 	now := time.Now().UnixMilli()
-	if nextIcon == "" && nextName == "" && nextType == "" {
+	if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline {
 		_, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
 	} else {
 		_, err := s.db.Exec(
-			`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, created_at, updated_at)
-			 VALUES (?, ?, ?, ?, '', ?, ?)
+			`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at)
+			 VALUES (?, ?, ?, ?, '', ?, ?, ?)
 			 ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
-			   device_type=excluded.device_type, updated_at=excluded.updated_at`,
-			mac, nextIcon, nextName, nextType, now, now,
+			   device_type=excluded.device_type, notify_offline=excluded.notify_offline,
+			   updated_at=excluded.updated_at`,
+			mac, nextIcon, nextName, nextType, nextNotifyOffline, now, now,
 		)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "db_error", err.Error())
@@ -143,6 +150,7 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	}
 	writeJSON(w, http.StatusOK, map[string]any{
 		"ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
+		"notifyOffline": nextNotifyOffline,
 	})
 }
 
@@ -154,17 +162,19 @@ func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request)
 		return
 	}
 	var icon, name, deviceType, banned sql.NullString
-	row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands FROM device_overrides WHERE mac = ?", mac)
-	if err := row.Scan(&icon, &name, &deviceType, &banned); err != nil && err != sql.ErrNoRows {
+	var notifyOffline bool
+	row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline FROM device_overrides WHERE mac = ?", mac)
+	if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline); err != nil && err != sql.ErrNoRows {
 		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
 		return
 	}
 	writeJSON(w, http.StatusOK, map[string]any{
-		"mac":         mac,
-		"icon":        icon.String,
-		"name":        name.String,
-		"type":        deviceType.String,
-		"bannedBands": banned.String,
+		"mac":           mac,
+		"icon":          icon.String,
+		"name":          name.String,
+		"type":          deviceType.String,
+		"bannedBands":   banned.String,
+		"notifyOffline": notifyOffline,
 	})
 }
 

+ 42 - 3
server-go/internal/httpapi/device_overrides_test.go

@@ -48,16 +48,55 @@ func doOverrideGet(t *testing.T, s *server, mac string) map[string]any {
 func TestDeviceOverrideNameTypeRoundtrip(t *testing.T) {
 	s := newOverrideTestServer(t)
 	mac := "aa:bb:cc:dd:ee:ff"
-	rec := doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv"}`)
+	rec := doOverridePut(t, s, mac, `{"icon":"tv","name":"TV Salón","type":"tv","notifyOffline":true}`)
 	if rec.Code != 200 {
 		t.Fatalf("put: %d %s", rec.Code, rec.Body.String())
 	}
 	got := doOverrideGet(t, s, mac)
-	if got["icon"] != "tv" || got["name"] != "TV Salón" || got["type"] != "tv" {
+	if got["icon"] != "tv" || got["name"] != "TV Salón" || got["type"] != "tv" || got["notifyOffline"] != true {
 		t.Errorf("roundtrip incompleto: %+v", got)
 	}
 }
 
+func TestDeviceOverrideNotifyOffline(t *testing.T) {
+	s := newOverrideTestServer(t)
+	mac := "aa:bb:cc:dd:ee:ff"
+
+	// Marcar opt-in: persiste el flag aunque icon/name/type queden vacíos.
+	if rec := doOverridePut(t, s, mac, `{"notifyOffline":true}`); rec.Code != 200 {
+		t.Fatalf("notifyOffline true: %d", rec.Code)
+	}
+	if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
+		t.Errorf("notifyOffline no persistió: %+v", got)
+	}
+
+	// Apagar el flag con el resto vacío: la fila se borra (cero estado).
+	if rec := doOverridePut(t, s, mac, `{"notifyOffline":false}`); rec.Code != 200 {
+		t.Fatalf("notifyOffline false: %d", rec.Code)
+	}
+	var n int
+	if err := s.db.QueryRow("SELECT COUNT(*) FROM device_overrides WHERE mac = ?", mac).Scan(&n); err != nil {
+		t.Fatalf("count: %v", err)
+	}
+	if n != 0 {
+		t.Errorf("la fila debió borrarse con notifyOffline=false y sin más campos, quedaron %d", n)
+	}
+
+	// El flag se conserva ante un put parcial que no lo envía (cliente antiguo).
+	doOverridePut(t, s, mac, `{"name":"TV","notifyOffline":true}`)
+	if rec := doOverridePut(t, s, mac, `{"icon":"tv"}`); rec.Code != 200 {
+		t.Fatalf("put parcial: %d", rec.Code)
+	}
+	if got := doOverrideGet(t, s, mac); got["notifyOffline"] != true {
+		t.Errorf("el put parcial pisó notifyOffline: %+v", got)
+	}
+
+	// Tipo inválido (string en un bool): el decode falla y devuelve 400.
+	if rec := doOverridePut(t, s, mac, `{"notifyOffline":"yes"}`); rec.Code != 400 {
+		t.Errorf("notifyOffline no booleano debió dar 400, dio %d", rec.Code)
+	}
+}
+
 func TestDeviceOverridePartialPutPreservesOthers(t *testing.T) {
 	s := newOverrideTestServer(t)
 	mac := "aa:bb:cc:dd:ee:ff"
@@ -123,7 +162,7 @@ func TestDeviceOverrideValidation(t *testing.T) {
 // con PathValue, como el resto de tests de handlers con PathValue).
 func TestDeviceDelete(t *testing.T) {
 	s := panelTestServer(t)
-	if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('AA:BB:CC:DD:EE:FF', 1, 2, 'watch')", ); err != nil {
+	if _, err := s.db.Exec("INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES ('AA:BB:CC:DD:EE:FF', 1, 2, 'watch')"); err != nil {
 		t.Fatalf("seed: %v", err)
 	}