| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488 |
- /**
- * NetPulse - DataProvider (contrato SÍNCRONO del frontend).
- *
- * Los componentes NUNCA ven HTTP: leen el bundle de dominio del contexto
- * (`useNetPulse()`). Internamente:
- * - Boot con el mock canónico → el primer paint es idéntico al mockup.
- * - Probe `GET /api/health` (timeout 2 s):
- * - OK → modo live: `GET /api/overview` + SSE `/api/stream`
- * (`snapshot` reemplaza el bundle, `alert` añade alerta). onerror →
- * `reconnecting` con backoff 2s→5s→15s y polling de `/api/overview`
- * a la cadencia del ajuste "Intervalo de refresco" hasta reconectar.
- * Cualquier 401 → redirect `/login`.
- * - Fallo → modo demo: `isDemo=true`, tick local cada 3 s con random walk
- * suave (cpu/ram/temp ±2, tráfico ±5 %, latencia WAN 6–11 ms).
- */
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
- import type {
- AdGuardStats,
- AgentInfo,
- AlertCategory,
- AlertConfigLevel,
- AlertEvent,
- AlertQuery,
- AlertsConfig,
- Device,
- DeviceQuery,
- DeviceTotals,
- DistributionNode,
- HealthScore,
- OverviewBundle,
- Paged,
- Router,
- TimeRange,
- TopoSemantics,
- TrafficPoint,
- VlanPort,
- MultiWanInfo,
- WanInfo,
- WireGuardStats,
- } from '@/data/types'
- import { VM_SUPPORTED } from '@/data/types'
- import {
- adguard as mockAdGuard,
- alerts as mockAlerts,
- DEMO_HEALTH_EN,
- DEMO_NAME_EN,
- DEMO_ROLE_EN,
- devices as mockDevices,
- deviceTotals as mockDeviceTotals,
- distributionNodes as mockDistributionNodes,
- healthScore as mockHealth,
- routers as mockRouters,
- trafficByRange as mockTraffic,
- wan as mockWan,
- wireguard as mockWireguard,
- } from '@/data/mock'
- import i18n from '@/i18n'
- import {
- countUnreadAlerts,
- isHiddenByLevel,
- loadDemoAlertsConfig,
- normalizeAlertsConfig,
- saveDemoAlertsConfig,
- } from '@/data/alertConfig'
- import { buildClientDevices } from '@/pages/devices-data'
- import { getRouterExtras } from '@/components/routers/routerExtras'
- import type { RouterExtras } from '@/components/routers/routerExtras'
- // ---------------------------------------------------------------------------
- // Tipos del contexto
- // ---------------------------------------------------------------------------
- export type ConnectionStatus = 'connected' | 'reconnecting' | 'demo'
- /** Punto de la serie real de rendimiento que sirve el backend (cpu/ram %,
- * temp °C) agregado por bucket; `t` es la etiqueta ya formateada. */
- export interface LivePerfPoint {
- t: string
- cpu: number
- ram: number
- temp: number
- }
- /** Series 1h/24h/7d del detalle de router (live). En demo no llegan. */
- export interface PerfSeriesLive {
- '1h'?: LivePerfPoint[]
- '24h'?: LivePerfPoint[]
- '7d'?: LivePerfPoint[]
- }
- export interface RouterDetailData {
- router: Router
- extras: RouterExtras
- clients: Device[]
- /** Series reales de rendimiento del router (live; ausente en demo). */
- series?: PerfSeriesLive
- /** Solo en el gateway */
- adguard?: AdGuardStats
- wireguard?: WireGuardStats
- /** VLANs del bridge (issue #315). Ausente si el router no tiene bridge vlan filtering. */
- vlans?: VlanPort[]
- /** Las varias conexiones a internet del router, si reporta más de una.
- * Solo lectura: las gestiona el panel del propio router. */
- multiWan?: MultiWanInfo
- /** Salud del sondeo SNMP (#930): contadores de éxito/fallo por router.
- * Ausente en routers que no se sondean por SNMP. */
- snmpOk?: number
- snmpFail?: number
- snmpConsecFail?: number
- lastSnmpErr?: string
- }
- export interface NetPulseData {
- health: HealthScore
- wan: WanInfo
- traffic: Record<TimeRange, TrafficPoint[]>
- adguard: AdGuardStats
- wireguard: WireGuardStats
- routers: Router[]
- devices: Device[]
- deviceTotals: DeviceTotals
- distributionNodes: DistributionNode[]
- topDevices: Device[]
- alerts: AlertEvent[]
- unreadAlerts: number
- /**
- * Versión del view-model del último overview (SPEC-65 D65-4). En demo y
- * antes del primer fetch vale VM_SUPPORTED (el canon local es vm=1).
- */
- vm: number
- /**
- * Semántica de topología precalculada por el servidor (SPEC-65 D65-3).
- * Ausente en demo y con servidores viejos → model.ts usa su cálculo local.
- */
- topology?: TopoSemantics
- /** Disponibilidad de usteer (roaming); ausente = no mostrar /roaming. */
- usteer?: { available: boolean }
- /** Daemon de roaming detectado: none | dawn | usteer | both (#428). */
- roamingDaemon?: 'none' | 'dawn' | 'usteer' | 'both'
- /** true si algún router reporta DAWN; la UI avisa de su deprecación (#426). */
- dawnDeprecated?: boolean
- /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
- orchestration?: boolean
- /** Segundos desde el arranque del server (#887); ausente = sin gracia. */
- serverUptimeSec?: number
- }
- export interface NetPulseApi extends NetPulseData {
- connectionStatus: ConnectionStatus
- /**
- * Agentes nativos registrados (GET /api/agents, Fase 3). 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[]
- /** Re-pide `/api/agents` cuanto antes (live; #284: encadena el sondeo
- * rápido si hay upgrades en marcha). En demo es no-op. */
- refreshAgents: () => Promise<void>
- /** true = sin backend: dataset local del mockup con tick simulado */
- isDemo: boolean
- /** Re-pide `/api/overview` (live); en demo es no-op */
- refresh: () => void
- /** Date.now() del último snapshot fresco (SSE o fetch de overview); 0 si aún no hubo */
- lastSnapshotAt: number
- /**
- * POST /api/refresh (live): fuerza un sondeo inmediato en el backend; el
- * snapshot fresco llega por SSE. Resuelve `true` si toca esperar snapshot
- * (202 o 429 — el siguiente tick del poller lo empuja igualmente) y `false` si no hay
- * backend (demo) o falló la petición. En demo es no-op → false.
- */
- requestServerRefresh: () => Promise<boolean>
- getRouterDetail: (id: string) => Promise<RouterDetailData | null>
- getDevices: (params?: DeviceQuery) => Promise<Paged<Device>>
- getAlerts: (params?: AlertQuery) => Promise<Paged<AlertEvent>>
- /**
- * Configuración de alertas por categoría (SPEC-ALERTAS §2). Live: GET/PUT
- * /api/alerts/config (kv en backend). Demo: localStorage (UI demostrable).
- */
- alertsConfig: AlertsConfig
- /** Cambia el nivel de UNA categoría (PUT parcial en live). Resuelve true si persistió. */
- setAlertConfig: (category: AlertCategory, level: AlertConfigLevel) => Promise<boolean>
- /** Read state en SERVIDOR (live): POST /api/alerts/read. Demo: estado local. Optimista. */
- markAlertsRead: (ids: string[]) => void
- /** Marca leídas TODAS las alertas actuales sin borrarlas (#1034): el feed
- * las conserva como leídas; en live POST /api/alerts/read-all. Demo:
- * estado local. Optimista. */
- markAllAlertsRead: () => void
- /** Acción destructiva "Vaciar registro" (#1034) - POST /api/alerts/clear
- * (live): borra el log del servidor. Demo: estado local. Optimista. */
- clearAllAlerts: () => void
- /** POST /api/alerts/silence (live): silencia alertas con la misma dedup key. */
- silenceAlert: (id: string, duration: '1h' | '24h' | 'forever') => void
- /** POST /api/alerts/impostor-approve (live): aprueba un BSSID como propio
- * (#1400); la alerta de impostor de ese BSSID se resuelve y no vuelve. */
- approveImpostorBssid: (bssid: string) => void
- /**
- * PUT /api/wireguard/peers/{key}/urgent (live): marca o desmarca un peer
- * WireGuard como urgente (#1441), por su clave pública estable. Optimista
- * con rollback: si el servidor rechaza, el flag vuelve a su valor previo.
- * Demo: solo estado local, sin llamada de red.
- */
- setPeerUrgent: (key: string, urgent: boolean) => void
- /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
- dismissAlert: (id: string) => void
- /**
- * Fase 5 (Plan B): POST /api/agents/{slug}/rearm — reinicia el servicio
- * procd del agente en el router (vía SSH del servidor) y espera a que
- * vuelva a empujar. Devuelve `{ recovered }` o, si el backend rechaza con
- * un código de error específico, `{ recovered:false, error: <código> }`
- * (not_found, router_unknown, not_openwrt, netgrip_managed,
- * ssh_unavailable, cooldown, ssh_failed…). null si la petición falló por
- * red o en demo (demo siempre null: no hay agentes que rearmar).
- */
- rearmAgent: (slug: string) => Promise<{ recovered: boolean; error?: string } | null>
- /**
- * Fase 6.3 (issue #243): POST /api/agents/{slug}/upgrade — ordena al agente
- * que se actualice con el binario embebido del servidor. Resuelve el estado
- * del envío; null si la petición falló (demo siempre null).
- */
- upgradeAgent: (slug: string) => Promise<'sent' | 'queued' | 'not_connected' | null>
- /**
- * #1462: POST /api/agents/{slug}/backup — pide al agente un snapshot
- * standalone de su config (evento SSE "config_backup"). 202 enviado, 409 no
- * conectado (a diferencia del upgrade NO se encola: un backup no es
- * imperativo). null si la petición falló (demo siempre null).
- */
- backupAgent: (slug: string) => Promise<'sent' | 'not_connected' | null>
- /** #1899: copia de config por SSH en una unidad OpenWrt sin agente. */
- backupRouterSsh: (routerId: string) => Promise<{ ok: boolean; error?: string } | null>
- /**
- * #251: POST /api/agents/upgrade-all — envía el upgrade a todos los agentes
- * con versión desactualizada. Devuelve el resumen por slug; null si falló.
- */
- upgradeAllAgents: () => Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null>
- /**
- * #246: POST /api/agents/{slug}/reinstall — reinstala el agente en el router
- * vía SSH (binario, env, servicio procd). Devuelve el resultado; null si
- * falló (demo siempre null).
- */
- reinstallAgent: (slug: string) => Promise<{ recovered: boolean; token?: string; output?: string; error?: string } | null>
- /**
- * #624: POST /api/agents/{slug}/uninstall — desinstala el agente nativo del
- * router vía SSH (detiene el init, borra binario/env/watchdog) y revoca su
- * token. Devuelve `{ gone }` o null si falló (demo siempre 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
- * one-liner de instalación manual (fallback para routers sin SSH desde el
- * server). El token rota en cada llamada (se muestra UNA vez); el comando
- * ya lleva el token nuevo. null si falló (demo siempre null).
- */
- createAgentInstall: (slug: string) => Promise<{ install: string; token?: string } | null>
- }
- // ---------------------------------------------------------------------------
- // Estado inicial = mock canónico (primer paint idéntico al mockup)
- // ---------------------------------------------------------------------------
- /** Canon ES por id: permite restaurar el castellano al volver de EN → ES. */
- const CANON_ROUTER_BY_ID = new Map(mockRouters.map((r) => [r.id, r]))
- const CANON_DEVICE_BY_ID = new Map(mockDevices.map((d) => [d.id, d]))
- /**
- * Traduce los textos propios del canon demo (ES) al idioma activo (issue #238).
- * SOLO modo demo: en live los nombres llegan del backend y no se tocan.
- * Idempotente: el ES se restaura siempre desde el canon, nunca del estado
- * previo, así un EN → ES → EN no degrada datos.
- */
- function localizeDemoBundle(prev: NetPulseData, lang: string): NetPulseData {
- const en = lang.startsWith('en')
- const nameOf = <T extends { id: string; name: string }>(item: T, canonById: Map<string, T>): string => {
- const esName = canonById.get(item.id)?.name ?? item.name
- return en ? (DEMO_NAME_EN[item.id] ?? esName) : esName
- }
- const routers = prev.routers.map((r) => {
- const esRole = CANON_ROUTER_BY_ID.get(r.id)?.role ?? r.role
- return {
- ...r,
- name: nameOf(r, CANON_ROUTER_BY_ID),
- role: en ? (DEMO_ROLE_EN[esRole] ?? esRole) : esRole,
- }
- })
- const devices = prev.devices.map((d) => ({ ...d, name: nameOf(d, CANON_DEVICE_BY_ID) }))
- const deviceNameById = new Map(devices.map((d) => [d.id, d.name]))
- const health: HealthScore = {
- ...prev.health,
- caption: en ? (DEMO_HEALTH_EN[prev.health.caption] ?? prev.health.caption) : mockHealth.caption,
- note: en ? (DEMO_HEALTH_EN[prev.health.note] ?? prev.health.note) : mockHealth.note,
- breakdown: prev.health.breakdown.map((b, i) => ({
- ...b,
- label: en ? (DEMO_HEALTH_EN[b.label] ?? b.label) : (mockHealth.breakdown[i]?.label ?? b.label),
- })),
- }
- return {
- ...prev,
- routers,
- devices,
- health,
- topDevices: prev.topDevices.map((d) => ({ ...d, name: deviceNameById.get(d.id) ?? d.name })),
- }
- }
- function initialBundle(): NetPulseData {
- return localizeDemoBundle(
- {
- health: mockHealth,
- wan: mockWan,
- traffic: mockTraffic,
- adguard: mockAdGuard,
- wireguard: mockWireguard,
- routers: mockRouters,
- devices: mockDevices,
- deviceTotals: mockDeviceTotals,
- distributionNodes: mockDistributionNodes,
- topDevices: [...mockDevices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
- alerts: mockAlerts,
- unreadAlerts: countUnreadAlerts(mockAlerts, loadDemoAlertsConfig()),
- vm: VM_SUPPORTED,
- },
- i18n.language,
- )
- }
- /**
- * Bundle VACÍO para el modo live: el primer paint ya es datos reales (los que
- * llegan del backend), nunca el mockup de diseño. Regla: BD/datos 100% vacíos.
- */
- function emptyBundle(): NetPulseData {
- return {
- health: { score: 0, label: 'Bueno', caption: '', note: '', breakdown: [] },
- wan: {
- plan: '—',
- downMbps: 0,
- upMbps: 0,
- latencyMs: 0,
- lossPct: 0,
- publicIp: '—',
- isp: '—',
- peakTodayMbps: 0,
- peakTodayTime: '—',
- avgDownMbps: 0,
- total24h: 0,
- },
- traffic: { '1h': [], '24h': [], '7d': [], '30d': [] },
- adguard: {
- host: '',
- port: 0,
- status: 'inactive',
- queries24h: 0,
- blocked24h: 0,
- blockedPct: 0,
- trackersBlocked: 0,
- dnsLatencyMs: 0,
- clientsUsing: 0,
- clientsTotal: 0,
- topBlocked: [],
- filterLists: 0,
- rules: 0,
- },
- wireguard: { interface: '', subnet: '', status: 'inactive', peers: [] },
- routers: [],
- devices: [],
- deviceTotals: { total: 0, online: 0, knownOffline: 0, newToday: 0 },
- distributionNodes: [],
- topDevices: [],
- alerts: [],
- unreadAlerts: 0,
- vm: VM_SUPPORTED,
- }
- }
- /** Extras de detalle vacíos (live sin datos aún); el mock NO se usa en live. */
- export const EMPTY_EXTRAS: RouterExtras = {
- mac: '—',
- firmware: '—',
- firmwareUpdated: false,
- lastReboot: '—',
- soc: '—',
- flash: '—',
- ramMb: 0,
- bandSplit: { band24: 0, band5: 0, band6: 0, cable: 0 },
- trafficNow: 0,
- gatewayLatencySpark: [],
- backhaulSignal: [],
- radios: [],
- ports: [],
- ethPorts: [],
- }
- // ---------------------------------------------------------------------------
- // Utilidades de red / demo
- // ---------------------------------------------------------------------------
- /** Redirect compartido 401 → /login (evento para AuthGate + assign). Lo usan
- * el provider y las páginas que hacen fetch directo (Roaming, UsteerPanel). */
- export function redirectLogin(): never {
- window.dispatchEvent(new Event('netpulse-unauthorized'))
- window.location.assign('/login')
- throw new Error('unauthorized')
- }
- /** Probe del backend: OK solo si responde JSON `{ ok: true }` (evita falsos
- * positivos del fallback SPA de la preview estática, que devuelve HTML 200). */
- async function probeBackend(): Promise<boolean> {
- try {
- const res = await fetch('/api/health', { signal: AbortSignal.timeout(2000) })
- if (!res.ok) return false
- if (!(res.headers.get('content-type') ?? '').includes('application/json')) return false
- const data = (await res.json()) as { ok?: boolean }
- return data?.ok === true
- } catch {
- return false
- }
- }
- const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))
- const walkInt = (v: number, step: number, min: number, max: number) =>
- clamp(Math.round(v + (Math.random() * 2 - 1) * step), min, max)
- const walkPct = (v: number, pct = 5, min = 0) =>
- Math.max(min, Math.round(v * (1 + ((Math.random() * 2 - 1) * pct) / 100) * 10) / 10)
- /** Tick del modo demo: random walk suave (design feel "vivo"). */
- function demoTick(prev: NetPulseData): NetPulseData {
- const routers = prev.routers.map((r) => ({
- ...r,
- cpu: walkInt(r.cpu ?? 0, 2, 2, 97),
- ram: walkInt(r.ram ?? 0, 2, 5, 97),
- temp: walkInt(r.temp ?? 0, 2, 30, 90),
- }))
- const wan: WanInfo = {
- ...prev.wan,
- downMbps: walkPct(prev.wan.downMbps, 5, 1),
- upMbps: walkPct(prev.wan.upMbps, 5, 0.5),
- latencyMs: 6 + Math.round(Math.random() * 5),
- }
- const traffic = Object.fromEntries(
- (Object.keys(prev.traffic) as TimeRange[]).map((range) => {
- const series = prev.traffic[range]
- if (series.length === 0) return [range, series]
- const last = series[series.length - 1]!
- const next = { ...last, down: walkPct(last.down, 5, 1), up: walkPct(last.up, 5, 0.5) }
- return [range, [...series.slice(0, -1), next]]
- }),
- ) as Record<TimeRange, TrafficPoint[]>
- const devices = prev.devices.map((d) =>
- d.online ? { ...d, trafficMbps: walkPct(d.trafficMbps, 5) } : d,
- )
- return {
- ...prev,
- routers,
- wan,
- traffic,
- devices,
- topDevices: [...devices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
- }
- }
- function toQuery(params: Record<string, string | number | undefined>): string {
- const q = new URLSearchParams()
- for (const [k, v] of Object.entries(params)) {
- if (v !== undefined && v !== '') q.set(k, String(v))
- }
- const s = q.toString()
- return s ? `?${s}` : ''
- }
- /** Flag de módulo (B3): el aviso de vm > VM_SUPPORTED sale UNA sola vez. */
- let vmVersionWarned = false
- /**
- * Cadencia del polling de respaldo del SSE, según el ajuste de UI
- * "Intervalo de refresco" (clave localStorage `netpulse-refresh`).
- * Devuelve null si el ajuste está en "Pausado" ('0') o es inválido.
- */
- function readFallbackPollMs(): number | null {
- try {
- const raw = localStorage.getItem('netpulse-refresh')
- if (raw === null) return DEFAULT_FALLBACK_MS
- const v = JSON.parse(raw) as unknown
- if (v === '3') return 3000
- if (v === '5') return 5000
- if (v === '10') return 10000
- if (v === '0') return null
- return DEFAULT_FALLBACK_MS
- } catch {
- return DEFAULT_FALLBACK_MS
- }
- }
- const BACKOFF_MS = [2000, 5000, 15000]
- // Polling de respaldo del SSE (live): cadencia por defecto si el ajuste
- // "Intervalo de refresco" no está configurado. El ajuste (netpulse-refresh)
- // lo sustituye: '3'|'5'|'10' → segundos, '0' → pausado.
- const DEFAULT_FALLBACK_MS = 15000
- const DEMO_TICK_MS = 3000
- // Refresco del estado de agentes (fresh cambia solo en el backend, TTL ~90 s)
- const AGENTS_POLL_MS = 30000
- // #284: mientras algún agente tiene un self-update en marcha se sondea cada
- // 2 s para que la UI muestre el paso en vivo (downloading/swapping/...).
- const AGENTS_FAST_POLL_MS = 2000
- // Ventana que considera "activo" un upgrade reportado (segundos).
- const UPGRADE_ACTIVE_WINDOW_S = 120
- // ---------------------------------------------------------------------------
- // Provider
- // ---------------------------------------------------------------------------
- const NetPulseContext = createContext<NetPulseApi | null>(null)
- export function DataProvider({ children }: { children: React.ReactNode }) {
- const [bundle, setBundle] = useState<NetPulseData>(initialBundle)
- const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('demo')
- // isDemo desde el primer render si hay flag de demo (evita que los managers
- // de Ajustes disparen fetches antes del boot y fuercen redirect a /login)
- const [isDemo, setIsDemo] = useState(() => sessionStorage.getItem('netpulse-demo') === '1')
- // Marca temporal del último snapshot fresco (el botón "Refrescar" gira
- // hasta que esto avanza o expira su timeout de seguridad)
- const [lastSnapshotAt, setLastSnapshotAt] = useState(0)
- // Config de alertas: arranca con la demo (localStorage); en live la
- // reemplaza GET /api/alerts/config durante el boot
- 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)
- const bundleRef = useRef(bundle)
- bundleRef.current = bundle
- const modeRef = useRef<'boot' | 'live' | 'demo'>('boot')
- // Estado de conexión en ref: el listener del ajuste "Intervalo de refresco"
- // (que cambia la cadencia del polling de respaldo) lo consulta sin rearmar
- // el effect de boot.
- const connectionStatusRef = useRef<ConnectionStatus>('demo')
- const setConnectionStatusTracked = useCallback((s: ConnectionStatus) => {
- connectionStatusRef.current = s
- setConnectionStatus(s)
- }, [])
- // Se sincroniza en applyAlertsConfig y en el fetch del boot (nunca en render)
- const configRef = useRef(alertsConfig)
- // fetchAgents vive dentro del effect de boot; este ref lo expone como
- // refreshAgents estable (#284: forzar una tanda tras enviar un upgrade).
- const refreshAgentsRef = useRef<() => Promise<void>>(async () => {})
- const refreshAgents = useCallback(() => refreshAgentsRef.current(), [])
- const applyOverview = useCallback((o: OverviewBundle) => {
- // SPEC-65 D65-4/D65-9 B3: view-model versionado. Un `vm` mayor que el
- // soportado avisa UNA sola vez por consola y nunca rompe la UI. Servidor
- // viejo sin `vm` → se asume la versión soportada. En demo no aplica
- // (el canon local es vm=1 y no pasa por aquí).
- const vm = o.vm ?? VM_SUPPORTED
- if (vm > VM_SUPPORTED && !vmVersionWarned) {
- vmVersionWarned = true
- console.warn(
- `[NetPulse] El servidor sirve view-model vm=${vm}, pero esta app soporta hasta vm=${VM_SUPPORTED}. ` +
- 'La UI sigue funcionando; actualiza la app para ver los campos nuevos.',
- )
- }
- setLastSnapshotAt(Date.now())
- setBundle((prev) => ({
- ...prev,
- health: o.health,
- wan: o.wan,
- traffic: o.traffic,
- adguard: o.adguard,
- wireguard: o.wireguard,
- routers: o.routers,
- deviceTotals: o.deviceTotals,
- distributionNodes: o.distributionNodes ?? [],
- topDevices: o.topDevices,
- alerts: o.alerts,
- unreadAlerts: o.unreadAlerts,
- vm,
- topology: o.topology,
- usteer: o.usteer,
- roamingDaemon: o.roamingDaemon,
- dawnDeprecated: o.dawnDeprecated,
- orchestration: o.orchestration,
- serverUptimeSec: o.serverUptimeSec,
- ...(o.devices ? { devices: o.devices } : {}),
- }))
- }, [])
- // -- boot ------------------------------------------------------------------
- useEffect(() => {
- let disposed = false
- let es: EventSource | null = null
- let pollId: number | undefined
- let reconnectId: number | undefined
- let tickId: number | undefined
- let agentsPollId: number | undefined
- let backoffIdx = 0
- const fetchJson = async (url: string): Promise<Response> => {
- const res = await fetch(url)
- if (res.status === 401) redirectLogin()
- return res
- }
- const fetchOverview = async (): Promise<boolean> => {
- try {
- const res = await fetchJson('/api/overview')
- if (!res.ok) return false
- applyOverview((await res.json()) as OverviewBundle)
- return true
- } catch {
- return false
- }
- }
- const fetchDevices = async (): Promise<void> => {
- try {
- const res = await fetchJson(`/api/devices${toQuery({ page: 1, pageSize: 500 })}`)
- if (!res.ok) return
- const json = (await res.json()) as Paged<Device>
- if (!disposed) setBundle((prev) => ({ ...prev, devices: json.items }))
- } catch {
- /* sin lista completa: se queda la del bundle */
- }
- }
- const stopPolling = () => {
- window.clearInterval(pollId)
- pollId = undefined
- }
- // Arranca (o re-arma) el polling de respaldo del SSE con la cadencia del
- // ajuste "Intervalo de refresco". Con el ajuste en "Pausado" no se arranca
- // nada (el SSE sigue reintentando por su backoff).
- const startFallbackPoll = () => {
- stopPolling()
- const ms = readFallbackPollMs()
- if (ms === null) return
- pollId = window.setInterval(() => {
- void fetchOverview()
- }, ms)
- }
- const stopSse = () => {
- es?.close()
- es = null
- }
- // #925: el pill amarillo "Reconnecting" solo aparece si la caída del SSE
- // se sostiene (> 5 s). Las reconexiones transientes (cambio de página,
- // refresh, proxies TLS que cortan el SSE) no deben llamar la atención:
- // el pill queda en "Live" y el SSE reconecta por debajo.
- let reconnectTimer: number | undefined
- const markReconnectingSoon = () => {
- if (reconnectTimer !== undefined) return
- reconnectTimer = window.setTimeout(() => {
- reconnectTimer = undefined
- setConnectionStatusTracked('reconnecting')
- }, 5000)
- }
- const clearReconnectTimer = () => {
- if (reconnectTimer === undefined) return
- window.clearTimeout(reconnectTimer)
- reconnectTimer = undefined
- }
- const startSse = () => {
- stopSse()
- if (disposed) return
- es = new EventSource('/api/stream')
- es.addEventListener('snapshot', (ev) => {
- try {
- applyOverview(JSON.parse((ev as MessageEvent).data as string) as OverviewBundle)
- backoffIdx = 0
- stopPolling()
- clearReconnectTimer()
- setConnectionStatusTracked('connected')
- } catch {
- /* payload inválido: se ignora */
- }
- })
- es.addEventListener('alert', (ev) => {
- try {
- const alert = JSON.parse((ev as MessageEvent).data as string) as AlertEvent
- // #1659: un nivel "none" oculta la categoría por completo. El
- // servidor ya no la emite; esto cubre el modo demo y una config
- // recién cambiada antes del siguiente snapshot.
- if (isHiddenByLevel(alert, configRef.current)) return
- setBundle((prev) => {
- // #891: dedupe por ID — un alert con ID ya presente NO se vuelve
- // a anteponer (duplicaba filas y sumaba al badge). Se reemplaza
- // en sitio: es la versión más reciente del mismo evento, y su
- // flag read viene de la verdad del servidor (engine.List).
- const idx = prev.alerts.findIndex((a) => a.id === alert.id)
- const existing = idx >= 0 ? prev.alerts[idx] : undefined
- if (existing) {
- const alerts = [...prev.alerts]
- alerts[idx] = alert
- const hadUnread = existing.read ? 0 : 1
- const hasUnread = alert.read ? 0 : 1
- return { ...prev, alerts, unreadAlerts: Math.max(0, prev.unreadAlerts - hadUnread + hasUnread) }
- }
- return {
- ...prev,
- alerts: [alert, ...prev.alerts],
- unreadAlerts: prev.unreadAlerts + (alert.read ? 0 : 1),
- }
- })
- } catch {
- /* payload inválido: se ignora */
- }
- })
- // #1434: resync del feed tras una mutación (clear/mark-read/dismiss/
- // resolve/silence). El poller solo emite snapshot al terminar cada
- // ciclo de sondeo; sin este evento Resumen y la campana se quedaban
- // stale hasta el próximo ciclo. Se aplica como parche del bundle.
- es.addEventListener('alerts', (ev) => {
- try {
- const data = JSON.parse((ev as MessageEvent).data as string) as {
- alerts?: AlertEvent[]
- unreadAlerts?: number
- }
- if (!Array.isArray(data.alerts)) return
- setBundle((prev) => ({
- ...prev,
- alerts: data.alerts as AlertEvent[],
- unreadAlerts: typeof data.unreadAlerts === 'number' ? data.unreadAlerts : prev.unreadAlerts,
- }))
- } catch {
- /* payload inválido: se ignora */
- }
- })
- es.onopen = () => {
- backoffIdx = 0
- stopPolling()
- clearReconnectTimer()
- setConnectionStatusTracked('connected')
- }
- es.onerror = () => {
- if (disposed) return
- markReconnectingSoon()
- stopSse()
- // Polling de respaldo (cadencia del ajuste "Intervalo de refresco")
- // hasta que el SSE reconecte.
- if (pollId === undefined) startFallbackPoll()
- // Reintento SSE con backoff 2s → 5s → 15s
- reconnectId = window.setTimeout(
- () => {
- backoffIdx = Math.min(backoffIdx + 1, BACKOFF_MS.length - 1)
- startSse()
- },
- BACKOFF_MS[backoffIdx],
- )
- }
- }
- const fetchAlertsConfig = async (): Promise<void> => {
- try {
- const res = await fetchJson('/api/alerts/config')
- if (!res.ok) return
- const cfg = normalizeAlertsConfig(await res.json())
- if (!disposed) {
- configRef.current = cfg
- setAlertsConfigState(cfg)
- }
- } catch {
- /* sin config: se quedan los defaults del SPEC §2 */
- }
- }
- // Agentes nativos (Fase 3): no forman parte del overview; se sondean
- // aparte cada ~30 s (2 s mientras hay upgrades en marcha, #284). Sin
- // agentes registrados → [] (sin badges).
- let upgradesActive = false
- 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)
- const nowSec = Math.floor(Date.now() / 1000)
- upgradesActive = list.some(
- (a) =>
- a.upgrade &&
- a.upgrade.step !== 'failed' &&
- nowSec - a.upgrade.ts < UPGRADE_ACTIVE_WINDOW_S,
- )
- } catch {
- /* sin agentes: se mantiene el último estado conocido */
- }
- }
- refreshAgentsRef.current = fetchAgents
- // Auto-programación del sondeo: rápido con upgrades activos, lento en
- // reposo (#284). El delay se decide tras cada tanda con la respuesta.
- const scheduleAgentsPoll = (delay: number) => {
- agentsPollId = window.setTimeout(async () => {
- await fetchAgents()
- if (!disposed) scheduleAgentsPoll(upgradesActive ? AGENTS_FAST_POLL_MS : AGENTS_POLL_MS)
- }, delay)
- }
- const startLive = async () => {
- modeRef.current = 'live'
- setIsDemo(false)
- setBundle(emptyBundle()) // live: cero datos del mockup, solo backend
- const ok = await fetchOverview()
- await fetchDevices()
- await fetchAlertsConfig()
- await fetchAgents()
- if (disposed) return
- if (ok) setConnectionStatusTracked('connected')
- else {
- markReconnectingSoon()
- startFallbackPoll()
- }
- scheduleAgentsPoll(AGENTS_POLL_MS)
- startSse()
- }
- const startDemo = () => {
- modeRef.current = 'demo'
- setIsDemo(true)
- setConnectionStatusTracked('demo')
- // Demo: el badge de no leídas respeta la config guardada (SPEC §2)
- setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, configRef.current) }))
- tickId = window.setInterval(() => {
- if (!disposed) setBundle((prev) => demoTick(prev))
- }, DEMO_TICK_MS)
- }
- void (async () => {
- // Modo demo local (flag del login): dataset simulado sin backend
- if (sessionStorage.getItem('netpulse-demo') === '1') {
- startDemo()
- return
- }
- const hasBackend = await probeBackend()
- if (disposed) return
- if (hasBackend) await startLive()
- else startDemo()
- })()
- // Si el usuario cambia el ajuste "Intervalo de refresco" en Ajustes, se
- // re-arma el polling de respaldo al momento (sin recargar). Solo aplica
- // mientras el SSE está caído y el modo es live; en connected el SSE empuja
- // y no hay polling que re-armar.
- const onRefreshChange = () => {
- if (disposed || modeRef.current !== 'live') return
- if (connectionStatusRef.current !== 'reconnecting') return
- startFallbackPoll()
- }
- window.addEventListener('netpulse-refresh-change', onRefreshChange)
- return () => {
- disposed = true
- window.removeEventListener('netpulse-refresh-change', onRefreshChange)
- stopSse()
- stopPolling()
- window.clearTimeout(reconnectId)
- window.clearInterval(tickId)
- window.clearTimeout(agentsPollId)
- clearReconnectTimer()
- }
- }, [applyOverview, setConnectionStatusTracked])
- // -- idioma del dataset demo (issue #238) ------------------------------------
- // En demo, los textos propios del canon (nombres de routers/devices, roles,
- // salud) se traducen al idioma activo. En live los datos vienen del backend
- // y no se tocan.
- useEffect(() => {
- const onLang = (lang: string) => {
- if (modeRef.current === 'live') return
- setBundle((prev) => localizeDemoBundle(prev, lang))
- }
- onLang(i18n.language)
- i18n.on('languageChanged', onLang)
- return () => {
- i18n.off('languageChanged', onLang)
- }
- }, [])
- // -- API pública --------------------------------------------------------------
- const refresh = useCallback(() => {
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/overview')
- if (res.status === 401) redirectLogin()
- if (res.ok) applyOverview((await res.json()) as OverviewBundle)
- } catch {
- /* el polling/SSE ya reintentará */
- }
- })()
- }, [applyOverview])
- // Sondeo manual (botón "Refrescar" de Topología): el backend sondea ya y
- // empuja el snapshot por SSE; aquí solo se dispara la petición. Un 429
- // (anti-martilleo, min 5 s) también cuenta como "espera": el siguiente tick
- // del poller empujará un snapshot fresco antes del timeout del botón.
- const requestServerRefresh = useCallback(async (): Promise<boolean> => {
- if (modeRef.current !== 'live') return false
- try {
- const res = await fetch('/api/refresh', { method: 'POST' })
- if (res.status === 401) redirectLogin()
- return res.status === 202 || res.status === 429
- } catch {
- return false
- }
- }, [])
- // -- Alertas: config + read state (SPEC-ALERTAS §2/§4) -----------------------
- /** Aplica una config nueva al estado y, en demo, la persiste y recalcula el badge. */
- const applyAlertsConfig = useCallback((cfg: AlertsConfig) => {
- configRef.current = cfg
- setAlertsConfigState(cfg)
- if (modeRef.current !== 'live') {
- saveDemoAlertsConfig(cfg)
- setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, cfg) }))
- }
- }, [])
- const setAlertConfig = useCallback(
- async (category: AlertCategory, level: AlertConfigLevel): Promise<boolean> => {
- const optimistic = { ...configRef.current, [category]: level }
- applyAlertsConfig(optimistic)
- if (modeRef.current !== 'live') return true
- try {
- const res = await fetch('/api/alerts/config', {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ [category]: level }),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) {
- // Resync con la verdad del servidor (p. ej. 400 por valor inválido)
- const g = await fetch('/api/alerts/config')
- if (g.status === 401) redirectLogin()
- if (g.ok) applyAlertsConfig(normalizeAlertsConfig(await g.json()))
- return false
- }
- applyAlertsConfig(normalizeAlertsConfig(await res.json()))
- refresh() // la lista/badge pueden cambiar con la nueva config
- return true
- } catch {
- return false
- }
- },
- [applyAlertsConfig, refresh],
- )
- /** Marca leídas de forma optimista; en live además POST /api/alerts/read. */
- const markAlertsRead = useCallback((ids: string[]) => {
- if (ids.length === 0) return
- const idSet = new Set(ids)
- setBundle((prev) => {
- const alerts = prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a))
- // En live NO se recalcula el contador localmente: el snapshot/SSE lo
- // corrige con la config por categoría del servidor (#224). Un filtrado
- // por `!read` a secas ignoraría categorías silenciadas y mostraría un
- // badge inconsistente hasta el siguiente snapshot.
- const unreadAlerts =
- modeRef.current === 'live'
- ? prev.unreadAlerts
- : countUnreadAlerts(alerts, configRef.current)
- return { ...prev, alerts, unreadAlerts }
- })
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/read', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ids }),
- })
- if (res.status === 401) redirectLogin()
- // #891: igual que en read-all — re-aplica el leído si un snapshot
- // pre-POST pisó el estado optimista mientras el POST estaba en vuelo.
- if (res.ok) {
- setBundle((prev) => ({
- ...prev,
- alerts: prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a)),
- }))
- }
- } catch {
- /* el próximo snapshot/SSE resincroniza el read state */
- }
- })()
- }, [])
- /** #1034: marca leídas todas las alertas actuales SIN borrarlas del log:
- * solo toca el read state (feed conservado, "Solo no leídas" es lo que
- * limpia la vista). Optimista; en live además POST /api/alerts/read-all. */
- const markAllAlertsRead = useCallback(() => {
- setBundle((prev) => ({
- ...prev,
- alerts: prev.alerts.map((a) => ({ ...a, read: true })),
- unreadAlerts: modeRef.current === 'live' ? prev.unreadAlerts : 0,
- }))
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/read-all', { method: 'POST' })
- if (res.status === 401) redirectLogin()
- // #891: igual que en markAlertsRead — re-aplica el leído por si un
- // snapshot pre-POST pisó el estado optimista mientras el POST volaba.
- if (res.ok) {
- setBundle((prev) => ({
- ...prev,
- alerts: prev.alerts.map((a) => ({ ...a, read: true })),
- }))
- }
- } catch {
- /* el próximo snapshot/SSE resincroniza el read state */
- }
- })()
- }, [])
- // #1034: "Vaciar registro" BORRA el feed (dismiss en servidor: alert_log +
- // conjunto dismissed, no reaparecen tras F5). Es la acción destructiva; el
- // botón "Marcar todo como leído" ya no toca este endpoint (marca leídas
- // todas sin borrar). Una alerta viva (volátil con la condición aún activa,
- // p.ej. agent-down) puede volver al re-evaluarse.
- const clearAllAlerts = useCallback(() => {
- setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/clear', { method: 'POST' })
- if (res.status === 401) redirectLogin()
- // #891: un snapshot tomado ANTES de que el POST llegara al servidor
- // puede haber pisado el estado optimista. Al resolver el POST, la
- // verdad del servidor YA incluye el clear, así que se re-aplica el
- // feed vacío por si llegó ese snapshot enrarecido.
- if (res.ok) {
- setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
- }
- } catch {
- /* idem: resync por snapshot */
- }
- })()
- }, [])
- /** Silencia una alerta por dedup key; el backend la filtra del feed. */
- const silenceAlert = useCallback((id: string, duration: '1h' | '24h' | 'forever') => {
- // Optimistic: remove the alert from the local feed immediately
- setBundle((prev) => {
- const target = prev.alerts.find((a) => a.id === id)
- if (!target) return prev
- const dedupKey = `${target.category}|${target.title}|${target.routerId ?? ''}`
- const alerts = prev.alerts.filter((a) => {
- const k = `${a.category}|${a.title}|${a.routerId ?? ''}`
- return k !== dedupKey
- })
- const unreadAlerts =
- modeRef.current === 'live'
- ? prev.unreadAlerts
- : countUnreadAlerts(alerts, configRef.current)
- return { ...prev, alerts, unreadAlerts }
- })
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/silence', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id, duration }),
- })
- if (res.status === 401) redirectLogin()
- } catch {
- /* resync por snapshot */
- }
- })()
- }, [])
- /** Aprueba un BSSID como propio (#1400): quita del feed las alertas de
- * impostor de ese BSSID (optimista) y lo persiste en el backend (live). */
- const approveImpostorBssid = useCallback((bssid: string) => {
- setBundle((prev) => {
- const alerts = prev.alerts.filter(
- (a) => !(a.type === 'wifi-ssid-impostor' && a.vars?.bssid === bssid),
- )
- const unreadAlerts =
- modeRef.current === 'live'
- ? prev.unreadAlerts
- : countUnreadAlerts(alerts, configRef.current)
- return { ...prev, alerts, unreadAlerts }
- })
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/impostor-approve', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ bssid }),
- })
- if (res.status === 401) redirectLogin()
- } catch {
- /* resync por snapshot */
- }
- })()
- }, [])
- /** Marca/desmarca un peer WG como urgente (#1441). Optimista con rollback:
- * un fallo de red deja el flag como estaba. La clave es la pública del peer
- * (`key`), no su id, que cambia cuando el peer casa con otro equipo. */
- const setPeerUrgent = useCallback((key: string, urgent: boolean) => {
- const previous =
- bundleRef.current.wireguard.peers.find((p) => p.key === key)?.urgent ?? false
- const apply = (value: boolean) =>
- setBundle((b) => ({
- ...b,
- wireguard: {
- ...b.wireguard,
- peers: b.wireguard.peers.map((p) => (p.key === key ? { ...p, urgent: value } : p)),
- },
- }))
- apply(urgent)
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch(`/api/wireguard/peers/${encodeURIComponent(key)}/urgent`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ urgent }),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) apply(previous)
- } catch {
- apply(previous)
- }
- })()
- }, [])
- /** Limpia una alerta del feed (issue #833): oculta la fila al instante y,
- * en live, la persiste como dismiss en el backend (no reaparece tras un
- * reinicio; si la condición se re-dispara, vuelve sola). */
- const dismissAlert = useCallback((id: string) => {
- setBundle((prev) => {
- const alerts = prev.alerts.filter((a) => a.id !== id)
- const unreadAlerts =
- modeRef.current === 'live'
- ? prev.unreadAlerts
- : countUnreadAlerts(alerts, configRef.current)
- return { ...prev, alerts, unreadAlerts }
- })
- if (modeRef.current !== 'live') return
- void (async () => {
- try {
- const res = await fetch('/api/alerts/dismiss', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ids: [id] }),
- })
- if (res.status === 401) redirectLogin()
- } catch {
- /* resync por snapshot */
- }
- })()
- }, [])
- /**
- * Fase 5 (Plan B): rearme del servicio del agente en el router. El
- * backend ejecuta `init.d restart` por SSH y espera hasta 30 s el push de
- * vuelta → por eso aquí NO hay timeout corto: se deja respirar. null =
- * petición fallida (red o demo); `{ recovered:false, error }` = rechazo
- * del backend con un código de error específico (#718) para que la UI
- * muestre el motivo real en vez de un mensaje genérico.
- */
- const rearmAgent = useCallback(
- async (slug: string): Promise<{ recovered: boolean; error?: string } | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/rearm`, {
- method: 'POST',
- signal: AbortSignal.timeout(60_000),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { error?: string }
- return { recovered: false, error: body.error ?? 'generic' }
- }
- const json = (await res.json()) as { recovered?: boolean; message?: string }
- return { recovered: json.recovered ?? false }
- } catch {
- return null
- }
- },
- [],
- )
- /**
- * Fase 6.3 (issue #243): ordena el self-update del agente. La API devuelve
- * 202 (comando enviado por SSE) o 409 (agente no conectado). null = fallo de
- * red/4xx-5xx/demo. Tras enviarlo, el agente se reinicia solo; el próximo
- * poll de agentes (~30 s) refleja la versión nueva y updateAvailable=false.
- */
- const upgradeAgent = useCallback(async (slug: string): Promise<'sent' | 'queued' | 'not_connected' | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/upgrade`, {
- method: 'POST',
- signal: AbortSignal.timeout(30_000),
- })
- if (res.status === 401) redirectLogin()
- if (res.status === 409) return 'not_connected'
- if (!res.ok) return null
- // 202: el comando salió por SSE o quedó encolado hasta que el
- // agente vuelva a conectar (#284).
- const body = (await res.json().catch(() => null)) as { status?: string } | null
- return body?.status === 'queued' ? 'queued' : 'sent'
- } catch {
- return null
- }
- }, [])
- const backupAgent = useCallback(async (slug: string): Promise<'sent' | 'not_connected' | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/backup`, {
- method: 'POST',
- signal: AbortSignal.timeout(30_000),
- })
- if (res.status === 401) redirectLogin()
- if (res.status === 409) return 'not_connected'
- if (!res.ok) return null
- // 202: el comando salió por SSE. El resultado real se ve al aparecer
- // la entrada nueva en GET /api/firmware-backups/{routerId} (el agente
- // sube el tar.gz con el mismo contrato que el backup del flujo
- // firmware, #1414); la UI lo sondea (AgentBackupButton).
- return 'sent'
- } catch {
- return null
- }
- }, [])
- // #1899: la copia la hace el propio servidor por SSH (sysupgrade
- // --create-backup + base64) y la guarda donde la UI ya lista backups, asi
- // que la entrada aparece en el mismo sitio que las del agente.
- const backupRouterSsh = useCallback(async (routerId: string): Promise<{ ok: boolean; error?: string } | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/firmware-backups/${encodeURIComponent(routerId)}`, {
- method: 'POST',
- signal: AbortSignal.timeout(150_000),
- })
- if (res.status === 401) redirectLogin()
- const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string }
- if (!res.ok) return { ok: false, error: body?.message ?? body?.error ?? `HTTP ${res.status}` }
- return { ok: true }
- } catch (e) {
- return { ok: false, error: String(e) }
- }
- }, [])
- const upgradeAllAgents = useCallback(async (): Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null> => { if (modeRef.current !== 'live') return null
- try {
- const res = await fetch('/api/agents/upgrade-all', {
- method: 'POST',
- signal: AbortSignal.timeout(60_000),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) return null
- return (await res.json()) as { sent: number; total: number; message: string; agents: { slug: string; status: string }[] }
- } catch {
- return null
- }
- }, [])
- const reinstallAgent = useCallback(async (slug: string): Promise<{ recovered: boolean; token?: string; output?: string; error?: string } | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/reinstall`, {
- method: 'POST',
- signal: AbortSignal.timeout(90_000),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { message?: string; output?: string }
- return { recovered: false, error: body.message ?? `HTTP ${res.status}`, output: body.output }
- }
- const json = (await res.json()) as { recovered: boolean; token?: string; output?: string }
- return { recovered: json.recovered, token: json.token, output: json.output }
- } catch {
- return { recovered: false, error: 'network' }
- }
- }, [])
- const uninstallAgent = useCallback(async (slug: string): Promise<{ gone: boolean; token?: boolean; error?: string } | null> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/uninstall`, {
- method: 'POST',
- signal: AbortSignal.timeout(90_000),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) {
- const body = (await res.json().catch(() => ({}))) as { message?: string }
- return { gone: false, error: body.message ?? `HTTP ${res.status}` }
- }
- const json = (await res.json()) as { gone: boolean; token?: boolean }
- return { gone: json.gone, token: json.token }
- } catch {
- return { gone: false, error: 'network' }
- }
- }, [])
- 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> => {
- if (modeRef.current !== 'live') return null
- try {
- const res = await fetch('/api/agents', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ slug }),
- signal: AbortSignal.timeout(30_000),
- })
- if (res.status === 401) redirectLogin()
- if (!res.ok) return null
- const json = (await res.json()) as { install?: string; token?: string }
- return json.install ? { install: json.install, token: json.token } : null
- } catch {
- return null
- }
- }, [])
- const getRouterDetail = useCallback(async (id: string): Promise<RouterDetailData | null> => {
- if (modeRef.current === 'live') {
- const res = await fetch(`/api/routers/${encodeURIComponent(id)}`)
- if (res.status === 401) redirectLogin()
- if (res.status === 404) return null
- if (!res.ok) return null
- const json = (await res.json()) as {
- router: Router
- ports?: RouterExtras['ethPorts']
- radios?: RouterExtras['radios'] | null
- backhaul?: RouterExtras['backhaul'] | null
- clients?: Device[]
- extras?: RouterExtras
- series?: PerfSeriesLive
- adguard?: AdGuardStats
- wireguard?: WireGuardStats
- vlans?: VlanPort[]
- multiWan?: MultiWanInfo
- snmpOk?: number
- snmpFail?: number
- snmpConsecFail?: number
- lastSnmpErr?: string
- }
- // Live: extras SOLO del backend (datos reales); nunca el mock local
- const extras: RouterExtras = {
- ...(json.extras ?? EMPTY_EXTRAS),
- ethPorts: json.ports ?? json.extras?.ethPorts ?? [],
- radios: json.radios ?? json.extras?.radios ?? [],
- backhaul: json.backhaul ?? json.extras?.backhaul,
- }
- return {
- router: json.router,
- extras,
- clients: json.clients ?? [],
- series: json.series,
- adguard: json.adguard,
- wireguard: json.wireguard,
- vlans: json.vlans,
- multiWan: json.multiWan,
- snmpOk: json.snmpOk,
- snmpFail: json.snmpFail,
- snmpConsecFail: json.snmpConsecFail,
- lastSnmpErr: json.lastSnmpErr,
- }
- }
- // Demo: resolución local desde mock + routerExtras (misma firma async)
- const { routers, devices, adguard, wireguard } = bundleRef.current
- const router = routers.find((r) => r.id === id)
- if (!router) return null
- const isGateway = router.roleBadge === 'Principal'
- return {
- router,
- extras: getRouterExtras(id),
- clients: devices.filter((d) => d.routerId === id),
- adguard: isGateway ? adguard : undefined,
- wireguard: isGateway ? wireguard : undefined,
- }
- }, [])
- const getDevices = useCallback(async (params: DeviceQuery = {}): Promise<Paged<Device>> => {
- const { q, routerId, band, type, status, page = 1, pageSize = 50 } = params
- if (modeRef.current === 'live') {
- const res = await fetch(`/api/devices${toQuery({ q, routerId, band, type, status, page, pageSize })}`)
- if (res.status === 401) redirectLogin()
- if (!res.ok) throw new Error(`GET /api/devices → ${res.status}`)
- return (await res.json()) as Paged<Device>
- }
- // Demo: filtra y pagina el dataset completo del mockup (47 clientes)
- let items = buildClientDevices(bundleRef.current.devices, true) as Device[]
- if (routerId) items = items.filter((d) => d.routerId === routerId)
- if (band) items = items.filter((d) => d.band === band)
- if (type) items = items.filter((d) => d.type === type)
- if (status) items = items.filter((d) => (status === 'online' ? d.online : !d.online))
- if (q) {
- const needle = q.toLowerCase()
- items = items.filter((d) =>
- `${d.name} ${d.ip} ${d.mac} ${d.manufacturer}`.toLowerCase().includes(needle),
- )
- }
- const start = (page - 1) * pageSize
- return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
- }, [])
- const getAlerts = useCallback(async (params: AlertQuery = {}): Promise<Paged<AlertEvent>> => {
- const { severity, category, unread, page = 1, pageSize = 20 } = params
- if (modeRef.current === 'live') {
- const res = await fetch(`/api/alerts${toQuery({ severity, category, unread: unread ? 1 : undefined, page, pageSize })}`)
- if (res.status === 401) redirectLogin()
- if (!res.ok) throw new Error(`GET /api/alerts → ${res.status}`)
- return (await res.json()) as Paged<AlertEvent>
- }
- let items = bundleRef.current.alerts
- if (severity) items = items.filter((a) => a.severity === severity)
- if (category) items = items.filter((a) => a.category === category)
- if (unread) items = items.filter((a) => !a.read)
- const start = (page - 1) * pageSize
- return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
- }, [])
- const value = useMemo<NetPulseApi>(
- () => ({
- ...bundle,
- connectionStatus,
- agents,
- refreshAgents,
- isDemo,
- refresh,
- lastSnapshotAt,
- requestServerRefresh,
- getRouterDetail,
- getDevices,
- getAlerts,
- alertsConfig,
- setAlertConfig,
- markAlertsRead,
- markAllAlertsRead,
- clearAllAlerts,
- silenceAlert,
- approveImpostorBssid,
- setPeerUrgent,
- dismissAlert,
- rearmAgent,
- upgradeAgent,
- backupAgent,
- backupRouterSsh,
- upgradeAllAgents,
- reinstallAgent,
- uninstallAgent,
- removeAgent,
- createAgentInstall,
- }),
- [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, backupAgent, upgradeAllAgents, backupRouterSsh, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
- )
- return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>
- }
- export function useNetPulse(): NetPulseApi {
- const ctx = useContext(NetPulseContext)
- if (!ctx) throw new Error('useNetPulse debe usarse dentro de <DataProvider>')
- return ctx
- }
|