Jelajahi Sumber

feat: make neighbour scans on demand by default (#1564)

* fix(agent): scan neighbours once per radio and log the cycle

The scan ran `iw dev <iface> scan` for every interface of `iw dev`, so a
radio with several BSSIDs (LAN plus a VLAN SSID) left the channel once per
BSSID in the same cycle. #1557 reports two client drops 44s apart on a
GL-MT6000 with exactly that layout. Targets are grouped by phy now, one per
radio, preferring the AP interface; without phy headers the old per-interface
behaviour stays.

The cycle also logs start, per-radio duration and BSS count (#1559). This is
the only probe that takes a radio off-channel, so a client drop can only be
correlated with it if the log says when it ran.

* feat(install): default periodic neighbour scans to off

iw scan takes the radio off-channel for 2-4s and beacon-sensitive clients can drop in that window (#1557). Periodic scans are now optional: both install agents write NETPULSE_SCAN_INTERVAL=0 and keep whatever value the unit already had (#851). Neighbours are refreshed on demand from the channel plan view.

* feat(server): throttle on-demand channel plan scans

With periodic scans off by default the scan endpoint becomes the only path, and opening the view requests a scan. Limit each unit to one forced scan every five minutes so several tabs cannot chain cycles, and release the turn when the agent is not connected.

* feat(web): request a scan when the channel plan view opens

Stale neighbour data no longer refreshes itself. Ask the agent for a scan after the first load when the newest scan is older than six hours, at most once per router every thirty minutes per session, and treat a 429 as already requested. The background poll never scans.

* docs: document the neighbour scan default in the channel plan

* fix(agent): keep the SSE retry delay short after a clean disconnect

The doubling ran after every sleep, so the reset on a successful connection was undone two lines later and the delay climbed to five minutes even when every disconnect was clean. With periodic scans off by default the on-demand scan depends on the stream being open, so a long delay leaves upgrades and scans queued.
Nacho 1 bulan lalu
induk
melakukan
ba8e1ba5fe

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.24
+3.0.25

+ 19 - 7
agent/internal/sseclient/sseclient.go

@@ -64,21 +64,33 @@ func (c *Client) Run(ctx context.Context) {
 		}
 		if err != nil {
 			c.logf("[netpulse-agent] SSE desconectado (%v), reintentando en %s", err, retry)
-		} else {
-			retry = c.minRetry
 		}
+		delay, next := c.retryDelay(retry, err == nil)
+		retry = next
 		select {
 		case <-ctx.Done():
 			return
-		case <-time.After(retry):
-		}
-		retry *= 2
-		if retry > c.maxRetry {
-			retry = c.maxRetry
+		case <-time.After(delay):
 		}
 	}
 }
 
+// retryDelay decide cuánto esperar antes del siguiente intento y el valor
+// acumulado para el siguiente fallo. Una conexión que llegó a establecerse
+// reinicia el backoff (#284); solo los fallos consecutivos lo hacen crecer
+// hasta maxRetry (#1563: el `retry *= 2` anterior también corría tras una
+// conexión limpia, así que el reinicio no servía de nada).
+func (c *Client) retryDelay(current time.Duration, established bool) (delay, next time.Duration) {
+	if established {
+		return c.minRetry, c.minRetry
+	}
+	next = current * 2
+	if next > c.maxRetry {
+		next = c.maxRetry
+	}
+	return current, next
+}
+
 func (c *Client) connect(ctx context.Context) error {
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url, nil)
 	if err != nil {

+ 44 - 0
agent/internal/sseclient/sseclient_test.go

@@ -0,0 +1,44 @@
+package sseclient
+
+import (
+	"testing"
+	"time"
+)
+
+// #1563: una conexión que llegó a establecerse reinicia el backoff, sin
+// importar cuántos cortes limpios hubiera antes.
+func TestRetryDelayResetsAfterCleanDisconnect(t *testing.T) {
+	c := &Client{minRetry: 5 * time.Second, maxRetry: 5 * time.Minute}
+
+	for _, current := range []time.Duration{5 * time.Second, 40 * time.Second, 5 * time.Minute} {
+		delay, next := c.retryDelay(current, true)
+		if delay != c.minRetry || next != c.minRetry {
+			t.Fatalf("corte limpio con current=%s: delay=%s next=%s, quería %s/%s",
+				current, delay, next, c.minRetry, c.minRetry)
+		}
+	}
+}
+
+// Solo los fallos consecutivos hacen crecer la espera, y nunca por encima de
+// maxRetry.
+func TestRetryDelayGrowsOnFailures(t *testing.T) {
+	c := &Client{minRetry: 5 * time.Second, maxRetry: 5 * time.Minute}
+
+	cases := []struct {
+		current time.Duration
+		delay   time.Duration
+		next    time.Duration
+	}{
+		{5 * time.Second, 5 * time.Second, 10 * time.Second},
+		{10 * time.Second, 10 * time.Second, 20 * time.Second},
+		{4 * time.Minute, 4 * time.Minute, 5 * time.Minute},
+		{5 * time.Minute, 5 * time.Minute, 5 * time.Minute},
+	}
+	for _, tc := range cases {
+		delay, next := c.retryDelay(tc.current, false)
+		if delay != tc.delay || next != tc.next {
+			t.Fatalf("fallo con current=%s: delay=%s next=%s, quería %s/%s",
+				tc.current, delay, next, tc.delay, tc.next)
+		}
+	}
+}

+ 104 - 0
agent/probe/iwdev.go

@@ -0,0 +1,104 @@
+// iwdev.go - `iw dev` parsing with the physical radio of every interface
+// (#1560). The neighbour scan is the only probe that takes a radio off-channel,
+// so it must run once per radio, not once per interface: a radio carrying
+// several BSSIDs (LAN plus a VLAN SSID) used to be scanned once per BSSID in
+// the same cycle, 2-4s each.
+package probe
+
+import (
+	"strconv"
+	"strings"
+)
+
+// IwDevIface is one interface from `iw dev` with the radio it belongs to.
+type IwDevIface struct {
+	Iface string
+	Phy   int    // -1 when the output had no phy# section
+	Type  string // "AP", "managed", "monitor", "P2P-device", "" if unknown
+}
+
+// ParseIwDevDetailed parses `iw dev` keeping the phy# section each interface
+// sits under and its mode. iw prints one phy#N header followed by every
+// interface of that radio, so the section in effect is the radio.
+func ParseIwDevDetailed(out string) []IwDevIface {
+	phy := -1
+	var res []IwDevIface
+	for _, raw := range strings.Split(out, "\n") {
+		fields := strings.Fields(strings.TrimSpace(raw))
+		if len(fields) == 0 {
+			continue
+		}
+		switch {
+		case strings.HasPrefix(fields[0], "phy#"):
+			if n, err := strconv.Atoi(strings.TrimPrefix(fields[0], "phy#")); err == nil {
+				phy = n
+			} else {
+				phy = -1
+			}
+		case fields[0] == "Interface" && len(fields) >= 2:
+			res = append(res, IwDevIface{Iface: fields[1], Phy: phy})
+		case fields[0] == "type" && len(fields) >= 2 && len(res) > 0:
+			// First `type` wins: some iw builds repeat the line once per
+			// virtual interface inside the same block.
+			if res[len(res)-1].Type == "" {
+				res[len(res)-1].Type = fields[1]
+			}
+		}
+	}
+	return res
+}
+
+// IwDevScanTargets picks the interface to scan for neighbours on every
+// physical radio, preferring one in AP mode. What a scan returns depends on
+// the radio, not on the BSSID it is run from, so scanning the second BSSID of
+// the same radio only keeps that radio off-channel for another 2-4s (#1557).
+// Without phy information (old iw, trimmed output) it falls back to one target
+// per interface, which is what the agent did before #1560.
+func IwDevScanTargets(ifaces []IwDevIface) []IwDevIface {
+	hasPhy := false
+	for _, i := range ifaces {
+		if i.Phy >= 0 {
+			hasPhy = true
+			break
+		}
+	}
+	if !hasPhy {
+		return ifaces
+	}
+	var order []int
+	groups := make(map[int][]IwDevIface, len(ifaces))
+	var loose []IwDevIface
+	for _, i := range ifaces {
+		if i.Phy < 0 {
+			loose = append(loose, i)
+			continue
+		}
+		if _, ok := groups[i.Phy]; !ok {
+			order = append(order, i.Phy)
+		}
+		groups[i.Phy] = append(groups[i.Phy], i)
+	}
+	res := make([]IwDevIface, 0, len(order)+len(loose))
+	for _, phy := range order {
+		res = append(res, pickScanIface(groups[phy]))
+	}
+	return append(res, loose...)
+}
+
+// pickScanIface prefers an AP interface because it is the one carrying
+// clients, which keeps the interface name in wifi_scans meaningful. Monitor
+// and P2P-device interfaces can also leave the radio off-channel without the
+// AP, so they are the last resort.
+func pickScanIface(group []IwDevIface) IwDevIface {
+	for _, i := range group {
+		if strings.EqualFold(i.Type, "AP") {
+			return i
+		}
+	}
+	for _, i := range group {
+		if !strings.EqualFold(i.Type, "monitor") && !strings.EqualFold(i.Type, "P2P-device") {
+			return i
+		}
+	}
+	return group[0]
+}

+ 235 - 0
agent/probe/iwdev_test.go

@@ -0,0 +1,235 @@
+package probe
+
+// iwdev_test.go - #1560: the neighbour scan ran once per interface, so a radio
+// with several BSSIDs left the channel once per BSSID. Field report #1557: a
+// GL-MT6000 with two 2.4 GHz SSIDs (LAN plus VLAN 10) dropped clients 44s
+// apart, which is two scans of the same radio in one cycle.
+
+import (
+	"context"
+	"log/slog"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+)
+
+// iwDevFlint2 is a real `iw dev` from our Flint2 (GL-MT6000, GL.iNet stock
+// firmware): one BSSID per radio, which is why our fleet never hit the double
+// scan.
+const iwDevFlint2 = `phy#1
+	Interface wlan1
+		ifindex 19
+		wdev 0x100000001
+		addr 94:83:c4:ba:bf:ab
+		ssid temiscira
+		type AP
+		channel 36 (5180 MHz), width: 80 MHz, center1: 5210 MHz
+		txpower 23.00 dBm
+phy#0
+	Interface wlan0
+		ifindex 18
+		wdev 0x1
+		addr 32:4e:8e:ac:c6:16
+		ssid temiscira
+		type AP
+		channel 1 (2412 MHz), width: 20 MHz, center1: 2412 MHz
+		txpower 20.00 dBm
+`
+
+// iwDevMultiBSSID is the layout reported in #1557 for the same box: radio 0
+// carries NETGEAR on the LAN and WiFi_10 on VLAN 10. Same `iw dev` shape as
+// iwDevFlint2, with the second BSSID of that radio added.
+const iwDevMultiBSSID = `phy#1
+	Interface phy1-ap0
+		ifindex 19
+		addr 94:83:c4:ba:bf:c0
+		ssid NETGEAR
+		type AP
+		channel 36 (5180 MHz), width: 80 MHz, center1: 5210 MHz
+phy#0
+	Interface phy0-ap0
+		ifindex 18
+		addr 94:83:c4:ba:bf:ab
+		ssid NETGEAR
+		type AP
+		channel 1 (2412 MHz), width: 20 MHz, center1: 2412 MHz
+	Interface phy0-ap1
+		ifindex 20
+		addr 96:83:c4:ba:bf:ab
+		ssid WiFi_10
+		type AP
+		channel 1 (2412 MHz), width: 20 MHz, center1: 2412 MHz
+`
+
+// iwDevNoPhy is the output without phy headers (trimmed or old iw): the
+// grouping cannot know which radio an interface belongs to.
+const iwDevNoPhy = `	Interface wlan1
+		ssid temiscira
+		type AP
+	Interface wlan0
+		ssid temiscira
+		type AP
+`
+
+func TestParseIwDevDetailedKeepsRadio(t *testing.T) {
+	got := ParseIwDevDetailed(iwDevMultiBSSID)
+	if len(got) != 3 {
+		t.Fatalf("interfaces: %+v", got)
+	}
+	want := []IwDevIface{
+		{Iface: "phy1-ap0", Phy: 1, Type: "AP"},
+		{Iface: "phy0-ap0", Phy: 0, Type: "AP"},
+		{Iface: "phy0-ap1", Phy: 0, Type: "AP"},
+	}
+	for i := range want {
+		if got[i] != want[i] {
+			t.Fatalf("iface %d: got %+v want %+v", i, got[i], want[i])
+		}
+	}
+}
+
+// TestScanTargetsOnePerRadio: two BSSIDs on phy#0 must collapse into one
+// target, and the AP interface of that radio is the one picked.
+func TestScanTargetsOnePerRadio(t *testing.T) {
+	targets := IwDevScanTargets(ParseIwDevDetailed(iwDevMultiBSSID))
+	if len(targets) != 2 {
+		t.Fatalf("dos radios deben dar dos targets: %+v", targets)
+	}
+	if targets[0].Iface != "phy1-ap0" || targets[0].Phy != 1 {
+		t.Fatalf("orden de aparición perdido: %+v", targets)
+	}
+	if targets[1].Iface != "phy0-ap0" || targets[1].Phy != 0 {
+		t.Fatalf("radio 0 debe escanearse una vez: %+v", targets)
+	}
+}
+
+func TestScanTargetsOnePerRadioOnOurFleet(t *testing.T) {
+	targets := IwDevScanTargets(ParseIwDevDetailed(iwDevFlint2))
+	if len(targets) != 2 || targets[0].Iface != "wlan1" || targets[1].Iface != "wlan0" {
+		t.Fatalf("una BSS por radio debe seguir dando un target por radio: %+v", targets)
+	}
+}
+
+// TestScanTargetsPrefersAP: a monitor or P2P interface sharing the radio with
+// the AP must not be the one scanned.
+func TestScanTargetsPrefersAP(t *testing.T) {
+	iwDev := "phy#0\n" +
+		"\tInterface mon0\n\t\ttype monitor\n" +
+		"\tInterface p2p-dev-wlan0\n\t\ttype P2P-device\n" +
+		"\tInterface phy0-ap0\n\t\ttype AP\n"
+	targets := IwDevScanTargets(ParseIwDevDetailed(iwDev))
+	if len(targets) != 1 || targets[0].Iface != "phy0-ap0" {
+		t.Fatalf("se debe escanear el AP: %+v", targets)
+	}
+}
+
+// TestScanTargetsFallsBackWithoutPhy: sin secciones phy# se mantiene el
+// comportamiento anterior (una interfaz por target).
+func TestScanTargetsFallsBackWithoutPhy(t *testing.T) {
+	targets := IwDevScanTargets(ParseIwDevDetailed(iwDevNoPhy))
+	if len(targets) != 2 || targets[0].Iface != "wlan1" || targets[1].Iface != "wlan0" {
+		t.Fatalf("fallback por interfaz: %+v", targets)
+	}
+	for _, tgt := range targets {
+		if tgt.Phy != -1 {
+			t.Fatalf("sin phy# el radio debe ser -1: %+v", tgt)
+		}
+	}
+}
+
+// recordingRunner keeps every command the prober runs, in order.
+type recordingRunner struct {
+	mu   sync.Mutex
+	cmds []string
+	outs map[string]string
+}
+
+func (r *recordingRunner) Run(_ context.Context, cmd string, _ time.Duration) (string, error) {
+	r.mu.Lock()
+	r.cmds = append(r.cmds, cmd)
+	r.mu.Unlock()
+	if out, ok := r.outs[cmd]; ok {
+		return out, nil
+	}
+	return "", &fakeErr{cmd}
+}
+
+func (r *recordingRunner) scanCmds() []string {
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	var res []string
+	for _, c := range r.cmds {
+		if strings.HasPrefix(c, "iw dev \"") && strings.Contains(c, " scan") {
+			res = append(res, c)
+		}
+	}
+	return res
+}
+
+// TestBuildScansOncePerRadio is the regression test for #1560: the same
+// multi-BSSID unit must run ONE scan, not one per BSSID.
+func TestBuildScansOncePerRadio(t *testing.T) {
+	run := &recordingRunner{outs: map[string]string{
+		CmdIwDev:                 iwDevMultiBSSID,
+		CmdScanIface("phy1-ap0"): scanVecino24,
+		CmdScanIface("phy0-ap0"): scanVecino24,
+		CmdScanIface("phy0-ap1"): scanVecino24,
+	}}
+	p := NewProber(run, Options{})
+
+	p.Build(context.Background(), "mt6000", "test")
+
+	got := run.scanCmds()
+	if len(got) != 2 {
+		t.Fatalf("dos radios deben dar dos scans, got %d: %v", len(got), got)
+	}
+	if !strings.Contains(got[0], "phy1-ap0") || !strings.Contains(got[1], "phy0-ap0") {
+		t.Fatalf("scans inesperados: %v", got)
+	}
+	for _, c := range got {
+		if strings.Contains(c, "phy0-ap1") {
+			t.Fatalf("la segunda BSS de la misma radio no se escanea: %v", got)
+		}
+	}
+}
+
+// scanVecino24 is a real single-neighbour scan output (rt2, 2.4 GHz).
+const scanVecino24 = `BSS c4:eb:39:0c:2b:c1(on phy0-ap0)
+	freq: 2437.0
+	signal: -67.00 dBm
+	SSID: Vecino_24
+`
+
+// TestScanLogsCycle covers #1559: a scan must leave a trace (start, per-radio
+// duration and result, total) so a client drop can be lined up with it.
+func TestScanLogsCycle(t *testing.T) {
+	var buf strings.Builder
+	prev := slog.Default()
+	slog.SetDefault(slog.New(slog.NewTextHandler(&buf, nil)))
+	defer slog.SetDefault(prev)
+
+	run := &recordingRunner{outs: map[string]string{
+		CmdIwDev:                 iwDevMultiBSSID,
+		CmdScanIface("phy1-ap0"): scanVecino24,
+		CmdScanIface("phy0-ap0"): scanVecino24,
+	}}
+	p := NewProber(run, Options{})
+	p.Build(context.Background(), "mt6000", "test")
+
+	log := buf.String()
+	for _, want := range []string{
+		"neighbor scan start",
+		"radios=2",
+		"neighbor scan radio",
+		`iface=phy0-ap0`,
+		"bss=1",
+		"duration_ms=",
+		"neighbor scan done",
+		"bss=2",
+	} {
+		if !strings.Contains(log, want) {
+			t.Fatalf("log sin %q:\n%s", want, log)
+		}
+	}
+}

+ 35 - 6
agent/probe/local.go

@@ -9,6 +9,7 @@ import (
 	"context"
 	"encoding/json"
 	"fmt"
+	"log/slog"
 	"net"
 	"os"
 	"os/exec"
@@ -245,6 +246,39 @@ func (p *Prober) scanDue() bool {
 	return false
 }
 
+// scanNeighbours runs one `iw dev <iface> scan` per physical radio (#1560)
+// and logs every cycle (#1559).
+//
+// The scan is the only probe that takes a radio off-channel, so it is also
+// the only one that can drop clients (#1557). Until now it left no trace in
+// the log, which made that correlation impossible from a router: the log line
+// carries the interfaces, per-radio duration and BSS count to line a drop up
+// against the scan that caused it.
+func (p *Prober) scanNeighbours(ctx context.Context, iwDev string) []ScanResult {
+	targets := IwDevScanTargets(ParseIwDevDetailed(iwDev))
+	if len(targets) == 0 {
+		return nil
+	}
+	names := make([]string, len(targets))
+	for i, t := range targets {
+		names[i] = t.Iface
+	}
+	start := time.Now()
+	slog.Info("neighbor scan start", "radios", len(targets), "ifaces", strings.Join(names, ","))
+	var scans []ScanResult
+	for _, t := range targets {
+		at := time.Now()
+		out := p.runBest(ctx, CmdScanIface(t.Iface), scanIfaceTimeout)
+		got := ParseScan("==IFACE==" + t.Iface + "\n" + out)
+		scans = append(scans, got...)
+		slog.Info("neighbor scan radio", "iface", t.Iface, "phy", t.Phy,
+			"bss", len(got), "duration_ms", time.Since(at).Milliseconds())
+	}
+	slog.Info("neighbor scan done", "bss", len(scans),
+		"duration_ms", time.Since(start).Milliseconds(), "empty", len(scans) == 0)
+	return scans
+}
+
 // probeVlans reports the bridge VLANs, preferring what the kernel says over
 // what the config declares.
 //
@@ -571,12 +605,7 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 		// sin NINGÚN vecino aunque las demás interfaces sí hubieran
 		// escaneado con éxito.
 		if p.scanDue() && iwDev != "" {
-			var sb strings.Builder
-			for _, iface := range IwDevIfaces(iwDev) {
-				sb.WriteString("==IFACE==" + iface + "\n")
-				sb.WriteString(p.runBest(ctx, CmdScanIface(iface), scanIfaceTimeout))
-			}
-			if scans := ParseScan(sb.String()); len(scans) > 0 {
+			if scans := p.scanNeighbours(ctx, iwDev); len(scans) > 0 {
 				wd.Scans = scans
 			}
 		}

+ 5 - 7
agent/probe/probe.go

@@ -1965,15 +1965,13 @@ func ParseIwDev(out string) []OwnBSSID {
 	return res
 }
 
-// IwDevIfaces (#1338) lista TODAS las interfaces de `iw dev` (cualquier
-// tipo, no solo AP como ParseIwDev): son las candidatas a escanear vecinos.
+// IwDevIfaces (#1338) lists EVERY interface of `iw dev` (any type, not only
+// AP like ParseIwDev). Since #1560 the scan groups them by radio with
+// ParseIwDevDetailed instead of scanning each one.
 func IwDevIfaces(out string) []string {
 	var res []string
-	for _, raw := range strings.Split(out, "\n") {
-		fields := strings.Fields(strings.TrimSpace(raw))
-		if len(fields) >= 2 && fields[0] == "Interface" {
-			res = append(res, fields[1])
-		}
+	for _, i := range ParseIwDevDetailed(out) {
+		res = append(res, i.Iface)
 	}
 	return res
 }

+ 8 - 7
agent/probe/scan_periface_test.go

@@ -100,8 +100,9 @@ func TestCmdScanIface(t *testing.T) {
 }
 
 // TestScanPorInterfazThrottle: el throttle (scanDue) sigue gobernando el
-// scan aunque ahora se lance por interfaz: 2 interfaces = 2 comandos en la
-// primera Build y 0 en la segunda (dentro del intervalo).
+// scan aunque ahora vaya por radio: dos BSSIDs en la MISMA radio dan un solo
+// comando por ciclo (#1560, antes eran dos: la radio salía del canal dos
+// veces seguidas) y ninguno en la segunda Build (dentro del intervalo).
 func TestScanPorInterfazThrottle(t *testing.T) {
 	iwDev := "phy#0\n" +
 		"\tInterface phy0-ap0\n\t\taddr 60:22:32:5b:5c:98\n\t\ttype AP\n" +
@@ -113,16 +114,16 @@ func TestScanPorInterfazThrottle(t *testing.T) {
 	ctx := context.Background()
 
 	p.Build(ctx, "rt", "test")
-	if run.scanCalls != 2 {
-		t.Fatalf("primera Build debería escanear las 2 interfaces, scanCalls=%d", run.scanCalls)
+	if run.scanCalls != 1 {
+		t.Fatalf("dos BSSIDs en la misma radio deben escanear UNA vez, scanCalls=%d", run.scanCalls)
 	}
 	p.Build(ctx, "rt", "test")
-	if run.scanCalls != 2 {
+	if run.scanCalls != 1 {
 		t.Fatalf("segunda Build dentro del intervalo NO debería escanear, scanCalls=%d", run.scanCalls)
 	}
 	p.ForceScan()
 	p.Build(ctx, "rt", "test")
-	if run.scanCalls != 4 {
-		t.Fatalf("ForceScan debería reescanear las 2 interfaces, scanCalls=%d", run.scanCalls)
+	if run.scanCalls != 2 {
+		t.Fatalf("ForceScan debería reescanear la radio, scanCalls=%d", run.scanCalls)
 	}
 }

+ 64 - 9
app/src/pages/ChannelPlan.tsx

@@ -63,6 +63,11 @@ interface ChannelPlanData {
   scans: Scan[]
 }
 
+// #1561: abrir la vista pide un scan si el último dato tiene más de 6 h (o no
+// hay), como mucho una vez cada 30 min por unidad.
+const AUTO_SCAN_STALE_MS = 6 * 60 * 60 * 1000
+const AUTO_SCAN_COOLDOWN_MS = 30 * 60 * 1000
+
 function bandFromFreq(freq: number): string {
   if (freq >= 2412 && freq <= 2484) return '2.4 GHz'
   if (freq >= 5180 && freq <= 5885) return '5 GHz'
@@ -230,22 +235,25 @@ export default function ChannelPlan() {
     }
   }, [sortedRouters, routerId])
 
-  const loadPlan = useCallback((rid: string, silent = false) => {
+  const loadPlan = useCallback((rid: string, silent = false): Promise<ChannelPlanData | undefined> => {
     if (!silent) {
       setLoading(true)
       setError('')
     }
-    fetch(`/api/wifi/channel-plan?routerId=${encodeURIComponent(rid)}`)
+    return fetch(`/api/wifi/channel-plan?routerId=${encodeURIComponent(rid)}`)
       .then(async (res) => {
         if (!res.ok) throw new Error(await res.text())
-        return res.json()
+        return res.json() as Promise<ChannelPlanData>
       })
       .then((d) => {
-        setData({ ...d, radios: d.radios ?? [], scans: d.scans ?? [] })
+        const plan: ChannelPlanData = { ...d, radios: d.radios ?? [], scans: d.scans ?? [] }
+        setData(plan)
         setLastRefresh(Date.now())
+        return plan
       })
       .catch((e) => {
         if (!silent) setError(String(e))
+        return undefined
       })
       .finally(() => {
         if (!silent) setLoading(false)
@@ -260,7 +268,9 @@ export default function ChannelPlan() {
     setScanError('')
     fetch(`/api/wifi/channel-plan/scan?routerId=${encodeURIComponent(routerId)}`, { method: 'POST' })
       .then(async (res) => {
-        if (!res.ok) throw new Error(await res.text())
+        // #1561: 429 = otra pestaña u otro admin acaba de pedirlo para esta
+        // unidad. El resultado llega igual, así que no es un error.
+        if (!res.ok && res.status !== 429) throw new Error(await res.text())
         setScanRequested(true)
         scanTimers.current.push(window.setTimeout(() => { void loadPlan(routerId, true) }, 12000))
         scanTimers.current.push(window.setTimeout(() => {
@@ -275,20 +285,65 @@ export default function ChannelPlan() {
       })
   }, [routerId, scanning, loadPlan, t])
 
+  // #1561: con el scan periódico apagado (#1558) el plan se queda viejo si
+  // nadie pulsa "Escanear ahora". Abrir la vista con datos de más de 6 h (o
+  // sin datos) pide un scan, como mucho una vez cada 30 min por unidad. El
+  // polling de fondo no lo dispara nunca, y el servidor limita a uno cada
+  // 5 min por agente.
+  const autoScanDone = useRef<string>('')
+  const autoScanIfStale = useCallback((rid: string, plan: ChannelPlanData | undefined) => {
+    if (!plan || autoScanDone.current === rid) return
+    autoScanDone.current = rid
+    const newest = plan.scans.reduce((max, s) => Math.max(max, s.ts ?? 0), 0)
+    if (newest > 0 && Date.now() - newest < AUTO_SCAN_STALE_MS) return
+    const key = `netpulse.channelPlan.autoScan.${rid}`
+    try {
+      const last = Number(sessionStorage.getItem(key) ?? 0)
+      if (last > 0 && Date.now() - last < AUTO_SCAN_COOLDOWN_MS) return
+    } catch {
+      return // sin almacenamiento no se autoescanea: mejor no encadenar
+    }
+    setScanning(true)
+    setScanRequested(true)
+    fetch(`/api/wifi/channel-plan/scan?routerId=${encodeURIComponent(rid)}`, { method: 'POST' })
+      .then((res) => {
+        if (!res.ok && res.status !== 429) {
+          setScanning(false)
+          setScanRequested(false)
+          return
+        }
+        try {
+          sessionStorage.setItem(key, String(Date.now()))
+        } catch {
+          /* idem */
+        }
+        scanTimers.current.push(window.setTimeout(() => { void loadPlan(rid, true) }, 12000))
+        scanTimers.current.push(window.setTimeout(() => {
+          void loadPlan(rid, true)
+          setScanning(false)
+          setScanRequested(false)
+        }, 35000))
+      })
+      .catch(() => {
+        setScanning(false)
+        setScanRequested(false)
+      })
+  }, [loadPlan])
+
   useEffect(() => {
     if (!routerId) return
     setActiveRadio('')
     setHidden(new Set())
     setSelected(null)
-    loadPlan(routerId)
+    void loadPlan(routerId).then((plan) => autoScanIfStale(routerId, plan))
     if (pollTimer.current) clearInterval(pollTimer.current)
-    // Refresco silencioso: los agentes escanean solos; la página sigue el
-    // último scan sin recargar a mano.
+    // Refresco silencioso: sigue el último scan sin recargar a mano. No
+    // pide scans (eso es del montaje y del botón).
     pollTimer.current = setInterval(() => loadPlan(routerId, true), 60000)
     return () => {
       if (pollTimer.current) clearInterval(pollTimer.current)
     }
-  }, [routerId, loadPlan])
+  }, [routerId, loadPlan, autoScanIfStale])
 
   const radioKey = (r: RadioRec) => `${r.section || r.iface}-${r.name}-${r.channel}`
   const radios: RadioRec[] = data?.radios ?? []

+ 2 - 0
docs/manual.en.md

@@ -371,6 +371,8 @@ Per router, one card per WiFi radio with the **current channel**, the **recommen
 
 The plan is computed from each radio's **neighbor scans**. There is a key difference here: routers running the **NetGrip** panel (the gateway and the APs managed by its panel) **do not scan neighbors**; routers with the **NetPulse agent** do. That is why some routers show no recommendation.
 
+Since agent 3.0.25 the periodic scan is **off by default** (`NETPULSE_SCAN_INTERVAL=0` in `/etc/netpulse-agent.env`): `iw scan` takes the radio off-channel for 2-4s and some beacon-sensitive clients (ESP8266/ESP32 devices, Cast speakers) get disassociated in that window (see #1557). Neighbors refresh when you open this page if the data is older than 6 hours (one scan per physical radio, with a 5 minute gap between requests) and with the **Scan now** button. To go back to periodic scans, set `NETPULSE_SCAN_INTERVAL=30m` (or any interval) in `/etc/netpulse-agent.env` and restart the agent.
+
 ### How to read it
 
 - **Current channel** in large text, **recommended channel** highlighted when different.

+ 2 - 0
docs/manual.es.md

@@ -371,6 +371,8 @@ Por cada router, una tarjeta por radio WiFi con el **canal actual**, el **canal
 
 El plan se calcula con los **scans de vecinos** de cada radio. Aquí hay una diferencia clave: los routers que corren el panel **NetGrip** (el gateway y los APs gestionados por su panel) **no escanean vecinos**; los routers con el **agente NetPulse** sí. Por eso a veces un router no muestra recomendación.
 
+Desde el agente 3.0.25 el sondeo periódico viene **desactivado** (`NETPULSE_SCAN_INTERVAL=0` en `/etc/netpulse-agent.env`): el `iw scan` saca la radio de su canal 2-4 s y algunos clientes sensibles a los beacons (ESP8266/ESP32, altavoces Cast) se desasocian en esa ventana (ver #1557). Los vecinos se refrescan al abrir esta página si los datos tienen más de 6 horas (un scan por radio física, con 5 minutos de margen entre peticiones) y con el botón **Escanear ahora**. Para volver al sondeo periódico, pon `NETPULSE_SCAN_INTERVAL=30m` (o el intervalo que quieras) en `/etc/netpulse-agent.env` y reinicia el agente.
+
 ### Cómo leerlo
 
 - **Canal actual** en grande, **canal recomendado** resaltado si es distinto.

+ 13 - 6
install-agent.sh

@@ -376,9 +376,16 @@ if [ -n "$SERVER_FP" ]; then
     FP_LINE="NETPULSE_SERVER_FP=$SERVER_FP"
 fi
 # #851: conservar las NETPULSE_* del usuario que este script no gestiona
-# (p. ej. NETPULSE_SCAN_INTERVAL=0): el rewrite toca solo las gestionadas
-# (SERVER/SLUG/TOKEN/SERVER_FP/PAIRING_TOKEN).
-USER_VARS=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_[A-Z0-9_]+=' $ENV_FILE 2>/dev/null | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)='") || USER_VARS=""
+# (p. ej. NETPULSE_WAN_TARGET): el rewrite toca solo las gestionadas
+# (SERVER/SLUG/TOKEN/SERVER_FP/PAIRING_TOKEN/SCAN_INTERVAL).
+# #1558: el scan periódico de vecinos sale APAGADO. Sacar la radio del canal
+# puede tirar clientes sensibles a beacons (#1557) y la vista de canales pide
+# el scan bajo demanda (#1561). Si el env ya trae NETPULSE_SCAN_INTERVAL, ese
+# valor manda (#851), también al reinstalar desde la UI.
+PREV_SCAN=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_SCAN_INTERVAL=' $ENV_FILE 2>/dev/null | tail -n 1") || PREV_SCAN=""
+SCAN_LINE="NETPULSE_SCAN_INTERVAL=0"
+if [ -n "$PREV_SCAN" ]; then SCAN_LINE="$PREV_SCAN"; fi
+USER_VARS=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_[A-Z0-9_]+=' $ENV_FILE 2>/dev/null | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|SCAN_INTERVAL)='") || USER_VARS=""
 ssh $SSH_IDENT_ARGS "$SSH" "cat > $ENV_FILE && chmod 600 $ENV_FILE" <<EOF
 # netpulse-agent — config (generado por install-agent.sh)
 NETPULSE_SERVER=$SERVER
@@ -387,9 +394,9 @@ $TOKEN_LINE
 $FP_LINE
 # defaults (líneas comentadas; descomenta para cambiar):
 # NETPULSE_INTERVAL=30              # segundos entre pushes
-# NETPULSE_SCAN_INTERVAL=30m        # min entre scans de vecinos; "0" = sin
-#                                   # scans periódicos (APs con clientes Intel:
-#                                   # cada off-channel gap puede costar un deauth)
+# NETPULSE_SCAN_INTERVAL: "0" = sin scans periódicos (bajo demanda desde
+# "Análisis de canales"); "30m" u otro valor los reactiva.
+$SCAN_LINE
 # NETPULSE_WAN_TARGET=1.1.1.1       # solo si este equipo es el gateway
 # NETPULSE_GW_TARGET=192.168.8.1    # ping al gateway (APs)
 # NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat

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

@@ -177,6 +177,12 @@ type server struct {
 	refreshMu   sync.Mutex
 	lastRefresh time.Time
 
+	// Anti-martilleo del scan bajo demanda del plan de canales (#1561): un
+	// scan por unidad cada planScanMinInterval. El scan saca la radio del
+	// canal, así que varias pestañas no pueden encadenarlos.
+	planScanMu   sync.Mutex
+	lastPlanScan map[string]time.Time
+
 	// Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
 	ingestLimit *ipRateLimit
 

+ 49 - 0
server-go/internal/httpapi/wifi_channelplan.go

@@ -1,7 +1,9 @@
 package httpapi
 
 import (
+	"math"
 	"net/http"
+	"strconv"
 	"strings"
 	"time"
 
@@ -129,6 +131,11 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 	// "refresh" fuerza en el agente un ciclo con ForceScan (el throttle del
 	// intervalo no aplica) y el push siguiente trae los vecinos nuevos a
 	// wifi_scans. Requiere el agente conectado por SSE.
+	//
+	// #1561: este endpoint es el único camino de scan con el default nuevo,
+	// así que lleva su propio anti-martilleo por unidad. Abrir la vista pide
+	// el scan, y sin límite dos pestañas (o dos admins) encadenarían ciclos
+	// sacando la radio del canal, que es justo lo que #1557 reporta.
 	mux.Handle("POST /api/wifi/channel-plan/scan", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		routerID := r.URL.Query().Get("routerId")
 		if routerID == "" {
@@ -140,10 +147,52 @@ func (s *server) registerChannelPlanRoutes(mux *http.ServeMux) {
 			writeError(w, http.StatusServiceUnavailable, "unavailable", "SSE agentHub no configurado")
 			return
 		}
+		if retry, ok := s.claimPlanScan(slug); !ok {
+			w.Header().Set("Retry-After", strconv.Itoa(retry))
+			writeJSON(w, http.StatusTooManyRequests, map[string]any{
+				"error":         "rate_limited",
+				"retryAfterSec": retry,
+			})
+			return
+		}
 		if !s.agentHub.Send(slug, "refresh", map[string]any{}) {
+			// Sin agente conectado el scan no va a ocurrir: se libera el
+			// turno para que el siguiente intento no espere 5 minutos.
+			s.releasePlanScan(slug)
 			writeError(w, http.StatusNotFound, "not_found", "el agente no está conectado por SSE")
 			return
 		}
 		writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
 	})))
 }
+
+// planScanMinInterval: mínimo entre scans bajo demanda de una misma unidad
+// (#1561). Un scan de vecinos tarda 2-4s por radio y saca la radio del canal.
+const planScanMinInterval = 5 * time.Minute
+
+// claimPlanScan reserva el turno de scan de la unidad o devuelve los segundos
+// que faltan para el siguiente. El estado vive en memoria: un reinicio del
+// server solo permite un scan de más.
+func (s *server) claimPlanScan(slug string) (int, bool) {
+	s.planScanMu.Lock()
+	defer s.planScanMu.Unlock()
+	now := time.Now()
+	if s.lastPlanScan == nil {
+		s.lastPlanScan = make(map[string]time.Time, 8)
+	}
+	if last, ok := s.lastPlanScan[slug]; ok {
+		if since := now.Sub(last); since < planScanMinInterval {
+			retry := int(math.Ceil((planScanMinInterval - since).Seconds()))
+			return retry, false
+		}
+	}
+	s.lastPlanScan[slug] = now
+	return 0, true
+}
+
+// releasePlanScan devuelve el turno cuando el scan no llegó a pedirse.
+func (s *server) releasePlanScan(slug string) {
+	s.planScanMu.Lock()
+	delete(s.lastPlanScan, slug)
+	s.planScanMu.Unlock()
+}

+ 53 - 0
server-go/internal/httpapi/wifi_channelplan_throttle_test.go

@@ -0,0 +1,53 @@
+// wifi_channelplan_throttle_test.go — anti-martilleo del scan bajo demanda
+// (#1561). Con el default de scan periódico en 0, abrir "Análisis de canales"
+// es el camino normal para refrescar vecinos, y varias pestañas no deben
+// encadenar ciclos que saquen la radio del canal.
+package httpapi
+
+import (
+	"testing"
+	"time"
+)
+
+func TestClaimPlanScanRateLimits(t *testing.T) {
+	s := &server{}
+
+	retry, ok := s.claimPlanScan("flint2")
+	if !ok || retry != 0 {
+		t.Fatalf("primer scan: ok=%v retry=%d, quería ok=true retry=0", ok, retry)
+	}
+
+	retry, ok = s.claimPlanScan("flint2")
+	if ok {
+		t.Fatal("segundo scan inmediato: quería rechazo")
+	}
+	if retry <= 0 || retry > int(planScanMinInterval.Seconds()) {
+		t.Fatalf("retryAfterSec=%d fuera de (0, %v]", retry, planScanMinInterval.Seconds())
+	}
+
+	// Otra unidad tiene su propio turno.
+	if _, ok := s.claimPlanScan("rt2"); !ok {
+		t.Fatal("otra unidad: quería turno concedido")
+	}
+}
+
+func TestClaimPlanScanAfterInterval(t *testing.T) {
+	s := &server{lastPlanScan: map[string]time.Time{
+		"flint2": time.Now().Add(-planScanMinInterval - time.Second),
+	}}
+	if _, ok := s.claimPlanScan("flint2"); !ok {
+		t.Fatal("pasado el intervalo: quería turno concedido")
+	}
+}
+
+func TestReleasePlanScanFreesTurn(t *testing.T) {
+	s := &server{}
+	if _, ok := s.claimPlanScan("flint2"); !ok {
+		t.Fatal("primer scan: quería turno")
+	}
+	// Send falla (agente sin SSE): liberar para que el reintento no espere.
+	s.releasePlanScan("flint2")
+	if _, ok := s.claimPlanScan("flint2"); !ok {
+		t.Fatal("tras release: quería turno concedido")
+	}
+}

+ 12 - 2
server-go/internal/reinstall/reinstall.go

@@ -110,10 +110,18 @@ chmod 644 ` + caPath + `
 // envRewriteBlock regenera /etc/netpulse-agent.env con las vars gestionadas
 // actuales, conservando las NETPULSE_* del usuario (#851). Usa las vars de
 // entorno del script anfitrión: SERVER, SLUG, TOKEN y SERVER_FP.
+//
+// #1558: el env sale con NETPULSE_SCAN_INTERVAL=0 activo. El scan periódico
+// de vecinos saca la radio del canal y puede tirar clientes sensibles a
+// beacons (#1557); la vista de canales pide el scan bajo demanda (#1561). Un
+// valor que ya esté en el env gana, para no pisar un override manual (#851).
 func envRewriteBlock(targets WanTargets) string {
 	return `USER_VARS=""
+SCAN_VALUE="0"
 if [ -f "$ENV_FILE" ]; then
-	USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET)=') || true
+	prev_scan=$(grep -E '^NETPULSE_SCAN_INTERVAL=' "$ENV_FILE" | tail -n 1) || prev_scan=""
+	if [ -n "$prev_scan" ]; then SCAN_VALUE=${prev_scan#NETPULSE_SCAN_INTERVAL=}; fi
+	USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)=') || true
 fi
 cat > "$ENV_FILE" <<EOF
 # netpulse-agent — config (generado por reinstall)
@@ -122,7 +130,9 @@ NETPULSE_SLUG=$SLUG
 NETPULSE_TOKEN=$TOKEN
 # NETPULSE_SERVER_FP=<sha256>    # pin SPKI del server (https); lo rellena el instalador
 # NETPULSE_INTERVAL=30           # segundos entre pushes
-# NETPULSE_SCAN_INTERVAL=30m     # min entre scans de vecinos; "0" = sin scans periódicos
+# NETPULSE_SCAN_INTERVAL: "0" = sin scans periódicos (bajo demanda desde
+# "Análisis de canales"); "30m" u otro valor los reactiva.
+NETPULSE_SCAN_INTERVAL=$SCAN_VALUE
 ` + func() string {
 		wanLine := "# NETPULSE_WAN_TARGET=1.1.1.1    # solo si este equipo es el gateway"
 		if targets.WanTarget != "" {

+ 82 - 0
server-go/internal/reinstall/scan_default_test.go

@@ -0,0 +1,82 @@
+package reinstall_test
+
+// scan_default_test.go - #1558: the env the reinstall writes must default
+// NETPULSE_SCAN_INTERVAL to 0 and still keep a value the unit already had.
+// These run the generated block with sh instead of matching strings: the
+// value depends on what the remote env file holds.
+
+import (
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+// envBlockForTest extracts the env rewrite block from the reinstall script,
+// the one shared with EnvScript.
+func envBlockForTest(t *testing.T) string {
+	t.Helper()
+	s := scriptForTest()
+	start := strings.Index(s, `USER_VARS=""`)
+	if start < 0 {
+		t.Fatal("no encuentro el bloque de env en el script")
+	}
+	end := strings.Index(s[start:], `chmod 600 "$ENV_FILE"`)
+	if end < 0 {
+		t.Fatal("el bloque de env no termina con chmod")
+	}
+	return s[start : start+end+len(`chmod 600 "$ENV_FILE"`)]
+}
+
+func runEnvBlock(t *testing.T, prev string) string {
+	t.Helper()
+	dir := t.TempDir()
+	envPath := filepath.Join(dir, "netpulse-agent.env")
+	if prev != "" {
+		if err := os.WriteFile(envPath, []byte(prev), 0o600); err != nil {
+			t.Fatal(err)
+		}
+	}
+	script := "ENV_FILE=" + envPath + "\n" +
+		"SERVER=http://192.168.1.226:3000\n" +
+		"SLUG=test-router\n" +
+		"TOKEN=" + strings.Repeat("a1", 32) + "\n" +
+		"SERVER_FP=\n" +
+		envBlockForTest(t) + "\n"
+	if out, err := exec.Command("sh", "-c", script).CombinedOutput(); err != nil {
+		t.Fatalf("el bloque de env falla: %v\n%s", err, out)
+	}
+	data, err := os.ReadFile(envPath)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return string(data)
+}
+
+// TestEnvDefaultsScanOff: sin SCAN_INTERVAL previo, el env sale con 0 activo.
+func TestEnvDefaultsScanOff(t *testing.T) {
+	env := runEnvBlock(t, "")
+	if !strings.Contains(env, "\nNETPULSE_SCAN_INTERVAL=0\n") {
+		t.Fatalf("falta el default 0 activo:\n%s", env)
+	}
+	// Comentado ya no sirve: el agente no lo leería.
+	if strings.Contains(env, "# NETPULSE_SCAN_INTERVAL=30m") {
+		t.Fatalf("el default viejo sigue comentado:\n%s", env)
+	}
+}
+
+// TestEnvKeepsScanOverride: un valor manual sobrevive al reinstall y no se
+// duplica (#851).
+func TestEnvKeepsScanOverride(t *testing.T) {
+	env := runEnvBlock(t, "NETPULSE_SCAN_INTERVAL=45m\nNETPULSE_HEARTBEAT_FILE=/tmp/hb\n")
+	if !strings.Contains(env, "\nNETPULSE_SCAN_INTERVAL=45m\n") {
+		t.Fatalf("override perdido:\n%s", env)
+	}
+	if got := strings.Count(env, "NETPULSE_SCAN_INTERVAL="); got != 1 {
+		t.Fatalf("SCAN_INTERVAL duplicado (%d):\n%s", got, env)
+	}
+	if !strings.Contains(env, "\nNETPULSE_HEARTBEAT_FILE=/tmp/hb\n") {
+		t.Fatalf("var de usuario perdida:\n%s", env)
+	}
+}

+ 3 - 2
server-go/internal/reinstall/script_test.go

@@ -48,7 +48,8 @@ func TestScriptEnvDocumentsDefaults(t *testing.T) {
 	s := scriptForTest()
 	for _, want := range []string{
 		"# NETPULSE_INTERVAL=30",
-		"# NETPULSE_SCAN_INTERVAL=30m",
+		`# NETPULSE_SCAN_INTERVAL: "0" = sin scans periódicos`,
+		"NETPULSE_SCAN_INTERVAL=$SCAN_VALUE",
 		"# NETPULSE_WAN_TARGET=1.1.1.1",
 		"# NETPULSE_GW_TARGET=192.168.8.1",
 		"# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat",
@@ -91,7 +92,7 @@ func TestScriptPreservesUserVars(t *testing.T) {
 	s := scriptForTest()
 	for _, want := range []string{
 		`USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE"`,
-		`grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET)='`,
+		`grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN|WAN_TARGET|GW_TARGET|SCAN_INTERVAL)='`,
 		`printf '%s\n' "$USER_VARS" >> "$ENV_FILE"`,
 	} {
 		if !strings.Contains(s, want) {