Przeglądaj źródła

feat(devices): let a client use the name of a chosen source (#2163) (#2283)

Nacho 1 dzień temu
rodzic
commit
db693a7f65

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- A client can use the name of a chosen source instead of the precedence the server picks, from the edit sheet: the options are only the sources that client actually has (DHCP reservation, DHCP, mDNS, reverse DNS and the rest), so picking one is always meaningful. The choice is stored per MAC next to the icon, the name and the type, `automatic` clears it, and a manually written name still wins over any source. The detail keeps showing the source in use and the full candidate list (#2163).
+
 ## [2.56.1] - 2026-12-02
 
 ### Fixed

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

@@ -525,6 +525,10 @@
       "action": "Edit",
       "name": "Name",
       "nameHint": "Empty = automatic name (DHCP hostname)",
+      "nameSource": "Name source",
+      "nameSourceAuto": "Automatic",
+      "nameSourceHint": "Use the name this source proposes for this client, while it has one. A manual name above still wins.",
+      "nameSourceNone": "This client has a single source, so there is nothing to choose.",
       "type": "Type",
       "icon": "Icon",
       "iconNames": {

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

@@ -525,6 +525,10 @@
       "action": "Editar",
       "name": "Nombre",
       "nameHint": "Vacío = nombre automático (hostname DHCP)",
+      "nameSource": "Fuente del nombre",
+      "nameSourceAuto": "Automática",
+      "nameSourceHint": "Usa el nombre que esta fuente propone para el cliente, mientras lo tenga. Un nombre manual arriba sigue mandando.",
+      "nameSourceNone": "Este cliente tiene una sola fuente, así que no hay nada que elegir.",
       "type": "Tipo",
       "icon": "Icono",
       "iconNames": {

+ 4 - 0
app/public/locales/ru/translation.json

@@ -539,6 +539,10 @@
       "action": "Изменить",
       "name": "Имя",
       "nameHint": "Пусто = автоматическое имя (DHCP hostname)",
+      "nameSource": "Источник имени",
+      "nameSourceAuto": "Автоматически",
+      "nameSourceHint": "Использовать имя, которое предлагает этот источник для клиента, пока оно есть. Имя, заданное вручную, по-прежнему важнее.",
+      "nameSourceNone": "У этого клиента только один источник, выбирать не из чего.",
       "type": "Тип",
       "icon": "Значок",
       "iconNames": {

+ 4 - 0
app/public/locales/zh/translation.json

@@ -432,6 +432,10 @@
       "action": "编辑",
       "name": "名称",
       "nameHint": "留空=自动命名(DHCP 主机名)",
+      "nameSource": "名称来源",
+      "nameSourceAuto": "自动",
+      "nameSourceHint": "使用该来源为此客户端提供的名称(只要它存在)。上方手动填写的名称仍然优先。",
+      "nameSourceNone": "此客户端只有一个来源,没有可选内容。",
       "type": "类型",
       "icon": "图标",
       "iconNames": {

+ 44 - 3
app/src/components/DeviceEditSheet.tsx

@@ -37,7 +37,10 @@ export interface DeviceEditSheetProps {
   saving?: boolean
   onClose: () => void
   /** Patch absoluto: '' en un campo = volver al valor automático (#797). */
-  onSave: (device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean }) => void
+  onSave: (
+    device: ClientDevice,
+    patch: { icon: string; name: string; type: string; notifyOffline: boolean; nameSource: 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). */
@@ -109,6 +112,8 @@ export function DeviceEditSheet({
     }
   }
   const [name, setName] = useState(device?.nameOverride ?? '')
+  // #2163: fuente de nombre elegida para este cliente ('' = automática).
+  const [nameSource, setNameSource] = useState(device?.nameSourceOverride ?? '')
   const [devType, setDevType] = useState(device?.typeOverride ?? '')
   const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false })
   const [reserveDraft, setReserveDraft] = useState(device?.ip ?? '')
@@ -143,8 +148,17 @@ export function DeviceEditSheet({
     setName(device?.nameOverride ?? '')
     setDevType(device?.typeOverride ?? '')
     setNotifyOffline(device?.notifyOffline ?? false)
+    setNameSource(device?.nameSourceOverride ?? '')
     setReserveDraft(device?.ip ?? '')
-  }, [device?.id, device?.iconOverride, device?.nameOverride, device?.typeOverride, device?.notifyOffline, device?.ip])
+  }, [
+    device?.id,
+    device?.iconOverride,
+    device?.nameOverride,
+    device?.typeOverride,
+    device?.notifyOffline,
+    device?.nameSourceOverride,
+    device?.ip,
+  ])
 
   useEffect(() => {
     if (!device || isDemo) return
@@ -175,7 +189,7 @@ export function DeviceEditSheet({
 
   const handleSave = () => {
     if (!device) return
-    onSave(device, { icon, name: name.trim(), type: devType, notifyOffline })
+    onSave(device, { icon, name: name.trim(), type: devType, notifyOffline, nameSource })
   }
 
   // #800: hostname DNS derivado del nombre visible (input del sheet o nombre
@@ -224,6 +238,33 @@ export function DeviceEditSheet({
               <p className="text-caption text-text-muted">{t('devices.edit.nameHint')}</p>
             </div>
 
+            {/* #2163: fuente de nombre elegida para este cliente. Solo se
+                ofrece lo que este cliente tiene de verdad: elegir mDNS en un
+                equipo que no anuncia nada no cambiaría el nombre. */}
+            <div className="space-y-2">
+              <label className="text-label uppercase text-text-muted">{t('devices.edit.nameSource')}</label>
+              <Select
+                value={nameSource || 'auto'}
+                onValueChange={(v) => setNameSource(v === 'auto' ? '' : v)}
+                disabled={saving || (device.nameCandidates ?? []).length < 2}
+              >
+                <SelectTrigger className="h-9 rounded-lg border-border bg-elevated text-sm text-text-primary">
+                  <SelectValue />
+                </SelectTrigger>
+                <SelectContent>
+                  <SelectItem value="auto">{t('devices.edit.nameSourceAuto')}</SelectItem>
+                  {(device.nameCandidates ?? []).map((c) => (
+                    <SelectItem key={c.source} value={c.source}>
+                      {t(`devices.detail.source.${c.source}`)}
+                    </SelectItem>
+                  ))}
+                </SelectContent>
+              </Select>
+              <p className="text-caption text-text-muted">
+                {(device.nameCandidates ?? []).length < 2 ? t('devices.edit.nameSourceNone') : t('devices.edit.nameSourceHint')}
+              </p>
+            </div>
+
             {/* Tipo (#797) */}
             <div className="space-y-2">
               <label className="text-label uppercase text-text-muted">{t('devices.edit.type')}</label>

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

@@ -308,6 +308,8 @@ export interface Device {
    * con una sola repetiría `nameSource`. La selección no cambia.
    */
   nameCandidates?: { source: NonNullable<Device['nameSource']>; value: string }[]
+  /** #2163: fuente elegida a mano para este cliente. Ausente = automática. */
+  nameSourceOverride?: NonNullable<Device['nameSource']>
   type: DeviceType
   manufacturer: string
   ip: string

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

@@ -1595,11 +1595,11 @@ export default function Devices() {
       // fallo silencioso: la sugerencia sigue para reintentar
     }
   }
-  const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean }>>(() => {
+  const [deviceOverrides, setDeviceOverrides] = useState<Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean; nameSourceOverride?: string }>>(() => {
     if (!isDemo) return {}
     try {
       const raw = localStorage.getItem('netpulse-device-overrides')
-      return raw ? (JSON.parse(raw) as Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean }>) : {}
+      return raw ? (JSON.parse(raw) as Record<string, { iconOverride?: string; nameOverride?: string; typeOverride?: string; notifyOffline?: boolean; nameSourceOverride?: string }>) : {}
     } catch {
       return {}
     }
@@ -1968,18 +1968,19 @@ export default function Devices() {
   const [savingOverride, setSavingOverride] = useState(false)
 
   const persistOverride = useCallback(
-    (id: string, patch: { iconOverride: string; nameOverride: string; typeOverride: string; notifyOffline: boolean } | null) => {
+    (id: string, patch: { iconOverride: string; nameOverride: string; typeOverride: string; notifyOffline: boolean; nameSourceOverride: string } | null) => {
       // #1631 F-29: en live el override lo persiste el servidor y no se toca
       // localStorage.
       if (!isDemo) return
       setDeviceOverrides((prev) => {
         const next = { ...prev }
-        if (patch && (patch.iconOverride || patch.nameOverride || patch.typeOverride || patch.notifyOffline)) {
+        if (patch && (patch.iconOverride || patch.nameOverride || patch.typeOverride || patch.notifyOffline || patch.nameSourceOverride)) {
           next[id] = {
             iconOverride: patch.iconOverride,
             nameOverride: patch.nameOverride,
             typeOverride: patch.typeOverride,
             notifyOffline: patch.notifyOffline,
+            nameSourceOverride: patch.nameSourceOverride,
           }
         } else {
           delete next[id]
@@ -1999,12 +2000,16 @@ export default function Devices() {
   // return de "sin cambios" impedía limpiar un override (p. ej. volver al
   // icono Auto).
   const handleEditSave = useCallback(
-    async (device: ClientDevice, patch: { icon: string; name: string; type: string; notifyOffline: boolean }) => {
+    async (
+      device: ClientDevice,
+      patch: { icon: string; name: string; type: string; notifyOffline: boolean; nameSource: string },
+    ) => {
       persistOverride(device.id, {
         iconOverride: patch.icon,
         nameOverride: patch.name,
         typeOverride: patch.type,
         notifyOffline: patch.notifyOffline,
+        nameSourceOverride: patch.nameSource,
       })
 
       if (!isDemo) {
@@ -2012,7 +2017,13 @@ export default function Devices() {
         const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/override`, {
           method: 'PUT',
           headers: { 'Content-Type': 'application/json' },
-          body: JSON.stringify({ icon: patch.icon, name: patch.name, type: patch.type, notifyOffline: patch.notifyOffline }),
+          body: JSON.stringify({
+            icon: patch.icon,
+            name: patch.name,
+            type: patch.type,
+            notifyOffline: patch.notifyOffline,
+            nameSource: patch.nameSource === 'auto' ? 'auto' : patch.nameSource,
+          }),
         })
         setSavingOverride(false)
         if (!res.ok) {

+ 26 - 0
server-go/internal/adapters/device_names.go

@@ -62,3 +62,29 @@ func nameCandidates(e nameEvidence) []NameCandidate {
 	}
 	return out
 }
+
+// NameSources es la lista cerrada de fuentes que un cliente puede elegir a
+// mano. El orden es el de precedencia por defecto.
+var NameSources = []string{"manual", "known_mac", "reservation", "dhcp", "glinet", "mdns", "rdns"}
+
+// ValidNameSource dice si la fuente forma parte del contrato.
+func ValidNameSource(source string) bool {
+	for _, s := range NameSources {
+		if s == source {
+			return true
+		}
+	}
+	return false
+}
+
+// candidateValue devuelve lo que propone una fuente concreta, o vacío si esa
+// fuente no tiene nada para este cliente. Es la pieza que usa la elección por
+// cliente (#2163): el nombre elegido sale de la evidencia, no se inventa.
+func candidateValue(e nameEvidence, source string) string {
+	for _, f := range nameCandidateOrder {
+		if f.source == source {
+			return f.value(e)
+		}
+	}
+	return ""
+}

+ 23 - 0
server-go/internal/adapters/device_names_test.go

@@ -46,3 +46,26 @@ func TestNameCandidatesUnaSolaFuenteNoEmite(t *testing.T) {
 		t.Fatalf("sin evidencia no debe emitir lista: %+v", got)
 	}
 }
+
+// #2163: la fuente elegida a mano para un cliente devuelve lo que esa fuente
+// propone, y nada cuando no tiene evidencia.
+func TestCandidateValuePorFuente(t *testing.T) {
+	e := nameEvidence{DHCP: "diskstation", MDNS: "nas.local", RDNS: "nas.example.net"}
+	if got := candidateValue(e, "mdns"); got != "nas.local" {
+		t.Fatalf("mdns = %q", got)
+	}
+	if got := candidateValue(e, "reservation"); got != "" {
+		t.Fatalf("una fuente sin evidencia debe devolver vacío, got %q", got)
+	}
+	if got := candidateValue(e, "inventada"); got != "" {
+		t.Fatalf("fuente desconocida = %q, want vacío", got)
+	}
+	for _, s := range NameSources {
+		if !ValidNameSource(s) {
+			t.Fatalf("%s debería ser válida", s)
+		}
+	}
+	if ValidNameSource("nope") {
+		t.Fatal("una fuente fuera del contrato no puede ser válida")
+	}
+}

+ 20 - 4
server-go/internal/adapters/live.go

@@ -1871,6 +1871,9 @@ type overrideInfo struct {
 	DeviceType    string
 	BannedBands   string
 	NotifyOffline bool
+	// NameSource (#2163): fuente de nombre que el usuario eligió para este
+	// cliente. Vacío = automática (la precedencia del servidor).
+	NameSource string
 }
 
 // loadDeviceOverrides lee los overrides manuales, con clave por la MAC tal
@@ -1885,17 +1888,17 @@ func (l *Live) loadDeviceOverrides() map[string]overrideInfo {
 	if l.db == nil {
 		return out
 	}
-	rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands, notify_offline FROM device_overrides")
+	rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands, notify_offline, name_source FROM device_overrides")
 	if err != nil {
 		return out
 	}
 	defer rows.Close()
 	for rows.Next() {
-		var mac, name, deviceType, bannedBands string
+		var mac, name, deviceType, bannedBands, nameSource string
 		var icon sql.NullString
 		var notifyOffline bool
-		if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, &notifyOffline); err == nil {
-			out[mac] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
+		if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, &notifyOffline, &nameSource); err == nil {
+			out[mac] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline, NameSource: nameSource}
 		}
 	}
 	return out
@@ -4585,6 +4588,19 @@ func (l *Live) buildDeviceSet(polled map[string]*routerPolled, gwID, wanPort str
 		// #2163 fase 2: la lista de candidatos sale con el cliente. Solo se
 		// emite cuando hay mas de uno (ver nameCandidates).
 		d.NameCandidates = nameCandidates(evidence)
+		// #2163: si el usuario eligió una fuente para este cliente, manda
+		// sobre la precedencia mientras esa fuente tenga algo que proponer.
+		// Un nombre manual completo (ov.Name) sigue por encima: eso es un
+		// nombre escrito, no una fuente, y ya se aplicó y fijó arriba.
+		if o, ok := deviceOverrides[mac]; ok && o.NameSource != "" {
+			d.NameSourceOverride = o.NameSource
+			if o.Name == "" {
+				if v := candidateValue(evidence, o.NameSource); v != "" {
+					d.Name = v
+					d.NameSource = o.NameSource
+				}
+			}
+		}
 		devices = append(devices, d)
 	}
 	// #1757: la VLAN de un cliente sale de la evidencia exacta del bridge (la

+ 10 - 6
server-go/internal/adapters/types.go

@@ -346,12 +346,16 @@ type Device struct {
 	// viaja cuando hay mas de una: con una sola repetiria nameSource. La
 	// seleccion no cambia (esa es la fase de la preferencia).
 	NameCandidates []NameCandidate `json:"nameCandidates,omitempty"`
-	Type           string          `json:"type"`
-	Manufacturer   string          `json:"manufacturer"`
-	IP             string          `json:"ip"`
-	MAC            string          `json:"mac"`
-	RouterID       string          `json:"routerId"`
-	Band           string          `json:"band"` // "5 GHz"|"2.4 GHz"|"cable"|"—"
+	// NameSourceOverride (#2163): fuente que el usuario eligió a mano para
+	// este cliente. Vacío = automática. Viaja para que el formulario muestre
+	// lo elegido sin adivinarlo a partir del nombre resuelto.
+	NameSourceOverride string `json:"nameSourceOverride,omitempty"`
+	Type               string `json:"type"`
+	Manufacturer       string `json:"manufacturer"`
+	IP                 string `json:"ip"`
+	MAC                string `json:"mac"`
+	RouterID           string `json:"routerId"`
+	Band               string `json:"band"` // "5 GHz"|"2.4 GHz"|"cable"|"—"
 	// WifiIface/SSID (#1757): interfaz AP y red a la que esta asociado un
 	// cliente inalambrico. El agente los declara desde iw; vacios cuando la
 	// fuente no los expone. La topologia cruza WifiIface con el bridge VLAN

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

@@ -287,6 +287,7 @@ CREATE TABLE IF NOT EXISTS device_overrides (
   device_type    TEXT NOT NULL DEFAULT '',
   banned_bands   TEXT NOT NULL DEFAULT '', -- lista separada por comas: '2.4,5,6'
   notify_offline INTEGER NOT NULL DEFAULT 0, -- issue #1354: alert opt-in cuando se desconecta
+  name_source    TEXT NOT NULL DEFAULT '',   -- #2163: fuente de nombre elegida por cliente ('' = automática)
   created_at     INTEGER NOT NULL,
   updated_at     INTEGER NOT NULL
 );
@@ -767,6 +768,8 @@ func Open(dir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "device_overrides", "device_type", "ALTER TABLE device_overrides ADD COLUMN device_type TEXT NOT NULL DEFAULT ''")
 	// issue #1354: opt-in alert when a marked device goes offline (0 = off).
 	migrate(sqldb, "device_overrides", "notify_offline", "ALTER TABLE device_overrides ADD COLUMN notify_offline INTEGER NOT NULL DEFAULT 0")
+	// #2163: fuente de nombre elegida a mano para un cliente ('' = automática).
+	migrate(sqldb, "device_overrides", "name_source", "ALTER TABLE device_overrides ADD COLUMN name_source TEXT NOT NULL DEFAULT ''")
 
 	// #1354: las filas de alert_log tipadas "device-offline" son eventos de
 	// ROUTER offline (ese slug lo emitía trackRouterOffline antes de partirlo

+ 29 - 11
server-go/internal/httpapi/device_overrides.go

@@ -67,6 +67,9 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 		Name          *string `json:"name"`
 		Type          *string `json:"type"`
 		NotifyOffline *bool   `json:"notifyOffline"`
+		// NameSource (#2163): fuente de nombre elegida para este cliente,
+		// "auto" o vacío para volver a la precedencia del servidor.
+		NameSource *string `json:"nameSource"`
 	}
 	if st := readJSONBody(w, r, &body); st != 0 {
 		writeBodyError(w, st, "invalid_body", "body JSON inválido")
@@ -80,6 +83,10 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 		writeError(w, http.StatusBadRequest, "invalid_type")
 		return
 	}
+	if body.NameSource != nil && *body.NameSource != "" && *body.NameSource != "auto" && !adapters.ValidNameSource(*body.NameSource) {
+		writeError(w, http.StatusBadRequest, "invalid_name_source")
+		return
+	}
 	name := ""
 	if body.Name != nil {
 		name = strings.TrimSpace(*body.Name)
@@ -94,10 +101,10 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 
 	// Valores actuales (los campos ausentes conservan lo persistido).
 	var curIcon sql.NullString
-	var curName, curType string
+	var curName, curType, curNameSource string
 	var curNotifyOffline bool
-	row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline FROM device_overrides WHERE mac = ?", mac)
-	switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline); err {
+	row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac)
+	switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline, &curNameSource); err {
 	case nil:
 	case sql.ErrNoRows:
 	default:
@@ -107,6 +114,7 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	nextIcon := curIcon.String
 	nextName, nextType := curName, curType
 	nextNotifyOffline := curNotifyOffline
+	nextNameSource := curNameSource
 	if body.Icon != nil {
 		nextIcon = *body.Icon
 	}
@@ -119,18 +127,26 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	if body.NotifyOffline != nil {
 		nextNotifyOffline = *body.NotifyOffline
 	}
+	if body.NameSource != nil {
+		// "auto" es la forma explícita de limpiar la elección.
+		if *body.NameSource == "auto" {
+			nextNameSource = ""
+		} else {
+			nextNameSource = *body.NameSource
+		}
+	}
 
 	now := time.Now().UnixMilli()
-	if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline {
+	if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline && nextNameSource == "" {
 		_, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
 	} else {
 		_, err := s.db.Exec(
-			`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at)
-			 VALUES (?, ?, ?, ?, '', ?, ?, ?)
+			`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, name_source, created_at, updated_at)
+			 VALUES (?, ?, ?, ?, '', ?, ?, ?, ?)
 			 ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
 			   device_type=excluded.device_type, notify_offline=excluded.notify_offline,
-			   updated_at=excluded.updated_at`,
-			mac, nextIcon, nextName, nextType, nextNotifyOffline, now, now,
+			   name_source=excluded.name_source, updated_at=excluded.updated_at`,
+			mac, nextIcon, nextName, nextType, nextNotifyOffline, nextNameSource, now, now,
 		)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "db_error", err.Error())
@@ -143,7 +159,7 @@ func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request)
 	}
 	writeJSON(w, http.StatusOK, map[string]any{
 		"ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
-		"notifyOffline": nextNotifyOffline,
+		"notifyOffline": nextNotifyOffline, "nameSource": nextNameSource,
 	})
 }
 
@@ -156,8 +172,9 @@ func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request)
 	}
 	var icon, name, deviceType, banned sql.NullString
 	var notifyOffline bool
-	row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline FROM device_overrides WHERE mac = ?", mac)
-	if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline); err != nil && err != sql.ErrNoRows {
+	var nameSource string
+	row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline, name_source FROM device_overrides WHERE mac = ?", mac)
+	if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline, &nameSource); err != nil && err != sql.ErrNoRows {
 		writeError(w, http.StatusInternalServerError, "db_error", err.Error())
 		return
 	}
@@ -168,6 +185,7 @@ func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request)
 		"type":          deviceType.String,
 		"bannedBands":   banned.String,
 		"notifyOffline": notifyOffline,
+		"nameSource":    nameSource,
 	})
 }
 

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

@@ -351,3 +351,41 @@ func TestDeviceDeleteLegacyNonMACNoGarbageTombstone(t *testing.T) {
 		t.Fatalf("no debía guardarse lápida para clave no-MAC, obtuve %d filas en deleted_clients", tombs)
 	}
 }
+
+// #2163: la fuente de nombre elegida por cliente se guarda, se devuelve y se
+// valida contra el contrato. "auto" la limpia sin borrar el resto.
+func TestDeviceOverrideNameSource(t *testing.T) {
+	s := newOverrideTestServer(t)
+	mac := "aa:bb:cc:dd:ee:01"
+
+	rec := doOverridePut(t, s, mac, `{"nameSource":"mdns"}`)
+	if rec.Code != http.StatusOK {
+		t.Fatalf("put nameSource: %d %s", rec.Code, rec.Body.String())
+	}
+	if got := doOverrideGet(t, s, mac); got["nameSource"] != "mdns" {
+		t.Fatalf("nameSource no persistió: %+v", got)
+	}
+
+	// Un nombre manual y la fuente conviven: el nombre sigue mandando.
+	if rec := doOverridePut(t, s, mac, `{"name":"NAS"}`); rec.Code != http.StatusOK {
+		t.Fatalf("put name: %d", rec.Code)
+	}
+	got := doOverrideGet(t, s, mac)
+	if got["name"] != "NAS" || got["nameSource"] != "mdns" {
+		t.Fatalf("la fuente se perdió al guardar el nombre: %+v", got)
+	}
+
+	// Fuera del contrato: 400.
+	if rec := doOverridePut(t, s, mac, `{"nameSource":"telepatia"}`); rec.Code != http.StatusBadRequest {
+		t.Fatalf("fuente inválida: %d, want 400", rec.Code)
+	}
+
+	// "auto" limpia la elección y conserva el nombre manual.
+	if rec := doOverridePut(t, s, mac, `{"nameSource":"auto"}`); rec.Code != http.StatusOK {
+		t.Fatalf("put auto: %d", rec.Code)
+	}
+	got = doOverrideGet(t, s, mac)
+	if got["nameSource"] != "" || got["name"] != "NAS" {
+		t.Fatalf("auto debe limpiar solo la fuente: %+v", got)
+	}
+}