DataProvider.tsx 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /**
  2. * NetPulse - DataProvider (contrato SÍNCRONO del frontend).
  3. *
  4. * Los componentes NUNCA ven HTTP: leen el bundle de dominio del contexto
  5. * (`useNetPulse()`). Internamente:
  6. * - Boot con el mock canónico → el primer paint es idéntico al mockup.
  7. * - Probe `GET /api/health` (timeout 2 s):
  8. * - OK → modo live: `GET /api/overview` + SSE `/api/stream`
  9. * (`snapshot` reemplaza el bundle, `alert` añade alerta). onerror →
  10. * `reconnecting` con backoff 2s→5s→15s y polling de `/api/overview`
  11. * a la cadencia del ajuste "Intervalo de refresco" hasta reconectar.
  12. * Cualquier 401 → redirect `/login`.
  13. * - Fallo → modo demo: `isDemo=true`, tick local cada 3 s con random walk
  14. * suave (cpu/ram/temp ±2, tráfico ±5 %, latencia WAN 6–11 ms).
  15. */
  16. import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
  17. import type {
  18. AdGuardStats,
  19. AgentInfo,
  20. AlertCategory,
  21. AlertConfigLevel,
  22. AlertEvent,
  23. AlertQuery,
  24. AlertsConfig,
  25. Device,
  26. DeviceQuery,
  27. DeviceTotals,
  28. DistributionNode,
  29. HealthScore,
  30. OverviewBundle,
  31. Paged,
  32. Router,
  33. TimeRange,
  34. TopoSemantics,
  35. TrafficPoint,
  36. VlanPort,
  37. MultiWanInfo,
  38. WanInfo,
  39. WireGuardStats,
  40. } from '@/data/types'
  41. import { VM_SUPPORTED } from '@/data/types'
  42. import {
  43. adguard as mockAdGuard,
  44. alerts as mockAlerts,
  45. DEMO_HEALTH_EN,
  46. DEMO_NAME_EN,
  47. DEMO_ROLE_EN,
  48. devices as mockDevices,
  49. deviceTotals as mockDeviceTotals,
  50. distributionNodes as mockDistributionNodes,
  51. healthScore as mockHealth,
  52. routers as mockRouters,
  53. trafficByRange as mockTraffic,
  54. wan as mockWan,
  55. wireguard as mockWireguard,
  56. } from '@/data/mock'
  57. import i18n from '@/i18n'
  58. import {
  59. countUnreadAlerts,
  60. isHiddenByLevel,
  61. loadDemoAlertsConfig,
  62. normalizeAlertsConfig,
  63. saveDemoAlertsConfig,
  64. } from '@/data/alertConfig'
  65. import { buildClientDevices } from '@/pages/devices-data'
  66. import { getRouterExtras } from '@/components/routers/routerExtras'
  67. import type { RouterExtras } from '@/components/routers/routerExtras'
  68. // ---------------------------------------------------------------------------
  69. // Tipos del contexto
  70. // ---------------------------------------------------------------------------
  71. export type ConnectionStatus = 'connected' | 'reconnecting' | 'demo'
  72. /** Punto de la serie real de rendimiento que sirve el backend (cpu/ram %,
  73. * temp °C) agregado por bucket; `t` es la etiqueta ya formateada. */
  74. export interface LivePerfPoint {
  75. t: string
  76. cpu: number
  77. ram: number
  78. temp: number
  79. }
  80. /** Series 1h/24h/7d del detalle de router (live). En demo no llegan. */
  81. export interface PerfSeriesLive {
  82. '1h'?: LivePerfPoint[]
  83. '24h'?: LivePerfPoint[]
  84. '7d'?: LivePerfPoint[]
  85. }
  86. export interface RouterDetailData {
  87. router: Router
  88. extras: RouterExtras
  89. clients: Device[]
  90. /** Series reales de rendimiento del router (live; ausente en demo). */
  91. series?: PerfSeriesLive
  92. /** Solo en el gateway */
  93. adguard?: AdGuardStats
  94. wireguard?: WireGuardStats
  95. /** VLANs del bridge (issue #315). Ausente si el router no tiene bridge vlan filtering. */
  96. vlans?: VlanPort[]
  97. /** Las varias conexiones a internet del router, si reporta más de una.
  98. * Solo lectura: las gestiona el panel del propio router. */
  99. multiWan?: MultiWanInfo
  100. /** Salud del sondeo SNMP (#930): contadores de éxito/fallo por router.
  101. * Ausente en routers que no se sondean por SNMP. */
  102. snmpOk?: number
  103. snmpFail?: number
  104. snmpConsecFail?: number
  105. lastSnmpErr?: string
  106. }
  107. export interface NetPulseData {
  108. health: HealthScore
  109. wan: WanInfo
  110. traffic: Record<TimeRange, TrafficPoint[]>
  111. adguard: AdGuardStats
  112. wireguard: WireGuardStats
  113. routers: Router[]
  114. devices: Device[]
  115. deviceTotals: DeviceTotals
  116. distributionNodes: DistributionNode[]
  117. topDevices: Device[]
  118. alerts: AlertEvent[]
  119. unreadAlerts: number
  120. /**
  121. * Versión del view-model del último overview (SPEC-65 D65-4). En demo y
  122. * antes del primer fetch vale VM_SUPPORTED (el canon local es vm=1).
  123. */
  124. vm: number
  125. /**
  126. * Semántica de topología precalculada por el servidor (SPEC-65 D65-3).
  127. * Ausente en demo y con servidores viejos → model.ts usa su cálculo local.
  128. */
  129. topology?: TopoSemantics
  130. /** Disponibilidad de usteer (roaming); ausente = no mostrar /roaming. */
  131. usteer?: { available: boolean }
  132. /** Daemon de roaming detectado: none | dawn | usteer | both (#428). */
  133. roamingDaemon?: 'none' | 'dawn' | 'usteer' | 'both'
  134. /** true si algún router reporta DAWN; la UI avisa de su deprecación (#426). */
  135. dawnDeprecated?: boolean
  136. /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
  137. orchestration?: boolean
  138. /** Segundos desde el arranque del server (#887); ausente = sin gracia. */
  139. serverUptimeSec?: number
  140. }
  141. export interface NetPulseApi extends NetPulseData {
  142. connectionStatus: ConnectionStatus
  143. /**
  144. * Agentes nativos registrados (GET /api/agents, Fase 3). El `slug` casa con
  145. * el `id` del router. En demo: lista vacía (sin badges, comportamiento
  146. * honesto — no se mockean agentes). Se refresca cada ~30 s en live.
  147. */
  148. agents: AgentInfo[]
  149. /** Re-pide `/api/agents` cuanto antes (live; #284: encadena el sondeo
  150. * rápido si hay upgrades en marcha). En demo es no-op. */
  151. refreshAgents: () => Promise<void>
  152. /** true = sin backend: dataset local del mockup con tick simulado */
  153. isDemo: boolean
  154. /** Re-pide `/api/overview` (live); en demo es no-op */
  155. refresh: () => void
  156. /** Date.now() del último snapshot fresco (SSE o fetch de overview); 0 si aún no hubo */
  157. lastSnapshotAt: number
  158. /**
  159. * POST /api/refresh (live): fuerza un sondeo inmediato en el backend; el
  160. * snapshot fresco llega por SSE. Resuelve `true` si toca esperar snapshot
  161. * (202 o 429 — el siguiente tick del poller lo empuja igualmente) y `false` si no hay
  162. * backend (demo) o falló la petición. En demo es no-op → false.
  163. */
  164. requestServerRefresh: () => Promise<boolean>
  165. getRouterDetail: (id: string) => Promise<RouterDetailData | null>
  166. getDevices: (params?: DeviceQuery) => Promise<Paged<Device>>
  167. getAlerts: (params?: AlertQuery) => Promise<Paged<AlertEvent>>
  168. /**
  169. * Configuración de alertas por categoría (SPEC-ALERTAS §2). Live: GET/PUT
  170. * /api/alerts/config (kv en backend). Demo: localStorage (UI demostrable).
  171. */
  172. alertsConfig: AlertsConfig
  173. /** Cambia el nivel de UNA categoría (PUT parcial en live). Resuelve true si persistió. */
  174. setAlertConfig: (category: AlertCategory, level: AlertConfigLevel) => Promise<boolean>
  175. /** Read state en SERVIDOR (live): POST /api/alerts/read. Demo: estado local. Optimista. */
  176. markAlertsRead: (ids: string[]) => void
  177. /** Marca leídas TODAS las alertas actuales sin borrarlas (#1034): el feed
  178. * las conserva como leídas; en live POST /api/alerts/read-all. Demo:
  179. * estado local. Optimista. */
  180. markAllAlertsRead: () => void
  181. /** Acción destructiva "Vaciar registro" (#1034) - POST /api/alerts/clear
  182. * (live): borra el log del servidor. Demo: estado local. Optimista. */
  183. clearAllAlerts: () => void
  184. /** POST /api/alerts/silence (live): silencia alertas con la misma dedup key. */
  185. silenceAlert: (id: string, duration: '1h' | '24h' | 'forever') => void
  186. /** POST /api/alerts/impostor-approve (live): aprueba un BSSID como propio
  187. * (#1400); la alerta de impostor de ese BSSID se resuelve y no vuelve. */
  188. approveImpostorBssid: (bssid: string) => void
  189. /**
  190. * PUT /api/wireguard/peers/{key}/urgent (live): marca o desmarca un peer
  191. * WireGuard como urgente (#1441), por su clave pública estable. Optimista
  192. * con rollback: si el servidor rechaza, el flag vuelve a su valor previo.
  193. * Demo: solo estado local, sin llamada de red.
  194. */
  195. setPeerUrgent: (key: string, urgent: boolean) => void
  196. /** POST /api/alerts/dismiss (live): limpia una alerta del feed (#833). Demo: estado local. Optimista. */
  197. dismissAlert: (id: string) => void
  198. /**
  199. * Fase 5 (Plan B): POST /api/agents/{slug}/rearm — reinicia el servicio
  200. * procd del agente en el router (vía SSH del servidor) y espera a que
  201. * vuelva a empujar. Devuelve `{ recovered }` o, si el backend rechaza con
  202. * un código de error específico, `{ recovered:false, error: <código> }`
  203. * (not_found, router_unknown, not_openwrt, netgrip_managed,
  204. * ssh_unavailable, cooldown, ssh_failed…). null si la petición falló por
  205. * red o en demo (demo siempre null: no hay agentes que rearmar).
  206. */
  207. rearmAgent: (slug: string) => Promise<{ recovered: boolean; error?: string } | null>
  208. /**
  209. * Fase 6.3 (issue #243): POST /api/agents/{slug}/upgrade — ordena al agente
  210. * que se actualice con el binario embebido del servidor. Resuelve el estado
  211. * del envío; null si la petición falló (demo siempre null).
  212. */
  213. upgradeAgent: (slug: string) => Promise<'sent' | 'queued' | 'not_connected' | null>
  214. /**
  215. * #1462: POST /api/agents/{slug}/backup — pide al agente un snapshot
  216. * standalone de su config (evento SSE "config_backup"). 202 enviado, 409 no
  217. * conectado (a diferencia del upgrade NO se encola: un backup no es
  218. * imperativo). null si la petición falló (demo siempre null).
  219. */
  220. backupAgent: (slug: string) => Promise<'sent' | 'not_connected' | null>
  221. /** #1899: copia de config por SSH en una unidad OpenWrt sin agente. */
  222. backupRouterSsh: (routerId: string) => Promise<{ ok: boolean; error?: string } | null>
  223. /**
  224. * #251: POST /api/agents/upgrade-all — envía el upgrade a todos los agentes
  225. * con versión desactualizada. Devuelve el resumen por slug; null si falló.
  226. */
  227. upgradeAllAgents: () => Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null>
  228. /**
  229. * #246: POST /api/agents/{slug}/reinstall — reinstala el agente en el router
  230. * vía SSH (binario, env, servicio procd). Devuelve el resultado; null si
  231. * falló (demo siempre null).
  232. */
  233. reinstallAgent: (slug: string) => Promise<{ recovered: boolean; token?: string; output?: string; error?: string } | null>
  234. /**
  235. * #624: POST /api/agents/{slug}/uninstall — desinstala el agente nativo del
  236. * router vía SSH (detiene el init, borra binario/env/watchdog) y revoca su
  237. * token. Devuelve `{ gone }` o null si falló (demo siempre null).
  238. */
  239. uninstallAgent: (slug: string) => Promise<{ gone: boolean; token?: boolean; error?: string } | null>
  240. /**
  241. * #1382: DELETE /api/agents/{slug} — retira el agente de la flota (revoca
  242. * su token y olvida su estado). Para equipos dados de baja de la red; si
  243. * el equipo vuelve, hay que re-enrolarlo. Distinto de uninstallAgent, que
  244. * desinstala el software del router vía SSH.
  245. */
  246. removeAgent: (slug: string) => Promise<{ error?: string } | null>
  247. /**
  248. * #245: POST /api/agents — crea/rota el token del agente y devuelve el
  249. * one-liner de instalación manual (fallback para routers sin SSH desde el
  250. * server). El token rota en cada llamada (se muestra UNA vez); el comando
  251. * ya lleva el token nuevo. null si falló (demo siempre null).
  252. */
  253. createAgentInstall: (slug: string) => Promise<{ install: string; token?: string } | null>
  254. }
  255. // ---------------------------------------------------------------------------
  256. // Estado inicial = mock canónico (primer paint idéntico al mockup)
  257. // ---------------------------------------------------------------------------
  258. /** Canon ES por id: permite restaurar el castellano al volver de EN → ES. */
  259. const CANON_ROUTER_BY_ID = new Map(mockRouters.map((r) => [r.id, r]))
  260. const CANON_DEVICE_BY_ID = new Map(mockDevices.map((d) => [d.id, d]))
  261. /**
  262. * Traduce los textos propios del canon demo (ES) al idioma activo (issue #238).
  263. * SOLO modo demo: en live los nombres llegan del backend y no se tocan.
  264. * Idempotente: el ES se restaura siempre desde el canon, nunca del estado
  265. * previo, así un EN → ES → EN no degrada datos.
  266. */
  267. function localizeDemoBundle(prev: NetPulseData, lang: string): NetPulseData {
  268. const en = lang.startsWith('en')
  269. const nameOf = <T extends { id: string; name: string }>(item: T, canonById: Map<string, T>): string => {
  270. const esName = canonById.get(item.id)?.name ?? item.name
  271. return en ? (DEMO_NAME_EN[item.id] ?? esName) : esName
  272. }
  273. const routers = prev.routers.map((r) => {
  274. const esRole = CANON_ROUTER_BY_ID.get(r.id)?.role ?? r.role
  275. return {
  276. ...r,
  277. name: nameOf(r, CANON_ROUTER_BY_ID),
  278. role: en ? (DEMO_ROLE_EN[esRole] ?? esRole) : esRole,
  279. }
  280. })
  281. const devices = prev.devices.map((d) => ({ ...d, name: nameOf(d, CANON_DEVICE_BY_ID) }))
  282. const deviceNameById = new Map(devices.map((d) => [d.id, d.name]))
  283. const health: HealthScore = {
  284. ...prev.health,
  285. caption: en ? (DEMO_HEALTH_EN[prev.health.caption] ?? prev.health.caption) : mockHealth.caption,
  286. note: en ? (DEMO_HEALTH_EN[prev.health.note] ?? prev.health.note) : mockHealth.note,
  287. breakdown: prev.health.breakdown.map((b, i) => ({
  288. ...b,
  289. label: en ? (DEMO_HEALTH_EN[b.label] ?? b.label) : (mockHealth.breakdown[i]?.label ?? b.label),
  290. })),
  291. }
  292. return {
  293. ...prev,
  294. routers,
  295. devices,
  296. health,
  297. topDevices: prev.topDevices.map((d) => ({ ...d, name: deviceNameById.get(d.id) ?? d.name })),
  298. }
  299. }
  300. function initialBundle(): NetPulseData {
  301. return localizeDemoBundle(
  302. {
  303. health: mockHealth,
  304. wan: mockWan,
  305. traffic: mockTraffic,
  306. adguard: mockAdGuard,
  307. wireguard: mockWireguard,
  308. routers: mockRouters,
  309. devices: mockDevices,
  310. deviceTotals: mockDeviceTotals,
  311. distributionNodes: mockDistributionNodes,
  312. topDevices: [...mockDevices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
  313. alerts: mockAlerts,
  314. unreadAlerts: countUnreadAlerts(mockAlerts, loadDemoAlertsConfig()),
  315. vm: VM_SUPPORTED,
  316. },
  317. i18n.language,
  318. )
  319. }
  320. /**
  321. * Bundle VACÍO para el modo live: el primer paint ya es datos reales (los que
  322. * llegan del backend), nunca el mockup de diseño. Regla: BD/datos 100% vacíos.
  323. */
  324. function emptyBundle(): NetPulseData {
  325. return {
  326. health: { score: 0, label: 'Bueno', caption: '', note: '', breakdown: [] },
  327. wan: {
  328. plan: '—',
  329. downMbps: 0,
  330. upMbps: 0,
  331. latencyMs: 0,
  332. lossPct: 0,
  333. publicIp: '—',
  334. isp: '—',
  335. peakTodayMbps: 0,
  336. peakTodayTime: '—',
  337. avgDownMbps: 0,
  338. total24h: 0,
  339. },
  340. traffic: { '1h': [], '24h': [], '7d': [], '30d': [] },
  341. adguard: {
  342. host: '',
  343. port: 0,
  344. status: 'inactive',
  345. queries24h: 0,
  346. blocked24h: 0,
  347. blockedPct: 0,
  348. trackersBlocked: 0,
  349. dnsLatencyMs: 0,
  350. clientsUsing: 0,
  351. clientsTotal: 0,
  352. topBlocked: [],
  353. filterLists: 0,
  354. rules: 0,
  355. },
  356. wireguard: { interface: '', subnet: '', status: 'inactive', peers: [] },
  357. routers: [],
  358. devices: [],
  359. deviceTotals: { total: 0, online: 0, knownOffline: 0, newToday: 0 },
  360. distributionNodes: [],
  361. topDevices: [],
  362. alerts: [],
  363. unreadAlerts: 0,
  364. vm: VM_SUPPORTED,
  365. }
  366. }
  367. /** Extras de detalle vacíos (live sin datos aún); el mock NO se usa en live. */
  368. export const EMPTY_EXTRAS: RouterExtras = {
  369. mac: '—',
  370. firmware: '—',
  371. firmwareUpdated: false,
  372. lastReboot: '—',
  373. soc: '—',
  374. flash: '—',
  375. ramMb: 0,
  376. bandSplit: { band24: 0, band5: 0, band6: 0, cable: 0 },
  377. trafficNow: 0,
  378. gatewayLatencySpark: [],
  379. backhaulSignal: [],
  380. radios: [],
  381. ports: [],
  382. ethPorts: [],
  383. }
  384. // ---------------------------------------------------------------------------
  385. // Utilidades de red / demo
  386. // ---------------------------------------------------------------------------
  387. /** Redirect compartido 401 → /login (evento para AuthGate + assign). Lo usan
  388. * el provider y las páginas que hacen fetch directo (Roaming, UsteerPanel). */
  389. export function redirectLogin(): never {
  390. window.dispatchEvent(new Event('netpulse-unauthorized'))
  391. window.location.assign('/login')
  392. throw new Error('unauthorized')
  393. }
  394. /** Probe del backend: OK solo si responde JSON `{ ok: true }` (evita falsos
  395. * positivos del fallback SPA de la preview estática, que devuelve HTML 200). */
  396. async function probeBackend(): Promise<boolean> {
  397. try {
  398. const res = await fetch('/api/health', { signal: AbortSignal.timeout(2000) })
  399. if (!res.ok) return false
  400. if (!(res.headers.get('content-type') ?? '').includes('application/json')) return false
  401. const data = (await res.json()) as { ok?: boolean }
  402. return data?.ok === true
  403. } catch {
  404. return false
  405. }
  406. }
  407. const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))
  408. const walkInt = (v: number, step: number, min: number, max: number) =>
  409. clamp(Math.round(v + (Math.random() * 2 - 1) * step), min, max)
  410. const walkPct = (v: number, pct = 5, min = 0) =>
  411. Math.max(min, Math.round(v * (1 + ((Math.random() * 2 - 1) * pct) / 100) * 10) / 10)
  412. /** Tick del modo demo: random walk suave (design feel "vivo"). */
  413. function demoTick(prev: NetPulseData): NetPulseData {
  414. const routers = prev.routers.map((r) => ({
  415. ...r,
  416. cpu: walkInt(r.cpu ?? 0, 2, 2, 97),
  417. ram: walkInt(r.ram ?? 0, 2, 5, 97),
  418. temp: walkInt(r.temp ?? 0, 2, 30, 90),
  419. }))
  420. const wan: WanInfo = {
  421. ...prev.wan,
  422. downMbps: walkPct(prev.wan.downMbps, 5, 1),
  423. upMbps: walkPct(prev.wan.upMbps, 5, 0.5),
  424. latencyMs: 6 + Math.round(Math.random() * 5),
  425. }
  426. const traffic = Object.fromEntries(
  427. (Object.keys(prev.traffic) as TimeRange[]).map((range) => {
  428. const series = prev.traffic[range]
  429. if (series.length === 0) return [range, series]
  430. const last = series[series.length - 1]!
  431. const next = { ...last, down: walkPct(last.down, 5, 1), up: walkPct(last.up, 5, 0.5) }
  432. return [range, [...series.slice(0, -1), next]]
  433. }),
  434. ) as Record<TimeRange, TrafficPoint[]>
  435. const devices = prev.devices.map((d) =>
  436. d.online ? { ...d, trafficMbps: walkPct(d.trafficMbps, 5) } : d,
  437. )
  438. return {
  439. ...prev,
  440. routers,
  441. wan,
  442. traffic,
  443. devices,
  444. topDevices: [...devices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
  445. }
  446. }
  447. function toQuery(params: Record<string, string | number | undefined>): string {
  448. const q = new URLSearchParams()
  449. for (const [k, v] of Object.entries(params)) {
  450. if (v !== undefined && v !== '') q.set(k, String(v))
  451. }
  452. const s = q.toString()
  453. return s ? `?${s}` : ''
  454. }
  455. /** Flag de módulo (B3): el aviso de vm > VM_SUPPORTED sale UNA sola vez. */
  456. let vmVersionWarned = false
  457. /**
  458. * Cadencia del polling de respaldo del SSE, según el ajuste de UI
  459. * "Intervalo de refresco" (clave localStorage `netpulse-refresh`).
  460. * Devuelve null si el ajuste está en "Pausado" ('0') o es inválido.
  461. */
  462. function readFallbackPollMs(): number | null {
  463. try {
  464. const raw = localStorage.getItem('netpulse-refresh')
  465. if (raw === null) return DEFAULT_FALLBACK_MS
  466. const v = JSON.parse(raw) as unknown
  467. if (v === '3') return 3000
  468. if (v === '5') return 5000
  469. if (v === '10') return 10000
  470. if (v === '0') return null
  471. return DEFAULT_FALLBACK_MS
  472. } catch {
  473. return DEFAULT_FALLBACK_MS
  474. }
  475. }
  476. const BACKOFF_MS = [2000, 5000, 15000]
  477. // Polling de respaldo del SSE (live): cadencia por defecto si el ajuste
  478. // "Intervalo de refresco" no está configurado. El ajuste (netpulse-refresh)
  479. // lo sustituye: '3'|'5'|'10' → segundos, '0' → pausado.
  480. const DEFAULT_FALLBACK_MS = 15000
  481. const DEMO_TICK_MS = 3000
  482. // Refresco del estado de agentes (fresh cambia solo en el backend, TTL ~90 s)
  483. const AGENTS_POLL_MS = 30000
  484. // #284: mientras algún agente tiene un self-update en marcha se sondea cada
  485. // 2 s para que la UI muestre el paso en vivo (downloading/swapping/...).
  486. const AGENTS_FAST_POLL_MS = 2000
  487. // Ventana que considera "activo" un upgrade reportado (segundos).
  488. const UPGRADE_ACTIVE_WINDOW_S = 120
  489. // ---------------------------------------------------------------------------
  490. // Provider
  491. // ---------------------------------------------------------------------------
  492. const NetPulseContext = createContext<NetPulseApi | null>(null)
  493. export function DataProvider({ children }: { children: React.ReactNode }) {
  494. const [bundle, setBundle] = useState<NetPulseData>(initialBundle)
  495. const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('demo')
  496. // isDemo desde el primer render si hay flag de demo (evita que los managers
  497. // de Ajustes disparen fetches antes del boot y fuercen redirect a /login)
  498. const [isDemo, setIsDemo] = useState(() => sessionStorage.getItem('netpulse-demo') === '1')
  499. // Marca temporal del último snapshot fresco (el botón "Refrescar" gira
  500. // hasta que esto avanza o expira su timeout de seguridad)
  501. const [lastSnapshotAt, setLastSnapshotAt] = useState(0)
  502. // Config de alertas: arranca con la demo (localStorage); en live la
  503. // reemplaza GET /api/alerts/config durante el boot
  504. const [alertsConfig, setAlertsConfigState] = useState<AlertsConfig>(loadDemoAlertsConfig)
  505. // Agentes nativos (live); demo = siempre vacío
  506. const [agents, setAgents] = useState<AgentInfo[]>([])
  507. // Refs para closures estables (getters async con la misma firma en ambos modos)
  508. const bundleRef = useRef(bundle)
  509. bundleRef.current = bundle
  510. const modeRef = useRef<'boot' | 'live' | 'demo'>('boot')
  511. // Estado de conexión en ref: el listener del ajuste "Intervalo de refresco"
  512. // (que cambia la cadencia del polling de respaldo) lo consulta sin rearmar
  513. // el effect de boot.
  514. const connectionStatusRef = useRef<ConnectionStatus>('demo')
  515. const setConnectionStatusTracked = useCallback((s: ConnectionStatus) => {
  516. connectionStatusRef.current = s
  517. setConnectionStatus(s)
  518. }, [])
  519. // Se sincroniza en applyAlertsConfig y en el fetch del boot (nunca en render)
  520. const configRef = useRef(alertsConfig)
  521. // fetchAgents vive dentro del effect de boot; este ref lo expone como
  522. // refreshAgents estable (#284: forzar una tanda tras enviar un upgrade).
  523. const refreshAgentsRef = useRef<() => Promise<void>>(async () => {})
  524. const refreshAgents = useCallback(() => refreshAgentsRef.current(), [])
  525. const applyOverview = useCallback((o: OverviewBundle) => {
  526. // SPEC-65 D65-4/D65-9 B3: view-model versionado. Un `vm` mayor que el
  527. // soportado avisa UNA sola vez por consola y nunca rompe la UI. Servidor
  528. // viejo sin `vm` → se asume la versión soportada. En demo no aplica
  529. // (el canon local es vm=1 y no pasa por aquí).
  530. const vm = o.vm ?? VM_SUPPORTED
  531. if (vm > VM_SUPPORTED && !vmVersionWarned) {
  532. vmVersionWarned = true
  533. console.warn(
  534. `[NetPulse] El servidor sirve view-model vm=${vm}, pero esta app soporta hasta vm=${VM_SUPPORTED}. ` +
  535. 'La UI sigue funcionando; actualiza la app para ver los campos nuevos.',
  536. )
  537. }
  538. setLastSnapshotAt(Date.now())
  539. setBundle((prev) => ({
  540. ...prev,
  541. health: o.health,
  542. wan: o.wan,
  543. traffic: o.traffic,
  544. adguard: o.adguard,
  545. wireguard: o.wireguard,
  546. routers: o.routers,
  547. deviceTotals: o.deviceTotals,
  548. distributionNodes: o.distributionNodes ?? [],
  549. topDevices: o.topDevices,
  550. alerts: o.alerts,
  551. unreadAlerts: o.unreadAlerts,
  552. vm,
  553. topology: o.topology,
  554. usteer: o.usteer,
  555. roamingDaemon: o.roamingDaemon,
  556. dawnDeprecated: o.dawnDeprecated,
  557. orchestration: o.orchestration,
  558. serverUptimeSec: o.serverUptimeSec,
  559. ...(o.devices ? { devices: o.devices } : {}),
  560. }))
  561. }, [])
  562. // -- boot ------------------------------------------------------------------
  563. useEffect(() => {
  564. let disposed = false
  565. let es: EventSource | null = null
  566. let pollId: number | undefined
  567. let reconnectId: number | undefined
  568. let tickId: number | undefined
  569. let agentsPollId: number | undefined
  570. let backoffIdx = 0
  571. const fetchJson = async (url: string): Promise<Response> => {
  572. const res = await fetch(url)
  573. if (res.status === 401) redirectLogin()
  574. return res
  575. }
  576. const fetchOverview = async (): Promise<boolean> => {
  577. try {
  578. const res = await fetchJson('/api/overview')
  579. if (!res.ok) return false
  580. applyOverview((await res.json()) as OverviewBundle)
  581. return true
  582. } catch {
  583. return false
  584. }
  585. }
  586. const fetchDevices = async (): Promise<void> => {
  587. try {
  588. const res = await fetchJson(`/api/devices${toQuery({ page: 1, pageSize: 500 })}`)
  589. if (!res.ok) return
  590. const json = (await res.json()) as Paged<Device>
  591. if (!disposed) setBundle((prev) => ({ ...prev, devices: json.items }))
  592. } catch {
  593. /* sin lista completa: se queda la del bundle */
  594. }
  595. }
  596. const stopPolling = () => {
  597. window.clearInterval(pollId)
  598. pollId = undefined
  599. }
  600. // Arranca (o re-arma) el polling de respaldo del SSE con la cadencia del
  601. // ajuste "Intervalo de refresco". Con el ajuste en "Pausado" no se arranca
  602. // nada (el SSE sigue reintentando por su backoff).
  603. const startFallbackPoll = () => {
  604. stopPolling()
  605. const ms = readFallbackPollMs()
  606. if (ms === null) return
  607. pollId = window.setInterval(() => {
  608. void fetchOverview()
  609. }, ms)
  610. }
  611. const stopSse = () => {
  612. es?.close()
  613. es = null
  614. }
  615. // #925: el pill amarillo "Reconnecting" solo aparece si la caída del SSE
  616. // se sostiene (> 5 s). Las reconexiones transientes (cambio de página,
  617. // refresh, proxies TLS que cortan el SSE) no deben llamar la atención:
  618. // el pill queda en "Live" y el SSE reconecta por debajo.
  619. let reconnectTimer: number | undefined
  620. const markReconnectingSoon = () => {
  621. if (reconnectTimer !== undefined) return
  622. reconnectTimer = window.setTimeout(() => {
  623. reconnectTimer = undefined
  624. setConnectionStatusTracked('reconnecting')
  625. }, 5000)
  626. }
  627. const clearReconnectTimer = () => {
  628. if (reconnectTimer === undefined) return
  629. window.clearTimeout(reconnectTimer)
  630. reconnectTimer = undefined
  631. }
  632. const startSse = () => {
  633. stopSse()
  634. if (disposed) return
  635. es = new EventSource('/api/stream')
  636. es.addEventListener('snapshot', (ev) => {
  637. try {
  638. applyOverview(JSON.parse((ev as MessageEvent).data as string) as OverviewBundle)
  639. backoffIdx = 0
  640. stopPolling()
  641. clearReconnectTimer()
  642. setConnectionStatusTracked('connected')
  643. } catch {
  644. /* payload inválido: se ignora */
  645. }
  646. })
  647. es.addEventListener('alert', (ev) => {
  648. try {
  649. const alert = JSON.parse((ev as MessageEvent).data as string) as AlertEvent
  650. // #1659: un nivel "none" oculta la categoría por completo. El
  651. // servidor ya no la emite; esto cubre el modo demo y una config
  652. // recién cambiada antes del siguiente snapshot.
  653. if (isHiddenByLevel(alert, configRef.current)) return
  654. setBundle((prev) => {
  655. // #891: dedupe por ID — un alert con ID ya presente NO se vuelve
  656. // a anteponer (duplicaba filas y sumaba al badge). Se reemplaza
  657. // en sitio: es la versión más reciente del mismo evento, y su
  658. // flag read viene de la verdad del servidor (engine.List).
  659. const idx = prev.alerts.findIndex((a) => a.id === alert.id)
  660. const existing = idx >= 0 ? prev.alerts[idx] : undefined
  661. if (existing) {
  662. const alerts = [...prev.alerts]
  663. alerts[idx] = alert
  664. const hadUnread = existing.read ? 0 : 1
  665. const hasUnread = alert.read ? 0 : 1
  666. return { ...prev, alerts, unreadAlerts: Math.max(0, prev.unreadAlerts - hadUnread + hasUnread) }
  667. }
  668. return {
  669. ...prev,
  670. alerts: [alert, ...prev.alerts],
  671. unreadAlerts: prev.unreadAlerts + (alert.read ? 0 : 1),
  672. }
  673. })
  674. } catch {
  675. /* payload inválido: se ignora */
  676. }
  677. })
  678. // #1434: resync del feed tras una mutación (clear/mark-read/dismiss/
  679. // resolve/silence). El poller solo emite snapshot al terminar cada
  680. // ciclo de sondeo; sin este evento Resumen y la campana se quedaban
  681. // stale hasta el próximo ciclo. Se aplica como parche del bundle.
  682. es.addEventListener('alerts', (ev) => {
  683. try {
  684. const data = JSON.parse((ev as MessageEvent).data as string) as {
  685. alerts?: AlertEvent[]
  686. unreadAlerts?: number
  687. }
  688. if (!Array.isArray(data.alerts)) return
  689. setBundle((prev) => ({
  690. ...prev,
  691. alerts: data.alerts as AlertEvent[],
  692. unreadAlerts: typeof data.unreadAlerts === 'number' ? data.unreadAlerts : prev.unreadAlerts,
  693. }))
  694. } catch {
  695. /* payload inválido: se ignora */
  696. }
  697. })
  698. es.onopen = () => {
  699. backoffIdx = 0
  700. stopPolling()
  701. clearReconnectTimer()
  702. setConnectionStatusTracked('connected')
  703. }
  704. es.onerror = () => {
  705. if (disposed) return
  706. markReconnectingSoon()
  707. stopSse()
  708. // Polling de respaldo (cadencia del ajuste "Intervalo de refresco")
  709. // hasta que el SSE reconecte.
  710. if (pollId === undefined) startFallbackPoll()
  711. // Reintento SSE con backoff 2s → 5s → 15s
  712. reconnectId = window.setTimeout(
  713. () => {
  714. backoffIdx = Math.min(backoffIdx + 1, BACKOFF_MS.length - 1)
  715. startSse()
  716. },
  717. BACKOFF_MS[backoffIdx],
  718. )
  719. }
  720. }
  721. const fetchAlertsConfig = async (): Promise<void> => {
  722. try {
  723. const res = await fetchJson('/api/alerts/config')
  724. if (!res.ok) return
  725. const cfg = normalizeAlertsConfig(await res.json())
  726. if (!disposed) {
  727. configRef.current = cfg
  728. setAlertsConfigState(cfg)
  729. }
  730. } catch {
  731. /* sin config: se quedan los defaults del SPEC §2 */
  732. }
  733. }
  734. // Agentes nativos (Fase 3): no forman parte del overview; se sondean
  735. // aparte cada ~30 s (2 s mientras hay upgrades en marcha, #284). Sin
  736. // agentes registrados → [] (sin badges).
  737. let upgradesActive = false
  738. const fetchAgents = async (): Promise<void> => {
  739. try {
  740. const res = await fetchJson('/api/agents')
  741. if (!res.ok) return
  742. const json = (await res.json()) as { agents?: AgentInfo[] } | AgentInfo[]
  743. const list = Array.isArray(json) ? json : (json.agents ?? [])
  744. if (!disposed) setAgents(list)
  745. const nowSec = Math.floor(Date.now() / 1000)
  746. upgradesActive = list.some(
  747. (a) =>
  748. a.upgrade &&
  749. a.upgrade.step !== 'failed' &&
  750. nowSec - a.upgrade.ts < UPGRADE_ACTIVE_WINDOW_S,
  751. )
  752. } catch {
  753. /* sin agentes: se mantiene el último estado conocido */
  754. }
  755. }
  756. refreshAgentsRef.current = fetchAgents
  757. // Auto-programación del sondeo: rápido con upgrades activos, lento en
  758. // reposo (#284). El delay se decide tras cada tanda con la respuesta.
  759. const scheduleAgentsPoll = (delay: number) => {
  760. agentsPollId = window.setTimeout(async () => {
  761. await fetchAgents()
  762. if (!disposed) scheduleAgentsPoll(upgradesActive ? AGENTS_FAST_POLL_MS : AGENTS_POLL_MS)
  763. }, delay)
  764. }
  765. const startLive = async () => {
  766. modeRef.current = 'live'
  767. setIsDemo(false)
  768. setBundle(emptyBundle()) // live: cero datos del mockup, solo backend
  769. const ok = await fetchOverview()
  770. await fetchDevices()
  771. await fetchAlertsConfig()
  772. await fetchAgents()
  773. if (disposed) return
  774. if (ok) setConnectionStatusTracked('connected')
  775. else {
  776. markReconnectingSoon()
  777. startFallbackPoll()
  778. }
  779. scheduleAgentsPoll(AGENTS_POLL_MS)
  780. startSse()
  781. }
  782. const startDemo = () => {
  783. modeRef.current = 'demo'
  784. setIsDemo(true)
  785. setConnectionStatusTracked('demo')
  786. // Demo: el badge de no leídas respeta la config guardada (SPEC §2)
  787. setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, configRef.current) }))
  788. tickId = window.setInterval(() => {
  789. if (!disposed) setBundle((prev) => demoTick(prev))
  790. }, DEMO_TICK_MS)
  791. }
  792. void (async () => {
  793. // Modo demo local (flag del login): dataset simulado sin backend
  794. if (sessionStorage.getItem('netpulse-demo') === '1') {
  795. startDemo()
  796. return
  797. }
  798. const hasBackend = await probeBackend()
  799. if (disposed) return
  800. if (hasBackend) await startLive()
  801. else startDemo()
  802. })()
  803. // Si el usuario cambia el ajuste "Intervalo de refresco" en Ajustes, se
  804. // re-arma el polling de respaldo al momento (sin recargar). Solo aplica
  805. // mientras el SSE está caído y el modo es live; en connected el SSE empuja
  806. // y no hay polling que re-armar.
  807. const onRefreshChange = () => {
  808. if (disposed || modeRef.current !== 'live') return
  809. if (connectionStatusRef.current !== 'reconnecting') return
  810. startFallbackPoll()
  811. }
  812. window.addEventListener('netpulse-refresh-change', onRefreshChange)
  813. return () => {
  814. disposed = true
  815. window.removeEventListener('netpulse-refresh-change', onRefreshChange)
  816. stopSse()
  817. stopPolling()
  818. window.clearTimeout(reconnectId)
  819. window.clearInterval(tickId)
  820. window.clearTimeout(agentsPollId)
  821. clearReconnectTimer()
  822. }
  823. }, [applyOverview, setConnectionStatusTracked])
  824. // -- idioma del dataset demo (issue #238) ------------------------------------
  825. // En demo, los textos propios del canon (nombres de routers/devices, roles,
  826. // salud) se traducen al idioma activo. En live los datos vienen del backend
  827. // y no se tocan.
  828. useEffect(() => {
  829. const onLang = (lang: string) => {
  830. if (modeRef.current === 'live') return
  831. setBundle((prev) => localizeDemoBundle(prev, lang))
  832. }
  833. onLang(i18n.language)
  834. i18n.on('languageChanged', onLang)
  835. return () => {
  836. i18n.off('languageChanged', onLang)
  837. }
  838. }, [])
  839. // -- API pública --------------------------------------------------------------
  840. const refresh = useCallback(() => {
  841. if (modeRef.current !== 'live') return
  842. void (async () => {
  843. try {
  844. const res = await fetch('/api/overview')
  845. if (res.status === 401) redirectLogin()
  846. if (res.ok) applyOverview((await res.json()) as OverviewBundle)
  847. } catch {
  848. /* el polling/SSE ya reintentará */
  849. }
  850. })()
  851. }, [applyOverview])
  852. // Sondeo manual (botón "Refrescar" de Topología): el backend sondea ya y
  853. // empuja el snapshot por SSE; aquí solo se dispara la petición. Un 429
  854. // (anti-martilleo, min 5 s) también cuenta como "espera": el siguiente tick
  855. // del poller empujará un snapshot fresco antes del timeout del botón.
  856. const requestServerRefresh = useCallback(async (): Promise<boolean> => {
  857. if (modeRef.current !== 'live') return false
  858. try {
  859. const res = await fetch('/api/refresh', { method: 'POST' })
  860. if (res.status === 401) redirectLogin()
  861. return res.status === 202 || res.status === 429
  862. } catch {
  863. return false
  864. }
  865. }, [])
  866. // -- Alertas: config + read state (SPEC-ALERTAS §2/§4) -----------------------
  867. /** Aplica una config nueva al estado y, en demo, la persiste y recalcula el badge. */
  868. const applyAlertsConfig = useCallback((cfg: AlertsConfig) => {
  869. configRef.current = cfg
  870. setAlertsConfigState(cfg)
  871. if (modeRef.current !== 'live') {
  872. saveDemoAlertsConfig(cfg)
  873. setBundle((prev) => ({ ...prev, unreadAlerts: countUnreadAlerts(prev.alerts, cfg) }))
  874. }
  875. }, [])
  876. const setAlertConfig = useCallback(
  877. async (category: AlertCategory, level: AlertConfigLevel): Promise<boolean> => {
  878. const optimistic = { ...configRef.current, [category]: level }
  879. applyAlertsConfig(optimistic)
  880. if (modeRef.current !== 'live') return true
  881. try {
  882. const res = await fetch('/api/alerts/config', {
  883. method: 'PUT',
  884. headers: { 'Content-Type': 'application/json' },
  885. body: JSON.stringify({ [category]: level }),
  886. })
  887. if (res.status === 401) redirectLogin()
  888. if (!res.ok) {
  889. // Resync con la verdad del servidor (p. ej. 400 por valor inválido)
  890. const g = await fetch('/api/alerts/config')
  891. if (g.status === 401) redirectLogin()
  892. if (g.ok) applyAlertsConfig(normalizeAlertsConfig(await g.json()))
  893. return false
  894. }
  895. applyAlertsConfig(normalizeAlertsConfig(await res.json()))
  896. refresh() // la lista/badge pueden cambiar con la nueva config
  897. return true
  898. } catch {
  899. return false
  900. }
  901. },
  902. [applyAlertsConfig, refresh],
  903. )
  904. /** Marca leídas de forma optimista; en live además POST /api/alerts/read. */
  905. const markAlertsRead = useCallback((ids: string[]) => {
  906. if (ids.length === 0) return
  907. const idSet = new Set(ids)
  908. setBundle((prev) => {
  909. const alerts = prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a))
  910. // En live NO se recalcula el contador localmente: el snapshot/SSE lo
  911. // corrige con la config por categoría del servidor (#224). Un filtrado
  912. // por `!read` a secas ignoraría categorías silenciadas y mostraría un
  913. // badge inconsistente hasta el siguiente snapshot.
  914. const unreadAlerts =
  915. modeRef.current === 'live'
  916. ? prev.unreadAlerts
  917. : countUnreadAlerts(alerts, configRef.current)
  918. return { ...prev, alerts, unreadAlerts }
  919. })
  920. if (modeRef.current !== 'live') return
  921. void (async () => {
  922. try {
  923. const res = await fetch('/api/alerts/read', {
  924. method: 'POST',
  925. headers: { 'Content-Type': 'application/json' },
  926. body: JSON.stringify({ ids }),
  927. })
  928. if (res.status === 401) redirectLogin()
  929. // #891: igual que en read-all — re-aplica el leído si un snapshot
  930. // pre-POST pisó el estado optimista mientras el POST estaba en vuelo.
  931. if (res.ok) {
  932. setBundle((prev) => ({
  933. ...prev,
  934. alerts: prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a)),
  935. }))
  936. }
  937. } catch {
  938. /* el próximo snapshot/SSE resincroniza el read state */
  939. }
  940. })()
  941. }, [])
  942. /** #1034: marca leídas todas las alertas actuales SIN borrarlas del log:
  943. * solo toca el read state (feed conservado, "Solo no leídas" es lo que
  944. * limpia la vista). Optimista; en live además POST /api/alerts/read-all. */
  945. const markAllAlertsRead = useCallback(() => {
  946. setBundle((prev) => ({
  947. ...prev,
  948. alerts: prev.alerts.map((a) => ({ ...a, read: true })),
  949. unreadAlerts: modeRef.current === 'live' ? prev.unreadAlerts : 0,
  950. }))
  951. if (modeRef.current !== 'live') return
  952. void (async () => {
  953. try {
  954. const res = await fetch('/api/alerts/read-all', { method: 'POST' })
  955. if (res.status === 401) redirectLogin()
  956. // #891: igual que en markAlertsRead — re-aplica el leído por si un
  957. // snapshot pre-POST pisó el estado optimista mientras el POST volaba.
  958. if (res.ok) {
  959. setBundle((prev) => ({
  960. ...prev,
  961. alerts: prev.alerts.map((a) => ({ ...a, read: true })),
  962. }))
  963. }
  964. } catch {
  965. /* el próximo snapshot/SSE resincroniza el read state */
  966. }
  967. })()
  968. }, [])
  969. // #1034: "Vaciar registro" BORRA el feed (dismiss en servidor: alert_log +
  970. // conjunto dismissed, no reaparecen tras F5). Es la acción destructiva; el
  971. // botón "Marcar todo como leído" ya no toca este endpoint (marca leídas
  972. // todas sin borrar). Una alerta viva (volátil con la condición aún activa,
  973. // p.ej. agent-down) puede volver al re-evaluarse.
  974. const clearAllAlerts = useCallback(() => {
  975. setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
  976. if (modeRef.current !== 'live') return
  977. void (async () => {
  978. try {
  979. const res = await fetch('/api/alerts/clear', { method: 'POST' })
  980. if (res.status === 401) redirectLogin()
  981. // #891: un snapshot tomado ANTES de que el POST llegara al servidor
  982. // puede haber pisado el estado optimista. Al resolver el POST, la
  983. // verdad del servidor YA incluye el clear, así que se re-aplica el
  984. // feed vacío por si llegó ese snapshot enrarecido.
  985. if (res.ok) {
  986. setBundle((prev) => ({ ...prev, alerts: [], unreadAlerts: 0 }))
  987. }
  988. } catch {
  989. /* idem: resync por snapshot */
  990. }
  991. })()
  992. }, [])
  993. /** Silencia una alerta por dedup key; el backend la filtra del feed. */
  994. const silenceAlert = useCallback((id: string, duration: '1h' | '24h' | 'forever') => {
  995. // Optimistic: remove the alert from the local feed immediately
  996. setBundle((prev) => {
  997. const target = prev.alerts.find((a) => a.id === id)
  998. if (!target) return prev
  999. const dedupKey = `${target.category}|${target.title}|${target.routerId ?? ''}`
  1000. const alerts = prev.alerts.filter((a) => {
  1001. const k = `${a.category}|${a.title}|${a.routerId ?? ''}`
  1002. return k !== dedupKey
  1003. })
  1004. const unreadAlerts =
  1005. modeRef.current === 'live'
  1006. ? prev.unreadAlerts
  1007. : countUnreadAlerts(alerts, configRef.current)
  1008. return { ...prev, alerts, unreadAlerts }
  1009. })
  1010. if (modeRef.current !== 'live') return
  1011. void (async () => {
  1012. try {
  1013. const res = await fetch('/api/alerts/silence', {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({ id, duration }),
  1017. })
  1018. if (res.status === 401) redirectLogin()
  1019. } catch {
  1020. /* resync por snapshot */
  1021. }
  1022. })()
  1023. }, [])
  1024. /** Aprueba un BSSID como propio (#1400): quita del feed las alertas de
  1025. * impostor de ese BSSID (optimista) y lo persiste en el backend (live). */
  1026. const approveImpostorBssid = useCallback((bssid: string) => {
  1027. setBundle((prev) => {
  1028. const alerts = prev.alerts.filter(
  1029. (a) => !(a.type === 'wifi-ssid-impostor' && a.vars?.bssid === bssid),
  1030. )
  1031. const unreadAlerts =
  1032. modeRef.current === 'live'
  1033. ? prev.unreadAlerts
  1034. : countUnreadAlerts(alerts, configRef.current)
  1035. return { ...prev, alerts, unreadAlerts }
  1036. })
  1037. if (modeRef.current !== 'live') return
  1038. void (async () => {
  1039. try {
  1040. const res = await fetch('/api/alerts/impostor-approve', {
  1041. method: 'POST',
  1042. headers: { 'Content-Type': 'application/json' },
  1043. body: JSON.stringify({ bssid }),
  1044. })
  1045. if (res.status === 401) redirectLogin()
  1046. } catch {
  1047. /* resync por snapshot */
  1048. }
  1049. })()
  1050. }, [])
  1051. /** Marca/desmarca un peer WG como urgente (#1441). Optimista con rollback:
  1052. * un fallo de red deja el flag como estaba. La clave es la pública del peer
  1053. * (`key`), no su id, que cambia cuando el peer casa con otro equipo. */
  1054. const setPeerUrgent = useCallback((key: string, urgent: boolean) => {
  1055. const previous =
  1056. bundleRef.current.wireguard.peers.find((p) => p.key === key)?.urgent ?? false
  1057. const apply = (value: boolean) =>
  1058. setBundle((b) => ({
  1059. ...b,
  1060. wireguard: {
  1061. ...b.wireguard,
  1062. peers: b.wireguard.peers.map((p) => (p.key === key ? { ...p, urgent: value } : p)),
  1063. },
  1064. }))
  1065. apply(urgent)
  1066. if (modeRef.current !== 'live') return
  1067. void (async () => {
  1068. try {
  1069. const res = await fetch(`/api/wireguard/peers/${encodeURIComponent(key)}/urgent`, {
  1070. method: 'PUT',
  1071. headers: { 'Content-Type': 'application/json' },
  1072. body: JSON.stringify({ urgent }),
  1073. })
  1074. if (res.status === 401) redirectLogin()
  1075. if (!res.ok) apply(previous)
  1076. } catch {
  1077. apply(previous)
  1078. }
  1079. })()
  1080. }, [])
  1081. /** Limpia una alerta del feed (issue #833): oculta la fila al instante y,
  1082. * en live, la persiste como dismiss en el backend (no reaparece tras un
  1083. * reinicio; si la condición se re-dispara, vuelve sola). */
  1084. const dismissAlert = useCallback((id: string) => {
  1085. setBundle((prev) => {
  1086. const alerts = prev.alerts.filter((a) => a.id !== id)
  1087. const unreadAlerts =
  1088. modeRef.current === 'live'
  1089. ? prev.unreadAlerts
  1090. : countUnreadAlerts(alerts, configRef.current)
  1091. return { ...prev, alerts, unreadAlerts }
  1092. })
  1093. if (modeRef.current !== 'live') return
  1094. void (async () => {
  1095. try {
  1096. const res = await fetch('/api/alerts/dismiss', {
  1097. method: 'POST',
  1098. headers: { 'Content-Type': 'application/json' },
  1099. body: JSON.stringify({ ids: [id] }),
  1100. })
  1101. if (res.status === 401) redirectLogin()
  1102. } catch {
  1103. /* resync por snapshot */
  1104. }
  1105. })()
  1106. }, [])
  1107. /**
  1108. * Fase 5 (Plan B): rearme del servicio del agente en el router. El
  1109. * backend ejecuta `init.d restart` por SSH y espera hasta 30 s el push de
  1110. * vuelta → por eso aquí NO hay timeout corto: se deja respirar. null =
  1111. * petición fallida (red o demo); `{ recovered:false, error }` = rechazo
  1112. * del backend con un código de error específico (#718) para que la UI
  1113. * muestre el motivo real en vez de un mensaje genérico.
  1114. */
  1115. const rearmAgent = useCallback(
  1116. async (slug: string): Promise<{ recovered: boolean; error?: string } | null> => {
  1117. if (modeRef.current !== 'live') return null
  1118. try {
  1119. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/rearm`, {
  1120. method: 'POST',
  1121. signal: AbortSignal.timeout(60_000),
  1122. })
  1123. if (res.status === 401) redirectLogin()
  1124. if (!res.ok) {
  1125. const body = (await res.json().catch(() => ({}))) as { error?: string }
  1126. return { recovered: false, error: body.error ?? 'generic' }
  1127. }
  1128. const json = (await res.json()) as { recovered?: boolean; message?: string }
  1129. return { recovered: json.recovered ?? false }
  1130. } catch {
  1131. return null
  1132. }
  1133. },
  1134. [],
  1135. )
  1136. /**
  1137. * Fase 6.3 (issue #243): ordena el self-update del agente. La API devuelve
  1138. * 202 (comando enviado por SSE) o 409 (agente no conectado). null = fallo de
  1139. * red/4xx-5xx/demo. Tras enviarlo, el agente se reinicia solo; el próximo
  1140. * poll de agentes (~30 s) refleja la versión nueva y updateAvailable=false.
  1141. */
  1142. const upgradeAgent = useCallback(async (slug: string): Promise<'sent' | 'queued' | 'not_connected' | null> => {
  1143. if (modeRef.current !== 'live') return null
  1144. try {
  1145. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/upgrade`, {
  1146. method: 'POST',
  1147. signal: AbortSignal.timeout(30_000),
  1148. })
  1149. if (res.status === 401) redirectLogin()
  1150. if (res.status === 409) return 'not_connected'
  1151. if (!res.ok) return null
  1152. // 202: el comando salió por SSE o quedó encolado hasta que el
  1153. // agente vuelva a conectar (#284).
  1154. const body = (await res.json().catch(() => null)) as { status?: string } | null
  1155. return body?.status === 'queued' ? 'queued' : 'sent'
  1156. } catch {
  1157. return null
  1158. }
  1159. }, [])
  1160. const backupAgent = useCallback(async (slug: string): Promise<'sent' | 'not_connected' | null> => {
  1161. if (modeRef.current !== 'live') return null
  1162. try {
  1163. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/backup`, {
  1164. method: 'POST',
  1165. signal: AbortSignal.timeout(30_000),
  1166. })
  1167. if (res.status === 401) redirectLogin()
  1168. if (res.status === 409) return 'not_connected'
  1169. if (!res.ok) return null
  1170. // 202: el comando salió por SSE. El resultado real se ve al aparecer
  1171. // la entrada nueva en GET /api/firmware-backups/{routerId} (el agente
  1172. // sube el tar.gz con el mismo contrato que el backup del flujo
  1173. // firmware, #1414); la UI lo sondea (AgentBackupButton).
  1174. return 'sent'
  1175. } catch {
  1176. return null
  1177. }
  1178. }, [])
  1179. // #1899: la copia la hace el propio servidor por SSH (sysupgrade
  1180. // --create-backup + base64) y la guarda donde la UI ya lista backups, asi
  1181. // que la entrada aparece en el mismo sitio que las del agente.
  1182. const backupRouterSsh = useCallback(async (routerId: string): Promise<{ ok: boolean; error?: string } | null> => {
  1183. if (modeRef.current !== 'live') return null
  1184. try {
  1185. const res = await fetch(`/api/firmware-backups/${encodeURIComponent(routerId)}`, {
  1186. method: 'POST',
  1187. signal: AbortSignal.timeout(150_000),
  1188. })
  1189. if (res.status === 401) redirectLogin()
  1190. const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string }
  1191. if (!res.ok) return { ok: false, error: body?.message ?? body?.error ?? `HTTP ${res.status}` }
  1192. return { ok: true }
  1193. } catch (e) {
  1194. return { ok: false, error: String(e) }
  1195. }
  1196. }, [])
  1197. const upgradeAllAgents = useCallback(async (): Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null> => { if (modeRef.current !== 'live') return null
  1198. try {
  1199. const res = await fetch('/api/agents/upgrade-all', {
  1200. method: 'POST',
  1201. signal: AbortSignal.timeout(60_000),
  1202. })
  1203. if (res.status === 401) redirectLogin()
  1204. if (!res.ok) return null
  1205. return (await res.json()) as { sent: number; total: number; message: string; agents: { slug: string; status: string }[] }
  1206. } catch {
  1207. return null
  1208. }
  1209. }, [])
  1210. const reinstallAgent = useCallback(async (slug: string): Promise<{ recovered: boolean; token?: string; output?: string; error?: string } | null> => {
  1211. if (modeRef.current !== 'live') return null
  1212. try {
  1213. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/reinstall`, {
  1214. method: 'POST',
  1215. signal: AbortSignal.timeout(90_000),
  1216. })
  1217. if (res.status === 401) redirectLogin()
  1218. if (!res.ok) {
  1219. const body = (await res.json().catch(() => ({}))) as { message?: string; output?: string }
  1220. return { recovered: false, error: body.message ?? `HTTP ${res.status}`, output: body.output }
  1221. }
  1222. const json = (await res.json()) as { recovered: boolean; token?: string; output?: string }
  1223. return { recovered: json.recovered, token: json.token, output: json.output }
  1224. } catch {
  1225. return { recovered: false, error: 'network' }
  1226. }
  1227. }, [])
  1228. const uninstallAgent = useCallback(async (slug: string): Promise<{ gone: boolean; token?: boolean; error?: string } | null> => {
  1229. if (modeRef.current !== 'live') return null
  1230. try {
  1231. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/uninstall`, {
  1232. method: 'POST',
  1233. signal: AbortSignal.timeout(90_000),
  1234. })
  1235. if (res.status === 401) redirectLogin()
  1236. if (!res.ok) {
  1237. const body = (await res.json().catch(() => ({}))) as { message?: string }
  1238. return { gone: false, error: body.message ?? `HTTP ${res.status}` }
  1239. }
  1240. const json = (await res.json()) as { gone: boolean; token?: boolean }
  1241. return { gone: json.gone, token: json.token }
  1242. } catch {
  1243. return { gone: false, error: 'network' }
  1244. }
  1245. }, [])
  1246. const removeAgent = useCallback(async (slug: string): Promise<{ error?: string } | null> => {
  1247. if (modeRef.current !== 'live') return null
  1248. try {
  1249. const res = await fetch(`/api/agents/${encodeURIComponent(slug)}`, {
  1250. method: 'DELETE',
  1251. signal: AbortSignal.timeout(30_000),
  1252. })
  1253. if (res.status === 401) redirectLogin()
  1254. if (!res.ok && res.status !== 204) {
  1255. const body = (await res.json().catch(() => ({}))) as { message?: string }
  1256. return { error: body.message ?? `HTTP ${res.status}` }
  1257. }
  1258. return {}
  1259. } catch {
  1260. return { error: 'network' }
  1261. }
  1262. }, [])
  1263. const createAgentInstall = useCallback(async (slug: string): Promise<{ install: string; token?: string } | null> => {
  1264. if (modeRef.current !== 'live') return null
  1265. try {
  1266. const res = await fetch('/api/agents', {
  1267. method: 'POST',
  1268. headers: { 'Content-Type': 'application/json' },
  1269. body: JSON.stringify({ slug }),
  1270. signal: AbortSignal.timeout(30_000),
  1271. })
  1272. if (res.status === 401) redirectLogin()
  1273. if (!res.ok) return null
  1274. const json = (await res.json()) as { install?: string; token?: string }
  1275. return json.install ? { install: json.install, token: json.token } : null
  1276. } catch {
  1277. return null
  1278. }
  1279. }, [])
  1280. const getRouterDetail = useCallback(async (id: string): Promise<RouterDetailData | null> => {
  1281. if (modeRef.current === 'live') {
  1282. const res = await fetch(`/api/routers/${encodeURIComponent(id)}`)
  1283. if (res.status === 401) redirectLogin()
  1284. if (res.status === 404) return null
  1285. if (!res.ok) return null
  1286. const json = (await res.json()) as {
  1287. router: Router
  1288. ports?: RouterExtras['ethPorts']
  1289. radios?: RouterExtras['radios'] | null
  1290. backhaul?: RouterExtras['backhaul'] | null
  1291. clients?: Device[]
  1292. extras?: RouterExtras
  1293. series?: PerfSeriesLive
  1294. adguard?: AdGuardStats
  1295. wireguard?: WireGuardStats
  1296. vlans?: VlanPort[]
  1297. multiWan?: MultiWanInfo
  1298. snmpOk?: number
  1299. snmpFail?: number
  1300. snmpConsecFail?: number
  1301. lastSnmpErr?: string
  1302. }
  1303. // Live: extras SOLO del backend (datos reales); nunca el mock local
  1304. const extras: RouterExtras = {
  1305. ...(json.extras ?? EMPTY_EXTRAS),
  1306. ethPorts: json.ports ?? json.extras?.ethPorts ?? [],
  1307. radios: json.radios ?? json.extras?.radios ?? [],
  1308. backhaul: json.backhaul ?? json.extras?.backhaul,
  1309. }
  1310. return {
  1311. router: json.router,
  1312. extras,
  1313. clients: json.clients ?? [],
  1314. series: json.series,
  1315. adguard: json.adguard,
  1316. wireguard: json.wireguard,
  1317. vlans: json.vlans,
  1318. multiWan: json.multiWan,
  1319. snmpOk: json.snmpOk,
  1320. snmpFail: json.snmpFail,
  1321. snmpConsecFail: json.snmpConsecFail,
  1322. lastSnmpErr: json.lastSnmpErr,
  1323. }
  1324. }
  1325. // Demo: resolución local desde mock + routerExtras (misma firma async)
  1326. const { routers, devices, adguard, wireguard } = bundleRef.current
  1327. const router = routers.find((r) => r.id === id)
  1328. if (!router) return null
  1329. const isGateway = router.roleBadge === 'Principal'
  1330. return {
  1331. router,
  1332. extras: getRouterExtras(id),
  1333. clients: devices.filter((d) => d.routerId === id),
  1334. adguard: isGateway ? adguard : undefined,
  1335. wireguard: isGateway ? wireguard : undefined,
  1336. }
  1337. }, [])
  1338. const getDevices = useCallback(async (params: DeviceQuery = {}): Promise<Paged<Device>> => {
  1339. const { q, routerId, band, type, status, page = 1, pageSize = 50 } = params
  1340. if (modeRef.current === 'live') {
  1341. const res = await fetch(`/api/devices${toQuery({ q, routerId, band, type, status, page, pageSize })}`)
  1342. if (res.status === 401) redirectLogin()
  1343. if (!res.ok) throw new Error(`GET /api/devices → ${res.status}`)
  1344. return (await res.json()) as Paged<Device>
  1345. }
  1346. // Demo: filtra y pagina el dataset completo del mockup (47 clientes)
  1347. let items = buildClientDevices(bundleRef.current.devices, true) as Device[]
  1348. if (routerId) items = items.filter((d) => d.routerId === routerId)
  1349. if (band) items = items.filter((d) => d.band === band)
  1350. if (type) items = items.filter((d) => d.type === type)
  1351. if (status) items = items.filter((d) => (status === 'online' ? d.online : !d.online))
  1352. if (q) {
  1353. const needle = q.toLowerCase()
  1354. items = items.filter((d) =>
  1355. `${d.name} ${d.ip} ${d.mac} ${d.manufacturer}`.toLowerCase().includes(needle),
  1356. )
  1357. }
  1358. const start = (page - 1) * pageSize
  1359. return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
  1360. }, [])
  1361. const getAlerts = useCallback(async (params: AlertQuery = {}): Promise<Paged<AlertEvent>> => {
  1362. const { severity, category, unread, page = 1, pageSize = 20 } = params
  1363. if (modeRef.current === 'live') {
  1364. const res = await fetch(`/api/alerts${toQuery({ severity, category, unread: unread ? 1 : undefined, page, pageSize })}`)
  1365. if (res.status === 401) redirectLogin()
  1366. if (!res.ok) throw new Error(`GET /api/alerts → ${res.status}`)
  1367. return (await res.json()) as Paged<AlertEvent>
  1368. }
  1369. let items = bundleRef.current.alerts
  1370. if (severity) items = items.filter((a) => a.severity === severity)
  1371. if (category) items = items.filter((a) => a.category === category)
  1372. if (unread) items = items.filter((a) => !a.read)
  1373. const start = (page - 1) * pageSize
  1374. return { items: items.slice(start, start + pageSize), total: items.length, page, pageSize }
  1375. }, [])
  1376. const value = useMemo<NetPulseApi>(
  1377. () => ({
  1378. ...bundle,
  1379. connectionStatus,
  1380. agents,
  1381. refreshAgents,
  1382. isDemo,
  1383. refresh,
  1384. lastSnapshotAt,
  1385. requestServerRefresh,
  1386. getRouterDetail,
  1387. getDevices,
  1388. getAlerts,
  1389. alertsConfig,
  1390. setAlertConfig,
  1391. markAlertsRead,
  1392. markAllAlertsRead,
  1393. clearAllAlerts,
  1394. silenceAlert,
  1395. approveImpostorBssid,
  1396. setPeerUrgent,
  1397. dismissAlert,
  1398. rearmAgent,
  1399. upgradeAgent,
  1400. backupAgent,
  1401. backupRouterSsh,
  1402. upgradeAllAgents,
  1403. reinstallAgent,
  1404. uninstallAgent,
  1405. removeAgent,
  1406. createAgentInstall,
  1407. }),
  1408. [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],
  1409. )
  1410. return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>
  1411. }
  1412. export function useNetPulse(): NetPulseApi {
  1413. const ctx = useContext(NetPulseContext)
  1414. if (!ctx) throw new Error('useNetPulse debe usarse dentro de <DataProvider>')
  1415. return ctx
  1416. }