فهرست منبع

feat(devices): link clients with multiple MAC addresses (#1174)

Closes #1151. Some devices use a different MAC per SSID, so the same physical client showed up as two rows. New device_links table (alias -> canonical) with link/unlink endpoints (admin, no chains), list-level merging into the canonical entry (online = any, combined data, summed traffic, aliases in aliasMacs), a Linked MACs section in the edit sheet with a client picker, a suggestion banner for unlinked clients sharing hostname+IP never seen simultaneously (suggestions never merge on their own), and ghost/registry integration (aliases skip ghost rows, last known IP retained).
Nacho 2 ماه پیش
والد
کامیت
829fcf9970

+ 11 - 1
app/public/locales/en/translation.json

@@ -434,6 +434,10 @@
       "banTitle": "Block bands",
       "banHint": "Coming soon: block this device from 2.4/5/6 GHz networks.",
       "demoNotice": "Demo mode: changes are only saved in this browser.",
+      "linkedMacs": "Linked MACs",
+      "linkPlaceholder": "Link another client…",
+      "link": "Link",
+      "unlink": "Unlink",
       "dangerZone": "Danger zone",
       "delete": "Delete client",
       "deleteTitle": "Delete this client?",
@@ -459,6 +463,12 @@
       "planRun": "Run and apply",
       "planNone": "Nothing to apply"
     },
+    "suggestions": {
+      "title": "Possible duplicate clients",
+      "desc": "These clients share hostname and IP and are never seen at the same time: they may be one device with multiple MACs. Link them to show a single row.",
+      "link": "Link",
+      "dismiss": "Dismiss"
+    },
     "new": "New",
     "onlyOnline": "Only online",
     "onlineAll": "All",
@@ -2574,4 +2584,4 @@
     "disabledTitle": "Rack canvas is disabled",
     "disabledText": "It is a development view (labs). Enable it in Settings → Labs → Rack canvas to try it."
   }
-}
+}

+ 11 - 1
app/public/locales/es/translation.json

@@ -434,6 +434,10 @@
       "banTitle": "Bloquear bandas",
       "banHint": "Próximamente: impedir que se conecte a redes 2.4/5/6 GHz.",
       "demoNotice": "En modo demo los cambios solo se guardan en este navegador.",
+      "linkedMacs": "MACs enlazadas",
+      "linkPlaceholder": "Enlazar otro cliente…",
+      "link": "Enlazar",
+      "unlink": "Desenlazar",
       "dangerZone": "Zona de riesgo",
       "delete": "Borrar cliente",
       "deleteTitle": "¿Borrar este cliente?",
@@ -459,6 +463,12 @@
       "planRun": "Ejecutar y aplicar",
       "planNone": "Sin cambios que aplicar"
     },
+    "suggestions": {
+      "title": "Posibles clientes duplicados",
+      "desc": "Estos clientes comparten hostname e IP y nunca se ven a la vez: pueden ser un dispositivo con varias MACs. Enlázalos para que salgan en una sola fila.",
+      "link": "Enlazar",
+      "dismiss": "Descartar"
+    },
     "new": "Nuevo",
     "onlyOnline": "Solo online",
     "onlineAll": "Todos",
@@ -2574,4 +2584,4 @@
     "disabledTitle": "Rack canvas está desactivado",
     "disabledText": "Es una vista en desarrollo (labs). Actívala en Ajustes → Labs → Rack canvas si quieres probarla."
   }
-}
+}

+ 87 - 0
app/src/components/DeviceEditSheet.tsx

@@ -37,6 +37,10 @@ export interface DeviceEditSheetProps {
   onSave: (device: ClientDevice, patch: { icon: string; name: string; type: string }) => void
   /** #1145: tras borrar el cliente del registro (el padre cierra y refresca). */
   onDeleted?: () => void
+  /** #1151: resto de clientes (para el selector de enlace). */
+  clients?: ClientDevice[]
+  /** #1151: tras enlazar/desenlazar (el padre cierra y refresca). */
+  onLinkChanged?: () => void
 }
 
 // #797: tipos válidos del clasificador (paridad con adapters.ValidDeviceTypes
@@ -54,11 +58,51 @@ export function DeviceEditSheet({
   onClose,
   onSave,
   onDeleted,
+  clients,
+  onLinkChanged,
 }: DeviceEditSheetProps) {
   const { t } = useTranslation()
   const [deleteOpen, setDeleteOpen] = useState(false)
   const [deleting, setDeleting] = useState(false)
+  const [linkTarget, setLinkTarget] = useState('')
+  const [linkBusy, setLinkBusy] = useState(false)
   const [icon, setIcon] = useState(device?.iconOverride ?? '')
+
+  const otherClients = (clients ?? []).filter(
+    (c) => c.mac && c.mac !== device?.mac && c.mac !== device?.id && !(device?.aliasMacs ?? []).includes(c.mac),
+  )
+
+  const linkClient = async () => {
+    if (!linkTarget || !device?.mac) return
+    setLinkBusy(true)
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(linkTarget)}/link`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ target: device.mac }),
+      })
+      onLinkChanged?.()
+      onClose()
+    } catch {
+      // fallo silencioso: el botón vuelve a habilitarse
+    } finally {
+      setLinkBusy(false)
+    }
+  }
+
+  const unlinkAlias = async (alias: string) => {
+    if (!alias) return
+    setLinkBusy(true)
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(alias)}/link`, { method: 'DELETE' })
+      onLinkChanged?.()
+      onClose()
+    } catch {
+      // fallo silencioso
+    } finally {
+      setLinkBusy(false)
+    }
+  }
   const [name, setName] = useState(device?.nameOverride ?? '')
   const [devType, setDevType] = useState(device?.typeOverride ?? '')
   const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false })
@@ -472,6 +516,49 @@ export function DeviceEditSheet({
               </div>
             )}
 
+            {/* #1151: MACs enlazadas (mismo dispositivo, varias MACs) */}
+            {!isDemo && device?.mac && (
+              <div className="rounded-xl border border-border bg-elevated/40 p-3">
+                <div className="text-label uppercase tracking-wide text-text-muted">{t('devices.edit.linkedMacs')}</div>
+                {(device.aliasMacs?.length ?? 0) > 0 && (
+                  <ul className="mb-2 mt-1.5 space-y-1">
+                    {device.aliasMacs.map((alias) => (
+                      <li key={alias} className="flex items-center justify-between gap-2 rounded-lg bg-canvas/60 px-2 py-1.5">
+                        <span className="font-mono text-mono-sm text-text-primary">{alias}</span>
+                        <button
+                          type="button"
+                          disabled={linkBusy}
+                          onClick={() => void unlinkAlias(alias)}
+                          className="rounded-md px-2 py-0.5 text-caption text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+                        >
+                          {t('devices.edit.unlink')}
+                        </button>
+                      </li>
+                    ))}
+                  </ul>
+                )}
+                {otherClients.length > 0 && (
+                  <div className="mt-2 flex items-center gap-2">
+                    <Select value={linkTarget} onValueChange={setLinkTarget}>
+                      <SelectTrigger className="h-9 flex-1">
+                        <SelectValue placeholder={t('devices.edit.linkPlaceholder')} />
+                      </SelectTrigger>
+                      <SelectContent>
+                        {otherClients.map((c) => (
+                          <SelectItem key={c.mac} value={c.mac ?? ''}>
+                            {c.name || c.mac}
+                          </SelectItem>
+                        ))}
+                      </SelectContent>
+                    </Select>
+                    <Button size="sm" variant="outline" disabled={!linkTarget || linkBusy} onClick={() => void linkClient()}>
+                      {linkBusy ? t('common.loading') : t('devices.edit.link')}
+                    </Button>
+                  </div>
+                )}
+              </div>
+            )}
+
             {isDemo && (
               <p className="rounded-lg border border-warn/30 bg-warn/10 p-3 text-caption text-warn">
                 {t('devices.edit.demoNotice')}

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

@@ -255,6 +255,11 @@ export interface Device {
    */
   firstSeenMs?: number
   lastSeenMs?: number
+  /**
+   * #1151: MACs enlazadas a este cliente (mismo dispositivo con varias
+   * MACs, p. ej. una por SSID). Solo viaja en la entrada canónica.
+   */
+  aliasMacs?: string[]
 }
 
 /**

+ 70 - 0
app/src/pages/Devices.tsx

@@ -1351,6 +1351,37 @@ export default function Devices() {
   const navigate = useNavigate()
   const reduce = useReducedMotion()
   const { devices, deviceTotals, isDemo, routers, distributionNodes, refresh } = useNetPulse()
+  const { refreshKey } = useDashboard()
+  // #1151: candidatos a "mismo dispositivo con varias MACs" que el server
+  // detecta (hostname+IP compartidos, nunca simultáneos). Enlazar es manual.
+  const [linkSuggestions, setLinkSuggestions] = useState<[string, string][]>([])
+  const [dismissedLinks, setDismissedLinks] = useState<Set<string>>(new Set())
+  useEffect(() => {
+    if (isDemo) return
+    let alive = true
+    void fetchJson<{ linkSuggestions?: [string, string][] }>('/api/devices?page=1&pageSize=1')
+      .then((r) => {
+        if (alive && r.ok && Array.isArray(r.data?.linkSuggestions)) setLinkSuggestions(r.data.linkSuggestions)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [refreshKey, isDemo])
+
+  const linkPair = async (a: string, b: string) => {
+    try {
+      await fetchJson(`/api/devices/${encodeURIComponent(b)}/link`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ target: a }),
+      })
+      setLinkSuggestions((p) => p.filter(([x, y]) => !(x === a && y === b) && !(x === b && y === a)))
+      refresh()
+    } catch {
+      // fallo silencioso: la sugerencia sigue para reintentar
+    }
+  }
   const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string }>>(() => {
     try {
       const raw = localStorage.getItem('netpulse-device-overrides')
@@ -1801,6 +1832,43 @@ export default function Devices() {
       {/* ② Stats strip */}
       <StatsStrip allDevices={allDevices} onlyUnprotected={onlyUnprotected} onToggleUnprotected={toggleUnprotected} />
 
+      {/* #1151: sugerencias de enlace (mismo dispositivo, varias MACs) */}
+      {linkSuggestions.filter(([a, b]) => !dismissedLinks.has(a + b)).length > 0 && (
+        <div className="mb-4 rounded-2xl border border-accent/30 bg-accent/5 p-4">
+          <div className="text-label uppercase tracking-[0.06em] text-accent">{t('devices.suggestions.title')}</div>
+          <p className="mb-2 mt-1 text-caption text-text-muted">{t('devices.suggestions.desc')}</p>
+          <ul className="space-y-1.5">
+            {linkSuggestions
+              .filter(([a, b]) => !dismissedLinks.has(a + b))
+              .map(([a, b]) => {
+                const na = allDevices.find((d) => d.mac === a)?.name ?? a
+                const nb = allDevices.find((d) => d.mac === b)?.name ?? b
+                return (
+                  <li key={a + b} className="flex flex-wrap items-center gap-2 text-sm">
+                    <span className="font-medium text-text-primary">{na}</span>
+                    <span className="text-text-muted">·</span>
+                    <span className="font-medium text-text-primary">{nb}</span>
+                    <button
+                      type="button"
+                      onClick={() => void linkPair(a, b)}
+                      className="rounded-lg border border-accent/40 px-2.5 py-1 text-caption font-medium text-accent transition-colors hover:bg-accent/10"
+                    >
+                      {t('devices.suggestions.link')}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => setDismissedLinks((p) => new Set(p).add(a + b))}
+                      className="rounded-lg px-2.5 py-1 text-caption text-text-muted transition-colors hover:text-text-primary"
+                    >
+                      {t('devices.suggestions.dismiss')}
+                    </button>
+                  </li>
+                )
+              })}
+          </ul>
+        </div>
+      )}
+
       {/* ③ Filter bar */}
       <FilterBar
         routerIds={routerIds}
@@ -1946,6 +2014,8 @@ export default function Devices() {
         onClose={() => setEditingId(null)}
         onSave={handleEditSave}
         onDeleted={() => setEditingId(null)}
+        clients={allDevices}
+        onLinkChanged={() => setEditingId(null)}
       />
 
       <OnboardingIntake

+ 186 - 0
server-go/internal/adapters/device_links.go

@@ -0,0 +1,186 @@
+package adapters
+
+// device_links.go — cliente con varias MACs (#1151): un mismo dispositivo
+// (p. ej. un reloj que usa una MAC por SSID) puede aparecer como varios
+// clientes. El usuario enlaza las MACs (device_links: alias → canónico) y
+// la lista las fusiona en una sola entrada.
+
+import (
+	"strings"
+)
+
+// normalizeLinkMAC: formato canónico de identidad (mayúsculas, ':'). Igual
+// que normSeenMAC; nombre propio para no acoplar los dos ficheros.
+func normalizeLinkMAC(mac string) string {
+	return strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(mac), "-", ":"))
+}
+
+// DeviceLinks carga TODOS los enlaces alias → canónico. Mapa vacío si no hay
+// BD o no hay enlaces.
+func (l *Live) deviceLinks() map[string]string {
+	out := map[string]string{}
+	if l.db == nil {
+		return out
+	}
+	rows, err := l.db.DB.Query(`SELECT mac, canonical FROM device_links`)
+	if err != nil {
+		return out
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var alias, canonical string
+		if err := rows.Scan(&alias, &canonical); err != nil {
+			continue
+		}
+		out[normalizeLinkMAC(alias)] = normalizeLinkMAC(canonical)
+	}
+	return out
+}
+
+// mergeLinkedDevices funde los clientes enlazados en su entrada canónica:
+// online si cualquiera lo está, hostname/IP/fabricante combinados (el
+// canónico manda, las alias rellenan huecos) y el tráfico se suma (MACs
+// alternantes: nunca simultáneas, la suma es la actividad del cliente).
+// La entrada resultante lleva SIEMPRE la MAC canónica (identidad estable:
+// aunque el watch cambie de SSID y su alias sea la única vista, el cliente
+// conserva la MAC por la que el usuario lo enlazó) y AliasMacs con las MACs
+// fundidas.
+func mergeLinkedDevices(devices []Device, links map[string]string) []Device {
+	if len(devices) == 0 || len(links) == 0 {
+		return devices
+	}
+	groups := map[string][]Device{}
+	order := []string{}
+	loose := []Device{} // sin MAC: sin identidad enlazable, se conservan tal cual
+	for _, d := range devices {
+		mac := normalizeLinkMAC(d.MAC)
+		if mac == "" {
+			loose = append(loose, d)
+			continue
+		}
+		canonical, linked := links[mac]
+		if !linked {
+			canonical = mac
+		}
+		if _, seen := groups[canonical]; !seen {
+			order = append(order, canonical)
+		}
+		groups[canonical] = append(groups[canonical], d)
+	}
+	out := make([]Device, 0, len(devices))
+	for _, canonical := range order {
+		ds := groups[canonical]
+		if len(ds) == 1 {
+			// #1151: si la única entrada es una alias (el canónico no se ve
+			// ahora), expone la identidad canónica con la alias en AliasMacs.
+			d := ds[0]
+			mac := normalizeLinkMAC(d.MAC)
+			if c, linked := links[mac]; linked && c != mac {
+				d.MAC = c
+				d.ID = strings.ToLower(strings.ReplaceAll(c, ":", "-"))
+				d.AliasMacs = []string{mac}
+			}
+			out = append(out, d)
+			continue
+		}
+		// Primario: el dispositivo cuya MAC ES el canónico; si solo hay
+		// alias (el canónico no se ve ahora), el primero online o el primero.
+		primary := 0
+		for i := range ds {
+			if normalizeLinkMAC(ds[i].MAC) == canonical {
+				primary = i
+				break
+			}
+		}
+		if normalizeLinkMAC(ds[primary].MAC) != canonical {
+			for i := range ds {
+				if ds[i].Online {
+					primary = i
+					break
+				}
+			}
+		}
+		canon := ds[primary]
+		aliases := make([]string, 0, len(ds)-1)
+		for i, d := range ds {
+			if i == primary {
+				continue
+			}
+			aliases = append(aliases, normalizeLinkMAC(d.MAC))
+			if d.Online {
+				canon.Online = true
+			}
+			if canon.IP == "" {
+				canon.IP = d.IP
+			}
+			if canon.Hostname == "" {
+				canon.Hostname = d.Hostname
+			}
+			if canon.Name == "" || canon.Name == canon.MAC {
+				canon.Name = d.Name
+			}
+			if canon.Manufacturer == "" {
+				canon.Manufacturer = d.Manufacturer
+			}
+			canon.TrafficMbps += d.TrafficMbps
+		}
+		canon.MAC = canonical
+		canon.ID = strings.ToLower(strings.ReplaceAll(canonical, ":", "-"))
+		canon.AliasMacs = aliases
+		out = append(out, canon)
+	}
+	return append(out, loose...)
+}
+
+// LinkSuggestions: pares de clientes NO enlazados que comparten hostname no
+// vacío e IP y no están los dos online a la vez (#1151): candidatos a ser el
+// mismo dispositivo con varias MACs. Solo sugiere; nunca fusiona solo.
+func LinkSuggestions(devices []Device, links map[string]string) [][2]string {
+	type id struct{ host, ip string }
+	byID := map[id][]Device{}
+	for _, d := range devices {
+		host := strings.ToLower(strings.TrimSpace(d.Hostname))
+		if host == "" || d.IP == "" {
+			continue
+		}
+		if _, linked := links[normalizeLinkMAC(d.MAC)]; linked {
+			continue // ya enlazado
+		}
+		k := id{host: host, ip: d.IP}
+		byID[k] = append(byID[k], d)
+	}
+	var out [][2]string
+	seenPair := map[string]bool{}
+	for _, ds := range byID {
+		if len(ds) < 2 {
+			continue
+		}
+		online := 0
+		for _, d := range ds {
+			if d.Online {
+				online++
+			}
+		}
+		if online > 1 {
+			continue // dos a la vez: son dispositivos distintos
+		}
+		for i := 0; i < len(ds); i++ {
+			for j := i + 1; j < len(ds); j++ {
+				a, b := normalizeLinkMAC(ds[i].MAC), normalizeLinkMAC(ds[j].MAC)
+				if a == "" || b == "" || a == b {
+					continue
+				}
+				pair := a + "|" + b
+				if a > b {
+					pair = b + "|" + a
+				}
+				if seenPair[pair] {
+					continue
+				}
+				seenPair[pair] = true
+				out = append(out, [2]string{a, b})
+			}
+		}
+	}
+	return out
+}

+ 76 - 0
server-go/internal/adapters/device_links_test.go

@@ -0,0 +1,76 @@
+package adapters
+
+import "testing"
+
+// #1151: las MACs enlazadas se funden en la entrada canónica: online = OR,
+// datos combinados, tráfico sumado y AliasMacs con las alias fundidas.
+func TestMergeLinkedDevices(t *testing.T) {
+	links := map[string]string{"AA:AA:AA:00:00:02": "BB:BB:BB:00:00:01"}
+	devs := []Device{
+		{MAC: "BB:BB:BB:00:00:01", Online: true, Hostname: "watch", IP: "192.168.1.50", TrafficMbps: 1.2},
+		{MAC: "AA:AA:AA:00:00:02", Online: false, Manufacturer: "Google", TrafficMbps: 0.3},
+	}
+	out := mergeLinkedDevices(devs, links)
+	if len(out) != 1 {
+		t.Fatalf("devices = %d, want 1 (fundidas)", len(out))
+	}
+	g := out[0]
+	if g.MAC != "BB:BB:BB:00:00:01" || !g.Online {
+		t.Fatalf("canon = %+v, want MAC canonico online", g)
+	}
+	if len(g.AliasMacs) != 1 || g.AliasMacs[0] != "AA:AA:AA:00:00:02" {
+		t.Fatalf("aliasMacs = %v", g.AliasMacs)
+	}
+	if g.TrafficMbps < 1.49 || g.TrafficMbps > 1.51 {
+		t.Fatalf("traffic = %v, want 1.5 (suma)", g.TrafficMbps)
+	}
+	if g.Hostname != "watch" || g.Manufacturer != "Google" || g.IP != "192.168.1.50" {
+		t.Fatalf("merge de datos = %+v", g)
+	}
+}
+
+// El canónico puede no estar en la lista (solo se ve la alias): la salida
+// conserva la identidad canónica y toma online/datos de la alias.
+func TestMergeLinkedDevicesCanonicalNotSeen(t *testing.T) {
+	links := map[string]string{"AA:AA:AA:00:00:02": "BB:BB:BB:00:00:01"}
+	devs := []Device{{MAC: "AA:AA:AA:00:00:02", Online: true, IP: "192.168.1.51"}}
+	out := mergeLinkedDevices(devs, links)
+	if len(out) != 1 {
+		t.Fatalf("devices = %d, want 1", len(out))
+	}
+	if out[0].MAC != "BB:BB:BB:00:00:01" || !out[0].Online || out[0].IP != "192.168.1.51" {
+		t.Fatalf("canon = %+v, want identidad canonica con datos de la alias", out[0])
+	}
+}
+
+// Sin enlaces la lista sale intacta.
+func TestMergeLinkedDevicesNoLinks(t *testing.T) {
+	devs := []Device{{MAC: "AA:AA:AA:00:00:01"}, {MAC: "BB:BB:BB:00:00:02"}}
+	if out := mergeLinkedDevices(devs, map[string]string{}); len(out) != 2 {
+		t.Fatalf("devices = %d, want 2", len(out))
+	}
+}
+
+// Sugerencias: hostname+IP compartidos y no simultáneos sugieren; ya
+// enlazadas o ambas online no.
+func TestLinkSuggestions(t *testing.T) {
+	devs := []Device{
+		{MAC: "AA:AA:AA:00:00:01", Hostname: "watch", IP: "192.168.1.50", Online: true},
+		{MAC: "AA:AA:AA:00:00:02", Hostname: "watch", IP: "192.168.1.50", Online: false},
+		{MAC: "AA:AA:AA:00:00:03", Hostname: "other", IP: "192.168.1.60", Online: false},
+	}
+	if got := LinkSuggestions(devs, map[string]string{}); len(got) != 1 {
+		t.Fatalf("suggestions = %v, want 1 par", got)
+	}
+	// Ambas online: no sugiere.
+	both := []Device{devs[0], devs[1], devs[1]}
+	both[1].Online = true
+	both[2].Online = true
+	if got := LinkSuggestions(both, map[string]string{}); len(got) != 0 {
+		t.Fatalf("suggestions = %v, want 0 con las dos online", got)
+	}
+	// Ya enlazada: no sugiere.
+	if got := LinkSuggestions(devs, map[string]string{"AA:AA:AA:00:00:02": "AA:AA:AA:00:00:01"}); len(got) != 0 {
+		t.Fatalf("suggestions = %v, want 0 si ya enlazada", got)
+	}
+}

+ 28 - 6
server-go/internal/adapters/device_seen.go

@@ -31,9 +31,10 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) {
 		return
 	}
 	defer tx.Rollback() //nolint:errcheck // no-op tras Commit
-	stmt, err := tx.Prepare(`INSERT INTO device_seen (mac, first_seen, last_seen, name) VALUES (?, ?, ?, ?)
+	stmt, err := tx.Prepare(`INSERT INTO device_seen (mac, first_seen, last_seen, name, ip) VALUES (?, ?, ?, ?, ?)
 		ON CONFLICT(mac) DO UPDATE SET last_seen = excluded.last_seen,
-			name = CASE WHEN excluded.name != '' THEN excluded.name ELSE device_seen.name END`)
+			name = CASE WHEN excluded.name != '' THEN excluded.name ELSE device_seen.name END,
+			ip = CASE WHEN excluded.ip != '' THEN excluded.ip ELSE device_seen.ip END`)
 	if err != nil {
 		return
 	}
@@ -50,7 +51,7 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) {
 		if name == "" && d.Name != "" && !strings.EqualFold(d.Name, d.MAC) {
 			name = d.Name
 		}
-		if _, err := stmt.Exec(mac, nowMs, nowMs, name); err != nil {
+		if _, err := stmt.Exec(mac, nowMs, nowMs, name, d.IP); err != nil {
 			return
 		}
 	}
@@ -78,12 +79,12 @@ func (l *Live) applyDeviceSeen(devices []Device) {
 
 type seenRow struct {
 	first, last int64
-	name        string
+	name, ip    string
 }
 
 // seenByMac carga la tabla device_seen completa (una query, sin N+1).
 func (l *Live) seenByMac() (map[string]seenRow, error) {
-	rows, err := l.db.DB.Query(`SELECT mac, first_seen, last_seen, COALESCE(name, '') FROM device_seen`)
+	rows, err := l.db.DB.Query(`SELECT mac, first_seen, last_seen, COALESCE(name, ''), COALESCE(ip, '') FROM device_seen`)
 	if err != nil {
 		return nil, err
 	}
@@ -92,7 +93,7 @@ func (l *Live) seenByMac() (map[string]seenRow, error) {
 	for rows.Next() {
 		var mac string
 		var s seenRow
-		if err := rows.Scan(&mac, &s.first, &s.last, &s.name); err != nil {
+		if err := rows.Scan(&mac, &s.first, &s.last, &s.name, &s.ip); err != nil {
 			return nil, err
 		}
 		byMac[mac] = s
@@ -113,20 +114,38 @@ func (l *Live) ghostDevices(devices []Device) []Device {
 	for i := range devices {
 		live[normSeenMAC(devices[i].MAC)] = true
 	}
+	// #1151: una alias enlazada no sale como fantasma propio - su canónico la
+	// representa en la lista (si el canónico no está en el registro, la alias
+	// se muestra tal cual para no perder al cliente).
+	links := l.deviceLinks()
 	byMac, err := l.seenByMac()
 	if err != nil {
 		return nil
 	}
+	// #1151: aliases registradas de cada canónico (para que la hoja las
+	// muestre y permita desenlazarlas).
+	revAlias := map[string][]string{}
+	for alias, canonical := range links {
+		if _, registered := byMac[canonical]; registered {
+			revAlias[canonical] = append(revAlias[canonical], alias)
+		}
+	}
 	var out []Device
 	for rawMac, s := range byMac {
 		mac := normSeenMAC(rawMac)
 		if live[mac] {
 			continue
 		}
+		if canonical, linked := links[mac]; linked {
+			if _, canonRegistered := byMac[canonical]; canonRegistered {
+				continue
+			}
+		}
 		d := Device{
 			ID:          strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
 			MAC:         mac,
 			Type:        "desconocido",
+			IP:          s.ip,
 			Online:      false,
 			Band:        "—",
 			FirstSeenMs: s.first,
@@ -136,6 +155,9 @@ func (l *Live) ghostDevices(devices []Device) []Device {
 			d.Hostname = s.name
 			d.Name = s.name
 		}
+		if aliases := revAlias[mac]; len(aliases) > 0 {
+			d.AliasMacs = aliases
+		}
 		out = append(out, d)
 	}
 	return out

+ 2 - 1
server-go/internal/adapters/live.go

@@ -2779,7 +2779,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	// topología → los chips saltaban de posición al refrescar. Ordenar por
 	// MAC hace el contrato determinista para el mismo set de dispositivos.
 	sort.Slice(devices, func(i, j int) bool { return devices[i].MAC < devices[j].MAC })
-	return normalizeDevices(devices)
+	// #1151: canónicas + fusión de enlazadas (orden: normalizar -> fusionar).
+	return normalizeDevices(mergeLinkedDevices(devices, l.deviceLinks()))
 }
 
 // normalizeDevices: MACs a formato canónico (mayúsculas, ':') y dedup por

+ 3 - 0
server-go/internal/adapters/types.go

@@ -298,6 +298,9 @@ type Device struct {
 	// server NO pre-formatea (lección #899).
 	FirstSeenMs  int64  `json:"firstSeenMs,omitempty"`
 	LastSeenMs   int64  `json:"lastSeenMs,omitempty"`
+	// AliasMacs: MACs enlazadas a este cliente (#1151, mismo dispositivo con
+	// varias MACs - p. ej. una por SSID). Solo viaja en el canónico.
+	AliasMacs []string `json:"aliasMacs,omitempty"`
 	Traffic24hRx string `json:"traffic24hRx,omitempty"`
 	Traffic24hTx string `json:"traffic24hTx,omitempty"`
 	Adguard      *bool  `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)

+ 10 - 0
server-go/internal/db/db.go

@@ -133,6 +133,13 @@ CREATE TABLE IF NOT EXISTS device_seen (
   first_seen INTEGER NOT NULL,
   last_seen  INTEGER NOT NULL
 );
+-- #1151: cliente con varias MACs (un hostname, nunca simultáneas): cada fila
+-- dice "esta MAC es el mismo cliente que canonical". Clave = alias; el
+-- canónico no tiene fila propia (ausencia de fila = MAC canónica).
+CREATE TABLE IF NOT EXISTS device_links (
+  mac       TEXT PRIMARY KEY,
+  canonical TEXT NOT NULL
+);
 -- Routers configurados
 CREATE TABLE IF NOT EXISTS routers (
   id TEXT PRIMARY KEY,
@@ -572,6 +579,9 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "snmp_enabled", "ALTER TABLE routers ADD COLUMN snmp_enabled INTEGER NOT NULL DEFAULT 0")
 	// #1145: último nombre conocido del cliente (retención indefinida).
 	migrate(sqldb, "device_seen", "name", "ALTER TABLE device_seen ADD COLUMN name TEXT NOT NULL DEFAULT ''")
+	// #1151: última IP conocida (los fantasmas la conservan para la lista y
+	// las sugerencias de enlace).
+	migrate(sqldb, "device_seen", "ip", "ALTER TABLE device_seen ADD COLUMN ip TEXT NOT NULL DEFAULT ''")
 	// issue #863: sondeo HTTP de la consola de switches RTLPlayground. DEFAULT 1
 	// = comportamiento previo; se desactiva por router (la consola del firmware
 	// tiene una sola sesión global y cada login tumba la sesión humana).

+ 33 - 0
server-go/internal/httpapi/data.go

@@ -13,6 +13,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/clientbw"
+	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
 	"github.com/gnacho/netpulse/server-go/internal/roamcfg"
@@ -256,9 +257,41 @@ func (s *server) handleDevices(w http.ResponseWriter, r *http.Request) {
 	}
 	out := paginate(filtered, page, pageSize)
 	out["typeCounts"] = typeCounts
+	// #1151: candidatos a "mismo dispositivo con varias MACs" (hostname+IP
+	// compartidos, nunca simultáneos). Solo sugerencia: el enlazado es manual.
+	if suggestions := adapters.LinkSuggestions(items, loadDeviceLinks(s.db)); len(suggestions) > 0 {
+		out["linkSuggestions"] = suggestions
+	}
 	writeJSON(w, http.StatusOK, out)
 }
 
+// loadDeviceLinks: mapa alias → canónico desde la tabla device_links (una
+// query; vacío si no hay BD o no hay enlaces).
+func loadDeviceLinks(d *db.DB) map[string]string {
+	out := map[string]string{}
+	if d == nil {
+		return out
+	}
+	rows, err := d.Query(`SELECT mac, canonical FROM device_links`)
+	if err != nil {
+		return out
+	}
+	defer rows.Close()
+	for rows.Next() {
+		var alias, canonical string
+		if err := rows.Scan(&alias, &canonical); err != nil {
+			continue
+		}
+		out[normalizeMACKey(alias)] = normalizeMACKey(canonical)
+	}
+	return out
+}
+
+// normalizeMACKey: identidad canónica de enlace (mayúsculas, ':').
+func normalizeMACKey(mac string) string {
+	return strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(mac), "-", ":"))
+}
+
 // deviceMatches: substring (minúsculas) sobre name|hostname|ip|mac|manufacturer.
 func deviceMatches(d adapters.Device, query string) bool {
 	for _, v := range []string{d.Name, d.Hostname, d.IP, d.MAC, d.Manufacturer} {

+ 69 - 0
server-go/internal/httpapi/device_links.go

@@ -0,0 +1,69 @@
+package httpapi
+
+// device_links.go — enlace manual de clientes con varias MACs (#1151):
+// "esta MAC es el mismo dispositivo que esta otra". Un cliente canónico
+// agrupa a sus alias en la lista (mergeLinkedDevices en el adapter).
+
+import (
+	"net/http"
+)
+// handleDeviceLinkPut: body {"target": "<mac>"} — enlaza la MAC {mac} como
+// alias del cliente {target}. Reglas: no enlaces a sí mismo, ni alias ya
+// enlazada (desenlazar primero), ni target que sea a su vez alias (sin
+// cadenas: el merge resuelve un solo nivel a propósito).
+func (s *server) handleDeviceLinkPut(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Target string `json:"target"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	alias := normalizeMACKey(r.PathValue("mac"))
+	target := normalizeMACKey(body.Target)
+	if alias == "" || target == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
+		return
+	}
+	if alias == target {
+		writeError(w, http.StatusBadRequest, "invalid_input", "cannot link a MAC to itself")
+		return
+	}
+	links := loadDeviceLinks(s.db)
+	if _, already := links[alias]; already {
+		writeError(w, http.StatusConflict, "conflict", "this MAC is already linked; unlink it first")
+		return
+	}
+	if _, targetIsAlias := links[target]; targetIsAlias {
+		writeError(w, http.StatusConflict, "conflict", "target is itself a linked alias; link to the canonical MAC")
+		return
+	}
+	if _, err := s.db.Exec(
+		"INSERT INTO device_links (mac, canonical) VALUES (?, ?) ON CONFLICT(mac) DO UPDATE SET canonical = excluded.canonical",
+		alias, target,
+	); err != nil {
+		writeError(w, http.StatusInternalServerError, "storage_error", "")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"mac": alias, "canonical": target})
+}
+
+// handleDeviceLinkDelete: desenlaza la alias {mac} (vuelve a ser un cliente
+// independiente en la siguiente construcción de la lista).
+func (s *server) handleDeviceLinkDelete(w http.ResponseWriter, r *http.Request) {
+	alias := normalizeMACKey(r.PathValue("mac"))
+	if alias == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
+		return
+	}
+	res, err := s.db.Exec("DELETE FROM device_links WHERE mac = ?", alias)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "storage_error", "")
+		return
+	}
+	if n, _ := res.RowsAffected(); n == 0 {
+		writeError(w, http.StatusNotFound, "not_found", "")
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 44 - 0
server-go/internal/httpapi/device_overrides_test.go

@@ -151,3 +151,47 @@ func TestDeviceDelete(t *testing.T) {
 		t.Fatalf("status = %d, want 404", rec.Code)
 	}
 }
+
+// #1151: link con validaciones (self 400, ok 200, ya enlazada 409, target
+// alias 409) y unlink (204 / 404).
+func TestDeviceLinkPutDelete(t *testing.T) {
+	s := panelTestServer(t)
+	do := func(method, mac, body string) *httptest.ResponseRecorder {
+		r := httptest.NewRequest(method, "/api/devices/"+mac+"/link", strings.NewReader(body))
+		r.SetPathValue("mac", mac)
+		if body != "" {
+			r.Header.Set("Content-Type", "application/json")
+		}
+		rec := httptest.NewRecorder()
+		if method == http.MethodPut {
+			s.handleDeviceLinkPut(rec, r)
+		} else {
+			s.handleDeviceLinkDelete(rec, r)
+		}
+		return rec
+	}
+
+	// self-link: 400
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:01", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusBadRequest {
+		t.Fatalf("self link = %d, want 400", rec.Code)
+	}
+	// ok: 200
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:01"}`); rec.Code != http.StatusOK {
+		t.Fatalf("link = %d, want 200", rec.Code)
+	}
+	// ya enlazada: 409
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:02", `{"target":"AA:AA:AA:00:00:09"}`); rec.Code != http.StatusConflict {
+		t.Fatalf("relink = %d, want 409", rec.Code)
+	}
+	// target es a su vez alias: 409
+	if rec := do(http.MethodPut, "AA:AA:AA:00:00:03", `{"target":"AA:AA:AA:00:00:02"}`); rec.Code != http.StatusConflict {
+		t.Fatalf("target alias = %d, want 409", rec.Code)
+	}
+	// unlink: 204 y 404
+	if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNoContent {
+		t.Fatalf("unlink = %d, want 204", rec.Code)
+	}
+	if rec := do(http.MethodDelete, "AA:AA:AA:00:00:02", ""); rec.Code != http.StatusNotFound {
+		t.Fatalf("unlink de nuevo = %d, want 404", rec.Code)
+	}
+}

+ 2 - 0
server-go/internal/httpapi/server.go

@@ -356,6 +356,8 @@ func NewHandler(d Deps) http.Handler {
 	mux.Handle("PUT /api/devices/{mac}/override", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceOverridePut)))
 	mux.Handle("GET /api/devices/{mac}/override", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceOverrideGet)))
 	mux.Handle("PUT /api/devices/{mac}/ban", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceBanPut)))
+	mux.Handle("PUT /api/devices/{mac}/link", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceLinkPut)))
+	mux.Handle("DELETE /api/devices/{mac}/link", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceLinkDelete)))
 	mux.Handle("DELETE /api/devices/{mac}", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceDelete)))
 	// Onboarding de desconocidos (#772): "dejar como anónimo" silencia la
 	// alerta first-seen de la MAC sin darle nombre (el alta reutiliza