Explorar o código

fix(channels): 6 GHz blocks, shared scan window, explained survey gaps

The channel analysis recommended with a fixed 24h window while showing scans from 30 days, scored 6 GHz radios against 2.4 GHz channel numbers, and answered 503 when no unit reported a survey, which sent the user to a command their driver does not have. The window that loads the scans is now the one scored, 6 GHz has its own block table with PSC-only suggestions at 20 MHz and an out-of-band channel yields the no-data sentinel, and the survey lists every unit with the reason it has nothing.

Closes #1742
Nacho hai 1 mes
pai
achega
4c73d029a2

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

@@ -874,7 +874,7 @@
     },
     "survey": {
       "title": "Current channels",
-      "empty": "No router returned survey data. Verify that `iw dev wlanX survey dump` works on your routers.",
+      "empty": "No unit returned survey data. The reason for each unit is listed below.",
       "unreachable": "Router not reachable over SSH or no wireless interfaces.",
       "colChannel": "Channel",
       "colFreq": "MHz",
@@ -893,7 +893,14 @@
       "noScans": "This router does not report channel scans. NetGrip routers do not scan; use one running the NetPulse agent or check it is active.",
       "ownLabel": "Own network",
       "notParticipating": "This unit does not provide survey data. Units that do: {{units}}",
-      "unitNoSurvey": "This unit has no WiFi radios or returned no survey (SNMP/cable-only)."
+      "unitNoSurvey": "This unit does not provide survey data.",
+      "reason": {
+        "agentNoSurvey": "The NetPulse agent cannot read survey data from this unit's driver.",
+        "noSurveyData": "The survey ran but returned no channels.",
+        "sshUnreachable": "The unit is not reachable over SSH.",
+        "noWifi": "The unit has no wireless interfaces.",
+        "snmpOnly": "The unit is monitored over SNMP only, which carries no survey."
+      }
     },
     "events": {
       "title": "Roaming events",

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

@@ -874,7 +874,7 @@
     },
     "survey": {
       "title": "Canales actuales",
-      "empty": "Ningún router devolvió datos de survey. Verifica que el comando `iw dev wlanX survey dump` funciona en tus routers.",
+      "empty": "Ninguna unidad devolvió datos de survey. Abajo tienes el motivo de cada una.",
       "unreachable": "Router no accesible por SSH o sin interfaces wifi.",
       "colChannel": "Canal",
       "colFreq": "MHz",
@@ -893,7 +893,14 @@
       "noScans": "Este router no envía escaneos de canales. Si corre NetGrip no escanea; usa un router con el agente NetPulse o revisa que esté activo.",
       "ownLabel": "Red propia",
       "notParticipating": "Esta unidad no aporta datos de survey. Las que sí: {{units}}",
-      "unitNoSurvey": "Esta unidad no tiene radios WiFi o no devolvió survey (SNMP/solo cable)."
+      "unitNoSurvey": "Esta unidad no aporta datos de survey.",
+      "reason": {
+        "agentNoSurvey": "El agente NetPulse no puede leer el survey con el driver de esta unidad.",
+        "noSurveyData": "El survey se ejecutó pero no devolvió canales.",
+        "sshUnreachable": "La unidad no es accesible por SSH.",
+        "noWifi": "La unidad no tiene interfaces wifi.",
+        "snmpOnly": "La unidad solo se monitoriza por SNMP, que no lleva survey."
+      }
     },
     "events": {
       "title": "Eventos de itinerancia",

+ 46 - 6
app/src/components/channels/CurrentChannels.tsx

@@ -30,12 +30,35 @@ interface SurveyRouter {
   name: string
   available: boolean
   radios: SurveyRadio[]
+  /** #1742: por qué esta unidad no trae survey (código cerrado del contrato). */
+  reason?: string
 }
 interface SurveyOverview {
   available: boolean
   routers: SurveyRouter[]
 }
 
+// surveyReasonKey (#1742): el servidor manda un código cerrado en `reason`
+// (adapters.SurveyReason*) y aquí se traduce. Un código desconocido cae al
+// texto genérico para que una versión nueva del servidor no deje la tarjeta
+// vacía.
+function surveyReasonKey(reason?: string): string | null {
+  switch (reason) {
+    case 'agent_no_survey':
+      return 'roaming.survey.reason.agentNoSurvey'
+    case 'no_survey_data':
+      return 'roaming.survey.reason.noSurveyData'
+    case 'ssh_unreachable':
+      return 'roaming.survey.reason.sshUnreachable'
+    case 'no_wifi':
+      return 'roaming.survey.reason.noWifi'
+    case 'snmp_only':
+      return 'roaming.survey.reason.snmpOnly'
+    default:
+      return null
+  }
+}
+
 // Neighbor scan del channel-plan (#538): red visible en un canal.
 interface Scan {
   iface: string
@@ -95,7 +118,7 @@ function ChannelAnalysisChart({ bandName, channels, scans }: { bandName: string;
   const dBmMax = -20
   const dBmMin = -92
   if (channels.length === 0 || scans.length === 0) {
-    return <div className="text-caption text-text-muted">{t('roaming.survey.empty')}</div>
+    return <div className="text-caption text-text-muted">{t('roaming.survey.noScans')}</div>
   }
   const innerW = W - padL - padR
   const slot = innerW / channels.length
@@ -211,6 +234,11 @@ export function CurrentChannels({
   const activeBand = band === '5 GHz' ? '5 GHz' : '2.4 GHz'
   const channels = bandChannels(activeBand)
   const router = (overview?.routers ?? []).find((r) => r.routerId === routerId)
+  // #1742: motivo por unidad. Sin código conocido se usa el texto genérico.
+  const reasonText = (reason?: string) => {
+    const key = surveyReasonKey(reason)
+    return key ? t(key) : t('roaming.survey.unitNoSurvey')
+  }
 
   if (loading && !overview) {
     return (
@@ -233,13 +261,25 @@ export function CurrentChannels({
       </div>
     )
   }
-  // #1308: estados vacíos distinguibles. El mensaje genérico de "revisa iw"
-  // solo aplica cuando NADIE devuelve survey; si la unidad no participa (sin
-  // WiFi, SNMP, o sin agente con survey) se dice eso y se listan las que sí.
+  // #1308: estados vacíos distinguibles. El mensaje genérico solo aplica
+  // cuando NADIE devuelve survey. #1742: en vez de un hint que manda ejecutar
+  // `iw survey dump` (imposible en los AP Broadcom/dhd, donde el agente va por
+  // `wl`), se lista el motivo real de cada unidad que no aporta.
   if (!overview || !overview.available) {
+    const silent = (overview?.routers ?? []).map((r) => ({
+      id: r.routerId,
+      text: `${r.name}: ${reasonText(r.reason)}`,
+    }))
     return (
       <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
-        {t('roaming.survey.empty')}
+        <p>{t('roaming.survey.empty')}</p>
+        {silent.length > 0 && (
+          <ul className="mt-3 space-y-1 text-left">
+            {silent.map((row) => (
+              <li key={row.id}>{row.text}</li>
+            ))}
+          </ul>
+        )}
       </div>
     )
   }
@@ -257,7 +297,7 @@ export function CurrentChannels({
   if (!router.available) {
     return (
       <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
-        {t('roaming.survey.unitNoSurvey')}
+        {reasonText(router.reason)}
       </div>
     )
   }

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

@@ -5421,17 +5421,24 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 				r.Available = true
 				r.Radios = radios
 				any = true
+			} else {
+				// #1742: el agente solo empuja iw survey dump si el driver lo
+				// expone. En Broadcom/dhd no existe y la unidad queda sin datos
+				// sin que se pueda distinguir de "no lo intentó".
+				r.Reason = SurveyReasonAgentNoSurvey
 			}
 			out.Routers = append(out.Routers, r)
 			continue
 		}
 		if cfg.SnmpEnabled {
+			r.Reason = SurveyReasonSnmpOnly
 			out.Routers = append(out.Routers, r)
 			continue
 		}
 		// Lista de interfaces wifi (wlanX).
 		devsOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev 2>/dev/null | awk '/Interface/ {print $2}'", 0)
 		if err != nil {
+			r.Reason = SurveyReasonSSHUnreachable
 			out.Routers = append(out.Routers, r)
 			continue
 		}
@@ -5447,11 +5454,10 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 			}
 		}
 		if len(devs) == 0 {
+			r.Reason = SurveyReasonNoWifi
 			out.Routers = append(out.Routers, r)
 			continue
 		}
-		r.Available = true
-		any = true
 		for _, dev := range devs {
 			surveyOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev "+dev+" survey dump 2>/dev/null", 0)
 			if err != nil {
@@ -5474,12 +5480,20 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 			}
 			r.Radios = append(r.Radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
 		}
+		// #1742: SSH respondió pero ningún radio devolvió canales (iw survey
+		// dump vacío). Se dice, en vez de listar la unidad como participante
+		// sin datos.
+		if len(r.Radios) > 0 {
+			r.Available = true
+			any = true
+		} else {
+			r.Reason = SurveyReasonNoSurveyData
+		}
 		out.Routers = append(out.Routers, r)
 	}
-	if !any {
-		return nil, nil
-	}
-	out.Available = true
+	// #1742: se devuelve SIEMPRE la lista, con el motivo de cada unidad que no
+	// aporta. El handler ya no responde 503: la UI explica el caso concreto.
+	out.Available = any
 	return &out, nil
 }
 

+ 36 - 3
server-go/internal/adapters/live_snmp_skip_test.go

@@ -50,9 +50,17 @@ func TestGetSurveySkipsSnmpRouters(t *testing.T) {
 	if err != nil {
 		t.Fatalf("unexpected error: %v", err)
 	}
-	// Ningún router respondió -> (nil, nil).
-	if s != nil {
-		t.Fatalf("expected nil SurveyOverview, got %+v", s)
+	// Ningún router respondió. #1742: el overview ya no es nil, se devuelve
+	// available=false con el motivo por unidad para que la UI pueda explicar
+	// por qué no hay survey en vez de mandar a ejecutar `iw survey dump`.
+	if s == nil {
+		t.Fatal("expected overview with available=false, got nil")
+	}
+	if s.Available {
+		t.Fatalf("expected available=false, got %+v", s)
+	}
+	if len(s.Routers) != 1 || s.Routers[0].Reason != SurveyReasonSnmpOnly {
+		t.Fatalf("expected one snmp_only router, got %+v", s.Routers)
 	}
 }
 
@@ -94,3 +102,28 @@ func TestGetSurveyIncludesGateway(t *testing.T) {
 		t.Fatalf("expected gateway available with radios, got %+v", gw)
 	}
 }
+
+// #1742: una unidad agent-only sin survey empujado (el caso de los AP
+// Broadcom/dhd, donde el agente va por `wl` y no hay `iw survey dump`) deja
+// available=false con motivo agent_no_survey, en vez de desaparecer del
+// overview sin explicación.
+func TestGetSurveyAgentOnlyWithoutSurveyReportsReason(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	l.SetRouters([]RouterConfig{
+		{ID: "ap1", Name: "AP 1", Host: "192.168.1.2", AgentOnly: true},
+	})
+
+	s, err := l.GetSurvey(context.Background())
+	if err != nil {
+		t.Fatalf("unexpected error: %v", err)
+	}
+	if s == nil || s.Available {
+		t.Fatalf("expected overview with available=false, got %+v", s)
+	}
+	if len(s.Routers) != 1 || s.Routers[0].Reason != SurveyReasonAgentNoSurvey {
+		t.Fatalf("expected one agent_no_survey router, got %+v", s.Routers)
+	}
+	if s.Routers[0].Available {
+		t.Fatalf("expected the unit to stay unavailable, got %+v", s.Routers[0])
+	}
+}

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

@@ -931,16 +931,29 @@ type SurveyRadio struct {
 }
 
 // SurveyRouter es el survey de un router: lista de radios wifi-iface.
-// Available=false si SSH falló.
+// Available=false si SSH falló o si la unidad no tiene survey (entonces
+// Reason dice por qué).
 type SurveyRouter struct {
 	RouterID  string        `json:"routerId"`
 	Name      string        `json:"name"`
 	Available bool          `json:"available"`
+	Reason    string        `json:"reason,omitempty"`
 	Radios    []SurveyRadio `json:"radios"`
 }
 
-// SurveyOverview es la respuesta de GET /api/survey. Available=false si
-// ningún router responde → el handler devuelve 503.
+// Motivos por los que una unidad no aporta survey (#1742). Cerrado: la UI
+// traduce cada uno a una explicación accionable.
+const (
+	SurveyReasonAgentNoSurvey  = "agent_no_survey" // el agente no empuja iw survey dump
+	SurveyReasonNoSurveyData   = "no_survey_data"  // iw survey dump no devolvió canales
+	SurveyReasonSSHUnreachable = "ssh_unreachable" // SSH falló
+	SurveyReasonNoWifi         = "no_wifi"         // sin interfaces wifi
+	SurveyReasonSnmpOnly       = "snmp_only"       // unidad SNMP, sin SSH ni agente
+)
+
+// SurveyOverview es la respuesta de GET /api/survey. Available=false cuando
+// ninguna unidad aporta survey; el handler responde 200 igualmente para que
+// la UI pueda explicar el motivo de cada una (#1742).
 type SurveyOverview struct {
 	Available bool           `json:"available"`
 	Routers   []SurveyRouter `json:"routers"`

+ 61 - 6
server-go/internal/channelplan/store.go

@@ -193,8 +193,7 @@ type ChannelScore struct {
 
 // bandBlocks devuelve TODOS los canales/bloques puntuables de la banda a su
 // ancho (#1076): 2.4 GHz canal a canal (20 MHz); 5 GHz primarios cuyo bloque
-// completo cabe en la banda (DFS incluidos); 6 GHz solo los no-DFS (no
-// mantenemos la tabla PSC).
+// completo cabe en la banda (DFS incluidos); 6 GHz impares 1-233 sin DFS.
 func bandBlocks(band string, widthMhz int) []ChannelScore {
 	mk := func(ch int, dfs bool) ChannelScore {
 		return ChannelScore{Channel: ch, DFS: dfs, Recommendable: !dfs}
@@ -247,6 +246,30 @@ func bandBlocks(band string, widthMhz int) []ChannelScore {
 			}
 		}
 		return out
+	case "6 GHz":
+		// #1742: sin tabla propia, 6 GHz caía en candidateChannels y el motor
+		// sugería canales de 2.4 GHz (1, 5, 9...) que nadie había medido. La
+		// banda no tiene DFS en el ámbito doméstico y sus canales son los
+		// impares 1-233 (paso de 5 MHz, igual que 5 GHz: 4 números por 20 MHz).
+		// Los bloques se alinean desde el 1 con salto n*4 para no solaparse.
+		n := widthMhz / 20
+		if n < 1 {
+			n = 1
+		}
+		stride := n * 4
+		out := make([]ChannelScore, 0, 60)
+		for ch := 1; ch <= 233; ch += stride {
+			if ch+(n-1)*4 > 233 {
+				break
+			}
+			// A 20 MHz solo se sugieren los PSC (5, 21, 37...): son los que
+			// un cliente escanea para descubrir la red. El resto se puntúa
+			// igual, para informar de la congestión real.
+			c := mk(ch, false)
+			c.Recommendable = n > 1 || isPSC6(ch)
+			out = append(out, c)
+		}
+		return out
 	default:
 		out := make([]ChannelScore, 0, len(candidateChannels(band, widthMhz)))
 		for _, ch := range candidateChannels(band, widthMhz) {
@@ -341,7 +364,13 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 		for _, m := range byBand[band] {
 			bandNeighbors += len(m)
 		}
-		currentNotRecommendable := true
+		// #1742: un canal que no existe en su banda (el fallback wl de Broadcom
+		// devuelve índices hardware: 323, 195...) no se puede comparar con
+		// nada, así que no se sugiere cambio. Dentro de la banda se mantiene
+		// el criterio legacy: si no es primario de ningún bloque puntuable se
+		// asume que hay que moverlo.
+		currentKnown := channelInBand(band, r.Channel)
+		currentNotRecommendable := currentKnown
 		for _, b := range scores {
 			if b.Channel == r.Channel {
 				currentNotRecommendable = !b.Recommendable
@@ -349,6 +378,10 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 			}
 		}
 		switch {
+		case !currentKnown:
+			// 0 es el centinela de "sin datos" que la UI ya distingue de
+			// "mantén el actual".
+			rec.Recommended = 0
 		case currentNotRecommendable && bestCh != 0:
 			rec.Recommended = bestCh
 		case bestCh != 0 && bandNeighbors > 0 && bestScore < currentScore && bestScore*100 <= currentScore*70:
@@ -409,7 +442,8 @@ func channelScore(scans map[int][]ScanRow, channel int) int {
 // candidateChannels devuelve los canales candidatos no-DFS para la banda,
 // filtrando por el ancho del radio (#631): a 40/80/160 MHz solo valen los
 // canales cuyo bloque completo (canales ch..ch+(n-1)*4, n=w/20) no entra en
-// un canal DFS (52-64, 100-144) ni se sale de la banda.
+// un canal DFS (52-64, 100-144) ni se sale de la banda. 6 GHz tiene su propia
+// tabla de bloques en bandBlocks (#1742).
 func candidateChannels(band string, widthMhz int) []int {
 	var base []int
 	switch band {
@@ -418,8 +452,6 @@ func candidateChannels(band string, widthMhz int) []int {
 	case "5 GHz":
 		// UNII-1/3 canales no-DFS preferidos para uso doméstico.
 		base = []int{36, 40, 44, 48, 149, 153, 157, 161, 165}
-	case "6 GHz":
-		base = []int{1, 5, 9, 13, 17, 21, 25, 29}
 	default:
 		return nil
 	}
@@ -455,6 +487,29 @@ func validForWidth(ch, widthMhz int, band string) bool {
 	return true
 }
 
+// channelInBand indica si el canal que reporta el radio existe en su banda.
+// El fallback wl de Broadcom devuelve índices hardware (323, 195) que no son
+// canales de 6 GHz (#1742).
+func channelInBand(band string, ch int) bool {
+	switch band {
+	case "2.4 GHz":
+		return ch >= 1 && ch <= 14
+	case "5 GHz":
+		return ch >= 36 && ch <= 165 && (ch-4)%4 == 0
+	case "6 GHz":
+		return ch >= 1 && ch <= 233 && (ch-1)%4 == 0
+	default:
+		// Banda desconocida: no se juzga el canal, se deja el criterio previo.
+		return true
+	}
+}
+
+// isPSC6 marca los Preferred Scanning Channels de 6 GHz (5, 21, 37 ... 229):
+// los que un cliente escanea para descubrir la red.
+func isPSC6(ch int) bool {
+	return ch >= 5 && ch <= 229 && (ch-5)%16 == 0
+}
+
 // isDFSChannel: canales que en ETSI/EU requieren detección DFS (radio no
 // puede usarlos sin radar) — UNII-2A (52-64) y UNII-2C (100-144).
 func isDFSChannel(ch int) bool {

+ 90 - 0
server-go/internal/channelplan/store_test.go

@@ -631,3 +631,93 @@ func TestRecommendConservador(t *testing.T) {
 		t.Errorf("(c) empate técnico: se espera mantener 6: %+v", recs[0])
 	}
 }
+
+// TestRecommend6GHzUsaBloquesDeSuBanda (#1742): sin tabla propia el motor caía
+// en candidateChannels y sugería canales de 2.4 GHz (1, 5, 9...) que nadie
+// había medido.
+func TestRecommend6GHzUsaBloquesDeSuBanda(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)
+	// Vecina fuerte en el 37 (6135 MHz), medida en 6 GHz.
+	if err := st.SaveScan("rt1", time.Now().Unix(), []probe.ScanResult{
+		{BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 37, Freq: 6135, Signal: -50},
+	}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+
+	radios := []probe.Radio{
+		{Name: "6 GHz", Channel: 37, WidthMhz: 20},
+		{Name: "6 GHz", Channel: 37, WidthMhz: 80},
+	}
+	recs, err := st.Recommend("rt1", radios, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	if len(recs) != 2 {
+		t.Fatalf("esperaba 2 recomendaciones, got %d", len(recs))
+	}
+
+	// (a) 20 MHz: todos los bloques son canales de 6 GHz y solo los PSC se
+	// sugieren.
+	for _, s := range recs[0].Scores {
+		if s.Channel < 1 || s.Channel > 233 || (s.Channel-1)%4 != 0 {
+			t.Fatalf("canal %d no es un canal de 6 GHz", s.Channel)
+		}
+		if s.Recommendable && (s.Channel-5)%16 != 0 {
+			t.Errorf("a 20 MHz solo se sugieren PSC, canal %d no lo es", s.Channel)
+		}
+	}
+	if recs[0].Recommended == 37 || recs[0].Recommended == 0 {
+		t.Errorf("el 37 está ocupado, se esperaba otro PSC medido: %+v", recs[0])
+	}
+	if recs[0].Recommended == 1 {
+		t.Errorf("el 1 no es un canal de 6 GHz: %+v", recs[0])
+	}
+
+	// (b) 80 MHz: bloques de cuatro canales que caben en la banda.
+	for _, s := range recs[1].Scores {
+		if (s.Channel-1)%16 != 0 || s.Channel+12 > 233 {
+			t.Fatalf("bloque de 80 MHz inválido: %d", s.Channel)
+		}
+	}
+}
+
+// TestRecommendCanalFueraDeBandaNoSugiere (#1742): el fallback wl de Broadcom
+// reporta índices hardware (323, 195) en vez del canal. Sin canal comparable
+// no se sugiere nada: 0 es "sin datos", no "mantén".
+func TestRecommendCanalFueraDeBandaNoSugiere(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)
+	if err := st.SaveScan("rt1", time.Now().Unix(), []probe.ScanResult{
+		{BSSID: "00:11:22:33:44:55", SSID: "vecino", Channel: 37, Freq: 6135, Signal: -50},
+	}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+
+	radios := []probe.Radio{
+		{Name: "6 GHz", Channel: 323, WidthMhz: 20},
+		{Name: "6 GHz", Channel: 195, WidthMhz: 20},
+	}
+	recs, err := st.Recommend("rt1", radios, time.Hour)
+	if err != nil {
+		t.Fatalf("recommend: %v", err)
+	}
+	for _, r := range recs {
+		if r.Recommended != 0 {
+			t.Errorf("canal %d no mapeable: no se debe sugerir nada, got %d", r.Channel, r.Recommended)
+		}
+		if len(r.Scores) == 0 {
+			t.Errorf("la tira de 6 GHz debe puntuarse igualmente: %+v", r)
+		}
+	}
+}

+ 4 - 2
server-go/internal/httpapi/data.go

@@ -648,7 +648,9 @@ func (s *server) handleDot11r(w http.ResponseWriter, r *http.Request) {
 	writeJSON(w, http.StatusOK, dot11r)
 }
 
-// handleSurvey: 503 {error:'unavailable'} si ningún router responde.
+// handleSurvey: 200 con la lista de unidades y el motivo de las que no
+// aportan (#1742). Antes era 503 cuando nadie respondía y la UI no podía
+// explicar por qué.
 func (s *server) handleSurvey(w http.ResponseWriter, r *http.Request) {
 	survey, err := s.adapter.GetSurvey(r.Context())
 	if err != nil {
@@ -656,7 +658,7 @@ func (s *server) handleSurvey(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	if survey == nil {
-		writeError(w, http.StatusServiceUnavailable, "unavailable")
+		writeJSON(w, http.StatusOK, &adapters.SurveyOverview{Routers: []adapters.SurveyRouter{}})
 		return
 	}
 	writeJSON(w, http.StatusOK, survey)

+ 18 - 11
server-go/internal/httpapi/wifi_channelplan.go

@@ -96,30 +96,37 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 			}
 		}
 
-		recommendations, err := s.channelPlan.Recommend(slug, radios, 24*time.Hour)
-		if err != nil {
-			writeError(w, http.StatusInternalServerError, "channel_plan_error")
-			return
-		}
-		scans, err := s.channelPlan.RecentScans(slug, 24*time.Hour)
-		if err != nil {
-			writeError(w, http.StatusInternalServerError, "channel_plan_error")
-			return
-		}
+		// #1742: lo que se puntúa y lo que se enseña tienen que salir de la
+		// misma ventana. Antes se recomendaba con 24 h fijas y, si no había
+		// scans, solo la lista se ampliaba a 30 días: la vista mostraba filas
+		// con todos los vecinos a 0 porque el análisis nunca las había visto.
 		// #1214: flotas con NETPULSE_SCAN_INTERVAL=0 no escanean nunca por
 		// intervalo - con la ventana fija de 24h la vista moría en cuanto el
 		// último scan cumplía un día (solo quedaba el bloque propio
 		// sintético y un espectro vacío). Misma filosofía que #1080 con los
 		// radios: mejor el último dato conocido, aunque sea antiguo, que
 		// fingir que no hay nada; el "Escanear ahora" lo renueva al momento.
+		window := 24 * time.Hour
+		scans, err := s.channelPlan.RecentScans(slug, window)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "channel_plan_error")
+			return
+		}
 		if len(scans) == 0 {
-			scans, err = s.channelPlan.RecentScans(slug, 30*24*time.Hour)
+			window = 30 * 24 * time.Hour
+			scans, err = s.channelPlan.RecentScans(slug, window)
 			if err != nil {
 				writeError(w, http.StatusInternalServerError, "channel_plan_error")
 				return
 			}
 		}
 
+		recommendations, err := s.channelPlan.Recommend(slug, radios, window)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "channel_plan_error")
+			return
+		}
+
 		writeJSON(w, http.StatusOK, map[string]any{
 			"routerId": routerID,
 			"radios":   recommendations,