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

fix(agents): no upgrade flag on stale agents + remove-from-fleet action (#1385)

Stale agents no longer show an upgrade offer (freshness required), stale rows render red with Remove as the only action, and agents can be removed from the fleet via the existing DELETE endpoint with an in-app confirmation dialog.\n\nCloses #1382
Nacho 1 месяц назад
Родитель
Сommit
9dcab46b2b

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

@@ -1107,6 +1107,15 @@
       "uninstallConfirm": "Uninstall the agent from {{router}}? The service will be stopped and the binary/config/watchdog removed from the router, and its token revoked. You'll need to reinstall it to keep monitoring this router.",
       "uninstallConfirm": "Uninstall the agent from {{router}}? The service will be stopped and the binary/config/watchdog removed from the router, and its token revoked. You'll need to reinstall it to keep monitoring this router.",
       "uninstallDone": "Agent uninstalled from the router.",
       "uninstallDone": "Agent uninstalled from the router.",
       "uninstallFail": "Failed to uninstall",
       "uninstallFail": "Failed to uninstall",
+      "remove": "Remove",
+      "removing": "Removing…",
+      "removed": "Removed",
+      "removeRetry": "Retry",
+      "removeTip": "Removes the agent from the fleet: revokes its token and forgets its state. Only available while the device is disconnected (powered off or taken off the network); if it comes back it must be re-enrolled.",
+      "removeConfirm": "Remove the agent of {{router}} from the fleet? Its token will be revoked and its state forgotten. If the device is still on the network and reconnects, it will get a 401 and must be re-enrolled.",
+      "removeDone": "Agent removed from the fleet.",
+      "removeFail": "Failed to remove",
+      "removeTitle": "Remove agent from the fleet",
       "copyCmd": "Copy command",
       "copyCmd": "Copy command",
       "copyCmdTip": "Generates the manual install one-liner (fallback for routers without SSH). The token rotates on every generation.",
       "copyCmdTip": "Generates the manual install one-liner (fallback for routers without SSH). The token rotates on every generation.",
       "copied": "Command copied",
       "copied": "Command copied",

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

@@ -1107,6 +1107,15 @@
       "uninstallConfirm": "¿Desinstalar el agente de {{router}}? Se detendrá el servicio, se borrarán binario/config/watchdog del router y se revocará su token. Tendrás que volver a instalarlo para seguir monitorizando este router.",
       "uninstallConfirm": "¿Desinstalar el agente de {{router}}? Se detendrá el servicio, se borrarán binario/config/watchdog del router y se revocará su token. Tendrás que volver a instalarlo para seguir monitorizando este router.",
       "uninstallDone": "Agente desinstalado del router.",
       "uninstallDone": "Agente desinstalado del router.",
       "uninstallFail": "Fallo al desinstalar",
       "uninstallFail": "Fallo al desinstalar",
+      "remove": "Retirar",
+      "removing": "Retirando…",
+      "removed": "Retirado",
+      "removeRetry": "Reintentar",
+      "removeTip": "Retira el agente de la flota: revoca su token y olvida su estado. Solo disponible con el equipo desconectado (apagado o quitado de la red); si vuelve, habrá que enrolarlo de nuevo.",
+      "removeConfirm": "¿Retirar el agente de {{router}} de la flota? Se revocará su token y se olvidará su estado. Si el equipo sigue en la red y vuelve a conectar, recibirá 401 y habrá que re-enrolarlo.",
+      "removeDone": "Agente retirado de la flota.",
+      "removeFail": "Fallo al retirar",
+      "removeTitle": "Retirar agente de la flota",
       "copyCmd": "Copiar comando",
       "copyCmd": "Copiar comando",
       "copyCmdTip": "Genera el one-liner de instalación manual (fallback para routers sin SSH). El token se rota en cada generación.",
       "copyCmdTip": "Genera el one-liner de instalación manual (fallback para routers sin SSH). El token se rota en cada generación.",
       "copied": "Comando copiado",
       "copied": "Comando copiado",

+ 115 - 15
app/src/components/routers/AgentsSection.tsx

@@ -1,10 +1,20 @@
 import { useEffect, useMemo, useState } from 'react'
 import { useEffect, useMemo, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { Link } from 'react-router'
-import { Check, Clipboard, Clock, Loader2, Radar, RotateCcw, Unplug } from 'lucide-react'
+import { Check, Clipboard, Clock, Loader2, Radar, RotateCcw, Trash2, Unplug } from 'lucide-react'
 import { motion } from 'framer-motion'
 import { motion } from 'framer-motion'
 import { useNetPulse } from '@/data/DataProvider'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 import { useAuth } from '@/data/AuthContext'
+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
 import type { AgentInfo, Router } from '@/data/types'
 import type { AgentInfo, Router } from '@/data/types'
 import { relTimeFromTs } from '@/i18n'
 import { relTimeFromTs } from '@/i18n'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
@@ -58,7 +68,7 @@ const TIMELINE_STALLED_S = 90
 /** Fila de un agente con sus acciones de recuperación (estado local). */
 /** Fila de un agente con sus acciones de recuperación (estado local). */
 function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router | undefined; nowSec: number }) {
 function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router | undefined; nowSec: number }) {
   const { t } = useTranslation()
   const { t } = useTranslation()
-  const { reinstallAgent, uninstallAgent, createAgentInstall, refreshAgents } = useNetPulse()
+  const { reinstallAgent, uninstallAgent, removeAgent, createAgentInstall, refreshAgents } = useNetPulse()
   const auth = useAuth()
   const auth = useAuth()
   const [reinstallState, setReinstallState] = useState<ReinstallState>('idle')
   const [reinstallState, setReinstallState] = useState<ReinstallState>('idle')
   const [reinstallMsg, setReinstallMsg] = useState('')
   const [reinstallMsg, setReinstallMsg] = useState('')
@@ -82,6 +92,14 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
   // presente: no tiene sentido desinstalar algo que no está, ni un NetGrip
   // presente: no tiene sentido desinstalar algo que no está, ni un NetGrip
   // (que se gestiona desde su propio panel) ni un scraper externo.
   // (que se gestiona desde su propio panel) ni un scraper externo.
   const canUninstall = auth?.role === 'admin' && isOpenWrt && agent !== undefined && agent.kind !== 'external' && agent.kind !== 'netgrip'
   const canUninstall = auth?.role === 'admin' && isOpenWrt && agent !== undefined && agent.kind !== 'external' && agent.kind !== 'netgrip'
+  // #1382: retirar el agente de la flota (revoca token + olvida estado) solo
+  // se ofrece con el agente SIN pulso (equipo apagado o quitado de la red):
+  // retirar uno vivo deja un proceso empujando contra un token revocado.
+  // Es la única baja posible de agentes netgrip/external (sin SSH).
+  const canRemove = auth?.role === 'admin' && agent !== undefined && !agent.fresh
+  const [removeState, setRemoveState] = useState<ReinstallState>('idle')
+  const [removeMsg, setRemoveMsg] = useState('')
+  const [confirmRemove, setConfirmRemove] = useState(false)
 
 
   const slug = agent?.slug ?? router?.id ?? ''
   const slug = agent?.slug ?? router?.id ?? ''
   // #691: el relativo se calcula con el reloj compartido nowSec (prop), no con
   // #691: el relativo se calcula con el reloj compartido nowSec (prop), no con
@@ -156,13 +174,38 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
     window.setTimeout(() => setCopyState('idle'), 4000)
     window.setTimeout(() => setCopyState('idle'), 4000)
   }
   }
 
 
+  // #1382: retira el agente de la flota (DELETE /api/agents/{slug}: revoca
+  // el token y olvida su estado). Para equipos dados de baja de la red; si
+  // vuelven a conectar con el token viejo recibirán 401 (re-enrolar).
+  // Confirmación con diálogo propio (AlertDialog), acción destructiva.
+  const remove = async () => {
+    if (removeState === 'busy') return
+    setRemoveState('busy')
+    setRemoveMsg('')
+    const res = await removeAgent(slug)
+    if (res && !res.error) {
+      setRemoveState('done')
+      setRemoveMsg(t('routers.agents.removeDone'))
+      await refreshAgents()
+    } else {
+      setRemoveState('fail')
+      setRemoveMsg(res?.error ?? t('routers.agents.removeFail'))
+    }
+    window.setTimeout(() => setRemoveState('idle'), 8000)
+  }
+
   return (
   return (
     <>
     <>
     <motion.tr
     <motion.tr
       initial={{ opacity: 0, y: 6 }}
       initial={{ opacity: 0, y: 6 }}
       animate={{ opacity: 1, y: 0 }}
       animate={{ opacity: 1, y: 0 }}
       transition={{ duration: 0.25, ease: 'easeOut' }}
       transition={{ duration: 0.25, ease: 'easeOut' }}
-      className="border-b border-border/60 last:border-0"
+      className={cn(
+        'border-b border-border/60 last:border-0',
+        // #1382: agente sin pulso (equipo apagado o quitado de la red):
+        // toda la fila en acento rojo; la única acción ofrecida es Retirar.
+        isStale && 'bg-danger/5',
+      )}
     >
     >
       <td className="py-3 pr-3">
       <td className="py-3 pr-3">
         <div className="flex min-w-0 items-center gap-2.5">
         <div className="flex min-w-0 items-center gap-2.5">
@@ -234,22 +277,22 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
       </td>
       </td>
       <td className="py-3">
       <td className="py-3">
         <div className="flex flex-wrap items-center gap-2">
         <div className="flex flex-wrap items-center gap-2">
+          {/* #1382: con el agente SIN pulso la única acción operable es
+              Retirar (abajo): actualizar/rearmar/reinstalar/desinstalar
+              necesitan un equipo vivo en la red. */}
+          {!isStale && (
+          <>
           {/* Actualizar: self-update del agente con progreso en vivo (#243).
           {/* Actualizar: self-update del agente con progreso en vivo (#243).
               NetGrip (#363): el evento SSE dispara el self-update del propio
               NetGrip (#363): el evento SSE dispara el self-update del propio
-              panel; el reinstall no aplica (no hay proceso standalone), y el
-              rearm de un NetGrip STALE reinicia el servicio netgrip (#569). */}
+              panel; el reinstall no aplica (no hay proceso standalone). */}
           <AgentUpgradeButton agent={agent} className="h-8" />
           <AgentUpgradeButton agent={agent} className="h-8" />
           {isNetgrip ? (
           {isNetgrip ? (
-            // #569: un NetGrip STALE (caído) SÍ se puede recuperar desde
-            // aquí: el botón reinicia el servicio netgrip del router por SSH
-            // (recarga el env del agente embebido). El hint explica el caso
-            // fresco; el stale ofrece el botón + su hint.
-            <>
-              {!agent?.fresh && <AgentRearmButton agent={agent} />}
-              <span className="text-caption text-text-muted">
-                {agent?.fresh ? t('routers.agents.netgripHint') : t('routers.agents.netgripStaleHint')}
-              </span>
-            </>
+            // #363: NetGrip fresco se auto-actualiza desde su panel; el hint
+            // lo explica. (El rearm por SSH de un NetGrip caído de #569 quedó
+            // absorbido por la regla #1382: sin pulso -> solo Retirar.)
+            <span className="text-caption text-text-muted">
+              {t('routers.agents.netgripHint')}
+            </span>
           ) : (
           ) : (
             <>
             <>
           {/* Rearm: canal preferente para heartbeat stale (proceso vivo).
           {/* Rearm: canal preferente para heartbeat stale (proceso vivo).
@@ -340,6 +383,37 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
           )}
           )}
             </>
             </>
           )}
           )}
+          </>
+          )}
+          {/* #1382: Retirar de la flota (server-side, cualquier kind): revoca
+              el token y olvida el estado. Solo con el agente sin pulso
+              (equipo apagado o quitado de la red); si vuelve hay que
+              re-enrolarlo. */}
+          {canRemove && (
+            <button
+              type="button"
+              onClick={() => setConfirmRemove(true)}
+              disabled={removeState === 'busy'}
+              title={t('routers.agents.removeTip')}
+              className={cn(
+                'inline-flex h-8 items-center gap-1.5 rounded-lg border px-2.5 text-caption font-semibold transition-colors disabled:opacity-50',
+                removeState === 'done'
+                  ? 'border-ok/40 bg-ok/10 text-ok'
+                  : removeState === 'fail'
+                    ? 'border-danger/40 bg-danger/10 text-danger'
+                    : 'border-border text-text-secondary hover:border-danger/40 hover:text-danger',
+              )}
+            >
+              <Trash2 className={cn('h-3.5 w-3.5', removeState === 'busy' && 'animate-pulse')} strokeWidth={1.75} />
+              {removeState === 'busy'
+                ? t('routers.agents.removing')
+                : removeState === 'done'
+                  ? t('routers.agents.removed')
+                  : removeState === 'fail'
+                    ? t('routers.agents.removeRetry')
+                    : t('routers.agents.remove')}
+            </button>
+          )}
         </div>
         </div>
         {reinstallMsg && reinstallState !== 'idle' && (
         {reinstallMsg && reinstallState !== 'idle' && (
           <p className={cn('mt-1.5 text-caption', reinstallState === 'fail' ? 'text-danger' : 'text-text-muted')}>
           <p className={cn('mt-1.5 text-caption', reinstallState === 'fail' ? 'text-danger' : 'text-text-muted')}>
@@ -351,6 +425,11 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
             {uninstallMsg}
             {uninstallMsg}
           </p>
           </p>
         )}
         )}
+        {removeMsg && removeState !== 'idle' && (
+          <p className={cn('mt-1.5 text-caption', removeState === 'fail' ? 'text-danger' : 'text-text-muted')}>
+            {removeMsg}
+          </p>
+        )}
       </td>
       </td>
     </motion.tr>
     </motion.tr>
     {showTimeline && up &&
     {showTimeline && up &&
@@ -410,6 +489,27 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
           </motion.tr>
           </motion.tr>
         )
         )
       })()}
       })()}
+      {/* #1382: confirmación propia (no window.confirm) de la retirada del
+          agente de la flota. */}
+      <AlertDialog open={confirmRemove} onOpenChange={setConfirmRemove}>
+        <AlertDialogContent>
+          <AlertDialogHeader>
+            <AlertDialogTitle>{t('routers.agents.removeTitle')}</AlertDialogTitle>
+            <AlertDialogDescription>
+              {t('routers.agents.removeConfirm', { router: router?.name ?? slug })}
+            </AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>{t('settings.users.cancel')}</AlertDialogCancel>
+            <AlertDialogAction
+              onClick={() => void remove()}
+              className="bg-danger text-danger-foreground hover:bg-danger/90"
+            >
+              {t('routers.agents.remove')}
+            </AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
     </>
     </>
   )
   )
 }
 }

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

@@ -224,6 +224,13 @@ export interface NetPulseApi extends NetPulseData {
    * token. Devuelve `{ gone }` o null si falló (demo siempre null).
    * token. Devuelve `{ gone }` o null si falló (demo siempre null).
    */
    */
   uninstallAgent: (slug: string) => Promise<{ gone: boolean; token?: boolean; error?: string } | null>
   uninstallAgent: (slug: string) => Promise<{ gone: boolean; token?: boolean; error?: string } | null>
+  /**
+   * #1382: DELETE /api/agents/{slug} — retira el agente de la flota (revoca
+   * su token y olvida su estado). Para equipos dados de baja de la red; si
+   * el equipo vuelve, hay que re-enrolarlo. Distinto de uninstallAgent, que
+   * desinstala el software del router vía SSH.
+   */
+  removeAgent: (slug: string) => Promise<{ error?: string } | null>
   /**
   /**
    * #245: POST /api/agents — crea/rota el token del agente y devuelve el
    * #245: POST /api/agents — crea/rota el token del agente y devuelve el
    * one-liner de instalación manual (fallback para routers sin SSH desde el
    * one-liner de instalación manual (fallback para routers sin SSH desde el
@@ -1160,6 +1167,24 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
     }
   }, [])
   }, [])
 
 
+  const removeAgent = useCallback(async (slug: string): Promise<{ error?: string } | null> => {
+    if (modeRef.current !== 'live') return null
+    try {
+      const res = await fetch(`/api/agents/${encodeURIComponent(slug)}`, {
+        method: 'DELETE',
+        signal: AbortSignal.timeout(30_000),
+      })
+      if (res.status === 401) redirectLogin()
+      if (!res.ok && res.status !== 204) {
+        const body = (await res.json().catch(() => ({}))) as { message?: string }
+        return { error: body.message ?? `HTTP ${res.status}` }
+      }
+      return {}
+    } catch {
+      return { error: 'network' }
+    }
+  }, [])
+
   const createAgentInstall = useCallback(async (slug: string): Promise<{ install: string; token?: string } | null> => {
   const createAgentInstall = useCallback(async (slug: string): Promise<{ install: string; token?: string } | null> => {
     if (modeRef.current !== 'live') return null
     if (modeRef.current !== 'live') return null
     try {
     try {
@@ -1302,9 +1327,10 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       upgradeAllAgents,
       upgradeAllAgents,
       reinstallAgent,
       reinstallAgent,
       uninstallAgent,
       uninstallAgent,
+      removeAgent,
       createAgentInstall,
       createAgentInstall,
     }),
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
   )
   )
 
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 5 - 2
server-go/internal/httpapi/agent.go

@@ -656,10 +656,13 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				// (mismo criterio que finishIfTarget y upgrade-all: un agente
 				// (mismo criterio que finishIfTarget y upgrade-all: un agente
 				// más nuevo que el embebido no está desactualizado).
 				// más nuevo que el embebido no está desactualizado).
 				if agentKind == "netgrip" {
 				if agentKind == "netgrip" {
-					item.UpdateAvailable = item.Version != "" && cmpSemver(netgripLatest(), item.Version) > 0
+					item.UpdateAvailable = item.Fresh && item.Version != "" && cmpSemver(netgripLatest(), item.Version) > 0
 				} else {
 				} else {
-					item.UpdateAvailable = !agentbin.EmbeddedMismatch() && agentUpgradeable(matchedType) && item.Version != "" && vercmp.CmpBuild(item.Version, agentbin.EmbeddedAgentVersion) < 0
+					item.UpdateAvailable = item.Fresh && !agentbin.EmbeddedMismatch() && agentUpgradeable(matchedType) && item.Version != "" && vercmp.CmpBuild(item.Version, agentbin.EmbeddedAgentVersion) < 0
 				}
 				}
+				// #1382: un agente sin pulso reciente (equipo apagado o
+				// retirado de la red) no puede actualizarse; marcarlo como
+				// pendiente es ruido permanente en la tabla de flota.
 				// Progreso en vivo del upgrade (#284), si hay actividad reciente.
 				// Progreso en vivo del upgrade (#284), si hay actividad reciente.
 				if st, ok := s.upgrades.snapshot(slug); ok {
 				if st, ok := s.upgrades.snapshot(slug); ok {
 					ts := st.Ts.Unix()
 					ts := st.Ts.Unix()

+ 41 - 0
server-go/internal/httpapi/upgrade_api_test.go

@@ -368,6 +368,47 @@ func TestAgentsListUpdateAvailable(t *testing.T) {
 	}
 	}
 }
 }
 
 
+// TestAgentsListUpdateAvailableStale — #1382: un agente SIN pulso reciente
+// (equipo apagado o retirado de la red) no se ofrece como actualizable aunque
+// su última versión conocida sea vieja: no hay forma de aplicarle un upgrade
+// y el aviso sería ruido permanente en la tabla de flota.
+func TestAgentsListUpdateAvailableStale(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+
+	agentItem := func() map[string]any {
+		res := get(t, ts.URL, "/api/agents", ts.cookie)
+		body := readJSON(t, res)
+		for _, a := range body["agents"].([]any) {
+			if m, _ := a.(map[string]any); m["slug"] == "patio" {
+				return m
+			}
+		}
+		t.Fatalf("patio ausente: %v", body)
+		return nil
+	}
+
+	// Fresco con versión vieja: pendiente de actualizar.
+	upgradeIngest(t, ts, tok, upgradePayload("0.0.9"))
+	if patio := agentItem(); patio["updateAvailable"] != true {
+		t.Fatalf("fresco con 0.0.9 debe dar updateAvailable=true: %v", patio)
+	}
+
+	// El reloj avanza más allá del TTL del registry: la última versión
+	// conocida sigue siendo vieja, pero sin pulso no hay aviso.
+	now := time.Now()
+	ts.agents.SetClock(func() time.Time { return now.Add(2 * time.Hour) })
+	if patio := agentItem(); patio["fresh"] != false {
+		t.Fatalf("tras 2h sin push debe dar fresh=false: %v", patio)
+	}
+	if patio := agentItem(); patio["updateAvailable"] != false {
+		t.Fatalf("stale con 0.0.9 debe dar updateAvailable=false: %v", patio)
+	}
+}
+
 // TestAgentsUpgradeAll — #251: POST /api/agents/upgrade-all.
 // TestAgentsUpgradeAll — #251: POST /api/agents/upgrade-all.
 //   - 403 sin admin.
 //   - 403 sin admin.
 //   - Con un agente conectado y desactualizado → status "sent".
 //   - Con un agente conectado y desactualizado → status "sent".