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

feat(channels): conservative suggestions and honest own-network bell (#1225)

The channel engine stays silent without neighbor data and only suggests a change when the best block is >=30% cleaner than the current one (keeping = Recommended = current); a DFS-crossing current channel still gets the best clean block. The spectrum's synthetic own bell only draws as a fallback now that scans carry real own levels. First substantive slice of #1214
Nacho 2 месяцев назад
Родитель
Сommit
20f4f072aa

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

@@ -2042,6 +2042,8 @@
     "betterThanCurrent": "Better than your current channel ({{score}}/100).",
     "applyHint": "Suggestion: apply it from your router's settings.",
     "summarySuggested": "Best suggested channel",
+    "keepCurrent": "Keep your current channel: switching would not bring an appreciable gain. Channel changes are disruptive, so suggestions need a clear win.",
+    "noDataOpinion": "No neighbors visible on this band: not enough data to have an opinion. Run a scan now or enable periodic scanning on the agent.",
     "summaryCurrent": "Your current channel",
     "summaryNetworks": "Networks detected",
     "neighborsInBlock": "{{count}} networks in your block",

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

@@ -2042,6 +2042,8 @@
     "betterThanCurrent": "Mejor que tu canal actual ({{score}}/100).",
     "applyHint": "Sugerencia: aplícalo desde la configuración de tu router.",
     "summarySuggested": "Mejor canal sugerido",
+    "keepCurrent": "Mantén tu canal actual: no hay una mejora apreciable cambiando. Cambiar de canal es disruptivo y solo se sugiere con ganancia clara.",
+    "noDataOpinion": "Sin vecinos visibles en esta banda: no hay datos para opinar. Escanea ahora o habilita el escaneo periódico del agente.",
     "summaryCurrent": "Tu canal actual",
     "summaryNetworks": "Redes detectadas",
     "neighborsInBlock": "{{count}} redes en tu bloque",

+ 33 - 23
app/src/pages/ChannelPlan.tsx

@@ -239,17 +239,24 @@ export default function ChannelPlan() {
   // encima de las campanas vecinas que se solapen.
   const nets = useMemo<SpectrumNet[]>(() => {
     if (!active) return []
-    const own: SpectrumNet = {
-      key: 'own',
-      ssid: t('channelPlan.ownNetwork'),
-      bssid: '',
-      channel: active.channel,
-      freq: channelFreq(active.name, active.channel),
-      signal: -25,
-      widthMhz: active.widthMhz > 0 ? active.widthMhz : 20,
-      own: true,
-      color: themeColor('--accent'),
-    }
+    // #1214: la montaña sintética de "tu red" (a -25 fijos, se leía como
+    // "estoy a 30 dBm" en la rejilla) solo como fallback cuando los scans
+    // NO traen las propias: los agentes (#1087) ya las reportan a su señal
+    // real y la malla se ve con sus niveles verdaderos.
+    const hasOwnScans = bandScans.some((s) => s.own)
+    const own: SpectrumNet | null = hasOwnScans
+      ? null
+      : {
+          key: 'own',
+          ssid: t('channelPlan.ownNetwork'),
+          bssid: '',
+          channel: active.channel,
+          freq: channelFreq(active.name, active.channel),
+          signal: -25,
+          widthMhz: active.widthMhz > 0 ? active.widthMhz : 20,
+          own: true,
+          color: themeColor('--accent'),
+        }
     const neighbors: SpectrumNet[] = bandScans.map((s) => ({
       key: s.bssid + s.channel,
       ssid: s.ssid || t('channelPlan.hidden'),
@@ -263,7 +270,7 @@ export default function ChannelPlan() {
       own: s.own ?? false,
       color: s.own ? themeColor('--accent') : ssidColor(s.ssid || s.bssid),
     }))
-    return [...neighbors, own]
+    return own ? [...neighbors, own] : neighbors
   }, [active, bandScans, t])
 
   const allKeys = useMemo(() => new Set(nets.map((n) => n.key)), [nets])
@@ -319,17 +326,17 @@ export default function ChannelPlan() {
     return 0
   }, [active, scored])
 
-  // Mejor candidato = el RECOMENDADO por el motor (nunca un bloque DFS o no
-  // ortodoxo que empate a 100 en la normalización relativa, #1082).
+  // Mejor candidato = SOLO cuando el motor sugiere un CAMBIO (#1214: si
+  // recomienda el canal actual es un "mantén", y esa tarjeta se pinta por
+  // su lado; antes la UI caía a scored[0] y sugería cambios frívolos).
+  const suggestedChanged = !!active && active.recommended > 0 && active.recommended !== active.channel
   const bestCand = useMemo(() => {
-    if (scored.length === 0) return null
-    if (active && active.recommended > 0) {
-      const rec = scored.find((s) => s.channel === active.recommended)
-      if (rec) return rec
-    }
-    const recs = scored.filter((s) => s.recommendable)
-    return (recs.length > 0 ? recs : scored)[0]!
-  }, [scored, active])
+    if (!active || !suggestedChanged) return null
+    return scored.find((s) => s.channel === active.recommended) ?? null
+  }, [scored, active, suggestedChanged])
+  // #1214: ¿hay dato con el que opinar en la banda? (alguna vecina en los
+  // scores). Distingue "mantén tu canal" de "sin datos para opinar".
+  const bandHasNeighbors = useMemo(() => scored.some((s) => s.neighbors > 0), [scored])
   const suggested = active && active.recommended > 0 && active.recommended !== active.channel ? active.recommended : 0
   const ownCount = bandScans.filter((s) => s.own).length
   const neighborCount = bandScans.length - ownCount
@@ -524,7 +531,10 @@ export default function ChannelPlan() {
                   <p className="mt-1.5 text-xs text-text-muted">{t('channelPlan.applyHint')}</p>
                 </>
               ) : (
-                <p className="mt-2 text-sm text-text-secondary">{t('channelPlan.noBandScans')}</p>
+                <p className="mt-2 text-sm text-text-secondary">
+                  {/* #1214: el motor no sugiere cambio: mantiene (con dato) o sin datos */}
+                  {bandHasNeighbors ? t('channelPlan.keepCurrent') : t('channelPlan.noDataOpinion')}
+                </p>
               )}
             </div>
 

+ 29 - 3
server-go/internal/channelplan/store.go

@@ -325,10 +325,36 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		if currentScore == math.MaxInt {
 			currentScore = channelScore(byBand[band], r.Channel)
 		}
-		if bestCh != 0 && bestScore != math.MaxInt {
+		rec.CurrentScore = currentScore
+		rec.BestScore = bestScore
+		// #1214: sugerencias conservadoras. (1) Sin vecinas en la banda no
+		// hay dato con el que opinar. (2) Con dato, el cambio solo se
+		// sugiere si el mejor bloque recomendable es apreciablemente mejor
+		// (>=30% menos ruido ponderado) que el canal actual: cambiar de
+		// canal es disruptivo y el empate técnico no lo justifica. En ambos
+		// casos Recommended = canal ACTUAL ("mantén"); la UI distingue
+		// mantener de "sin datos" con las vecinas de los scores.
+		// EXCEPCIÓN: si el bloque ACTUAL cruza DFS o no es recomendable, se
+		// sugiere el mejor recomendable aunque no haya vecinos (el radar
+		// desaloja el canal igualmente; no es una sugerencia frívola).
+		bandNeighbors := 0
+		for _, m := range byBand[band] {
+			bandNeighbors += len(m)
+		}
+		currentNotRecommendable := true
+		for _, b := range scores {
+			if b.Channel == r.Channel {
+				currentNotRecommendable = !b.Recommendable
+				break
+			}
+		}
+		switch {
+		case currentNotRecommendable && bestCh != 0:
+			rec.Recommended = bestCh
+		case bestCh != 0 && bandNeighbors > 0 && bestScore < currentScore && bestScore*100 <= currentScore*70:
 			rec.Recommended = bestCh
-			rec.CurrentScore = currentScore
-			rec.BestScore = bestScore
+		default:
+			rec.Recommended = r.Channel
 		}
 		out = append(out, rec)
 	}

+ 71 - 6
server-go/internal/channelplan/store_test.go

@@ -66,9 +66,10 @@ func TestRecommendDevuelveScores(t *testing.T) {
 		t.Errorf("a 80 MHz deben puntuarse también bloques DFS: %+v", recs[0].Scores)
 	}
 	rec := recs[0]
-	best := byCh[rec.Recommended]
-	if best.DFS || !best.Recommendable {
-		t.Errorf("el recomendado debe ser un bloque no-DFS recomendable: %+v", best)
+	// #1214: sin scans que la tienda conozca, el motor MANTIENE el canal
+	// actual (no hay dato con el que opinar).
+	if rec.Recommended != rec.Channel {
+		t.Errorf("sin datos se debe mantener el canal actual: Recommended=%d, canal=%d", rec.Recommended, rec.Channel)
 	}
 	// #1076: el rango 68-92 (5350-5470 MHz) no es RLAN en ETSI: se puntúa
 	// pero nunca se recomienda.
@@ -78,9 +79,6 @@ func TestRecommendDevuelveScores(t *testing.T) {
 	if b, ok := byCh[52]; !ok || !b.DFS {
 		t.Errorf("el bloque 52-64 debe marcarse DFS: %+v", b)
 	}
-	if best.Score != rec.BestScore {
-		t.Errorf("el score del bloque recomendado debe ser BestScore: %+v, rec %+v", best, rec)
-	}
 }
 
 // TestRecommendScores24GHzTodosLosCanales (#1076): a 2.4 GHz se puntúan los
@@ -566,3 +564,70 @@ func TestRecommendCurrentDfsChannelScoreNotMaxInt(t *testing.T) {
 		t.Errorf("debería recomendar el 36 libre (no-DFS), got %d", rec.Recommended)
 	}
 }
+
+// TestRecommendConservador (#1214): el motor no sugiere cambios frívolos.
+// (a) canal actual limpio → mantiene (0). (b) canal actual sucio con un
+// bloque mucho más limpio → sugiere, y el sugerido es recomendable no-DFS.
+// (c) empate técnico (ruido similar en el actual y el mejor) → mantiene.
+func TestRecommendConservador(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+	st := channelplan.NewStore(d.DB)
+	now := time.Now().Unix()
+
+	// (a) 2.4: una vecina débil en ch11; el actual es ch1 (limpio) → mantiene.
+	if err := st.SaveScan("rt1", now, []probe.ScanResult{
+		{BSSID: "00:11:22:33:44:01", SSID: "vecino", Channel: 11, Freq: 2462, Signal: -88},
+	}); err != nil {
+		t.Fatalf("save a: %v", err)
+	}
+	recs, err := st.Recommend("rt1", []probe.Radio{{Name: "2.4 GHz", Channel: 1, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend a: %v", err)
+	}
+	// (a) el canal actual está limpio: se MANTIENE (Recommended = actual).
+	if recs[0].Recommended != 1 {
+		t.Errorf("(a) canal limpio: se espera mantener 1: %+v", recs[0])
+	}
+
+	// (b) ch6 con un vecino FUERTE (-40); 1 y 11 limpios → sugiere 1 o 11.
+	if err := st.SaveScan("rt2", now, []probe.ScanResult{
+		{BSSID: "00:11:22:33:44:02", SSID: "vecino", Channel: 6, Freq: 2437, Signal: -40},
+		{BSSID: "00:11:22:33:44:03", SSID: "vecino", Channel: 11, Freq: 2462, Signal: -88},
+	}); err != nil {
+		t.Fatalf("save b: %v", err)
+	}
+	recs, err = st.Recommend("rt2", []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend b: %v", err)
+	}
+	if recs[0].Recommended != 1 && recs[0].Recommended != 11 {
+		t.Errorf("(b) canal sucio: se esperaba sugerencia a 1 o 11: %+v", recs[0])
+	}
+	for _, s := range recs[0].Scores {
+		if s.Channel == recs[0].Recommended && (s.DFS || !s.Recommendable) {
+			t.Errorf("(b) el sugerido debe ser no-DFS recomendable: %+v", s)
+		}
+	}
+
+	// (c) empate técnico: los tres canales ortodoxos igual de ocupados (-70
+	// en 1, 6 y 11) → no hay mejora apreciable → se mantiene el actual.
+	if err := st.SaveScan("rt3", now, []probe.ScanResult{
+		{BSSID: "00:11:22:33:44:04", SSID: "vecino", Channel: 6, Freq: 2437, Signal: -70},
+		{BSSID: "00:11:22:33:44:05", SSID: "vecino", Channel: 1, Freq: 2412, Signal: -70},
+		{BSSID: "00:11:22:33:44:06", SSID: "vecino", Channel: 11, Freq: 2462, Signal: -70},
+	}); err != nil {
+		t.Fatalf("save c: %v", err)
+	}
+	recs, err = st.Recommend("rt3", []probe.Radio{{Name: "2.4 GHz", Channel: 6, WidthMhz: 20}}, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend c: %v", err)
+	}
+	// (c) empate técnico: se mantiene el actual (Recommended = canal actual).
+	if recs[0].Recommended != 6 {
+		t.Errorf("(c) empate técnico: se espera mantener 6: %+v", recs[0])
+	}
+}