Kaynağa Gözat

feat(settings): choose the fleet-wide order of name sources (#2163) (#2284)

Nacho 1 gün önce
ebeveyn
işleme
3ebfafdf53

+ 1 - 0
CHANGELOG.md

@@ -9,6 +9,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- The order in which name sources win can be set once for the whole fleet, in Settings: the five sources a name can come from (DHCP reservation, DHCP, GL.iNet, mDNS and reverse DNS) are reordered with two buttons and the server resolves clients with the first one that has something to propose. A manual name and a known-MAC alias always win, a client with its own source chosen in its sheet is not affected, and the automatic default is the precedence the server already had (#2163).
 - 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

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

@@ -2525,6 +2525,17 @@
         "netgrip_managed": "embedded in NetGrip (update NetGrip instead)",
         "router_unknown": "no router row (skipped)"
       }
+    },
+    "nameOrder": {
+      "title": "Device names",
+      "caption": "Which source wins when a client has more than one name.",
+      "hint": "A manual name and a known-MAC alias always win. A client with its own source chose it in its edit sheet.",
+      "save": "Save order",
+      "reset": "Automatic",
+      "up": "Move up",
+      "down": "Move down",
+      "loadError": "Could not load the order.",
+      "saveError": "Could not save the order."
     }
   },
   "statcard": {

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

@@ -2525,6 +2525,17 @@
         "netgrip_managed": "embebido en NetGrip (actualiza NetGrip)",
         "router_unknown": "sin fila de router (saltado)"
       }
+    },
+    "nameOrder": {
+      "title": "Nombres de dispositivos",
+      "caption": "Qué fuente gana cuando un cliente tiene más de un nombre.",
+      "hint": "Un nombre manual y el alias de una MAC conocida mandan siempre. Un cliente con fuente propia la eligió en su ficha.",
+      "save": "Guardar orden",
+      "reset": "Automático",
+      "up": "Subir",
+      "down": "Bajar",
+      "loadError": "No se pudo cargar el orden.",
+      "saveError": "No se pudo guardar el orden."
     }
   },
   "statcard": {

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

@@ -2549,6 +2549,17 @@
         "netgrip_managed": "встроен в NetGrip (обновляйте сам NetGrip)",
         "router_unknown": "строки роутера нет (пропущен)"
       }
+    },
+    "nameOrder": {
+      "title": "Имена устройств",
+      "caption": "Какой источник побеждает, когда у клиента несколько имён.",
+      "hint": "Имя, заданное вручную, и псевдоним известной MAC всегда важнее. Клиент со своим источником выбрал его в своей карточке.",
+      "save": "Сохранить порядок",
+      "reset": "Автоматически",
+      "up": "Выше",
+      "down": "Ниже",
+      "loadError": "Не удалось загрузить порядок.",
+      "saveError": "Не удалось сохранить порядок."
     }
   },
   "statcard": {

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

@@ -2199,6 +2199,17 @@
       "detecting": "检测中…",
       "detectFound": "在 {{host}} 检测到 AdGuard Home:确认密码后保存",
       "detectNotFound": "在网关或设备集群中未找到 AdGuard Home"
+    },
+    "nameOrder": {
+      "title": "设备名称",
+      "caption": "当一个客户端有多个名称时,哪个来源优先。",
+      "hint": "手动名称和已知 MAC 别名始终优先。自带来源的客户端是在其编辑面板中选择的。",
+      "save": "保存顺序",
+      "reset": "自动",
+      "up": "上移",
+      "down": "下移",
+      "loadError": "无法加载顺序。",
+      "saveError": "无法保存顺序。"
     }
   },
   "command": {

+ 175 - 0
app/src/components/DeviceNameOrderCard.tsx

@@ -0,0 +1,175 @@
+/**
+ * DeviceNameOrderCard — preferencia global de fuentes de nombre de cliente
+ * (#2163 fase 2). El servidor resuelve el nombre de un cliente con la primera
+ * fuente que tenga algo que proponer; este orden decide cuáles van antes.
+ *
+ * Solo se pueden reordenar las fuentes que no son nombres escritos por el
+ * usuario: el nombre manual y el alias de una MAC conocida mandan siempre. Un
+ * cliente con su propia fuente elegida (ficha del cliente) no se ve afectado.
+ */
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { ArrowDown, ArrowUp, Loader2, RotateCcw } from 'lucide-react'
+import { useNetPulse } from '@/data/DataProvider'
+import { fetchJson } from '@/lib/utils'
+
+/** Orden por defecto del servidor cuando no hay preferencia guardada. */
+const DEFAULT_ORDER = ['reservation', 'dhcp', 'glinet', 'mdns', 'rdns'] as const
+
+type Source = (typeof DEFAULT_ORDER)[number]
+
+/** Una fuente que el usuario no conoce no debe colarse en la lista. */
+function normalize(list: unknown): Source[] {
+  if (!Array.isArray(list)) return []
+  const seen = new Set<string>()
+  const out: Source[] = []
+  for (const item of list) {
+    if (typeof item !== 'string') continue
+    if (!(DEFAULT_ORDER as readonly string[]).includes(item) || seen.has(item)) continue
+    seen.add(item)
+    out.push(item as Source)
+  }
+  return out
+}
+
+export function DeviceNameOrderCard() {
+  const { t } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const [saved, setSaved] = useState<Source[]>([])
+  const [order, setOrder] = useState<Source[]>([...DEFAULT_ORDER])
+  const [loading, setLoading] = useState(true)
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState('')
+
+  const load = useCallback(async () => {
+    const res = await fetchJson<{ sources: string[] }>('/api/settings/nameorder')
+    if (res.ok && res.data) {
+      const list = normalize(res.data.sources)
+      setSaved(list)
+      // Sin preferencia guardada, la tarjeta muestra el orden por defecto:
+      // es lo que el servidor aplica y el punto del que se parte.
+      setOrder(list.length > 0 ? list : [...DEFAULT_ORDER])
+      setError('')
+    } else {
+      setError(t('settings.nameOrder.loadError'))
+    }
+    setLoading(false)
+  }, [t])
+
+  useEffect(() => {
+    if (isDemo) {
+      setLoading(false)
+      return
+    }
+    void load()
+  }, [isDemo, load])
+
+  const move = (index: number, delta: number) => {
+    setOrder((prev) => {
+      const next = [...prev]
+      const target = index + delta
+      if (target < 0 || target >= next.length) return prev
+      const a = next[index]
+      const b = next[target]
+      if (a === undefined || b === undefined) return prev
+      next[index] = b
+      next[target] = a
+      return next
+    })
+  }
+
+  const save = async (list: Source[]) => {
+    setBusy(true)
+    setError('')
+    try {
+      const res = await fetchJson<{ sources: string[] }>('/api/settings/nameorder', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ sources: list }),
+      })
+      if (!res.ok) {
+        setError(t('settings.nameOrder.saveError'))
+        return
+      }
+      const stored = normalize(res.data?.sources)
+      setSaved(stored)
+      setOrder(stored.length > 0 ? stored : [...DEFAULT_ORDER])
+    } catch {
+      setError(t('settings.nameOrder.saveError'))
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  const dirty = order.join(',') !== (saved.length > 0 ? saved.join(',') : DEFAULT_ORDER.join(','))
+
+  return (
+    <section className="h-full rounded-2xl border border-border bg-surface p-5">
+      <h2 className="font-display text-h2 text-text-primary">{t('settings.nameOrder.title')}</h2>
+      <p className="mt-0.5 text-sm text-text-secondary">{t('settings.nameOrder.caption')}</p>
+
+      {loading ? (
+        <div className="mt-4 flex items-center gap-2 text-caption text-text-muted">
+          <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+          {t('common.loading')}
+        </div>
+      ) : (
+        <>
+          <ol className="mt-4 space-y-1.5">
+            {order.map((source, i) => (
+              <li
+                key={source}
+                className="flex items-center gap-2 rounded-lg border border-border bg-canvas px-3 py-1.5"
+              >
+                <span className="w-4 shrink-0 font-mono text-caption text-text-muted">{i + 1}</span>
+                <span className="min-w-0 flex-1 truncate text-sm text-text-primary">
+                  {t(`devices.detail.source.${source}`)}
+                </span>
+                <button
+                  type="button"
+                  onClick={() => move(i, -1)}
+                  disabled={busy || i === 0}
+                  aria-label={t('settings.nameOrder.up')}
+                  className="flex h-6 w-6 items-center justify-center rounded border border-border text-text-muted transition-colors hover:text-accent disabled:opacity-40"
+                >
+                  <ArrowUp className="h-3 w-3" strokeWidth={2} />
+                </button>
+                <button
+                  type="button"
+                  onClick={() => move(i, 1)}
+                  disabled={busy || i === order.length - 1}
+                  aria-label={t('settings.nameOrder.down')}
+                  className="flex h-6 w-6 items-center justify-center rounded border border-border text-text-muted transition-colors hover:text-accent disabled:opacity-40"
+                >
+                  <ArrowDown className="h-3 w-3" strokeWidth={2} />
+                </button>
+              </li>
+            ))}
+          </ol>
+          {error && <p className="mt-2 text-caption text-danger">{error}</p>}
+          <div className="mt-3 flex items-center gap-2">
+            <button
+              type="button"
+              onClick={() => void save(order)}
+              disabled={busy || !dirty}
+              className="inline-flex h-8 items-center gap-1.5 rounded-lg bg-accent px-3 text-sm font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-40"
+            >
+              {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />}
+              {t('settings.nameOrder.save')}
+            </button>
+            <button
+              type="button"
+              onClick={() => void save([])}
+              disabled={busy || saved.length === 0}
+              className="inline-flex h-8 items-center gap-1.5 rounded-lg border border-border px-3 text-sm font-medium text-text-secondary transition-colors hover:text-text-primary disabled:opacity-40"
+            >
+              <RotateCcw className="h-3.5 w-3.5" strokeWidth={1.75} />
+              {t('settings.nameOrder.reset')}
+            </button>
+          </div>
+          <p className="mt-2 text-caption text-text-muted">{t('settings.nameOrder.hint')}</p>
+        </>
+      )}
+    </section>
+  )
+}

+ 9 - 0
app/src/pages/Settings.tsx

@@ -6,6 +6,7 @@ import { BadgeCheck, CalendarClock, Check, ChevronDown, ChevronRight, ChevronUp,
 import type { LucideIcon } from 'lucide-react'
 import Integrations from './Integrations'
 import SnmpCommunityField from '@/components/routers/SnmpCommunityField'
+import { DeviceNameOrderCard } from '@/components/DeviceNameOrderCard'
 import { HealthRing } from '@/components/HealthRing'
 import { KnownMacsManager } from '@/components/KnownMacsManager'
 import { SegmentedControl } from '@/components/SegmentedControl'
@@ -6275,6 +6276,14 @@ export default function Settings() {
           </Card>
         </div>
 
+        {/* #2163: orden global de fuentes de nombre. Solo admin y live: es
+            una preferencia del servidor, no del navegador. */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="order-35">
+            <DeviceNameOrderCard />
+          </div>
+        )}
+
         {/* ② Apariencia: tema (40%) | paleta + acento + densidad (60%) */}
         <div className="order-20">
           <Card title={t('settings.appearance')} caption={t('settings.appearanceCaption')} index={0} reduce={reduce}>

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

@@ -1,5 +1,7 @@
 package adapters
 
+import "strings"
+
 // device_names.go — candidatos de nombre de un cliente (#2163 fase 2).
 //
 // La seleccion de nombre es implicita: el server resuelve un nombre y guarda
@@ -88,3 +90,40 @@ func candidateValue(e nameEvidence, source string) string {
 	}
 	return ""
 }
+
+// PreferredNameSources ordena las fuentes no fijadas según la preferencia
+// global (#2163). Vacío o desconocido no cambia nada: el cliente sigue con la
+// precedencia de siempre.
+func PreferredNameSources(raw string) []string {
+	if strings.TrimSpace(raw) == "" {
+		return nil
+	}
+	out := make([]string, 0, len(NameSources))
+	seen := map[string]bool{}
+	for _, tok := range strings.Split(raw, ",") {
+		s := strings.TrimSpace(tok)
+		// "manual" y "known_mac" no entran: son nombres escritos por el
+		// usuario y mandan siempre, no son candidatos a reordenar.
+		if s == "" || s == "manual" || s == "known_mac" || seen[s] || !ValidNameSource(s) {
+			continue
+		}
+		seen[s] = true
+		out = append(out, s)
+	}
+	return out
+}
+
+// preferredName devuelve el primer valor que proponen las fuentes en el orden
+// pedido, con su fuente. Vacío cuando ninguna tiene nada.
+func preferredName(e nameEvidence, order []string) (string, string) {
+	for _, source := range order {
+		if v := candidateValue(e, source); v != "" {
+			return v, source
+		}
+	}
+	return "", ""
+}
+
+// ReorderableNameSources son las fuentes que la preferencia global puede
+// mover. Las fijadas (nombre manual y alias de MAC conocida) quedan fuera.
+var ReorderableNameSources = []string{"reservation", "dhcp", "glinet", "mdns", "rdns"}

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

@@ -69,3 +69,36 @@ func TestCandidateValuePorFuente(t *testing.T) {
 		t.Fatal("una fuente fuera del contrato no puede ser válida")
 	}
 }
+
+// #2163: la preferencia global reordena solo las fuentes que no son nombres
+// escritos a mano, ignora lo desconocido y no repite.
+func TestPreferredNameSources(t *testing.T) {
+	got := PreferredNameSources("mdns, dhcp,manual,known_mac,mdns,nope,rdns")
+	want := []string{"mdns", "dhcp", "rdns"}
+	if len(got) != len(want) {
+		t.Fatalf("orden = %v, esperaba %v", got, want)
+	}
+	for i := range want {
+		if got[i] != want[i] {
+			t.Fatalf("orden = %v, esperaba %v", got, want)
+		}
+	}
+	if PreferredNameSources("  ") != nil {
+		t.Fatal("vacío debe devolver nil (precedencia automática)")
+	}
+}
+
+// La primera fuente del orden con algo que proponer gana, aunque la
+// precedencia por defecto eligiera otra.
+func TestPreferredName(t *testing.T) {
+	e := nameEvidence{DHCP: "diskstation", MDNS: "nas.local"}
+	if v, src := preferredName(e, []string{"mdns", "dhcp"}); v != "nas.local" || src != "mdns" {
+		t.Fatalf("mdns primero = %q (%s)", v, src)
+	}
+	if v, src := preferredName(e, []string{"rdns", "dhcp", "mdns"}); v != "diskstation" || src != "dhcp" {
+		t.Fatalf("con rdns vacío debe caer a dhcp: %q (%s)", v, src)
+	}
+	if v, _ := preferredName(e, []string{"glinet"}); v != "" {
+		t.Fatalf("sin evidencia debe quedar vacío, got %q", v)
+	}
+}

+ 28 - 0
server-go/internal/adapters/live.go

@@ -1876,6 +1876,23 @@ type overrideInfo struct {
 	NameSource string
 }
 
+// preferredNameOrder lee la preferencia global de fuentes de nombre (#2163)
+// de la tabla kv. Sin BD o sin clave devuelve nil, que es la precedencia de
+// siempre. El valor es una lista separada por comas en orden de prioridad.
+func (l *Live) preferredNameOrder() []string {
+	if l.db == nil {
+		return nil
+	}
+	var raw string
+	if err := l.db.QueryRow("SELECT value FROM kv WHERE key = ?", NameOrderKey).Scan(&raw); err != nil {
+		return nil
+	}
+	return PreferredNameSources(raw)
+}
+
+// NameOrderKey es la clave kv de la preferencia global de fuentes (#2163).
+const NameOrderKey = "devices.name_order"
+
 // loadDeviceOverrides lee los overrides manuales, con clave por la MAC tal
 // como está guardada: ya canónica (AA:BB:CC:DD:EE:FF), porque el handler la
 // normaliza al escribir y la migración pasó las filas antiguas. Las MAC de
@@ -4376,6 +4393,10 @@ func (l *Live) buildDeviceSet(polled map[string]*routerPolled, gwID, wanPort str
 			}
 		}
 	}
+	// #2163: preferencia global de fuentes de nombre. Vacía = precedencia de
+	// siempre; con orden manda sobre ella, salvo en los nombres fijados
+	// (manual y alias) y salvo la elección por cliente.
+	nameOrder := l.preferredNameOrder()
 	devices := []Device{}
 	for mac := range allMacs {
 		upper := strings.ToUpper(mac)
@@ -4600,6 +4621,13 @@ func (l *Live) buildDeviceSet(polled map[string]*routerPolled, gwID, wanPort str
 					d.NameSource = o.NameSource
 				}
 			}
+		} else if len(nameOrder) > 0 && !d.namePinned {
+			// #2163: la preferencia global reordena las fuentes que no son
+			// nombres escritos por el usuario.
+			if v, src := preferredName(evidence, nameOrder); v != "" {
+				d.Name = v
+				d.NameSource = src
+			}
 		}
 		devices = append(devices, d)
 	}

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

@@ -389,3 +389,51 @@ func TestDeviceOverrideNameSource(t *testing.T) {
 		t.Fatalf("auto debe limpiar solo la fuente: %+v", got)
 	}
 }
+
+
+// #2163: la preferencia global de fuentes se guarda en orden, se valida y se
+// devuelve tal cual. Lista vacía = automática.
+func TestSettingsNameOrderRoundtrip(t *testing.T) {
+	s := newOverrideTestServer(t)
+
+	put := func(body string) *httptest.ResponseRecorder {
+		req := httptest.NewRequest("PUT", "/api/settings/nameorder", strings.NewReader(body))
+		req.Header.Set("Content-Type", "application/json")
+		rec := httptest.NewRecorder()
+		s.handleSettingsNameOrderPut(rec, req)
+		return rec
+	}
+	get := func() map[string]any {
+		req := httptest.NewRequest("GET", "/api/settings/nameorder", nil)
+		rec := httptest.NewRecorder()
+		s.handleSettingsNameOrderGet(rec, req)
+		var out map[string]any
+		if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+			t.Fatalf("get decode: %v", err)
+		}
+		return out
+	}
+
+	if rec := put(`{"sources":["mdns","dhcp"]}`); rec.Code != http.StatusOK {
+		t.Fatalf("put: %d %s", rec.Code, rec.Body.String())
+	}
+	got := get()["sources"].([]any)
+	if len(got) != 2 || got[0] != "mdns" || got[1] != "dhcp" {
+		t.Fatalf("orden guardado = %v", got)
+	}
+
+	// Las fuentes fijadas no se pueden reordenar y lo repetido es un error.
+	for _, bad := range []string{`{"sources":["manual"]}`, `{"sources":["dhcp","dhcp"]}`, `{"sources":["telepatia"]}`} {
+		if rec := put(bad); rec.Code != http.StatusBadRequest {
+			t.Fatalf("%s: %d, want 400", bad, rec.Code)
+		}
+	}
+
+	// Vaciar vuelve a la precedencia automática.
+	if rec := put(`{"sources":[]}`); rec.Code != http.StatusOK {
+		t.Fatalf("put vacío: %d", rec.Code)
+	}
+	if got := get()["sources"].([]any); len(got) != 0 {
+		t.Fatalf("tras vaciar, sources = %v", got)
+	}
+}

+ 63 - 0
server-go/internal/httpapi/settings.go

@@ -9,8 +9,10 @@ import (
 	"database/sql"
 	"net/http"
 	"strconv"
+	"strings"
 
 	"github.com/gnacho/netpulse/agent/macaddr"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/db"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
@@ -97,6 +99,13 @@ func kvGetFloat(db *sql.DB, key string) (float64, bool) {
 }
 
 // kvSetFloat escribe un número en el kv (UPSERT).
+func kvSetString(db *sql.DB, key, val string) error {
+	_, err := db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		key, val)
+	return err
+}
+
 func kvSetFloat(db *sql.DB, key string, val float64) error {
 	_, err := db.Exec(
 		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
@@ -147,6 +156,11 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 	// GET /api/settings/integrations - toggles server-side de integraciones
 	// (#968): ntfy/telegram/proxmox (ausente = activo) y mqtt (lee la clave
 	// existente mqtt.enabled via el manager, que ya fusiona env + kv).
+	// GET/PUT /api/settings/nameorder - preferencia global de fuentes de
+	// nombre de cliente (#2163). Lista vacia = precedencia automatica.
+	mux.Handle("GET /api/settings/nameorder", auth.RequireAdmin(http.HandlerFunc(s.handleSettingsNameOrderGet)))
+	mux.Handle("PUT /api/settings/nameorder", auth.RequireAdmin(http.HandlerFunc(s.handleSettingsNameOrderPut)))
+
 	mux.Handle("GET /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		writeJSON(w, http.StatusOK, s.integrationsView())
 	})))
@@ -394,3 +408,52 @@ func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
 		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
 	})))
 }
+
+// handleSettingsNameOrderGet devuelve la preferencia global de fuentes de
+// nombre (#2163). Lista vacía = precedencia automática del servidor.
+func (s *server) handleSettingsNameOrderGet(w http.ResponseWriter, _ *http.Request) {
+	// Siempre un array: null obligaria al cliente a distinguir dos vacios.
+	sources := adapters.PreferredNameSources(kvGet(s.db.DB, adapters.NameOrderKey))
+	if sources == nil {
+		sources = []string{}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"sources": sources})
+}
+
+// handleSettingsNameOrderPut guarda la preferencia global. Solo admite las
+// fuentes reordenables: el nombre manual y el alias de una MAC conocida son
+// nombres escritos por el usuario y mandan siempre.
+func (s *server) handleSettingsNameOrderPut(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Sources []string `json:"sources"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "")
+		return
+	}
+	allowed := map[string]bool{}
+	for _, src := range adapters.ReorderableNameSources {
+		allowed[src] = true
+	}
+	seen := map[string]bool{}
+	for _, src := range body.Sources {
+		if !allowed[src] || seen[src] {
+			writeError(w, http.StatusBadRequest, "invalid_name_source")
+			return
+		}
+		seen[src] = true
+	}
+	if err := kvSetString(s.db.DB, adapters.NameOrderKey, strings.Join(body.Sources, ",")); err != nil {
+		writeError(w, http.StatusInternalServerError, "kv_error")
+		return
+	}
+	// Un sondeo inmediato para que el orden se vea en la siguiente vista.
+	if s.pollNow != nil {
+		s.pollNow()
+	}
+	sources := adapters.PreferredNameSources(strings.Join(body.Sources, ","))
+	if sources == nil {
+		sources = []string{}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"sources": sources})
+}