4
0
Эх сурвалжийг харах

merge: badge Agente en Routers/RouterDetail/Home — /api/agents en DataProvider (30s), fresh/caído con tooltips, i18n desde fase6/agent-badge

agent 4 сар өмнө
parent
commit
28bf44f4ea

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

@@ -405,6 +405,13 @@
     }
     }
   },
   },
   "routers": {
   "routers": {
+    "agent": {
+      "badge": "Agent",
+      "freshTip": "netpulse-agent v{{version}} · pushes every 15 s",
+      "freshTipUnknown": "netpulse-agent · pushes every 15 s",
+      "stale": "Agent down",
+      "staleTip": "No data from agent — polling via SSH"
+    },
     "colClients": "Clients",
     "colClients": "Clients",
     "colCpu": "CPU",
     "colCpu": "CPU",
     "colDevice": "Device",
     "colDevice": "Device",

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

@@ -405,6 +405,13 @@
     }
     }
   },
   },
   "routers": {
   "routers": {
+    "agent": {
+      "badge": "Agente",
+      "freshTip": "netpulse-agent v{{version}} · empuja cada 15 s",
+      "freshTipUnknown": "netpulse-agent · empuja cada 15 s",
+      "stale": "Agente caído",
+      "staleTip": "Sin datos del agente — sondeando por SSH"
+    },
     "colClients": "Clientes",
     "colClients": "Clientes",
     "colCpu": "CPU",
     "colCpu": "CPU",
     "colDevice": "Equipo",
     "colDevice": "Equipo",

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

@@ -8,6 +8,8 @@ import type { Router } from '@/data/mock'
 import { HealthRing, STATUS_COLORS } from '@/components/HealthRing'
 import { HealthRing, STATUS_COLORS } from '@/components/HealthRing'
 import { Sparkline } from '@/components/Sparkline'
 import { Sparkline } from '@/components/Sparkline'
 import { StatusPill } from '@/components/StatusPill'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 
 
 function MiniMetric({
 function MiniMetric({
@@ -38,6 +40,7 @@ interface RouterCardProps {
 /** Tarjeta de router (design.md §10.2): StatusRing, mini-métricas, sparkline, chevron. */
 /** Tarjeta de router (design.md §10.2): StatusRing, mini-métricas, sparkline, chevron. */
 export function RouterCard({ router, index = 0, className }: RouterCardProps) {
 export function RouterCard({ router, index = 0, className }: RouterCardProps) {
   const { t } = useTranslation()
   const { t } = useTranslation()
+  const agent = useAgentFor(router.id)
   const warn = router.status === 'warn'
   const warn = router.status === 'warn'
   const offline = router.status === 'offline'
   const offline = router.status === 'offline'
   return (
   return (
@@ -63,11 +66,12 @@ export function RouterCard({ router, index = 0, className }: RouterCardProps) {
               <RouterIcon className="h-5 w-5" strokeWidth={1.75} />
               <RouterIcon className="h-5 w-5" strokeWidth={1.75} />
             </div>
             </div>
             <div className="min-w-0">
             <div className="min-w-0">
-              <div className="flex items-center gap-2">
+              <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                 <span className="truncate font-display text-h2 text-text-primary">{router.name}</span>
                 <span className="truncate font-display text-h2 text-text-primary">{router.name}</span>
                 <span className="shrink-0 rounded-full bg-accent-soft px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">
                 <span className="shrink-0 rounded-full bg-accent-soft px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">
                   {roleLabel(router.roleBadge)}
                   {roleLabel(router.roleBadge)}
                 </span>
                 </span>
+                <AgentBadge agent={agent} className="shrink-0" />
               </div>
               </div>
               <div className="truncate text-caption text-text-muted">{router.modelShort}</div>
               <div className="truncate text-caption text-text-muted">{router.modelShort}</div>
             </div>
             </div>

+ 35 - 0
app/src/components/routers/AgentBadge.tsx

@@ -0,0 +1,35 @@
+import { useTranslation } from 'react-i18next'
+import type { AgentInfo } from '@/data/types'
+import { StatusPill } from '@/components/StatusPill'
+import { cn } from '@/lib/utils'
+
+interface AgentBadgeProps {
+  /** Agente del router; undefined/null → no se renderiza nada (demo, sin agentes) */
+  agent: AgentInfo | undefined
+  className?: string
+}
+
+/**
+ * Badge "Agente" (Fase 6 piloto):
+ * - `fresh` → tono info discreto, tooltip con versión y cadencia de push.
+ * - caído  → tono warn pulsante, tooltip "sondeando por SSH" (las alertas de
+ *   categoría system ya narran la caída/recuperación; aquí solo el estado).
+ */
+export function AgentBadge({ agent, className }: AgentBadgeProps) {
+  const { t } = useTranslation()
+  if (!agent) return null
+  const title = agent.fresh
+    ? agent.version
+      ? t('routers.agent.freshTip', { version: agent.version })
+      : t('routers.agent.freshTipUnknown')
+    : t('routers.agent.staleTip')
+  return (
+    <span title={title} className={cn('inline-flex', className)}>
+      <StatusPill
+        tone={agent.fresh ? 'info' : 'warn'}
+        label={agent.fresh ? t('routers.agent.badge') : t('routers.agent.stale')}
+        pulse={!agent.fresh}
+      />
+    </span>
+  )
+}

+ 5 - 1
app/src/components/routers/FleetCard.tsx

@@ -10,6 +10,8 @@ import { HealthRing } from '@/components/HealthRing'
 import { MetricBar } from '@/components/MetricBar'
 import { MetricBar } from '@/components/MetricBar'
 import { Sparkline } from '@/components/Sparkline'
 import { Sparkline } from '@/components/Sparkline'
 import { StatusPill } from '@/components/StatusPill'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
@@ -57,6 +59,7 @@ interface FleetCardProps {
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
   const { t } = useTranslation()
   const { t } = useTranslation()
   const { isDemo } = useNetPulse()
   const { isDemo } = useNetPulse()
+  const agent = useAgentFor(router.id)
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
   const warn = router.status === 'warn'
   const reduce = useReducedMotion()
   const reduce = useReducedMotion()
@@ -104,8 +107,9 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
               <RouterIcon className="h-[22px] w-[22px]" strokeWidth={1.75} />
               <RouterIcon className="h-[22px] w-[22px]" strokeWidth={1.75} />
             </motion.div>
             </motion.div>
             <div className="min-w-0">
             <div className="min-w-0">
-              <div className="flex items-center gap-2">
+              <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
                 <h3 className="truncate font-display text-h2 text-text-primary">{router.name}</h3>
                 <h3 className="truncate font-display text-h2 text-text-primary">{router.name}</h3>
+                <AgentBadge agent={agent} />
               </div>
               </div>
               <div className="truncate text-caption text-text-muted">
               <div className="truncate text-caption text-text-muted">
                 {isGateway ? 'GL.iNet Flint 2 · GL-MT6000' : `OpenWrt · ${router.modelShort}`}
                 {isGateway ? 'GL.iNet Flint 2 · GL-MT6000' : `OpenWrt · ${router.modelShort}`}

+ 11 - 3
app/src/components/routers/FleetTable.tsx

@@ -9,6 +9,7 @@ import { fmtEs } from '@/data/mock'
 import { useNetPulse } from '@/data/DataProvider'
 import { useNetPulse } from '@/data/DataProvider'
 import { MetricBar } from '@/components/MetricBar'
 import { MetricBar } from '@/components/MetricBar'
 import { StatusPill } from '@/components/StatusPill'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
 import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
 import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 
 
@@ -76,10 +77,11 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
   const { t } = useTranslation()
   const { t } = useTranslation()
   const navigate = useNavigate()
   const navigate = useNavigate()
   const reduce = useReducedMotion()
   const reduce = useReducedMotion()
-  const { routers } = useNetPulse()
+  const { routers, agents } = useNetPulse()
   const [sortKey, setSortKey] = useState<SortKey>('name')
   const [sortKey, setSortKey] = useState<SortKey>('name')
   const [asc, setAsc] = useState(true)
   const [asc, setAsc] = useState(true)
   const [openId, setOpenId] = useState<string | null>(null)
   const [openId, setOpenId] = useState<string | null>(null)
+  const agentBySlug = useMemo(() => new Map(agents.map((a) => [a.slug, a])), [agents])
 
 
   const sorted = useMemo(() => {
   const sorted = useMemo(() => {
     const arr = [...routers]
     const arr = [...routers]
@@ -162,7 +164,10 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                         <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                         <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                       </span>
                       </span>
                       <span>
                       <span>
-                        <span className="block font-medium text-text-primary">{r.name}</span>
+                        <span className="flex items-center gap-2">
+                          <span className="font-medium text-text-primary">{r.name}</span>
+                          <AgentBadge agent={agentBySlug.get(r.id)} />
+                        </span>
                         <span className="block text-caption text-text-muted">{r.modelShort}</span>
                         <span className="block text-caption text-text-muted">{r.modelShort}</span>
                       </span>
                       </span>
                     </div>
                     </div>
@@ -221,7 +226,10 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                   )}>
                   )}>
                     <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                     <RouterIcon className="h-4 w-4" strokeWidth={1.75} />
                   </span>
                   </span>
-                  <span className="truncate font-medium text-text-primary">{r.name}</span>
+                  <span className="min-w-0">
+                    <span className="block truncate font-medium text-text-primary">{r.name}</span>
+                    <AgentBadge agent={agentBySlug.get(r.id)} className="mt-1" />
+                  </span>
                 </span>
                 </span>
                 <span className="flex shrink-0 items-center gap-2">
                 <span className="flex shrink-0 items-center gap-2">
                   <StatusPill
                   <StatusPill

+ 12 - 0
app/src/components/routers/RouterDetailHeader.tsx

@@ -6,6 +6,8 @@ import { roleLabel } from '@/i18n'
 import type { Router } from '@/data/mock'
 import type { Router } from '@/data/mock'
 import { HealthRing } from '@/components/HealthRing'
 import { HealthRing } from '@/components/HealthRing'
 import { StatusPill } from '@/components/StatusPill'
 import { StatusPill } from '@/components/StatusPill'
+import { AgentBadge } from '@/components/routers/AgentBadge'
+import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 
 
 /** ① Detail header (router-detail.md §①) — identidad + StatusRing 96px. */
 /** ① Detail header (router-detail.md §①) — identidad + StatusRing 96px. */
@@ -13,6 +15,7 @@ export function RouterDetailHeader({ router }: { router: Router }) {
   const { t } = useTranslation()
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const reduce = useReducedMotion()
   const isGateway = router.roleBadge === 'Principal'
   const isGateway = router.roleBadge === 'Principal'
+  const agent = useAgentFor(router.id)
   const pills = [
   const pills = [
     { label: roleLabel(router.roleBadge), tone: 'accent' as const, pulse: false },
     { label: roleLabel(router.roleBadge), tone: 'accent' as const, pulse: false },
     {
     {
@@ -73,6 +76,15 @@ export function RouterDetailHeader({ router }: { router: Router }) {
                   <StatusPill tone={p.tone} label={p.label} pulse={p.pulse} />
                   <StatusPill tone={p.tone} label={p.label} pulse={p.pulse} />
                 </motion.span>
                 </motion.span>
               ))}
               ))}
+              {agent && (
+                <motion.span
+                  initial={reduce ? false : { opacity: 0, scale: 0.9 }}
+                  animate={{ opacity: 1, scale: 1 }}
+                  transition={{ duration: 0.2, delay: 0.15 + pills.length * 0.06 }}
+                >
+                  <AgentBadge agent={agent} />
+                </motion.span>
+              )}
             </div>
             </div>
           </div>
           </div>
         </div>
         </div>

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

@@ -15,6 +15,7 @@
 import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
 import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
 import type {
 import type {
   AdGuardStats,
   AdGuardStats,
+  AgentInfo,
   AlertCategory,
   AlertCategory,
   AlertConfigLevel,
   AlertConfigLevel,
   AlertEvent,
   AlertEvent,
@@ -87,6 +88,12 @@ export interface NetPulseData {
 
 
 export interface NetPulseApi extends NetPulseData {
 export interface NetPulseApi extends NetPulseData {
   connectionStatus: ConnectionStatus
   connectionStatus: ConnectionStatus
+  /**
+   * Agentes nativos registrados (GET /api/agents, Fase 6). El `slug` casa con
+   * el `id` del router. En demo: lista vacía (sin badges, comportamiento
+   * honesto — no se mockean agentes). Se refresca cada ~30 s en live.
+   */
+  agents: AgentInfo[]
   /** true = sin backend: dataset local del mockup con tick simulado */
   /** true = sin backend: dataset local del mockup con tick simulado */
   isDemo: boolean
   isDemo: boolean
   /** Re-pide `/api/overview` (live); en demo es no-op */
   /** Re-pide `/api/overview` (live); en demo es no-op */
@@ -280,6 +287,8 @@ function toQuery(params: Record<string, string | number | undefined>): string {
 const BACKOFF_MS = [2000, 5000, 15000]
 const BACKOFF_MS = [2000, 5000, 15000]
 const POLL_MS = 15000
 const POLL_MS = 15000
 const DEMO_TICK_MS = 3000
 const DEMO_TICK_MS = 3000
+// Refresco del estado de agentes (fresh cambia solo en el backend, TTL ~90 s)
+const AGENTS_POLL_MS = 30000
 
 
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 // Provider
 // Provider
@@ -299,6 +308,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   // Config de alertas: arranca con la demo (localStorage); en live la
   // Config de alertas: arranca con la demo (localStorage); en live la
   // reemplaza GET /api/alerts/config durante el boot
   // reemplaza GET /api/alerts/config durante el boot
   const [alertsConfig, setAlertsConfigState] = useState<AlertsConfig>(loadDemoAlertsConfig)
   const [alertsConfig, setAlertsConfigState] = useState<AlertsConfig>(loadDemoAlertsConfig)
+  // Agentes nativos (live); demo = siempre vacío
+  const [agents, setAgents] = useState<AgentInfo[]>([])
 
 
   // Refs para closures estables (getters async con la misma firma en ambos modos)
   // Refs para closures estables (getters async con la misma firma en ambos modos)
   const bundleRef = useRef(bundle)
   const bundleRef = useRef(bundle)
@@ -332,6 +343,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     let pollId: number | undefined
     let pollId: number | undefined
     let reconnectId: number | undefined
     let reconnectId: number | undefined
     let tickId: number | undefined
     let tickId: number | undefined
+    let agentsPollId: number | undefined
     let backoffIdx = 0
     let backoffIdx = 0
 
 
     const fetchJson = async (url: string): Promise<Response> => {
     const fetchJson = async (url: string): Promise<Response> => {
@@ -437,6 +449,20 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       }
       }
     }
     }
 
 
+    // Agentes nativos (Fase 6): no forman parte del overview; se sondean
+    // aparte cada ~30 s. Sin agentes registrados → [] (sin badges).
+    const fetchAgents = async (): Promise<void> => {
+      try {
+        const res = await fetchJson('/api/agents')
+        if (!res.ok) return
+        const json = (await res.json()) as { agents?: AgentInfo[] } | AgentInfo[]
+        const list = Array.isArray(json) ? json : (json.agents ?? [])
+        if (!disposed) setAgents(list)
+      } catch {
+        /* sin agentes: se mantiene el último estado conocido */
+      }
+    }
+
     const startLive = async () => {
     const startLive = async () => {
       modeRef.current = 'live'
       modeRef.current = 'live'
       setIsDemo(false)
       setIsDemo(false)
@@ -444,12 +470,14 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       const ok = await fetchOverview()
       const ok = await fetchOverview()
       await fetchDevices()
       await fetchDevices()
       await fetchAlertsConfig()
       await fetchAlertsConfig()
+      await fetchAgents()
       if (disposed) return
       if (disposed) return
       if (ok) setConnectionStatus('connected')
       if (ok) setConnectionStatus('connected')
       else {
       else {
         setConnectionStatus('reconnecting')
         setConnectionStatus('reconnecting')
         pollId = window.setInterval(() => void fetchOverview(), POLL_MS)
         pollId = window.setInterval(() => void fetchOverview(), POLL_MS)
       }
       }
+      agentsPollId = window.setInterval(() => void fetchAgents(), AGENTS_POLL_MS)
       startSse()
       startSse()
     }
     }
 
 
@@ -482,6 +510,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       stopPolling()
       stopPolling()
       window.clearTimeout(reconnectId)
       window.clearTimeout(reconnectId)
       window.clearInterval(tickId)
       window.clearInterval(tickId)
+      window.clearInterval(agentsPollId)
     }
     }
   }, [applyOverview])
   }, [applyOverview])
 
 
@@ -689,6 +718,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     () => ({
     () => ({
       ...bundle,
       ...bundle,
       connectionStatus,
       connectionStatus,
+      agents,
       isDemo,
       isDemo,
       refresh,
       refresh,
       lastSnapshotAt,
       lastSnapshotAt,
@@ -701,7 +731,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       markAlertsRead,
       markAlertsRead,
       markAllAlertsRead,
       markAllAlertsRead,
     }),
     }),
-    [bundle, connectionStatus, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead],
+    [bundle, connectionStatus, agents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead],
   )
   )
 
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

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

@@ -260,6 +260,21 @@ export interface OverviewBundle {
   ts: number
   ts: number
 }
 }
 
 
+/**
+ * Item de `GET /api/agents` (Fase 6): agente nativo registrado en un router.
+ * `slug` coincide con el `id` del router (mismo alfabeto que routerstore).
+ * `fresh` = el agente empujó dentro del TTL (~90 s); false → caído, el
+ * backend vuelve a sondear por SSH.
+ */
+export interface AgentInfo {
+  slug: string
+  /** Unix SEGUNDOS del último push; null si nunca empujó */
+  lastSeen: number | null
+  /** Versión del binario netpulse-agent ("" si aún no se conoce) */
+  version?: string
+  fresh: boolean
+}
+
 /** Respuesta paginada (`GET /api/devices`, `GET /api/alerts`). */
 /** Respuesta paginada (`GET /api/devices`, `GET /api/alerts`). */
 export interface Paged<T> {
 export interface Paged<T> {
   items: T[]
   items: T[]

+ 8 - 0
app/src/hooks/useAgentFor.ts

@@ -0,0 +1,8 @@
+import { useNetPulse } from '@/data/DataProvider'
+import type { AgentInfo } from '@/data/types'
+
+/** Agente nativo registrado en un router: casa `slug` con `router.id` (Fase 6). */
+export function useAgentFor(routerId: string): AgentInfo | undefined {
+  const { agents } = useNetPulse()
+  return agents.find((a) => a.slug === routerId)
+}