Kaynağa Gözat

feat(routers): show why an integration unit is offline (#1714)

Nacho 1 ay önce
ebeveyn
işleme
4fb1c2a1cf

+ 1 - 0
CHANGELOG.md

@@ -19,6 +19,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ### Added
 
 - Inactive agents in the fleet table now offer Rearm, Reinstall and the copyable install command next to Remove, so a rejected token (HTTP 401 after a reboot or a server move) can be fixed without removing the agent or losing its history. NetGrip rows offer Rearm only and external pushers keep Remove only.
+- The card and the detail of a unit pushed by an integration (RouterOS and other vendors) show why it is offline: authentication rejected, missing API endpoint (old firmware, REST needs RouterOS 7+), connection refused or pusher stopped, with the raw pusher error on the tooltip.
 - The on-box server init script now refuses to start when its data dir is not a real mount (default overlay paths excluded), so an unmounted USB stick can no longer leave a fresh SQLite database on flash. It also moves to `START=99` to let USB mounts settle first.
 
 ### Changed

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

@@ -1142,7 +1142,8 @@
       "peersConnected": "Connected peers",
       "serverActive": "Server active",
       "transfer30d": "Transfer 30 d"
-    }
+    },
+    "statusReasonTitle": "Why this unit is down"
   },
   "routers": {
     "agent": {
@@ -1309,7 +1310,14 @@
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s",
     "noVitals": "No system metrics",
-    "noVitalsTip": "Monitored through SNMP or a beacon: this unit does not report CPU, RAM or temperature"
+    "noVitalsTip": "Monitored through SNMP or a beacon: this unit does not report CPU, RAM or temperature",
+    "statusReason": {
+      "pusher_auth_failed": "Authentication rejected: the device does not accept the stored credentials (wrong user or password).",
+      "pusher_api_not_found": "The API endpoint does not exist: the firmware is too old for the REST API (RouterOS 7 or newer required).",
+      "pusher_conn_refused": "Connection refused: the device is not answering on the API service or port (check www/www-ssl or api, and the firewall).",
+      "pusher_stopped": "The integration pusher is stopped: start it from Settings > Integrations.",
+      "pusher_error": "The integration pusher logged an error; check its details in Settings > Integrations."
+    }
   },
   "reports": {
     "availability": "Availability per router",

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

@@ -1142,7 +1142,8 @@
       "peersConnected": "Peers conectados",
       "serverActive": "Servidor activo",
       "transfer30d": "Transferencia 30 d"
-    }
+    },
+    "statusReasonTitle": "Por qué está caída esta unidad"
   },
   "routers": {
     "agent": {
@@ -1309,7 +1310,14 @@
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s",
     "noVitals": "Sin métricas de sistema",
-    "noVitalsTip": "Monitorizado por SNMP o beacon: este equipo no reporta CPU, RAM ni temperatura"
+    "noVitalsTip": "Monitorizado por SNMP o beacon: este equipo no reporta CPU, RAM ni temperatura",
+    "statusReason": {
+      "pusher_auth_failed": "Autenticación rechazada: el equipo no acepta las credenciales guardadas (usuario o contraseña incorrectos).",
+      "pusher_api_not_found": "El endpoint de la API no existe: el firmware es demasiado viejo para el API REST (RouterOS necesita 7 o superior).",
+      "pusher_conn_refused": "Conexión rechazada: el equipo no responde en el servicio o puerto de la API (revisa www/www-ssl o api, y el firewall).",
+      "pusher_stopped": "El pusher de la integración está parado: arráncalo desde Ajustes > Integraciones.",
+      "pusher_error": "El pusher de la integración registró un error; revisa su detalle en Ajustes > Integraciones."
+    }
   },
   "reports": {
     "availability": "Disponibilidad por router",

+ 16 - 1
app/src/components/RouterCard.tsx

@@ -1,5 +1,5 @@
 import { Link } from 'react-router'
-import { ChevronRight, Cpu, MemoryStick, Router as RouterIcon, Thermometer, Users } from 'lucide-react'
+import { ChevronRight, Cpu, MemoryStick, Router as RouterIcon, Thermometer, TriangleAlert, Users } from 'lucide-react'
 import { motion } from 'framer-motion'
 import type { LucideIcon } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
@@ -104,6 +104,21 @@ export function RouterCard({ router, index = 0, className }: RouterCardProps) {
           <MiniMetric icon={Users} value={String(router.clients)} label={t('common.clients')} />
         </div>
 
+        {/* #1703: motivo de caída de una unidad empujada por una integración
+            (RouterOS y resto de vendors): credenciales rechazadas, endpoint
+            ausente (firmware viejo), conexión rechazada o pusher parado. El
+            texto crudo del último error va en el tooltip. Las unidades con
+            pusher nunca llegan "unreachable" (eso exige sondeo SSH). */}
+        {offline && router.statusReason && (
+          <p
+            className="mt-3 flex items-center gap-1.5 text-caption font-medium text-danger"
+            title={router.statusReasonMsg || undefined}
+          >
+            <TriangleAlert className="h-3.5 w-3.5 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+            {t(`routers.statusReason.${router.statusReason}`, { defaultValue: router.statusReason })}
+          </p>
+        )}
+
         <div className="mt-4 flex items-center justify-between gap-3 border-t border-border pt-3">
           <Sparkline data={router.sparkline} width={100} height={28} color={STATUS_COLORS[router.status] === '#34D399' ? '#22D3EE' : STATUS_COLORS[router.status]} />
           <div className="flex items-center gap-2">

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

@@ -47,6 +47,14 @@ export interface Router {
    * re-onboard explícito (POST /api/routers/{id}/accept-host-key).
    */
   hostKeyChanged?: boolean
+  /**
+   * #1703: motivo de caída de una unidad empujada por una integración
+   * (p. ej. RouterOS): código estable que la UI traduce a texto. Solo llega
+   * con la unidad offline/unreachable y con integración detrás.
+   */
+  statusReason?: string
+  /** #1703: último error crudo del pusher, para el tooltip del motivo. */
+  statusReasonMsg?: string
   /**
    * #441: false cuando la fuente del router no puede reportar métricas de
    * sistema (switch SNMP o pusher beacon/scraper). En ese caso cpu/ram/temp

+ 24 - 0
app/src/pages/RouterDetail.tsx

@@ -215,6 +215,30 @@ export default function RouterDetail() {
         </motion.div>
       )}
 
+      {/* #1703: motivo de caída de una unidad empujada por una integración
+          (RouterOS y resto de vendors). El detalle es donde el admin acaba
+          cuando la tarjeta le manda aquí: el motivo completo con el error
+          crudo del pusher en el tooltip. Las unidades con pusher nunca
+          llegan "unreachable" (eso exige sondeo SSH). */}
+      {router.status === 'offline' && router.statusReason && (
+        <motion.div
+          initial={reduce ? false : { opacity: 0, y: -8 }}
+          animate={{ opacity: 1, y: 0 }}
+          transition={{ duration: 0.3, ease: 'easeOut', delay: 0.35 }}
+          className="lg:col-span-12"
+        >
+          <div role="alert" className="flex items-start gap-3 rounded-2xl border border-danger/50 bg-danger/10 px-5 py-4">
+            <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-danger" strokeWidth={1.75} />
+            <div className="min-w-0 flex-1" title={router.statusReasonMsg || undefined}>
+              <div className="text-sm font-semibold text-danger">{t('routerDetail.statusReasonTitle')}</div>
+              <p className="mt-0.5 text-sm text-text-secondary">
+                {t(`routers.statusReason.${router.statusReason}`, { defaultValue: router.statusReason })}
+              </p>
+            </div>
+          </div>
+        </motion.div>
+      )}
+
       {/* #1369: lldpd escuchando solo en el bridge (br-lan) → 0 vecinos LLDP
           silencioso en nss-dp/DSA. El agente lo detecta y avisa aquí. */}
       {router.lldpHint === 'lldpd-bridge-only' && (

+ 7 - 0
docs/external-integrations.md

@@ -123,6 +123,13 @@ Contract rules:
 
 The working RouterOS implementation in [`netpulse-integrations/routeros`](https://github.com/gnacho/netpulse-integrations/tree/main/routeros) shows configuration, token use, signing and pushing. RouterOS is supported only through this integration: the server has no RouterOS adapter or credentials. It is also a reference for the transport, not a template that requires copying the whole native agent.
 
+RouterOS requirements for the integration:
+
+- **RouterOS 7 or newer.** The REST API arrived in RouterOS 7.1, and the `www` service serves it from 7.9; on older versions only the binary API path works. On RouterOS 6 with only the web service enabled the unit shows offline.
+- **The `www-ssl` (preferred) or `www` service enabled** (`IP > Services`). The pusher prefers the binary API (`api`, port 8728) when it is reachable and falls back to REST on the web service, so the `api` and `api-ssl` services are not required: web-only is a supported setup with reduced coverage (system identity and resource only).
+- **Account policies `api`, `rest-api` and `read`** (`System > Users`): the REST API logs the user in through the API, so the group needs both policies plus read access. The built-in read-only groups already carry them.
+- When the unit goes offline, the router card and the router detail show the reason the pusher last logged: authentication rejected (wrong credentials), API endpoint not found (firmware too old for REST), connection refused (service or firewall) or pusher stopped. The raw error is on the tooltip.
+
 Asuswrt/Merlin follows the same external contract through [`netpulse-integrations/asuswrt`](https://github.com/gnacho/netpulse-integrations/tree/main/asuswrt). It reuses the portable probes from `agent/probe`, but not the native command, backup or upgrade runtime. Existing `asuswrt` router rows migrate to `external` with their agent tokens preserved.
 
 ## Preserve the meaning of the data

+ 1 - 0
docs/manual.en.md

@@ -107,6 +107,7 @@ Routers are onboarded under **Settings > Devices** (see the onboarding procedure
 - The **colored dot** per router: green = online, amber = warned (for example high temperature), red = down.
 - The **card** summarizes the key metrics; the warning icon appears when temperature exceeds the threshold.
 - In the **agents section**, "Agent down" means the agent was registered but stopped reporting. It may be a stopped process or a rejected token (for example after moving the server): rearm first and, if it still does not push, reinstall (see the recovery procedure below).
+- A unit pushed by an **integration** (RouterOS and other vendors) that shows "Offline" also shows the reason on its card: authentication rejected, missing API endpoint (old firmware, REST arrived in RouterOS 7), connection refused or pusher stopped. The RouterOS requirements live in the external integrations doc.
 - "No system metrics" means that device is monitored by SNMP or beacon and does not report CPU/RAM/temperature.
 
 ### Design decisions

+ 1 - 0
docs/manual.es.md

@@ -107,6 +107,7 @@ Los routers se dan de alta en **Ajustes > Dispositivos** (ver el procedimiento d
 - El **punto de color** de cada router: verde = online, ámbar = con aviso (por ejemplo temperatura alta), rojo = caído.
 - La **tarjeta** resume las métricas clave; el icono de aviso aparece cuando la temperatura supera el umbral.
 - En la **sección de agentes**, "Agente caído" significa que el agente estaba registrado pero dejó de reportar. Puede ser un proceso parado o un token rechazado (por ejemplo tras mover el servidor): rearma primero y, si sigue sin empujar, reinstala (ver el procedimiento de recuperación más abajo).
+- Una unidad empujada por una **integración** (RouterOS y resto de vendors) que aparece "Offline" muestra también el motivo en su tarjeta: autenticación rechazada, endpoint de la API inexistente (firmware viejo, el REST llega en RouterOS 7), conexión rechazada o pusher parado. Los requisitos de RouterOS están en la documentación de integraciones externas.
 - "Sin métricas de sistema" indica que ese dispositivo se monitoriza por SNMP o por beacon y no reporta CPU/RAM/temperatura.
 
 ### Decisiones de diseño

+ 8 - 6
server-go/cmd/netpulse/main.go

@@ -662,6 +662,11 @@ func run() error {
 	// alertas de "velocidad por debajo del plan" se emiten por el MISMO
 	// motor del adapter (la lista de eventos es por instancia). Solo en
 	// live: en demo no hay red real que medir y las rutas quedan en 503.
+	// Supervisor de pushers externos (#1674): procesos en memoria como usuario
+	// netpulse (sin systemd). La raíz de datos vive bajo DATA_DIR/integrations.
+	// Se crea antes del SetEnrich (#1703) para que el snapshot SSE lleve el
+	// motivo de caída de las integraciones igual que /api/overview.
+	integrationsMgr := rintegration.NewManager(filepath.Join(cfg.DataDir, "integrations"))
 	var stScheduler *speedtest.Scheduler
 	if !cfg.DemoMode {
 		stStore, err := speedtest.NewStore(dbHandle.DB)
@@ -677,9 +682,10 @@ func run() error {
 		})
 		// El snapshot SSE debe llevar las mismas inyecciones kv que
 		// /api/overview (contratado #151, speedtest #511): sin esto el
-		// primer evento pisaría los campos en la UI.
+		// primer evento pisaría los campos en la UI. #1703: también el
+		// motivo de caída de las unidades empujadas por integraciones.
 		p.SetEnrich(func(ov *adapters.Overview) {
-			httpapi.EnrichOverview(dbHandle.DB, stScheduler, ov)
+			httpapi.EnrichOverview(dbHandle.DB, stScheduler, ov, rintegration.StatusReasons(dbHandle.DB, integrationsMgr))
 			// #887: el snapshot SSE también lleva el uptime para la gracia
 			// post-arranque en el frontend.
 			ov.ServerUptimeSec = int64(time.Since(serverStarted).Seconds())
@@ -770,10 +776,6 @@ func run() error {
 		log.Printf("[netpulse] aviso: NETPULSE_MCP_ENABLED=1 pero no hay token store; MCP desactivado")
 	}
 
-	// Supervisor de pushers externos (#1674): procesos en memoria como usuario
-	// netpulse (sin systemd). La raíz de datos vive bajo DATA_DIR/integrations.
-	integrationsMgr := rintegration.NewManager(filepath.Join(cfg.DataDir, "integrations"))
-
 	// Catálogo de vendors por descubrimiento (#1697): fetch de vendors.json
 	// del repo de integraciones con TTL y caché en kv, semilla embebida como
 	// respaldo offline.

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

@@ -195,6 +195,15 @@ type Router struct {
 	// (issue #603). Se rechaza la conexión (posible MITM) hasta que el admin
 	// confirme el re-onboard explícito tras verificar fuera de banda.
 	HostKeyChanged bool `json:"hostKeyChanged,omitempty"`
+	// StatusReason (#1703): código estable del motivo de caída de una unidad
+	// empujada por una integración (p. ej. RouterOS): credenciales rechazadas,
+	// endpoint ausente (firmware viejo), conexión rechazada o pusher parado.
+	// Lo inyecta EnrichOverview desde la tabla router_integrations y el log
+	// del pusher; la UI lo traduce y solo lo pinta con la unidad caída.
+	StatusReason string `json:"statusReason,omitempty"`
+	// StatusReasonMsg (#1703): texto crudo del último error registrado del
+	// pusher, para el tooltip junto al motivo traducido.
+	StatusReasonMsg string `json:"statusReasonMsg,omitempty"`
 	// VitalsAvailable: false cuando la fuente de datos del router no puede
 	// reportar métricas de sistema (#441): switches sondeados por SNMP (#309)
 	// o pushers externos por beacon/scraper (#291). En ese caso CPU/RAM/Temp

+ 30 - 2
server-go/internal/httpapi/data.go

@@ -16,6 +16,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
 	"github.com/gnacho/netpulse/server-go/internal/roamcfg"
 	"github.com/gnacho/netpulse/server-go/internal/roamevents"
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
@@ -123,17 +124,29 @@ func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
 	out.Alerts = engine.List()
 	out.UnreadAlerts = engine.UnreadCount()
 	out.ServerUptimeSec = int64(time.Since(s.started).Seconds())
-	EnrichOverview(s.db.DB, s.speedtest, &out)
+	EnrichOverview(s.db.DB, s.speedtest, &out, s.pusherStatusReasons())
 	writeJSON(w, http.StatusOK, &out)
 }
 
+// pusherStatusReasons (#1703): motivo de caída por slug de integración, para
+// que la tarjeta de la unidad muestre POR QUÉ está offline. nil sin base de
+// datos o sin supervisor de pushers (demo).
+func (s *server) pusherStatusReasons() map[string]string {
+	if s.db == nil || s.integrations == nil {
+		return nil
+	}
+	return rintegration.StatusReasons(s.db.DB, s.integrations)
+}
+
 // EnrichOverview inyecta los campos que viven en el kv del server (menú de
 // orquestación #121, velocidad contratada #151 y última medición del
 // speedtest #511). La usan handleOverview Y el poller antes de emitir el
 // snapshot SSE: sin la segunda, el evento pisaría la copia enriquecida del
 // HTTP y los campos desaparecerían de la UI al primer snapshot (bug
 // preexistente de #151 que el speedtest hizo evidente).
-func EnrichOverview(handle *sql.DB, sched *speedtest.Scheduler, out *adapters.Overview) {
+// pusherReasons (#1703) es el mapa slug->motivo de las integraciones que no
+// están empujando; solo se aplica a unidades caídas.
+func EnrichOverview(handle *sql.DB, sched *speedtest.Scheduler, out *adapters.Overview, pusherReasons map[string]string) {
 	// Menú de orquestación: opt-in por admin (#121). Se expone aquí (no en
 	// el adapter) porque el kv vive en el server, no en el poller.
 	out.Orchestration = kvGetBool(handle, orchestrationKey)
@@ -165,6 +178,21 @@ func EnrichOverview(handle *sql.DB, sched *speedtest.Scheduler, out *adapters.Ov
 			out.WAN.SpeedtestServer = last.ServerName
 		}
 	}
+	// #1703: motivo de caída de las unidades empujadas por integraciones
+	// (RouterOS y resto de vendors). Solo con la unidad caída: una unidad
+	// online no tiene nada que explicar, y "unreachable" por SSH lleva sus
+	// propios avisos (accessMissing/hostKeyChanged).
+	if len(pusherReasons) > 0 {
+		for i := range out.Routers {
+			r := &out.Routers[i]
+			if r.Status != "offline" && r.Status != "unreachable" {
+				continue
+			}
+			if code, ok := pusherReasons[r.ID]; ok {
+				r.StatusReason = code
+			}
+		}
+	}
 }
 
 // fmtContractPlan formatea el par contratado para el campo plan del overview:

+ 4 - 4
server-go/internal/httpapi/data_internal_test.go

@@ -20,7 +20,7 @@ func TestEnrichOverviewPlanFromContract(t *testing.T) {
 		t.Fatalf("set up: %v", err)
 	}
 	out := &adapters.Overview{WAN: adapters.WAN{Plan: "—"}}
-	EnrichOverview(db, nil, out)
+	EnrichOverview(db, nil, out, nil)
 	if out.WAN.Plan != "600/100 Mbps" {
 		t.Fatalf("plan = %q, esperado %q", out.WAN.Plan, "600/100 Mbps")
 	}
@@ -35,7 +35,7 @@ func TestEnrichOverviewPlanKeepsDecimals(t *testing.T) {
 	_ = kvSetFloat(db, wanSpeedDownKey, 94.9)
 	_ = kvSetFloat(db, wanSpeedUpKey, 9.4)
 	out := &adapters.Overview{WAN: adapters.WAN{Plan: "—"}}
-	EnrichOverview(db, nil, out)
+	EnrichOverview(db, nil, out, nil)
 	if out.WAN.Plan != "94.9/9.4 Mbps" {
 		t.Fatalf("plan = %q, esperado %q", out.WAN.Plan, "94.9/9.4 Mbps")
 	}
@@ -48,7 +48,7 @@ func TestEnrichOverviewPlanNotClobbered(t *testing.T) {
 	_ = kvSetFloat(db, wanSpeedDownKey, 600)
 	_ = kvSetFloat(db, wanSpeedUpKey, 100)
 	out := &adapters.Overview{WAN: adapters.WAN{Plan: "600/600 Mbps"}}
-	EnrichOverview(db, nil, out)
+	EnrichOverview(db, nil, out, nil)
 	if out.WAN.Plan != "600/600 Mbps" {
 		t.Fatalf("plan = %q, no debe pisarse con el contrato", out.WAN.Plan)
 	}
@@ -59,7 +59,7 @@ func TestEnrichOverviewPlanNotClobbered(t *testing.T) {
 func TestEnrichOverviewPlanSinContrato(t *testing.T) {
 	db := newTestKV(t)
 	out := &adapters.Overview{WAN: adapters.WAN{Plan: "—"}}
-	EnrichOverview(db, nil, out)
+	EnrichOverview(db, nil, out, nil)
 	if out.WAN.Plan != "—" {
 		t.Fatalf("plan = %q, esperado sin cambios", out.WAN.Plan)
 	}

+ 52 - 0
server-go/internal/httpapi/data_reasons_test.go

@@ -0,0 +1,52 @@
+// data_reasons_test.go — #1703: EnrichOverview inyecta el motivo de caída de
+// las unidades empujadas por integraciones solo cuando están offline o
+// unreachable; las online no llevan motivo.
+package httpapi_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+)
+
+func TestEnrichOverviewAppliesPusherReasons(t *testing.T) {
+	// EnrichOverview lee kv: necesita una base real (panic con nil).
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	handle := d.DB
+	ov := &adapters.Overview{
+		Routers: []adapters.Router{
+			{ID: "hex", Type: "external", Status: "offline"},
+			{ID: "hex-ok", Type: "external", Status: "online"},
+			{ID: "gw", Type: "glinet", Status: "unreachable"},
+		},
+	}
+	reasons := map[string]string{
+		"hex":    "pusher_auth_failed",
+		"gw":     "pusher_stopped",
+		"hex-ok": "pusher_auth_failed", // unidad online: no debe aplicarse
+	}
+	httpapi.EnrichOverview(handle, nil, ov, reasons)
+
+	if got := ov.Routers[0].StatusReason; got != "pusher_auth_failed" {
+		t.Errorf("hex: StatusReason = %q, want pusher_auth_failed", got)
+	}
+	if got := ov.Routers[1].StatusReason; got != "" {
+		t.Errorf("hex-ok (online): StatusReason = %q, want empty", got)
+	}
+	if got := ov.Routers[2].StatusReason; got != "pusher_stopped" {
+		t.Errorf("gw (unreachable): StatusReason = %q, want pusher_stopped", got)
+	}
+
+	// Sin motivos (demo / sin integraciones): nada cambia.
+	ov2 := &adapters.Overview{Routers: []adapters.Router{{ID: "hex", Type: "external", Status: "offline"}}}
+	httpapi.EnrichOverview(handle, nil, ov2, nil)
+	if ov2.Routers[0].StatusReason != "" {
+		t.Errorf("nil reasons: StatusReason = %q, want empty", ov2.Routers[0].StatusReason)
+	}
+}

+ 203 - 0
server-go/internal/rintegration/reason.go

@@ -0,0 +1,203 @@
+package rintegration
+
+import (
+	"database/sql"
+	"os"
+	"path/filepath"
+	"strconv"
+	"strings"
+	"time"
+)
+
+// Códigos estables de motivo de caída de una integración (issue #1703). La UI
+// los traduce a texto; un código desconocido se muestra tal cual.
+const (
+	ReasonAuthFailed  = "pusher_auth_failed"
+	ReasonAPINotFound = "pusher_api_not_found"
+	ReasonConnRefused = "pusher_conn_refused"
+	ReasonStopped     = "pusher_stopped"
+	ReasonError       = "pusher_error"
+)
+
+// logTailBytes acota la lectura del log del pusher: los fallos se repiten en
+// cada ciclo (el intervalo típico es de 30-60 s), así que el último error de
+// poll está siempre en la cola del fichero.
+const logTailBytes = 16 * 1024
+
+// LastPollError devuelve el mensaje del último "collection failed" del log del
+// pusher de slug (vacío si no hay ninguno o el log no existe). El pusher
+// registra cada fallo de poll con slog y reintenta en el ciclo siguiente, así
+// que la cola del log es la única fuente del motivo concreto (401, conexión
+// rechazada, endpoint ausente...) cuando deja de empujar.
+func (m *Manager) LastPollError(slug string) string {
+	if m == nil || slug == "" {
+		return ""
+	}
+	data, err := readLastBytes(filepath.Join(m.dir, slug+".log"), logTailBytes)
+	if err != nil {
+		return ""
+	}
+	lines := strings.Split(string(data), "\n")
+	for i := len(lines) - 1; i >= 0; i-- {
+		line := lines[i]
+		if !strings.Contains(line, "collection failed") {
+			continue
+		}
+		return slogErrValue(line)
+	}
+	return ""
+}
+
+// readLastBytes devuelve como máximo los últimos n bytes de path.
+func readLastBytes(path string, n int64) ([]byte, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return nil, err
+	}
+	defer f.Close()
+	st, err := f.Stat()
+	if err != nil {
+		return nil, err
+	}
+	if st.Size() > n {
+		if _, err := f.Seek(-n, 2); err != nil {
+			return nil, err
+		}
+	}
+	buf := make([]byte, min64(n, st.Size()))
+	if _, err := f.Read(buf); err != nil && len(buf) == 0 {
+		return nil, err
+	}
+	return buf, nil
+}
+
+func min64(a, b int64) int64 {
+	if a < b {
+		return a
+	}
+	return b
+}
+
+// slogErrValue extrae el valor de err="..." de una línea de slog en formato
+// texto, des-escapando las secuencias que escribe el handler.
+func slogErrValue(line string) string {
+	i := strings.LastIndex(line, `err="`)
+	if i < 0 {
+		// Forma sin comillas (valor sin espacios): resto de la línea.
+		if j := strings.LastIndex(line, "err="); j >= 0 {
+			return strings.TrimSpace(line[j+4:])
+		}
+		return ""
+	}
+	rest := line[i+5:]
+	var b strings.Builder
+	for k := 0; k < len(rest); k++ {
+		c := rest[k]
+		if c == '\\' && k+1 < len(rest) {
+			k++
+			switch rest[k] {
+			case 'n':
+				b.WriteByte('\n')
+			case 't':
+				b.WriteByte('\t')
+			default:
+				b.WriteByte(rest[k])
+			}
+			continue
+		}
+		if c == '"' {
+			break
+		}
+		b.WriteByte(c)
+	}
+	return b.String()
+}
+
+// ClassifyPollError mapea el texto de error de un pusher a un código estable
+// de motivo. Los patrones cubren los fallos observables de un poll: credenciales
+// rechazadas (401/unauthorized), endpoint REST ausente (404: firmware viejo,
+// el REST llega en RouterOS 7) y familia de conexión (refused/timeout/route).
+// Cualquier otro error no vacío cae al código genérico.
+func ClassifyPollError(msg string) string {
+	m := strings.ToLower(msg)
+	switch {
+	case m == "":
+		return ""
+	case strings.Contains(m, "401"),
+		strings.Contains(m, "unauthorized"),
+		strings.Contains(m, "invalid user name or password"),
+		strings.Contains(m, "bad username"):
+		return ReasonAuthFailed
+	case strings.Contains(m, "404"), strings.Contains(m, "not found"):
+		return ReasonAPINotFound
+	case strings.Contains(m, "connection refused"),
+		strings.Contains(m, "no route to host"),
+		strings.Contains(m, "i/o timeout"),
+		strings.Contains(m, "host is down"),
+		strings.Contains(m, "connection reset"):
+		return ReasonConnRefused
+	default:
+		return ReasonError
+	}
+}
+
+// StatusReasons calcula slug -> código de motivo para las integraciones cuya
+// unidad no está empujando (issue #1703): la tarjeta del router lo muestra
+// junto al estado offline. Se omite una integración deshabilitada (la UI ya la
+// pinta "paused") y una con push fresco (los códigos de frescura son los
+// mismos que usa la vista de integraciones: 3 intervalos). El estado "stopped"
+// es motivo por sí mismo; el resto clasifica el último error registrado
+// (LastError de instalación, o el log del pusher para fallos de poll).
+func StatusReasons(db *sql.DB, m *Manager) map[string]string {
+	if db == nil || m == nil {
+		return nil
+	}
+	rows, err := NewStore(db).List()
+	if err != nil {
+		return nil
+	}
+	out := map[string]string{}
+	for _, r := range rows {
+		if !r.Enabled {
+			continue
+		}
+		code := ""
+		switch r.State {
+		case "stopped":
+			code = ReasonStopped
+		default:
+			if freshPush(db, r) {
+				continue
+			}
+			if r.State == "error" && r.LastError != "" {
+				code = ClassifyPollError(r.LastError)
+			}
+			if code == "" || code == ReasonError {
+				if msg := m.LastPollError(r.Slug); msg != "" {
+					code = ClassifyPollError(msg)
+				}
+			}
+		}
+		if code != "" {
+			out[r.Slug] = code
+		}
+	}
+	return out
+}
+
+// freshPush: la integración empujó dentro de 3 intervalos (misma regla que
+// integrationItemOf en httpapi). Lee agent.last_push_ts.<slug> del kv.
+func freshPush(db *sql.DB, r Row) bool {
+	if r.IntervalS <= 0 {
+		return false
+	}
+	val, ok := kvGet(db, "agent.last_push_ts."+r.Slug)
+	if !ok {
+		return false
+	}
+	sec, err := strconv.ParseInt(val, 10, 64)
+	if err != nil || sec <= 0 {
+		return false
+	}
+	return time.Now().Unix()-sec <= int64(r.IntervalS)*3
+}

+ 155 - 0
server-go/internal/rintegration/reason_test.go

@@ -0,0 +1,155 @@
+package rintegration
+
+import (
+	"database/sql"
+	"fmt"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func TestClassifyPollError(t *testing.T) {
+	cases := []struct {
+		msg  string
+		want string
+	}{
+		{"", ""},
+		// REST 401 y login fallido por la API binaria.
+		{`routeros: GET /rest/system/resource: 401 Unauthorized: {"message":"bad username and password"}`, ReasonAuthFailed},
+		{`routeros api: login: invalid user name or password`, ReasonAuthFailed},
+		// Endpoint ausente: firmware sin REST (RouterOS 6 con solo www).
+		{`routeros: GET /rest/system/resource: 404 Not Found: <html>`, ReasonAPINotFound},
+		// Familia de conexión.
+		{`routeros api: dial tcp 10.0.0.1:8728: connect: connection refused; rest: dial tcp: connection refused`, ReasonConnRefused},
+		{`routeros: GET /rest/system/resource: context deadline exceeded (i/o timeout)`, ReasonConnRefused},
+		// Cualquier otro error no vacío cae al genérico.
+		{"routeros: no rows from /system/resource/print", ReasonError},
+	}
+	for _, c := range cases {
+		if got := ClassifyPollError(c.msg); got != c.want {
+			t.Errorf("ClassifyPollError(%q) = %q, want %q", c.msg, got, c.want)
+		}
+	}
+}
+
+// writeTestLog añade body al log del slug, igual que hace el Manager.
+func writeTestLog(t *testing.T, dir, slug, body string) {
+	t.Helper()
+	p := filepath.Join(dir, slug+".log")
+	f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+	if err != nil {
+		t.Fatalf("open log: %v", err)
+	}
+	if _, err := f.WriteString(body); err != nil {
+		t.Fatalf("write log: %v", err)
+	}
+	if err := f.Close(); err != nil {
+		t.Fatalf("close log: %v", err)
+	}
+}
+
+func setTestLastPush(t *testing.T, d *sql.DB, slug string, sec int64) {
+	t.Helper()
+	_, err := d.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		"agent.last_push_ts."+slug, fmt.Sprintf("%d", sec),
+	)
+	if err != nil {
+		t.Fatalf("setLastPush: %v", err)
+	}
+}
+
+func TestLastPollError(t *testing.T) {
+	dir := t.TempDir()
+	m := NewManager(dir)
+
+	// Sin log: vacío y sin error.
+	if got := m.LastPollError("hex"); got != "" {
+		t.Fatalf("empty log: got %q", got)
+	}
+
+	// Log con una línea limpia y la última de fallo con escapes de slog.
+	writeTestLog(t, dir, "hex", strings.Join([]string{
+		`2026-10-31T09:00:00Z INF routeros-pusher: pushed slug=hex`,
+		`2026-10-31T09:01:00Z ERR routeros-pusher: collection failed err="routeros api: dial tcp: connection refused; rest: 401 Unauthorized"`,
+	}, "\n")+"\n")
+	got := m.LastPollError("hex")
+	want := `routeros api: dial tcp: connection refused; rest: 401 Unauthorized`
+	if got != want {
+		t.Fatalf("LastPollError = %q, want %q", got, want)
+	}
+
+	// Varias líneas de fallo: gana la ÚLTIMA.
+	writeTestLog(t, dir, "hex", `2026-10-31T09:02:00Z ERR routeros-pusher: collection failed err="routeros: GET /rest/system/resource: 404 Not Found"`+"\n")
+	if got := m.LastPollError("hex"); !strings.Contains(got, "404") {
+		t.Fatalf("LastPollError = %q, want the latest 404 line", got)
+	}
+
+	// Escapes de slog dentro del valor (comillas y barra invertida).
+	writeTestLog(t, dir, "esc", `2026-10-31T09:03:00Z ERR routeros-pusher: collection failed err="rest: bad reply \"x\" + \\ tail"`+"\n")
+	if got := m.LastPollError("esc"); got != `rest: bad reply "x" + \ tail` {
+		t.Fatalf("unescape: got %q", got)
+	}
+}
+
+func TestStatusReasons(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	st := NewStore(d.DB)
+	dir := t.TempDir()
+	m := NewManager(dir)
+
+	// pusher parado: motivo propio, sin mirar el log.
+	if err := st.Upsert(Row{Slug: "hex", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "stopped"}); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+	// integración deshabilitada: se omite.
+	if err := st.Upsert(Row{Slug: "off", Vendor: "routeros", IntervalS: 30, Enabled: false, State: "running"}); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+	// integración con push fresco: se omite aunque el log tenga fallos.
+	if err := st.Upsert(Row{Slug: "fresh", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+	setTestLastPush(t, d.DB, "fresh", time.Now().Unix())
+	writeTestLog(t, dir, "fresh", `2026-10-31T09:00:00Z ERR routeros-pusher: collection failed err="x: 401 Unauthorized"`+"\n")
+	// integración stale con fallo de poll en el log: clasifica.
+	if err := st.Upsert(Row{Slug: "hexbad", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+	setTestLastPush(t, d.DB, "hexbad", time.Now().Add(-time.Hour).Unix())
+	writeTestLog(t, dir, "hexbad", `2026-10-31T09:00:00Z ERR routeros-pusher: collection failed err="routeros: GET /rest/system/resource: 401 Unauthorized"`+"\n")
+	// integración stale sin log ni LastError: sin motivo (no está en el mapa).
+	if err := st.Upsert(Row{Slug: "silent", Vendor: "routeros", IntervalS: 30, Enabled: true, State: "running"}); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+
+	got := StatusReasons(d.DB, m)
+	if got["hex"] != ReasonStopped {
+		t.Errorf("hex: got %q, want %q", got["hex"], ReasonStopped)
+	}
+	if _, ok := got["off"]; ok {
+		t.Errorf("disabled integration must be skipped, got %q", got["off"])
+	}
+	if _, ok := got["fresh"]; ok {
+		t.Errorf("fresh integration must be skipped, got %q", got["fresh"])
+	}
+	if got["hexbad"] != ReasonAuthFailed {
+		t.Errorf("hexbad: got %q, want %q", got["hexbad"], ReasonAuthFailed)
+	}
+	if _, ok := got["silent"]; ok {
+		t.Errorf("silent stale integration must have no reason, got %q", got["silent"])
+	}
+
+	// nil-safety: sin db o sin manager no hay mapa.
+	if StatusReasons(nil, m) != nil || StatusReasons(d.DB, nil) != nil {
+		t.Error("nil db/manager must return nil map")
+	}
+}