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

merge: Fase 6.5 app consume view-model — mock.ts single-source desde demo-canon.json, badges infra sellada, topología semántica server con fallback, check vm desde fase65/viewmodel-app

agent 4 месяцев назад
Родитель
Сommit
374734228e

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

@@ -523,6 +523,9 @@
     "peers": {
       "overflowTitle": "{{count}} more peers",
       "overflowAria": "{{count}} additional WireGuard peers"
+    },
+    "ring": {
+      "overflowAria": "{{count}} more clients on {{router}}"
     }
   },
   "settings": {

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

@@ -523,6 +523,9 @@
     "peers": {
       "overflowTitle": "{{count}} peers más",
       "overflowAria": "{{count}} peers WireGuard adicionales"
+    },
+    "ring": {
+      "overflowAria": "{{count}} clientes más en {{router}}"
     }
   },
   "settings": {

+ 24 - 1
app/src/components/topology/TopologyMap.tsx

@@ -374,7 +374,7 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const navigate = useNavigate()
-  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, internetNode, links, peerNodes, relatedTo, routerNodes, wan } = model
+  const { chips, ctsByHost, ctCountByHost, distNodes, hiddenPeers, internetNode, links, peerNodes, relatedTo, ringOverflowChips, routerNodes, wan } = model
   const containerRef = useRef<HTMLDivElement>(null)
   const svgRef = useRef<SVGSVGElement>(null)
   const viewRef = useRef<View>({ ...INITIAL_VIEW })
@@ -1017,6 +1017,29 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
           </g>
         )}
 
+        {/* --------- Clientes ocultos del anillo ("+N", semántica server) ------ */}
+        {ringOverflowChips.map((chip, i) => {
+          const routerName = routerNodes.find((n) => n.id === chip.routerId)?.router.name ?? chip.routerId
+          return (
+            <g key={`ring-overflow-${chip.routerId}`} transform={`translate(${chip.x} ${chip.y})`}>
+              <motion.g
+                initial={reduce ? { opacity: 1 } : { opacity: 0, scale: 0.6 }}
+                animate={{ opacity: nodeOpacity(`ring-overflow-${chip.routerId}`), scale: 1 }}
+                transition={reduce ? { duration: 0 } : { delay: (2.2 + i * 0.1) * T, duration: 0.35 }}
+                style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
+              >
+                <g role="img" aria-label={t('topology.ring.overflowAria', { count: chip.count, router: routerName })}>
+                  <title>{t('topology.ring.overflowAria', { count: chip.count, router: routerName })}</title>
+                  <rect x={-15} y={-11} width={30} height={22} rx={8} fill="rgb(var(--elevated))" stroke={COLOR.accent} strokeWidth={1.5} />
+                  <text x={0} y={3.5} textAnchor="middle" fontSize={9.5} fontWeight={700} fill={COLOR.accent}>
+                    +{chip.count}
+                  </text>
+                </g>
+              </motion.g>
+            </g>
+          )
+        })}
+
         {/* ------------------------- Nodos de distribución (switch inferido) --- */}
         {distNodes.map((dv, i) => (
           <DistNodeGroup

+ 178 - 5
app/src/components/topology/model.ts

@@ -15,7 +15,7 @@
  * con arcos prohibidos (uplink, etiqueta, WAN, abanico cableado); cableados
  * en abanicos por hub; CTs en grid bajo el host.
  */
-import type { Band, Device, DistributionNode, Router, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
+import type { Band, Device, DistributionNode, Router, TopoSemantics, TopoSemLink, WanInfo, WGPeer, WireGuardStats } from '@/data/mock'
 
 /** viewBox del lienzo SVG */
 export const VB_W = 1000
@@ -117,6 +117,23 @@ export interface TopologyInput {
   wan: WanInfo
   wireguard: WireGuardStats
   distributionNodes?: DistributionNode[]
+  /**
+   * Semántica de topología precalculada server-side (SPEC-65 D65-3/D65-9 B2):
+   * anillos (miembros y orden), enlaces (from/to/kind) y "+N" de peers
+   * ocultos. La GEOMETRÍA (coordenadas, radios, paths) sigue 100% aquí.
+   * Ausente (servidor viejo o demo local) → cálculo local exacto de siempre.
+   */
+  topology?: TopoSemantics
+  /** Versión del view-model (SPEC-65 D65-4): la semántica aplica si vm >= 1. */
+  vm?: number
+}
+
+/** Chip "+N" de un anillo desbordado (posición ya calculada, geometría local). */
+export interface RingOverflowChip {
+  routerId: string
+  count: number
+  x: number
+  y: number
 }
 
 export interface TopologyModel {
@@ -135,6 +152,11 @@ export interface TopologyModel {
   ctCountByHost: Map<string, number>
   /** radios de los anillos wifi realmente usados por router (guías punteadas) */
   ringRadii: Map<string, number[]>
+  /**
+   * Chips "+N" por anillo desbordado (SPEC-65 D65-3 hiddenPeers, solo con
+   * semántica server-side): clientes del anillo que exceden el aforo visible.
+   */
+  ringOverflowChips: RingOverflowChip[]
   links: TopoLink[]
   totalPackets: number
   activeLinkCount: number
@@ -341,7 +363,10 @@ function flowFor(mbps: number, alive = false): { packets: number; packetDur: num
 // Builder
 // ---------------------------------------------------------------------------
 
-export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [] }: TopologyInput): TopologyModel {
+export function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [], topology, vm }: TopologyInput): TopologyModel {
+  // SPEC-65 D65-3/D65-9 B2: la semántica server-side aplica con vm >= 1 y
+  // `topology` presente; sin ella, fallback EXACTO al cálculo local.
+  const sem = topology && (vm ?? 1) >= 1 ? topology : undefined
   const gateway = routers.find((r) => r.roleBadge === 'Principal') ?? routers[0]
   const aps = routers.filter((r) => r.id !== gateway?.id).slice(0, AP_COORDS.length)
 
@@ -374,7 +399,36 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     if (isWired(d) && !d.port && gatewayNode) return gatewayNode.id
     return d.routerId
   }
-  const childrenOf = (hubId: string) => online.filter((d) => hubOf(d) === hubId)
+  // SPEC-65 D65-3/D65-9 B2: con semántica server-side, los anillos llegan
+  // calculados (miembros y orden: cableados primero, luego 5/2.4 GHz) junto
+  // con el "+N" (hiddenPeers = ring − aforo visible de los anillos canónicos:
+  // gateway 5+8=13, AP 7+13=20). Sin semántica, fallback al cálculo local.
+  const GW_RING_VISIBLE = GATEWAY_RINGS.reduce((a, r) => a + r.cap, 0)
+  const AP_RING_VISIBLE = AP_RINGS.reduce((a, r) => a + r.cap, 0)
+  const ringOrder = new Map<string, string[]>()
+  const ringVisible = new Map<string, Set<string>>()
+  const ringOverflow = new Map<string, number>()
+  if (sem) {
+    for (const node of routerNodes) {
+      const ring = sem.rings[node.id] ?? []
+      ringOrder.set(node.id, ring)
+      const cap = node.id === gatewayNode?.id ? GW_RING_VISIBLE : AP_RING_VISIBLE
+      ringVisible.set(node.id, new Set(ring.slice(0, cap)))
+      const hidden = sem.hiddenPeers?.[node.id] ?? 0
+      if (hidden > 0) ringOverflow.set(node.id, hidden)
+    }
+  }
+  const childrenOf = (hubId: string): Device[] => {
+    const ring = ringOrder.get(hubId)
+    if (ring) return ring.map((id) => deviceById.get(id)).filter((d): d is Device => d !== undefined)
+    return online.filter((d) => hubOf(d) === hubId)
+  }
+  /** Chips visibles del anillo: con semántica, los ocultos ("+N") no se pintan. */
+  const isVisibleInRing = (d: Device): boolean => {
+    if (!sem) return true
+    const vis = ringVisible.get(hubOf(d))
+    return vis ? vis.has(d.id) : true
+  }
   const isWired = (d: Device) => d.band === 'cable'
 
   /** Hubs que son dispositivos con hijos propios (switch gestionado, hipervisor) */
@@ -401,7 +455,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const dists = distributionNodes.filter(
       (n) => n.routerId === node.id && (n.kind === 'inferred' || n.kind === 'managed'),
     )
-    const directWired = childrenOf(node.id).filter(isWired)
+    const directWired = childrenOf(node.id).filter((d) => isWired(d) && isVisibleInRing(d))
     const hubs = directWired.filter((d) => deviceHubs.has(d.id))
     const plain = directWired.filter((d) => !deviceHubs.has(d.id))
 
@@ -468,7 +522,9 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const ringRadii = new Map<string, number[]>()
   for (const node of routerNodes) {
     const isGw = node.id === gatewayNode?.id
-    const wifi = childrenOf(node.id).filter((d) => !isWired(d)).map((d) => mkChip(d, node.id))
+    const wifi = childrenOf(node.id)
+      .filter((d) => !isWired(d) && isVisibleInRing(d))
+      .map((d) => mkChip(d, node.id))
     if (wifi.length === 0) continue
     const excludes: [number, number][] = []
     if (isGw) {
@@ -558,6 +614,19 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     chips.push(...kids)
   }
 
+  // Chips "+N" de anillos desbordados (solo con semántica server-side):
+  // posición en el anillo externo — geometría 100% local (ángulo libre:
+  // gateway 60° entre el fan WAN y el uplink patio; AP 250° bajo el router).
+  const ringOverflowChips: RingOverflowChip[] = []
+  for (const [routerId, count] of ringOverflow) {
+    const node = routerById.get(routerId)
+    if (!node) continue
+    const radii = ringRadii.get(routerId)
+    const isGw = routerId === gatewayNode?.id
+    const r = radii?.[radii.length - 1] ?? (isGw ? GATEWAY_RINGS : AP_RINGS)[(isGw ? GATEWAY_RINGS : AP_RINGS).length - 1].r
+    ringOverflowChips.push({ routerId, count, ...pos(node.x, node.y, isGw ? 60 : 250, r) })
+  }
+
   // -- peers WireGuard (arriba; túnel trazado vía Internet) -------------------
   // Hay 4 coordenadas canónicas: los activos que exceden se agrupan en el
   // chip "+N" (antes se descartaban silenciosamente).
@@ -687,6 +756,109 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     })
   })
 
+  // SPEC-65 D65-3/D65-9 B2: con semántica server-side, la LISTA de enlaces
+  // (from/to/kind) la manda el servidor; aquí solo se asigna la geometría
+  // (paths, etiquetas, flujo). En canon hay paridad 1:1 con los enlaces
+  // derivados localmente (golden test Go), así que se reutiliza la geometría
+  // ya calculada; para un enlace sin equivalente local (live con datos que
+  // el cálculo local no reproduce) se genera con las mismas reglas visuales.
+  if (sem) {
+    /** Geometría de un enlace semántico sin equivalente derivado localmente. */
+    const semLinkGeometry = (sl: TopoSemLink, wgIdx: number): TopoLink | null => {
+      const curve = (a: { x: number; y: number; r: number }, b: { x: number; y: number }): string => {
+        const edge = pos(a.x, a.y, angleTo(a.x, a.y, b.x, b.y), a.r + 2)
+        const dx = b.x - edge.x
+        const dy = b.y - edge.y
+        return `M ${edge.x} ${edge.y} Q ${edge.x + dx * 0.5 - dy * 0.1} ${edge.y + dy * 0.5 + dx * 0.1}, ${b.x} ${b.y}`
+      }
+      switch (sl.kind) {
+        case 'wan': {
+          if (!gatewayNode || sl.to !== gatewayNode.id) return null
+          return {
+            id: 'wan', kind: 'wan',
+            d: 'M 500 92 C 500 122, 500 162, 500 208',
+            lx: 518, ly: 162, label: `Fibra ${wan.plan} · ${wan.latencyMs} ms`,
+            width: 3, ...flowFor(600),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'uplink': {
+          const i = apNodes.findIndex((n) => n.id === sl.to)
+          const node = i >= 0 ? apNodes[i] : routerById.get(sl.to)
+          if (!node) return null
+          const isWifi = node.router.backhaul === 'wifi'
+          const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
+          const p = i >= 0 ? UPLINK_PATHS[i] : null
+          const from = gatewayNode ?? null
+          return {
+            id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
+            d: p?.d ?? (from ? curve(from, node) : ''),
+            lx: p?.lx ?? 0, ly: p?.ly ?? 0,
+            label,
+            width: isWifi ? 2 : 3, ...flowFor(Math.max(subtreeTraffic(node.id), isWifi ? 40 : 120)),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'dist': {
+          const dv = distNodes.find((n) => n.id === sl.to)
+          const rn = routerById.get(sl.from)
+          if (!dv || !rn) return null
+          const edge = pos(rn.x, rn.y, angleTo(rn.x, rn.y, dv.x, dv.y), rn.r + 2)
+          const mid = { x: (edge.x + dv.x) / 2, y: (edge.y + dv.y) / 2 }
+          return {
+            id: `dist-${dv.id}`, kind: 'dist',
+            d: `M ${edge.x} ${edge.y} Q ${mid.x + 6} ${mid.y - 6}, ${dv.x} ${dv.y}`,
+            lx: 0, ly: 0, label: '',
+            width: 2.5, ...flowFor(subtreeTraffic(dv.id), true),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'wired': {
+          const chip = chipById.get(sl.to)
+          const hub = hubPos(sl.from)
+          if (!chip || !hub) return null
+          const mbps = deviceHubs.has(chip.id) ? chip.device.trafficMbps + subtreeTraffic(chip.id) : chip.device.trafficMbps
+          return {
+            id: `wired-${chip.id}`, kind: 'wired',
+            d: curve(hub, chip),
+            lx: 0, ly: 0, label: '',
+            width: chip.isCt ? 1.2 : 1.4, ...flowFor(mbps, true),
+            from: sl.from, to: sl.to,
+          }
+        }
+        case 'wg': {
+          const pn = peerNodes.find((p) => p.id === sl.from)
+          if (!pn) return null
+          const p = WG_PATHS[wgIdx] ?? { d: '', dur: 3.2 }
+          const d = p.d || `M ${pn.x + 7} ${pn.y + 18} C ${pn.x + 60} ${pn.y + 56}, ${internetNode.x - 40} ${internetNode.y + 36}, ${internetNode.x - 26} ${internetNode.y + 22}`
+          return {
+            id: `wg-${pn.peer.id}`, kind: 'wg',
+            d, lx: 0, ly: 0, label: '',
+            width: 2, packets: 1, packetDur: p.dur,
+            from: sl.from, to: sl.to,
+          }
+        }
+      }
+    }
+    const derivedByKey = new Map(links.map((l) => [`${l.kind}|${l.from}|${l.to}`, l] as const))
+    const semLinks: TopoLink[] = []
+    let wgIdx = 0
+    for (const sl of sem.links) {
+      const key = `${sl.kind}|${sl.from}|${sl.to}` as const
+      const hit = derivedByKey.get(key)
+      if (hit) {
+        semLinks.push(hit)
+        derivedByKey.delete(key)
+        if (sl.kind === 'wg') wgIdx++
+        continue
+      }
+      const gen = semLinkGeometry(sl, sl.kind === 'wg' ? wgIdx++ : 0)
+      if (gen) semLinks.push(gen)
+    }
+    links.length = 0
+    links.push(...semLinks)
+  }
+
   /** Guardrail de rendimiento: máx ~60 paquetes simultáneos (mockup) */
   let totalPackets = links.reduce((acc, l) => acc + l.packets, 0)
   if (totalPackets > 60) {
@@ -819,6 +991,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     ctsByHost,
     ctCountByHost,
     ringRadii,
+    ringOverflowChips,
     links,
     totalPackets,
     activeLinkCount,

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

@@ -30,10 +30,12 @@ import type {
   Paged,
   Router,
   TimeRange,
+  TopoSemantics,
   TrafficPoint,
   WanInfo,
   WireGuardStats,
 } from '@/data/types'
+import { VM_SUPPORTED } from '@/data/types'
 import {
   adguard as mockAdGuard,
   alerts as mockAlerts,
@@ -84,6 +86,16 @@ export interface NetPulseData {
   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
 }
 
 export interface NetPulseApi extends NetPulseData {
@@ -141,6 +153,7 @@ function initialBundle(): NetPulseData {
     topDevices: [...mockDevices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
     alerts: mockAlerts,
     unreadAlerts: mockAlerts.filter((a) => !a.read).length,
+    vm: VM_SUPPORTED,
   }
 }
 
@@ -188,6 +201,7 @@ function emptyBundle(): NetPulseData {
     topDevices: [],
     alerts: [],
     unreadAlerts: 0,
+    vm: VM_SUPPORTED,
   }
 }
 
@@ -284,6 +298,9 @@ function toQuery(params: Record<string, string | number | undefined>): string {
   return s ? `?${s}` : ''
 }
 
+/** Flag de módulo (B3): el aviso de vm > VM_SUPPORTED sale UNA sola vez. */
+let vmVersionWarned = false
+
 const BACKOFF_MS = [2000, 5000, 15000]
 const POLL_MS = 15000
 const DEMO_TICK_MS = 3000
@@ -319,6 +336,18 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   const configRef = useRef(alertsConfig)
 
   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,
@@ -333,6 +362,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       topDevices: o.topDevices,
       alerts: o.alerts,
       unreadAlerts: o.unreadAlerts,
+      vm,
+      topology: o.topology,
     }))
   }, [])
 

+ 23 - 335
app/src/data/mock.ts

@@ -1,7 +1,13 @@
 /**
  * NetPulse — Datos mock canónicos (design.md §11).
  * CONTRATO: todas las páginas importan de `@/data/mock`.
- * No modificar valores sin actualizar design.md.
+ *
+ * SPEC-65 D65-1 (single-source): el canon (routers, devices, deviceTotals,
+ * distributionNodes, adguard, wireguard, wan, health) vive SOLO en
+ * `demo-canon.json`, generado desde Go (`go run ./cmd/gen-demo-canon` en
+ * server-go). NUNCA editar el JSON a mano: hay un test Go de frescura.
+ * Aquí quedan solo: paleta, tráfico local del tick demo (random walk — no
+ * está en el JSON a propósito), alertas del tick demo y helpers.
  */
 
 // ---------------------------------------------------------------------------
@@ -10,10 +16,12 @@
 // ---------------------------------------------------------------------------
 
 import { numLocale } from '@/i18n'
+import canon from '@/data/demo-canon.json'
 import type {
   AdGuardStats,
   AlertEvent,
   Device,
+  DeviceTotals,
   DistributionNode,
   HealthScore,
   Router,
@@ -29,6 +37,7 @@ export type {
   AlertSeverity,
   Band,
   Device,
+  DeviceInfra,
   DeviceTotals,
   DeviceType,
   DistributionNode,
@@ -38,6 +47,8 @@ export type {
   Router,
   Status,
   TimeRange,
+  TopoSemantics,
+  TopoSemLink,
   TrafficPoint,
   WanInfo,
   WGPeer,
@@ -50,106 +61,21 @@ export type {
 
 export const CHART_COLORS = ['#22D3EE', '#A78BFA', '#34D399', '#FBBF24', '#FB7185', '#60A5FA'] as const
 
-// ---------------------------------------------------------------------------
-// Routers (canon §11)
-// ---------------------------------------------------------------------------
-
-export const routers: Router[] = [
-  {
-    id: 'flint2',
-    name: 'Gateway',
-    model: 'GL.iNet Flint 2 (GL-MT6000)',
-    modelShort: 'GL.iNet Flint 2',
-    role: 'Main gateway',
-    roleBadge: 'Principal',
-    ip: '192.168.8.1',
-    backhaul: 'cable',
-    status: 'online',
-    health: 98,
-    cpu: 23,
-    ram: 41,
-    temp: 54,
-    uptime: '32d 14h',
-    // D5: recuento real de clientes online atribuidos (enumeración del dataset)
-    clients: 26,
-    sparkline: [8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40],
-  },
-  {
-    id: 'living',
-    name: 'Living Room',
-    model: 'OpenWrt AP (Xiaomi AX3000T)',
-    modelShort: 'Xiaomi AX3000T',
-    role: 'Access point',
-    roleBadge: 'AP',
-    ip: '192.168.8.2',
-    backhaul: 'cable',
-    lldp: { chassis: 'AX3000T', caps: 'Bridge, Wlan', portDesc: 'eth0' },
-    status: 'online',
-    health: 95,
-    cpu: 12,
-    ram: 38,
-    temp: 47,
-    uptime: '32d 14h',
-    clients: 20,
-    sparkline: [4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28],
-  },
-  {
-    id: 'estudio',
-    name: 'Study',
-    model: 'OpenWrt (NanoPi R4S)',
-    modelShort: 'NanoPi R4S',
-    role: 'AP + switch',
-    roleBadge: 'AP',
-    ip: '192.168.8.3',
-    backhaul: 'cable',
-    lldp: { chassis: 'NanoPi-R4S', caps: 'Bridge, Router', portDesc: 'eth0' },
-    status: 'online',
-    health: 92,
-    cpu: 18,
-    ram: 44,
-    temp: 51,
-    uptime: '11d 3h',
-    clients: 8,
-    sparkline: [2, 2, 1, 1, 2, 4, 8, 15, 22, 25, 24, 22, 26, 24, 21, 24, 28, 31, 29, 24, 18, 12, 8, 4],
-  },
-  {
-    id: 'patio',
-    name: 'Patio',
-    model: 'OpenWrt (TP-Link EAP225)',
-    modelShort: 'TP-Link EAP225',
-    role: 'Outdoor AP',
-    roleBadge: 'AP',
-    ip: '192.168.8.4',
-    backhaul: 'wifi',
-    status: 'warn',
-    health: 68,
-    cpu: 31,
-    ram: 57,
-    temp: 71,
-    uptime: '4d 2h',
-    clients: 5,
-    hotMetric: 'temp',
-    sparkline: [1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2],
-  },
-]
 
 // ---------------------------------------------------------------------------
-// WAN (vía Flint 2)
+// Canon demo (SPEC-65 D65-1): re-exportado desde demo-canon.json con casteo
+// explícito al contrato de `@/data/types` (el JSON se tipa por inferencia).
+// Los valores del JSON son la verdad reconciliada del canon Go de fase 6.
 // ---------------------------------------------------------------------------
 
-export const wan: WanInfo = {
-  plan: '600/600 Mbps',
-  downMbps: 84.2,
-  upMbps: 12.6,
-  latencyMs: 8,
-  lossPct: 0,
-  publicIp: '84.122.x.x',
-  isp: 'Digi',
-  peakTodayMbps: 412,
-  peakTodayTime: '21:14',
-  avgDownMbps: 61,
-  total24h: '1.32 TB',
-}
+export const routers = canon.routers as unknown as Router[]
+export const devices = canon.devices as unknown as Device[]
+export const deviceTotals: DeviceTotals = canon.deviceTotals
+export const distributionNodes = canon.distributionNodes as unknown as DistributionNode[]
+export const adguard = canon.adguard as unknown as AdGuardStats
+export const wireguard = canon.wireguard as unknown as WireGuardStats
+export const wan: WanInfo = canon.wan
+export const healthScore = canon.health as unknown as HealthScore
 
 // ---------------------------------------------------------------------------
 // Tráfico WAN — series por rango (valle nocturno 5–15, pico tarde 300–412,
@@ -199,244 +125,6 @@ export const trafficByRange: Record<TimeRange, TrafficPoint[]> = {
   ],
 }
 
-// ---------------------------------------------------------------------------
-// Health Score global
-// ---------------------------------------------------------------------------
-
-export const healthScore: HealthScore = {
-  score: 92,
-  label: 'Excelente',
-  caption: 'Network health score',
-  note: 'Penalized by the Patio temperature.',
-  breakdown: [
-    { label: 'Patio temp.', delta: -4 },
-    { label: 'Patio coverage', delta: -2 },
-    { label: 'congested 2.4 GHz channel', delta: -2 },
-  ],
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos (totales + destacados)
-// ---------------------------------------------------------------------------
-
-// D5: totales derivados de la enumeración real del dataset reconciliado
-// (65 IDs únicos: 59 online · 6 conocidos offline · 3 nuevos hoy).
-export const deviceTotals = {
-  total: 65,
-  online: 59,
-  knownOffline: 6,
-  newToday: 3,
-}
-
-export const devices: Device[] = [
-  {
-    id: 'imac-salon', name: 'iMac Living Room', type: 'ordenador', manufacturer: 'Apple',
-    ip: '192.168.8.21', mac: 'A4:83:E7:21:0B:3C', routerId: 'living', band: '5 GHz',
-    signalDbm: -48, trafficMbps: 32.4, online: true,
-    sparkline: [12, 15, 18, 22, 26, 30, 34, 32, 28, 30, 32, 31],
-  },
-  {
-    id: 'tv-samsung', name: 'TV Samsung', type: 'tv', manufacturer: 'Samsung',
-    ip: '192.168.8.34', mac: '8C:EA:48:5D:2F:91', routerId: 'living', band: '5 GHz',
-    signalDbm: -52, trafficMbps: 18.1, online: true,
-    sparkline: [8, 10, 14, 16, 18, 20, 19, 18, 17, 18, 18, 18],
-  },
-  {
-    id: 'pixel-8-pro', name: 'Pixel 8 Pro', type: 'movil', manufacturer: 'Google',
-    ip: '192.168.8.45', mac: 'F2:6D:19:A8:44:C2', routerId: 'flint2', band: '5 GHz',
-    signalDbm: -41, trafficMbps: 6.2, online: true,
-    sparkline: [3, 4, 5, 7, 6, 8, 6, 5, 7, 6, 6, 6],
-  },
-  {
-    id: 'macbook-air', name: 'MacBook Air', type: 'portatil', manufacturer: 'Apple',
-    ip: '192.168.8.23', mac: '3C:22:FB:71:9E:05', routerId: 'estudio', band: '5 GHz',
-    signalDbm: -45, trafficMbps: 4.8, online: true,
-    sparkline: [2, 3, 4, 5, 5, 6, 5, 4, 5, 5, 5, 5],
-  },
-  {
-    id: 'ps5', name: 'PS5', type: 'consola', manufacturer: 'Sony',
-    ip: '192.168.8.31', mac: '78:C8:81:0A:6B:D4', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 12.7, online: true, port: 'lan1',
-    sparkline: [4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13],
-  },
-  {
-    id: 'robot-aspirador', name: 'Robot vacuum', type: 'iot', manufacturer: 'Roborock',
-    ip: '192.168.8.61', mac: 'B0:4A:39:2E:77:10', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -67, trafficMbps: 0.02, online: true,
-    sparkline: [0.01, 0.02, 0.02, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02],
-  },
-  {
-    id: 'camara-porche', name: 'Porch camera', type: 'camara', manufacturer: 'Reolink',
-    ip: '192.168.8.71', mac: 'EC:71:DB:44:12:8A', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -72, trafficMbps: 1.1, online: true,
-    sparkline: [1, 1.1, 1.1, 1.2, 1.1, 1, 1.1, 1.1, 1.2, 1.1, 1.1, 1.1],
-  },
-  {
-    id: 'nest-mini', name: 'Nest Mini', type: 'altavoz', manufacturer: 'Google',
-    ip: '192.168.8.52', mac: '1A:2B:3C:4D:5E:6F', routerId: 'estudio', band: '2.4 GHz',
-    signalDbm: -55, trafficMbps: 0.4, online: true,
-    sparkline: [0.3, 0.4, 0.4, 0.5, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4],
-  },
-  {
-    id: 'nas-synology', name: 'NAS Synology', type: 'servidor', manufacturer: 'Synology',
-    ip: '192.168.8.10', mac: '00:11:32:9C:51:B7', routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: 2.3, online: true, port: 'lan4',
-    sparkline: [1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3],
-  },
-  {
-    id: 'bombillas-ikea', name: 'Ikea bulbs ×6', type: 'iot', manufacturer: 'Ikea',
-    ip: '192.168.8.8x', mac: '—', routerId: 'living', band: '2.4 GHz',
-    signalDbm: -60, trafficMbps: 0, online: true,
-    sparkline: [0, 0, 0.01, 0, 0, 0.01, 0, 0, 0, 0.01, 0, 0],
-  },
-  {
-    id: 'galaxy-tab-s9', name: 'Galaxy Tab S9', type: 'tablet', manufacturer: 'Samsung',
-    ip: '192.168.8.48', mac: 'D6:91:2F:07:B3:55', routerId: 'living', band: '5 GHz',
-    signalDbm: -50, trafficMbps: 1.8, online: true, isNew: true,
-    sparkline: [0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1.2, 1.6, 1.8],
-  },
-
-  // -- Fixtures de topología v5 (mockup aprobado: switch gestionado LLDP, --
-  // -- hipervisor con CTs anidados, switch/bridge inferido vía FDB) ----------
-
-  // Switch gestionado Netgear GS308E (Salón, uplink lan3): D1 — existe como
-  // Device (badge "Switch gestionado" en /devices) Y como DistributionNode
-  // kind='managed' (dist-living-lan3, misma chassis-MAC); el mapa nunca
-  // renderiza su chip (filtro por MAC en model.ts).
-  {
-    id: 'switch-netgear', name: 'Switch GS308E', type: 'switch', manufacturer: 'Netgear',
-    ip: '192.168.8.13', mac: '28:C6:8E:1D:90:44', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 0.4, online: true, attachTo: 'living', port: 'lan3',
-    lldp: { chassis: 'GS308E', mgmt: '192.168.8.13', caps: 'Bridge', portDesc: 'ge5' },
-    sparkline: [0.3, 0.4, 0.4, 0.5, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4],
-  },
-
-  // 3 clientes tras el switch gestionado GS308E (Salón, lan3) — cuelgan del
-  // DistributionNode kind='managed' (identificado vía LLDP).
-  {
-    id: 'xbox-series-s', name: 'Xbox Series S', type: 'consola', manufacturer: 'Microsoft',
-    ip: '192.168.8.35', mac: '7C:ED:8D:4A:11:22', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 9.8, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [3, 5, 7, 9, 11, 12, 10, 9, 10, 9, 10, 9.8],
-  },
-  {
-    id: 'apple-tv-4k', name: 'Apple TV 4K', type: 'tv', manufacturer: 'Apple',
-    ip: '192.168.8.36', mac: 'F0:18:98:2B:33:44', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 15.2, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [6, 8, 10, 12, 14, 16, 15, 14, 15, 15, 15, 15.2],
-  },
-  {
-    id: 'receptor-denon', name: 'Receptor Denon', type: 'altavoz', manufacturer: 'Denon',
-    ip: '192.168.8.37', mac: '00:05:CD:55:66:77', routerId: 'living', band: 'cable',
-    signalDbm: null, trafficMbps: 0.6, online: true, attachTo: 'dist-living-lan3',
-    sparkline: [0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6],
-  },
-
-  // Hipervisor Proxmox (gateway lan5, 2.5G) + 10 CTs anidados (MACs OUI BC:24:11)
-  {
-    id: 'pve', name: 'Proxmox pve', type: 'servidor', manufacturer: 'Supermicro',
-    ip: '192.168.8.5', mac: '3C:52:82:10:20:30', routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: 12.3, online: true, port: 'lan5',
-    sparkline: [8, 9, 10, 11, 12, 13, 12, 12, 12, 12, 12, 12.3],
-  },
-  ...([
-    ['ct-pihole', 'Pi-hole', 'servidor', 8.41, 6.1],
-    ['ct-home-assistant', 'Home Assistant', 'iot', 8.42, 4.2],
-    ['ct-nextcloud', 'Nextcloud', 'servidor', 8.43, 7.8],
-    ['ct-jellyfin', 'Jellyfin', 'servidor', 8.44, 9.4],
-    ['ct-immich', 'Immich', 'servidor', 8.45, 3.3],
-    ['ct-gitea', 'Gitea', 'servidor', 8.46, 1.2],
-    ['ct-uptime-kuma', 'Uptime Kuma', 'iot', 8.47, 0.4],
-    ['ct-adguard-sync', 'AdGuard sync', 'servidor', 8.48, 0.8],
-    ['ct-postgres', 'Postgres', 'servidor', 8.49, 2.1],
-    ['ct-redis', 'Redis', 'servidor', 8.50, 0.9],
-  ] as const).map(([id, name, type, ipSuffix, mbps], i): Device => ({
-    id, name, type: type as Device['type'], manufacturer: 'Proxmox VE (CT)',
-    ip: `192.168.${ipSuffix}`, mac: `BC:24:11:00:2${i}:${(0x10 + i).toString(16).toUpperCase().padStart(2, '0')}`,
-    routerId: 'flint2', band: 'cable', signalDbm: null, trafficMbps: mbps, online: true,
-    attachTo: 'pve',
-    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.1, mbps - 2 + ((i + j) % 5))),
-  })),
-
-  // Tras el switch/bridge inferido (gateway lan3, OUI heterogéneo, sin IP).
-  // D3: pc-sobremesa, raspberry-pi e impresora-hp ya existen como clientes
-  // preexistentes (enriquecidos con attachTo en devices-data.ts, igual que en
-  // el dataset Go) — aquí solo los 5 IDs nuevos; cada ID aparece 1 sola vez.
-  ...([
-    ['tv-salon-cable', 'TV Living (wired)', 'tv', 'Samsung', '8C:EA:48:AA:02:02', 8.61, 24.4],
-    ['xbox-one', 'Xbox One', 'consola', 'Microsoft', '7C:ED:8D:AA:05:05', 8.64, 4.2],
-    ['receptor-av', 'AV Receiver', 'altavoz', 'Denon', '00:05:CD:AA:06:06', 8.65, 0.3],
-    ['deco-orange', 'Orange STB', 'tv', 'Sagemcom', '48:83:B4:AA:07:07', 8.66, 1.1],
-    ['pc-invitado', 'Guest PC', 'ordenador', '—', 'A2:F4:11:AA:08:08', 8.67, 0.8],
-  ] as const).map(([id, name, type, man, mac, ipSuffix, mbps], i): Device => ({
-    id, name, type: type as Device['type'], manufacturer: man,
-    ip: `192.168.${ipSuffix}`, mac, routerId: 'flint2', band: 'cable',
-    signalDbm: null, trafficMbps: mbps, online: true, attachTo: 'dist-flint2-lan3',
-    sparkline: Array.from({ length: 12 }, (_, j) => Math.max(0.05, mbps - 1.5 + ((i + j) % 4) * 0.5)),
-  })),
-]
-
-// ---------------------------------------------------------------------------
-// Nodos de distribución (topología v5): inferidos del FDB en live; en demo,
-// fixtures equivalentes al mockup aprobado (switch lan3 + hipervisor lan5).
-// ---------------------------------------------------------------------------
-
-export const distributionNodes: DistributionNode[] = [
-  { id: 'dist-flint2-lan3', kind: 'inferred', routerId: 'flint2', port: 'lan3', macCount: 8 },
-  { id: 'dist-pve', kind: 'hypervisor', routerId: 'flint2', port: 'lan5', macCount: 11, hostDeviceId: 'pve', name: 'Proxmox pve' },
-  // Switch gestionado Netgear GS308E en el AP Salón (uplink lan3), identificado
-  // vía LLDP (chasis + IP de mgmt + caps + puerto remoto). 4 MACs: switch + 3
-  // equipos. D1: `mac` = chassis-MAC del Device 'switch-netgear' (excluye su chip).
-  {
-    id: 'dist-living-lan3', kind: 'managed', routerId: 'living', port: 'lan3', macCount: 4,
-    name: 'GS308E', ip: '192.168.8.13', mac: '28:C6:8E:1D:90:44',
-    lldp: { chassis: 'GS308E', mgmt: '192.168.8.13', caps: 'Bridge', portDesc: 'ge5' },
-  },
-]
-
-// ---------------------------------------------------------------------------
-// AdGuard Home (en Flint 2, :3000)
-// ---------------------------------------------------------------------------
-
-export const adguard: AdGuardStats = {
-  host: '192.168.8.1',
-  port: 3000,
-  status: 'active',
-  queries24h: 84312,
-  blocked24h: 15687,
-  blockedPct: 18.6,
-  trackersBlocked: 9204,
-  dnsLatencyMs: 14,
-  clientsUsing: 60,
-  clientsTotal: 65,
-  topBlocked: [
-    { domain: 'graph.facebook.com', count: 1204 },
-    { domain: 'adservice.google.com', count: 986 },
-    { domain: 'metrics.icloud.com', count: 731 },
-    { domain: 'telemetry.nvidia.com', count: 512 },
-    { domain: 'ads.tiktok.com', count: 448 },
-  ],
-  filterLists: 6,
-  rules: 218442,
-}
-
-// ---------------------------------------------------------------------------
-// WireGuard (servidor en Flint 2, wg0 · 10.0.0.1/24)
-// ---------------------------------------------------------------------------
-
-export const wireguard: WireGuardStats = {
-  interface: 'wg0',
-  subnet: '10.0.0.1/24',
-  status: 'active',
-  peers: [
-    { id: 'pixel-8-pro', name: 'Pixel 8 Pro', type: 'movil', tunnelIp: '10.0.0.2', active: true, lastHandshake: '38s ago', rx: '1.2 GB', tx: '214 MB' },
-    { id: 'macbook-air', name: 'MacBook Air', type: 'portatil', tunnelIp: '10.0.0.3', active: true, lastHandshake: '1 min ago', rx: '640 MB', tx: '88 MB' },
-    { id: 'ipad-air', name: 'iPad Air', type: 'tablet', tunnelIp: '10.0.0.4', active: false, lastHandshake: '2 days ago', rx: '3.1 GB', tx: '402 MB' },
-    { id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', tunnelIp: '10.0.0.5', active: false, lastHandshake: '6h ago', rx: '812 MB', tx: '121 MB' },
-    { id: 'casa-familia', name: 'Family home', type: 'sitio', tunnelIp: '10.0.0.6', active: false, lastHandshake: '9 days ago', rx: '12 GB', tx: '4.2 GB' },
-  ],
-}
-
 // ---------------------------------------------------------------------------
 // Alertas (canon §11)
 // ---------------------------------------------------------------------------

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

@@ -99,6 +99,13 @@ export interface AdGuardStats {
 
 export type PeerType = 'movil' | 'portatil' | 'tablet' | 'sitio'
 
+/**
+ * Rol de infraestructura sellado server-side (SPEC-65 D65-2):
+ * "hypervisor" (host Proxmox/VMware/…), "ct" (CT/VM anidado bajo un
+ * hipervisor), "managed-switch" (switch con gestión identificado por LLDP).
+ */
+export type DeviceInfra = 'hypervisor' | 'ct' | 'managed-switch'
+
 export interface WGPeer {
   id: string
   name: string
@@ -167,6 +174,12 @@ export interface Device {
    * (hipervisor / switch gestionado identificado).
    */
   attachTo?: string
+  /**
+   * Rol de infraestructura sellado server-side (SPEC-65 D65-2): la app NO
+   * infiere; pinta el badge si viene. Ausente = dispositivo normal (la app
+   * puede seguir infiriendo como fallback para datos viejos, B2).
+   */
+  infra?: DeviceInfra
 }
 
 /**
@@ -239,6 +252,36 @@ export interface DeviceTotals {
   newToday: number
 }
 
+/**
+ * Versión del view-model que la app soporta (SPEC-65 D65-4). Si el servidor
+ * manda `vm` mayor → la app avisa una vez por consola y sigue (nunca rompe).
+ */
+export const VM_SUPPORTED = 1
+
+/** Enlace semántico del mapa (SPEC-65 D65-3), sin geometría. */
+export interface TopoSemLink {
+  /** id: router | device | distnode | "internet" | "peer-<wgPeerId>" */
+  from: string
+  to: string
+  kind: 'wan' | 'uplink' | 'wired' | 'dist' | 'wg'
+  /** puerto físico si aplica */
+  port?: string
+}
+
+/**
+ * Modelo SEMÁNTICO de la topología (SPEC-65 D65-3): asignaciones de anillo,
+ * enlaces y conteos de peers ocultos llegan calculados del servidor; la app
+ * conserva solo la geometría de píxeles. Ausente en snapshots viejos → la
+ * app usa su cálculo local como fallback.
+ */
+export interface TopoSemantics {
+  links: TopoSemLink[]
+  /** routerId → ids de Device en su anillo (cableados primero, luego 5/2.4 GHz) */
+  rings: Record<string, string[]>
+  /** routerId → nº de clientes no pintados como chip (el "+N") */
+  hiddenPeers?: Record<string, number>
+}
+
 /** Bundle de `GET /api/overview` y del evento SSE `snapshot`. */
 export interface OverviewBundle {
   health: HealthScore
@@ -257,6 +300,13 @@ export interface OverviewBundle {
    * colector o primera pasada): el mapa cuelga los cableados del router.
    */
   distributionNodes?: DistributionNode[]
+  /**
+   * Versión del view-model (SPEC-65 D65-4). Siempre presente en servidores
+   * nuevos; ausente en servidores viejos (se asume VM_SUPPORTED).
+   */
+  vm?: number
+  /** Semántica de topología precalculada (SPEC-65 D65-3); ausente = fallback local. */
+  topology?: TopoSemantics
   ts: number
 }
 

+ 13 - 6
app/src/pages/Devices.tsx

@@ -143,8 +143,9 @@ function signalTextClass(dbm: number | null): string {
 
 // ---------------------------------------------------------------------------
 // Taxonomía de infraestructura (D6): hipervisor (host con CTs), CT (contenedor
-// anidado, tooltip con su host) y switch gestionado (device con LLDP). Se
-// deriva de attachTo/lldp + los distributionNodes del provider.
+// anidado, tooltip con su host) y switch gestionado. SPEC-65 D65-2/B2: si el
+// servidor sella `device.infra` manda; si no, fallback a la inferencia local
+// de attachTo/lldp + los distributionNodes del provider.
 // ---------------------------------------------------------------------------
 
 type InfraKind = 'hypervisor' | 'ct' | 'managedSwitch'
@@ -978,10 +979,16 @@ export default function Devices() {
     const byId = new Map(list.map((d) => [d.id, d]))
     const infra = new Map<string, InfraInfo>()
     for (const d of list) {
-      if (hosts.has(d.id)) infra.set(d.id, { kind: 'hypervisor' })
-      else if (d.attachTo && hosts.has(d.attachTo)) {
-        infra.set(d.id, { kind: 'ct', host: byId.get(d.attachTo)?.name ?? d.attachTo })
-      } else if (d.lldp) infra.set(d.id, { kind: 'managedSwitch' })
+      // SPEC-65 D65-2/B2: prioridad al sello server-side `device.infra`;
+      // la inferencia local queda como fallback para datos viejos.
+      const sealed = d.infra
+      if (sealed === 'hypervisor' || (!sealed && hosts.has(d.id))) {
+        infra.set(d.id, { kind: 'hypervisor' })
+      } else if (sealed === 'ct' || (!sealed && d.attachTo && hosts.has(d.attachTo))) {
+        infra.set(d.id, { kind: 'ct', host: byId.get(d.attachTo ?? '')?.name ?? d.attachTo })
+      } else if (sealed === 'managed-switch' || (!sealed && d.lldp)) {
+        infra.set(d.id, { kind: 'managedSwitch' })
+      }
     }
     if (infra.size === 0) return { allDevices: list, infraById: infra }
     return { allDevices: list.map((d) => (infra.has(d.id) ? { ...d, group: 'infra' as const } : d)), infraById: infra }

+ 3 - 3
app/src/pages/Topology.tsx

@@ -46,11 +46,11 @@ function ControlButton({
 export default function Topology() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { routers, devices, wan, wireguard, distributionNodes, lastSnapshotAt, requestServerRefresh } =
+  const { routers, devices, wan, wireguard, distributionNodes, topology, vm, lastSnapshotAt, requestServerRefresh } =
     useNetPulse()
   const model = useMemo(
-    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes }),
-    [routers, devices, wan, wireguard, distributionNodes],
+    () => buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes, topology, vm }),
+    [routers, devices, wan, wireguard, distributionNodes, topology, vm],
   )
   const [showLabels, setShowLabels] = useState(true)
   const [flow, setFlow] = useState(true)

+ 61 - 302
app/src/pages/devices-data.ts

@@ -1,16 +1,20 @@
 /**
- * Devices — extensión local del canon (design.md §11 / devices.md §④).
- * Los dispositivos destacados de `@/data/mock` se reutilizan tal cual;
- * la entrada agregada "Bombillas Ikea ×6" se expande en sus 6 bombillas
- * individuales y se añaden los clientes restantes hasta los totales del
- * canon reconciliado (D5): 65 conocidos · 59 online · 6 offline
- * (online por router: Gateway 26, Salón 20, Estudio 8, Patio 5).
- * Regla D3: cada ID existe exactamente 1 vez en el dataset (mock.ts +
- * este archivo), espejo del dataset demo de Go. Nada aquí contradice
- * `@/data/mock`.
+ * Devices — enriquecido local de clientes (design.md §11 / devices.md §④).
+ *
+ * SPEC-65 D65-1 (single-source): el canon de dispositivos (65 IDs únicos,
+ * D3/D5: 59 online · 6 offline · 3 nuevos hoy; online por router Gateway 26,
+ * Salón 20, Estudio 8, Patio 5) vive SOLO en `@/data/demo-canon.json`
+ * (re-exportado por `@/data/mock`) y ya trae inline los metadatos de cliente
+ * (hostname, DHCP, primer visto, tráfico 24h, AdGuard, grupo). Este módulo
+ * ya NO expande ni duplica el canon: solo fusiona metadatos.
+ * - Canon con metadatos inline (demo local o API demo): se usan tal cual
+ *   (el JSON es la verdad reconciliada).
+ * - Live sin metadatos (servidor real): se fusionan los detalles conocidos
+ *   por id (CANON_DETAILS) o se derivan valores plausibles — nunca se
+ *   inventan dispositivos que la API no ha reportado.
  */
 import type { LucideIcon } from 'lucide-react'
-import { BookOpen, Printer } from 'lucide-react'
+import { BookOpen, Network } from 'lucide-react'
 import type { Device } from '@/data/mock'
 import { devices as canonDevices } from '@/data/mock'
 
@@ -41,11 +45,13 @@ export interface ClientDevice extends Device {
 
 // 'infra' primero (D6): hipervisores, CTs y switches gestionados de un vistazo.
 // El grupo 'infra' no deriva del `type`: lo asigna Devices.tsx cruzando
+// device.infra (sellado server-side, SPEC-65 D65-2) o, como fallback,
 // attachTo/lldp con los distributionNodes del provider.
 export const GROUP_ORDER: FilterGroup[] = ['infra', 'moviles', 'ordenadores', 'tv', 'iot', 'red', 'otros']
 
 // ---------------------------------------------------------------------------
-// Detalles extra de los dispositivos canónicos (mock.ts §Dispositivos)
+// Detalles extra de los dispositivos canónicos: fallback para live cuando la
+// API no trae metadatos inline (el canon JSON del demo ya los trae todos).
 // ---------------------------------------------------------------------------
 
 const CANON_DETAILS: Record<string, Omit<ClientDevice, keyof Device>> = {
@@ -89,296 +95,17 @@ const CANON_DETAILS: Record<string, Omit<ClientDevice, keyof Device>> = {
     hostname: 'galaxy-tab-s9', dhcpLease: 'renews in 11h 5min', firstSeen: 'today',
     traffic24hRx: '640 MB', traffic24hTx: '48 MB', adguard: true, group: 'moviles', newThisWeek: true,
   },
-  // D1: el GS308E vuelve a ser Device (además del distnode managed de mock.ts).
-  // Su grupo visible es 'infra' (lo reasigna Devices.tsx al detectar `lldp`).
+  // D1: el GS308E vuelve a ser Device (además del distnode managed del canon).
+  // Su grupo visible es 'infra' (lo reasigna Devices.tsx con device.infra/lldp).
   'switch-netgear': {
     hostname: 'gs308e', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
     traffic24hRx: '96 MB', traffic24hTx: '42 MB', adguard: false, group: 'red',
   },
 }
 
-// ---------------------------------------------------------------------------
-// Sparkline determinista (mock): paseo pseudo-aleatorio alrededor de `base`
-// ---------------------------------------------------------------------------
-
-function spark(seed: number, base: number, spread: number): number[] {
-  let s = seed
-  const out: number[] = []
-  for (let i = 0; i < 12; i++) {
-    s = (s * 9301 + 49297) % 233280
-    const r = s / 233280
-    out.push(Math.max(0, +(base + (r - 0.45) * spread).toFixed(2)))
-  }
-  out[out.length - 1] = base
-  return out
-}
-
-function extra(spec: Omit<Device, 'sparkline'> & { seed?: number; spread?: number }): Device {
-  const { seed = 1, spread, ...d } = spec
-  return { ...d, sparkline: d.online ? spark(seed, d.trafficMbps, spread ?? d.trafficMbps * 0.8) : [] }
-}
-
-function bulb(n: number, name: string, ip: string, mac: string, dbm: number): ClientDevice {
-  return {
-    id: `bombilla-${n}`, name, type: 'iot', manufacturer: 'Ikea Trådfri',
-    ip, mac, routerId: 'living', band: '2.4 GHz', signalDbm: dbm,
-    trafficMbps: 0, online: true, sparkline: spark(40 + n, 0.005, 0.02),
-    hostname: `tradfri-${n}`, dhcpLease: 'renews in 12h 0min', firstSeen: '280 days ago',
-    traffic24hRx: '4 MB', traffic24hTx: '1 MB', adguard: true, group: 'iot',
-  }
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos adicionales (canon: los destacados ya están en mock.ts;
-// aquí está el resto hasta los 65 IDs únicos del dataset reconciliado, D3/D5)
-// ---------------------------------------------------------------------------
-
-const ADDITIONAL: ClientDevice[] = [
-  // —— Gateway (flint2) ——
-  {
-    ...extra({ id: 'iphone-ana', name: "Ana's iPhone", type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.44', mac: 'F4:D4:88:19:C2:71', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -46, trafficMbps: 2.1, online: true, seed: 11 }),
-    hostname: 'iphone-de-ana', dhcpLease: 'renews in 6h 40min', firstSeen: '190 days ago',
-    traffic24hRx: '2.8 GB', traffic24hTx: '240 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'macbook-pro', name: "Marc's MacBook Pro", type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.26', mac: 'F0:18:98:5A:11:E9', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -44, trafficMbps: 8.6, online: true, seed: 12 }),
-    hostname: 'macbook-pro-marc', dhcpLease: 'renews in 4h 16min', firstSeen: '230 days ago',
-    traffic24hRx: '12.4 GB', traffic24hTx: '1.9 GB', adguard: true, group: 'ordenadores',
-  },
-  // D3: pc-sobremesa y raspberry-pi cuelgan del switch inferido (attachTo),
-  // enriquecidos in situ igual que en el dataset Go — no se duplican en mock.ts.
-  {
-    ...extra({ id: 'pc-sobremesa', name: 'Desktop PC', type: 'ordenador', manufacturer: 'ASUSTeK',
-      ip: '192.168.8.11', mac: '04:D4:C4:8B:30:A7', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 21.3, online: true, attachTo: 'dist-flint2-lan3', seed: 13 }),
-    hostname: 'desktop-8f2k1', dhcpLease: 'Static IP (reservation)', firstSeen: '310 days ago',
-    traffic24hRx: '84 GB', traffic24hTx: '6.2 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'raspberry-pi', name: 'Raspberry Pi 4', type: 'servidor', manufacturer: 'Raspberry Pi',
-      ip: '192.168.8.12', mac: 'DC:A6:32:4F:77:02', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 0.8, online: true, attachTo: 'dist-flint2-lan3', seed: 14 }),
-    hostname: 'raspberrypi', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
-    traffic24hRx: '3.4 GB', traffic24hTx: '890 MB', adguard: true, group: 'red',
-  },
-  {
-    ...extra({ id: 'timbre-nest', name: 'Nest doorbell', type: 'camara', manufacturer: 'Google',
-      ip: '192.168.8.72', mac: 'F4:F5:D8:66:01:B8', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -58, trafficMbps: 0.6, online: true, seed: 16 }),
-    hostname: 'nest-doorbell', dhcpLease: 'renews in 9h 44min', firstSeen: '170 days ago',
-    traffic24hRx: '1.2 GB', traffic24hTx: '140 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'enchufe-lavadora', name: 'Washing machine plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.81', mac: '50:C7:BF:22:E1:9C', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0.01, online: true, seed: 17, spread: 0.02 }),
-    hostname: 'tapo-p110-lavadora', dhcpLease: 'renews in 12h 0min', firstSeen: '140 days ago',
-    traffic24hRx: '8 MB', traffic24hTx: '2 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ id: 'pixel-7', name: 'Pixel 7', type: 'movil', manufacturer: 'Google',
-      ip: '192.168.8.46', mac: '3C:5A:B4:08:D7:5E', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -49, trafficMbps: 1.4, online: true, seed: 18 }),
-    hostname: 'pixel-7', dhcpLease: 'renews in 7h 3min', firstSeen: '205 days ago',
-    traffic24hRx: '1.9 GB', traffic24hTx: '180 MB', adguard: true, group: 'moviles',
-  },
-  // D3: una única identidad — la cableada al switch inferido (gateway lan3).
-  {
-    ...extra({ id: 'impresora-hp', name: 'HP Printer', type: 'iot', manufacturer: 'HP',
-      ip: '192.168.8.62', mac: '3C:D9:2B:AA:03:03', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 0.1, online: true, attachTo: 'dist-flint2-lan3',
-      seed: 15, spread: 0.2 }),
-    hostname: 'hp-laserjet-m209', dhcpLease: 'renews in 5h 22min', firstSeen: '60 days ago',
-    traffic24hRx: '2.4 GB', traffic24hTx: '120 MB', adguard: true, group: 'iot',
-    iconOverride: Printer,
-  },
-  {
-    ...extra({ id: 'ipad-air', name: 'iPad Air', type: 'tablet', manufacturer: 'Apple',
-      ip: '192.168.8.47', mac: '8C:85:90:2F:B4:11', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -54, trafficMbps: 0, online: false }),
-    hostname: 'ipad-air', dhcpLease: 'Expired', firstSeen: '260 days ago',
-    traffic24hRx: '6.4 GB', traffic24hTx: '520 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', manufacturer: 'Lenovo',
-      ip: '192.168.8.27', mac: '54:EE:75:9A:03:F1', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -50, trafficMbps: 0, online: false }),
-    hostname: 'thinkpad-t14', dhcpLease: 'Expired', firstSeen: '160 days ago',
-    traffic24hRx: '812 MB', traffic24hTx: '121 MB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'kindle', name: 'Kindle Paperwhite', type: 'desconocido', manufacturer: 'Amazon',
-      ip: '192.168.8.49', mac: '44:65:0D:71:28:C3', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -58, trafficMbps: 0, online: false }),
-    hostname: 'kindle-paperwhite', dhcpLease: 'Expired', firstSeen: '220 days ago',
-    traffic24hRx: '220 MB', traffic24hTx: '8 MB', adguard: true, group: 'otros',
-    iconOverride: BookOpen,
-  },
-]
-
-const LIVING: ClientDevice[] = [
-  // —— Salón (living) ——
-  bulb(1, 'Living room bulb 1', '192.168.8.90', 'CC:86:EC:10:04:21', -58),
-  bulb(2, 'Living room bulb 2', '192.168.8.91', 'CC:86:EC:10:04:22', -59),
-  bulb(3, 'Floor lamp bulb', '192.168.8.92', 'CC:86:EC:10:04:23', -61),
-  bulb(4, 'Entryway bulb', '192.168.8.93', 'CC:86:EC:10:04:24', -64),
-  bulb(5, 'Hallway bulb', '192.168.8.94', 'CC:86:EC:10:04:25', -66),
-  bulb(6, 'Kitchen bulb', '192.168.8.95', 'CC:86:EC:10:04:26', -60),
-  {
-    ...extra({ id: 'chromecast', name: 'Chromecast HD', type: 'tv', manufacturer: 'Google',
-      ip: '192.168.8.36', mac: '54:60:09:E3:5B:0A', routerId: 'living', band: '5 GHz',
-      signalDbm: -54, trafficMbps: 3.9, online: true, seed: 21 }),
-    hostname: 'chromecast-hd', dhcpLease: 'renews in 6h 12min', firstSeen: '200 days ago',
-    traffic24hRx: '21 GB', traffic24hTx: '380 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'homepod-mini', name: 'HomePod mini', type: 'altavoz', manufacturer: 'Apple',
-      ip: '192.168.8.53', mac: 'F0:D1:A9:3E:77:5C', routerId: 'living', band: '5 GHz',
-      signalDbm: -47, trafficMbps: 0.3, online: true, seed: 22 }),
-    hostname: 'homepod-mini', dhcpLease: 'renews in 10h 41min', firstSeen: '190 days ago',
-    traffic24hRx: '2.2 GB', traffic24hTx: '96 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'galaxy-s23', name: 'Galaxy S23', type: 'movil', manufacturer: 'Samsung',
-      ip: '192.168.8.42', mac: '5C:0A:5B:88:1D:E4', routerId: 'living', band: '5 GHz',
-      signalDbm: -51, trafficMbps: 0.9, online: true, seed: 23 }),
-    hostname: 'galaxy-s23', dhcpLease: 'renews in 8h 55min', firstSeen: '175 days ago',
-    traffic24hRx: '3.2 GB', traffic24hTx: '290 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'echo-dot', name: 'Echo Dot', type: 'altavoz', manufacturer: 'Amazon',
-      ip: '192.168.8.54', mac: '74:C2:46:19:F0:6B', routerId: 'living', band: '2.4 GHz',
-      signalDbm: -56, trafficMbps: 0.2, online: true, seed: 24 }),
-    hostname: 'echo-dot-cocina', dhcpLease: 'renews in 11h 18min', firstSeen: '210 days ago',
-    traffic24hRx: '1.1 GB', traffic24hTx: '74 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'nintendo-switch', name: 'Nintendo Switch', type: 'consola', manufacturer: 'Nintendo',
-      ip: '192.168.8.33', mac: '58:BD:A3:4C:E2:09', routerId: 'living', band: '5 GHz',
-      signalDbm: -53, trafficMbps: 0.1, online: true, seed: 25, spread: 0.3 }),
-    hostname: 'switch-oled', dhcpLease: 'renews in 5h 47min', firstSeen: '240 days ago',
-    traffic24hRx: '8.6 GB', traffic24hTx: '310 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'portatil-invitado', name: 'Guest laptop', type: 'portatil', manufacturer: 'Desconocido',
-      ip: '192.168.8.29', mac: 'A2:7E:9C:41:0B:6D', routerId: 'living', band: '5 GHz',
-      signalDbm: -58, trafficMbps: 0.7, online: true, isNew: true, seed: 26 }),
-    hostname: 'unknown-7f2a', dhcpLease: 'renews in 2h 9min', firstSeen: 'today',
-    traffic24hRx: '480 MB', traffic24hTx: '62 MB', adguard: false, group: 'ordenadores',
-    newThisWeek: true,
-  },
-  // D3: xbox-series-s tiene UNA identidad — la cableada al GS308E de mock.ts
-  // (attachTo dist-living-lan3, online); la vieja versión wifi/offline se elimina.
-  {
-    ...extra({ id: 'portatil-antiguo', name: 'Old laptop', type: 'portatil', manufacturer: 'HP',
-      ip: '192.168.8.28', mac: '3C:52:82:5D:90:17', routerId: 'living', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0, online: false }),
-    hostname: 'hp-pavilion-15', dhcpLease: 'Expired', firstSeen: '300 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const ESTUDIO: ClientDevice[] = [
-  // —— Estudio ——
-  {
-    ...extra({ id: 'mac-mini', name: 'Mac mini', type: 'ordenador', manufacturer: 'Apple',
-      ip: '192.168.8.22', mac: 'A4:83:E7:66:2C:98', routerId: 'estudio', band: 'cable',
-      signalDbm: null, trafficMbps: 1.9, online: true, seed: 31 }),
-    hostname: 'mac-mini', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '44 GB', traffic24hTx: '5.6 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'enchufe-ventilador', name: 'Fan plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.82', mac: '9C:53:22:B1:4E:70', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -59, trafficMbps: 0.01, online: true, seed: 32, spread: 0.02 }),
-    hostname: 'tapo-p110-ventilador', dhcpLease: 'renews in 12h 0min', firstSeen: '120 days ago',
-    traffic24hRx: '7 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'ipad-pro', name: 'iPad Pro', type: 'tablet', manufacturer: 'Apple',
-      ip: '192.168.8.51', mac: 'F0:18:98:91:5A:2B', routerId: 'estudio', band: '5 GHz',
-      signalDbm: -49, trafficMbps: 0.8, online: true, seed: 33 }),
-    hostname: 'ipad-pro', dhcpLease: 'renews in 9h 26min', firstSeen: '160 days ago',
-    traffic24hRx: '5.1 GB', traffic24hTx: '390 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'hue-hub', name: 'Hub Philips Hue', type: 'iot', manufacturer: 'Signify',
-      ip: '192.168.8.15', mac: '00:17:88:2A:91:CE', routerId: 'estudio', band: 'cable',
-      signalDbm: null, trafficMbps: 0.02, online: true, seed: 34, spread: 0.04 }),
-    hostname: 'philips-hue-bridge', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '96 MB', traffic24hTx: '22 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ id: 'sonos-one', name: 'Sonos One', type: 'altavoz', manufacturer: 'Sonos',
-      ip: '192.168.8.55', mac: '48:A6:B8:14:72:E0', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -57, trafficMbps: 0.5, online: true, seed: 35 }),
-    hostname: 'sonos-one-estudio', dhcpLease: 'renews in 10h 4min', firstSeen: '195 days ago',
-    traffic24hRx: '3.8 GB', traffic24hTx: '110 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'iphone-trabajo', name: 'Work iPhone', type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.50', mac: '8C:85:90:47:C1:93', routerId: 'estudio', band: '5 GHz',
-      signalDbm: -47, trafficMbps: 0.3, online: true, isNew: true, seed: 36 }),
-    hostname: 'iphone-15-pro-work', dhcpLease: 'renews in 3h 38min', firstSeen: 'today',
-    traffic24hRx: '320 MB', traffic24hTx: '41 MB', adguard: true, group: 'moviles',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'macbook-viejo', name: 'Old MacBook', type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.25', mac: '3C:22:FB:0E:66:A1', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -60, trafficMbps: 0, online: false }),
-    hostname: 'macbook-pro-2015', dhcpLease: 'Expired', firstSeen: '320 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const PATIO: ClientDevice[] = [
-  // —— Patio ——
-  {
-    ...extra({ id: 'camara-jardin', name: 'Garden camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.73', mac: 'EC:71:DB:44:12:9B', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -74, trafficMbps: 1.4, online: true, seed: 41 }),
-    hostname: 'reolink-jardin', dhcpLease: 'renews in 8h 49min', firstSeen: '4 days ago',
-    traffic24hRx: '14 GB', traffic24hTx: '820 MB', adguard: true, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'sensor-riego', name: 'Irrigation sensor', type: 'iot', manufacturer: 'Tuya',
-      ip: '192.168.8.89', mac: 'D8:1F:12:5B:08:44', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -71, trafficMbps: 0.01, online: true, seed: 42, spread: 0.02 }),
-    hostname: 'tuya-riego-01', dhcpLease: 'renews in 12h 0min', firstSeen: '5 days ago',
-    traffic24hRx: '2 MB', traffic24hTx: '1 MB', adguard: false, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'enchufe-calefactor', name: 'Heater plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.80', mac: '50:C7:BF:31:7A:05', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -75, trafficMbps: 0.02, online: true, seed: 43, spread: 0.03 }),
-    hostname: 'tapo-p110-calefactor', dhcpLease: 'renews in 12h 0min', firstSeen: '96 days ago',
-    traffic24hRx: '6 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'camara-garaje', name: 'Garage camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.74', mac: 'EC:71:DB:44:13:02', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -78, trafficMbps: 0, online: false }),
-    hostname: 'reolink-garaje', dhcpLease: 'Expired', firstSeen: '130 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: false, group: 'iot',
-  },
-]
-
 // ---------------------------------------------------------------------------
 // Builder: enriquece una lista de `Device` (mock local o API) con los
 // metadatos de cliente (hostname, DHCP, AdGuard, grupo de filtro).
-// - `withSynthetic=true` (modo demo local, sin backend): expande el canon a
-//   los 65 clientes del dataset reconciliado (agregado de bombillas +
-//   adicionales).
-// - `withSynthetic=false` (backend live): solo fusiona detalles conocidos por
-//   id y deriva valores plausibles para clientes nuevos — nunca inventa
-//   dispositivos que la API no ha reportado.
 // ---------------------------------------------------------------------------
 
 const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
@@ -396,6 +123,9 @@ const TYPE_TO_GROUP: Record<Device['type'], FilterGroup> = {
   desconocido: 'otros',
 }
 
+/** Iconos lucide referenciados POR NOMBRE en el canon JSON (iconOverride). */
+const ICON_BY_NAME: Record<string, LucideIcon> = { BookOpen, Network }
+
 function slug(name: string): string {
   return (
     name
@@ -420,19 +150,48 @@ function defaultDetails(d: Device): Omit<ClientDevice, keyof Device> {
   }
 }
 
-export function buildClientDevices(canon: Device[], withSynthetic: boolean): ClientDevice[] {
-  const expanded: ClientDevice[] = canon
-    .filter((d) => !withSynthetic || d.id !== 'bombillas-ikea')
-    .map((d) => ({ ...d, ...(CANON_DETAILS[d.id] ?? defaultDetails(d)) }))
-  if (!withSynthetic) return expanded
-  return [...expanded, ...ADDITIONAL, ...LIVING, ...ESTUDIO, ...PATIO]
+/** Metadatos de cliente que pueden venir inline (canon JSON / API demo). */
+interface InlineDetails {
+  hostname?: string
+  dhcpLease?: string
+  firstSeen?: string
+  traffic24hRx?: string
+  traffic24hTx?: string
+  adguard?: boolean
+  group?: FilterGroup
+  iconOverride?: string
+  newThisWeek?: boolean
+}
+
+/** Extrae los metadatos inline del canon; null si el Device no los trae. */
+function inlineDetails(d: Device): Omit<ClientDevice, keyof Device> | null {
+  const raw = d as Device & InlineDetails
+  if (typeof raw.hostname !== 'string' || typeof raw.group !== 'string') return null
+  return {
+    hostname: raw.hostname,
+    dhcpLease: raw.dhcpLease ?? '—',
+    firstSeen: raw.firstSeen ?? '—',
+    traffic24hRx: raw.traffic24hRx ?? '—',
+    traffic24hTx: raw.traffic24hTx ?? '—',
+    adguard: raw.adguard ?? true,
+    group: raw.group ?? TYPE_TO_GROUP[d.type],
+    newThisWeek: raw.newThisWeek,
+    iconOverride: raw.iconOverride ? ICON_BY_NAME[raw.iconOverride] : undefined,
+  }
 }
 
-const canonExpanded: ClientDevice[] = canonDevices
-  .filter((d) => d.id !== 'bombillas-ikea')
-  .map((d) => ({ ...d, ...CANON_DETAILS[d.id] }))
+/**
+ * Fusiona metadatos de cliente sobre la lista de Devices. Prioridad:
+ * inline (canon JSON / API demo) > CANON_DETAILS (ids conocidos) > defaults.
+ * `withSynthetic` se conserva por compatibilidad de firma: desde D65-1 el
+ * canon ya llega completo (65 IDs) y nunca se sintetizan devices extra.
+ */
+export function buildClientDevices(canon: Device[], withSynthetic = false): ClientDevice[] {
+  void withSynthetic // legado de la firma: el canon ya viene completo (D65-1)
+  return canon.map((d) => ({ ...d, ...(inlineDetails(d) ?? CANON_DETAILS[d.id] ?? defaultDetails(d)) }))
+}
 
-export const allDevices: ClientDevice[] = [...canonExpanded, ...ADDITIONAL, ...LIVING, ...ESTUDIO, ...PATIO]
+export const allDevices: ClientDevice[] = buildClientDevices(canonDevices, true)
 
 /** Señal débil: online con < −70 dBm (devices.md §②) */
 export const weakSignalCount = allDevices.filter((d) => d.online && d.signalDbm !== null && d.signalDbm < -70).length