Răsfoiți Sursa

feat(channelplan): apply the recommended channel from the plan page (#501)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 luni în urmă
părinte
comite
65ae97311b

+ 12 - 1
agent/probe/local.go

@@ -275,8 +275,19 @@ func (p *Prober) probeWireless(ctx context.Context, full bool) *WirelessData {
 		}
 		if combined == "" {
 			if out := p.runBest(ctx, CmdRadios, 8*time.Second); out != "" {
+				radios := ParseRadios(out)
+				// Sección UCI por banda (#500): habilita aplicar cambios de
+				// canal desde el server. Best-effort: sin uci, sin sección.
+				if secOut := p.runBest(ctx, CmdRadioSections, 5*time.Second); secOut != "" {
+					sections := ParseRadioSections(secOut)
+					for i := range radios {
+						if sec, ok := sections[radios[i].Name]; ok {
+							radios[i].Section = sec
+						}
+					}
+				}
 				p.radiosMu.Lock()
-				p.radiosCache, p.radiosAt = ParseRadios(out), time.Now()
+				p.radiosCache, p.radiosAt = radios, time.Now()
 				wd.Radios = p.radiosCache
 				p.radiosMu.Unlock()
 			}

+ 58 - 0
agent/probe/probe.go

@@ -78,6 +78,9 @@ const (
 	// emite "==IFACE==<iface>" antes de cada scan y parsea BSS/freq/signal/SSID.
 	// Si `iw` no está disponible, la sección Scans queda vacía (best-effort).
 	CmdScan = `for i in $(iw dev 2>/dev/null | awk '/Interface / {print $2}'); do echo "==IFACE==$i"; iw dev "$i" scan 2>/dev/null; done`
+	// CmdRadioSections (#500): secciones wifi-device de UCI con su banda, para
+	// resolver "2.4 GHz" → radio0 (la relación iface→sección no sale de iwinfo).
+	CmdRadioSections = `uci -q show wireless 2>/dev/null | grep -E "=wifi-device$|\.band=|\.hwmode="`
 	// CmdPortStates: "<name> <operstate> <speed>" por interfaz.
 	CmdPortStates = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
 		`echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1)"; done`
@@ -248,6 +251,10 @@ type Radio struct {
 	WidthMhz int     `json:"widthMhz"`
 	PowerDbm float64 `json:"powerDbm"`
 	Clients  int     `json:"clients"`
+	// Section es la sección UCI de la radio ("radio0"), para que el server
+	// pueda construir cambios de canal (uci set wireless.<section>.channel).
+	// Vacía si no se pudo resolver (#500).
+	Section string `json:"section,omitempty"`
 }
 
 // ---------------------------------------------------------------------------
@@ -1107,6 +1114,57 @@ func ParseRadios(out string) []Radio {
 	return radios
 }
 
+// ParseRadioSections parsea la salida de CmdRadioSections y devuelve
+// banda ("2.4 GHz"|"5 GHz"|"6 GHz") → sección UCI ("radio0"). Solo se queda
+// con la primera sección por banda (si hay varias, la primera gana; el
+// channel plan trabaja por banda).
+func ParseRadioSections(out string) map[string]string {
+	sections := map[string]string{}
+	secBand := map[string]string{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, "wireless.") {
+			continue
+		}
+		parts := strings.SplitN(line, "=", 2)
+		if len(parts) != 2 {
+			continue
+		}
+		key := strings.TrimPrefix(parts[0], "wireless.")
+		val := strings.Trim(parts[1], "'")
+		rel, opt, hasOpt := strings.Cut(key, ".")
+		if !hasOpt {
+			if val == "wifi-device" {
+				secBand[rel] = "" // sección conocida, banda pendiente
+			}
+			continue
+		}
+		band, ok := secBand[rel]
+		if !ok || band != "" {
+			continue
+		}
+		switch {
+		case opt == "band" || (opt == "hwmode" && (val == "11g" || val == "11a")):
+			switch {
+			case val == "2g" || val == "11g":
+				secBand[rel] = "2.4 GHz"
+			case val == "5g" || val == "11a":
+				secBand[rel] = "5 GHz"
+			case val == "6g":
+				secBand[rel] = "6 GHz"
+			}
+		}
+	}
+	for sec, band := range secBand {
+		if band != "" {
+			if _, exists := sections[band]; !exists {
+				sections[band] = sec
+			}
+		}
+	}
+	return sections
+}
+
 // ParseScan parsea la salida de CmdScan: bloques "==IFACE==<iface>" seguidos de
 // la salida de `iw dev <iface> scan`. Extrae BSS, freq, signal y SSID.
 func ParseScan(out string) []ScanResult {

+ 41 - 0
agent/probe/probe_test.go

@@ -937,3 +937,44 @@ func TestBoardInfoParsesASUFields(t *testing.T) {
 		t.Errorf("campos básicos corruptos: %+v", b)
 	}
 }
+
+func TestParseRadioSections(t *testing.T) {
+	out := `wireless.radio0=wifi-device
+wireless.radio0.type='mac80211'
+wireless.radio0.band='2g'
+wireless.radio0.channel='1'
+wireless.default_radio0=wifi-iface
+wireless.radio1=wifi-device
+wireless.radio1.band='5g'
+wireless.radio1.channel='44'
+wireless.default_radio1=wifi-iface
+`
+	got := ParseRadioSections(out)
+	if len(got) != 2 {
+		t.Fatalf("want 2 sections, got %d: %v", len(got), got)
+	}
+	if got["2.4 GHz"] != "radio0" || got["5 GHz"] != "radio1" {
+		t.Errorf("wrong mapping: %v", got)
+	}
+}
+
+func TestParseRadioSectionsLegacyHwmode(t *testing.T) {
+	out := `wireless.wifi0=wifi-device
+wireless.wifi0.hwmode='11g'
+wireless.wifi1=wifi-device
+wireless.wifi1.hwmode='11a'
+`
+	got := ParseRadioSections(out)
+	if got["2.4 GHz"] != "wifi0" || got["5 GHz"] != "wifi1" {
+		t.Errorf("wrong legacy hwmode mapping: %v", got)
+	}
+}
+
+func TestParseRadioSectionsEmpty(t *testing.T) {
+	if got := ParseRadioSections(""); len(got) != 0 {
+		t.Errorf("want empty map, got %v", got)
+	}
+	if got := ParseRadioSections("network.lan=interface\n"); len(got) != 0 {
+		t.Errorf("want empty map for unrelated config, got %v", got)
+	}
+}

+ 38 - 3
agent/runtime/helpers.go

@@ -4,6 +4,7 @@ package runtime
 import (
 	"bytes"
 	"encoding/json"
+	"fmt"
 	"net/http"
 	"time"
 
@@ -25,17 +26,51 @@ func postJSON(opts Options, transport http.RoundTripper, path string, body any)
 	if err != nil {
 		return
 	}
+	if err := postJSONBytes(opts, transport, path, payload); err != nil {
+		opts.logger().Warn("[netpulse-agent] POST falló", "path", path, "err", err)
+	}
+}
+
+// postJSONBytes hace el POST y devuelve el error de transporte/estado.
+func postJSONBytes(opts Options, transport http.RoundTripper, path string, payload []byte) error {
 	req, err := http.NewRequest("POST", opts.Server+path, bytes.NewReader(payload))
 	if err != nil {
-		return
+		return err
 	}
 	req.Header.Set("Content-Type", "application/json")
 	req.Header.Set("Authorization", "Bearer "+opts.Token)
 	hc := &http.Client{Transport: transport, Timeout: 10 * time.Second}
 	resp, err := hc.Do(req)
 	if err != nil {
-		opts.logger().Warn("[netpulse-agent] POST falló", "path", path, "err", err)
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode >= 300 {
+		return fmt.Errorf("status %d", resp.StatusCode)
+	}
+	return nil
+}
+
+// postJSONWithRetry reintenta un POST crítico con backoff. Para el
+// apply-result: un plan cuyo resultado no se reporta queda "applying" para
+// siempre en el server, y aplicar ops como `service network restart` corta
+// la red del propio agente justo cuando toca reportar (#500). Corre en
+// goroutine: no bloquea el stream SSE.
+func postJSONWithRetry(opts Options, transport http.RoundTripper, path string, body any, what string) {
+	payload, err := json.Marshal(body)
+	if err != nil {
 		return
 	}
-	resp.Body.Close()
+	go func() {
+		backoff := []time.Duration{2 * time.Second, 5 * time.Second, 10 * time.Second, 20 * time.Second, 40 * time.Second,
+			time.Minute, time.Minute, time.Minute, time.Minute, time.Minute}
+		for i, wait := range backoff {
+			if err := postJSONBytes(opts, transport, path, payload); err == nil {
+				return
+			}
+			opts.logger().Warn("[netpulse-agent] "+what+" falló, reintentando", "intento", i+1, "espera", wait.String())
+			time.Sleep(wait)
+		}
+		opts.logger().Error("[netpulse-agent] " + what + " no reportado tras reintentos")
+	}()
 }

+ 2 - 2
agent/runtime/runtime.go

@@ -291,8 +291,8 @@ func (a *agent) handleApply(ex *executor.Executor, transport http.RoundTripper,
 		a.log.Info("[netpulse-agent] apply ejecutado por agente", "plan_id", payload.PlanID, "status", result.Status, "ms", result.DurationMs)
 	}
 
-	postJSON(a.opts, transport, "/api/agents/"+a.opts.Slug+"/apply-result",
-		map[string]any{"planId": payload.PlanID, "result": result})
+	postJSONWithRetry(a.opts, transport, "/api/agents/"+a.opts.Slug+"/apply-result",
+		map[string]any{"planId": payload.PlanID, "result": result}, "apply-result")
 }
 
 func (o Options) logger() *slog.Logger {

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

@@ -1371,6 +1371,18 @@
     "noScans": "No recent scans. Enable the agent on a router to collect neighbors.",
     "noRadios": "This router does not report WiFi radios.",
     "apply": "Apply channel",
+    "gateway": " (Gateway)",
+    "signal": "Signal",
+    "score": "Score",
+    "updateAgent": "Update the router's agent to apply channels.",
+    "applyingState": "Applying…",
+    "appliedState": "Channel applied",
+    "failedState": "Could not apply",
+    "revertTo": "Back to {{ch}}",
+    "timeout": "No response from the plan (timeout)",
+    "applyConfirmTitle": "Change the {{band}} channel",
+    "applyConfirmBody": "The {{band}} channel will move from {{from}} to {{to}}. That router's network restarts for a few seconds and its WiFi clients will reconnect. The change is recorded as a plan and you can go back to the previous channel with one click.",
+    "applyConfirmAction": "Apply",
     "scanInfo": "Scans from the last 24 hours"
   },
   "firmwareUpgrades": {

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

@@ -1371,6 +1371,18 @@
     "noScans": "No hay scans recientes. Activa el agente en un router para recoger vecinos.",
     "noRadios": "Este dispositivo no reporta radios WiFi.",
     "apply": "Aplicar canal",
+    "gateway": " (Puerta de enlace)",
+    "signal": "Señal",
+    "score": "Puntuación",
+    "updateAgent": "Actualiza el agente del router para poder aplicar el canal.",
+    "applyingState": "Aplicando…",
+    "appliedState": "Canal aplicado",
+    "failedState": "No se pudo aplicar",
+    "revertTo": "Volver al {{ch}}",
+    "timeout": "Sin respuesta del plan (tiempo agotado)",
+    "applyConfirmTitle": "Cambiar el canal de {{band}}",
+    "applyConfirmBody": "El canal de {{band}} pasará de {{from}} a {{to}}. La red de ese router se reiniciará unos segundos y sus clientes WiFi se reconectarán. El cambio queda registrado como plan y podrás volver al canal anterior con un clic.",
+    "applyConfirmAction": "Aplicar",
     "scanInfo": "Scans de las últimas 24 h"
   },
   "firmwareUpgrades": {

+ 210 - 31
app/src/pages/ChannelPlan.tsx

@@ -1,8 +1,19 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNetPulse } from '@/data/DataProvider'
-import { Signal, Radio as RadioIcon, AlertCircle } from 'lucide-react'
+import { Signal, Radio as RadioIcon, AlertCircle, CheckCircle2, Loader2 } from 'lucide-react'
 import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
 
 interface Scan {
   iface: string
@@ -16,6 +27,7 @@ interface Scan {
 
 interface RadioRec {
   iface: string
+  section?: string
   name: string
   channel: number
   widthMhz: number
@@ -30,6 +42,13 @@ interface ChannelPlanData {
   scans: Scan[]
 }
 
+interface RadioApplyState {
+  busy: boolean
+  status?: 'applied' | 'failed'
+  error?: string
+  prevChannel?: number
+}
+
 function bandFromFreq(freq: number): string {
   if (freq >= 2412 && freq <= 2484) return '2.4 GHz'
   if (freq >= 5180 && freq <= 5885) return '5 GHz'
@@ -44,6 +63,9 @@ export default function ChannelPlan() {
   const [data, setData] = useState<ChannelPlanData | null>(null)
   const [loading, setLoading] = useState(false)
   const [error, setError] = useState('')
+  const [applyState, setApplyState] = useState<Record<string, RadioApplyState>>({})
+  const [confirmTarget, setConfirmTarget] = useState<RadioRec | null>(null)
+  const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null)
 
   const sortedRouters = useMemo(() => {
     return [...routers].sort((a, b) => (a.roleBadge === 'Principal' ? -1 : 1) || a.name.localeCompare(b.name))
@@ -55,11 +77,10 @@ export default function ChannelPlan() {
     }
   }, [sortedRouters, routerId])
 
-  useEffect(() => {
-    if (!routerId) return
+  const loadPlan = useCallback((rid: string) => {
     setLoading(true)
     setError('')
-    fetch(`/api/wifi/channel-plan?routerId=${encodeURIComponent(routerId)}`)
+    fetch(`/api/wifi/channel-plan?routerId=${encodeURIComponent(rid)}`)
       .then(async (res) => {
         if (!res.ok) throw new Error(await res.text())
         return res.json()
@@ -67,7 +88,96 @@ export default function ChannelPlan() {
       .then((d) => setData({ ...d, radios: d.radios ?? [], scans: d.scans ?? [] }))
       .catch((e) => setError(String(e)))
       .finally(() => setLoading(false))
-  }, [routerId])
+  }, [])
+
+  useEffect(() => {
+    if (!routerId) return
+    loadPlan(routerId)
+  }, [routerId, loadPlan])
+
+  useEffect(() => {
+    return () => {
+      if (pollTimer.current) clearInterval(pollTimer.current)
+    }
+  }, [])
+
+  const radioKey = (r: RadioRec) => r.section || r.name
+
+  const applyChannel = useCallback(
+    (r: RadioRec, target: number, prevChannel: number) => {
+      const key = radioKey(r)
+      setApplyState((s) => ({ ...s, [key]: { busy: true } }))
+      const ops = [
+        {
+          kind: 'uci_set',
+          args: { config: 'wireless', section: r.section, option: 'channel', value: String(target) },
+          desc: `channel ${r.section} -> ${target}`,
+        },
+        { kind: 'uci_commit', args: { config: 'wireless' }, desc: 'commit wireless' },
+        { kind: 'service', args: { name: 'network', action: 'restart' }, desc: 'reload network' },
+      ]
+      const fail = (err: string) => {
+        if (pollTimer.current) clearInterval(pollTimer.current)
+        pollTimer.current = null
+        setApplyState((s) => ({ ...s, [key]: { busy: false, status: 'failed', error: err } }))
+      }
+      fetch('/api/plans', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ routerId, resource: 'wireless', diff: ops }),
+      })
+        .then(async (res) => {
+          if (!res.ok) throw new Error(await res.text())
+          return res.json()
+        })
+        .then((plan) =>
+          fetch(`/api/plans/${plan.id}/apply`, { method: 'POST' }).then(async (res) => {
+            if (!res.ok) throw new Error(await res.text())
+          }).then(() => plan),
+        )
+        .then((plan) => {
+          let ticks = 0
+          pollTimer.current = setInterval(() => {
+            ticks++
+            if (ticks > 60) return fail(t('channelPlan.timeout'))
+            fetch(`/api/plans/${plan.id}`)
+              .then(async (res) => {
+                if (!res.ok) throw new Error(await res.text())
+                return res.json()
+              })
+              .then((p: { status?: string; result?: { error?: string } }) => {
+                if (p.status === 'applied') {
+                  if (pollTimer.current) clearInterval(pollTimer.current)
+                  pollTimer.current = null
+                  setApplyState((s) => ({ ...s, [key]: { busy: false, status: 'applied', prevChannel } }))
+                  loadPlan(routerId)
+                } else if (p.status === 'failed' || p.status === 'rolled_back') {
+                  fail(p.result?.error || t('channelPlan.failedState'))
+                }
+              })
+              .catch((e) => fail(String(e)))
+          }, 3000)
+        })
+        .catch((e) => fail(String(e)))
+    },
+    [routerId, loadPlan, t],
+  )
+
+  const onConfirmApply = () => {
+    if (!confirmTarget) return
+    const r = confirmTarget
+    setConfirmTarget(null)
+    if (r.recommended > 0 && r.recommended !== r.channel) {
+      applyChannel(r, r.recommended, r.channel)
+    }
+  }
+
+  const onRevert = (r: RadioRec) => {
+    const key = radioKey(r)
+    const prev = applyState[key]?.prevChannel
+    if (!prev) return
+    applyChannel(r, prev, r.channel)
+  }
 
   return (
     <div className="space-y-4 md:space-y-5">
@@ -81,12 +191,16 @@ export default function ChannelPlan() {
           <span className="text-caption font-medium text-text-secondary">{t('channelPlan.router')}</span>
           <select
             value={routerId}
-            onChange={(e) => setRouterId(e.target.value)}
+            onChange={(e) => {
+              setApplyState({})
+              setRouterId(e.target.value)
+            }}
             className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
           >
             {sortedRouters.map((r) => (
               <option key={r.id} value={r.id}>
-                {r.name}{r.roleBadge === 'Principal' ? ' (Gateway)' : ''}
+                {r.name}
+                {r.roleBadge === 'Principal' ? ` ${t('channelPlan.gateway')}` : ''}
               </option>
             ))}
           </select>
@@ -114,32 +228,78 @@ export default function ChannelPlan() {
             </div>
           ) : (
             <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
-              {data.radios.map((r, idx) => (
-                <div
-                  key={idx}
-                  className={cn(
-                    'rounded-2xl border border-border bg-surface p-5',
-                    r.recommended !== r.channel && r.recommended > 0 && 'border-accent/40'
-                  )}
-                >
-                  <div className="mb-3 flex items-center gap-2">
-                    <RadioIcon className="h-4 w-4 text-accent" strokeWidth={1.75} />
-                    <h3 className="text-sm font-semibold text-text-primary">{r.name}</h3>
-                  </div>
-                  <div className="grid grid-cols-2 gap-4">
-                    <div>
-                      <div className="text-caption text-text-muted">{t('channelPlan.currentChannel')}</div>
-                      <div className="text-2xl font-bold text-text-primary">{r.channel}</div>
+              {data.radios.map((r, idx) => {
+                const key = radioKey(r)
+                const st: RadioApplyState = applyState[key] ?? { busy: false }
+                const canApply = !!r.section && r.recommended > 0 && r.recommended !== r.channel && !st.busy
+                const showScore = r.bestScore > 0 && r.currentScore > 0 && r.currentScore < 900000
+                return (
+                  <div
+                    key={idx}
+                    className={cn(
+                      'rounded-2xl border border-border bg-surface p-5',
+                      r.recommended !== r.channel && r.recommended > 0 && 'border-accent/40',
+                    )}
+                  >
+                    <div className="mb-3 flex items-center justify-between gap-2">
+                      <div className="flex items-center gap-2">
+                        <RadioIcon className="h-4 w-4 text-accent" strokeWidth={1.75} />
+                        <h3 className="text-sm font-semibold text-text-primary">{r.name}</h3>
+                      </div>
+                      {showScore && (
+                        <span className="text-caption text-text-muted">
+                          {t('channelPlan.score')}: {r.currentScore} → {r.bestScore}
+                        </span>
+                      )}
                     </div>
-                    <div>
-                      <div className="text-caption text-text-muted">{t('channelPlan.recommendedChannel')}</div>
-                      <div className={cn('text-2xl font-bold', r.recommended === r.channel ? 'text-text-primary' : 'text-accent')}>
-                        {r.recommended > 0 ? r.recommended : '-'}
+                    <div className="grid grid-cols-2 gap-4">
+                      <div>
+                        <div className="text-caption text-text-muted">{t('channelPlan.currentChannel')}</div>
+                        <div className="text-2xl font-bold text-text-primary">{r.channel}</div>
+                      </div>
+                      <div>
+                        <div className="text-caption text-text-muted">{t('channelPlan.recommendedChannel')}</div>
+                        <div className={cn('text-2xl font-bold', r.recommended === r.channel ? 'text-text-primary' : 'text-accent')}>
+                          {r.recommended > 0 ? r.recommended : '-'}
+                        </div>
                       </div>
                     </div>
+                    <div className="mt-4 flex flex-wrap items-center gap-2">
+                      {canApply ? (
+                        <Button size="sm" onClick={() => setConfirmTarget(r)}>
+                          {t('channelPlan.apply')}
+                        </Button>
+                      ) : r.recommended > 0 && r.recommended !== r.channel && !r.section ? (
+                        <span className="text-caption text-text-muted">{t('channelPlan.updateAgent')}</span>
+                      ) : null}
+                      {st.busy && (
+                        <span className="inline-flex items-center gap-1.5 text-caption text-text-secondary">
+                          <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+                          {t('channelPlan.applyingState')}
+                        </span>
+                      )}
+                      {st.status === 'applied' && st.prevChannel && (
+                        <>
+                          <span className="inline-flex items-center gap-1.5 text-caption text-emerald-600 dark:text-emerald-400">
+                            <CheckCircle2 className="h-3.5 w-3.5" strokeWidth={1.75} />
+                            {t('channelPlan.appliedState')}
+                          </span>
+                          <Button size="sm" variant="outline" disabled={st.busy} onClick={() => onRevert(r)}>
+                            {t('channelPlan.revertTo', { ch: st.prevChannel })}
+                          </Button>
+                        </>
+                      )}
+                      {st.status === 'failed' && (
+                        <span className="inline-flex items-center gap-1.5 text-caption text-rose-600 dark:text-rose-400">
+                          <AlertCircle className="h-3.5 w-3.5" strokeWidth={1.75} />
+                          {t('channelPlan.failedState')}
+                          {st.error ? `: ${st.error}` : ''}
+                        </span>
+                      )}
+                    </div>
                   </div>
-                </div>
-              ))}
+                )
+              })}
             </div>
           )}
 
@@ -156,7 +316,7 @@ export default function ChannelPlan() {
                       <th className="py-2 pr-4">BSSID</th>
                       <th className="py-2 pr-4">{t('channelPlan.band')}</th>
                       <th className="py-2 pr-4">{t('channelPlan.currentChannel')}</th>
-                      <th className="py-2 pr-4">Signal</th>
+                      <th className="py-2 pr-4">{t('channelPlan.signal')}</th>
                     </tr>
                   </thead>
                   <tbody className="text-text-primary">
@@ -181,6 +341,25 @@ export default function ChannelPlan() {
           </div>
         </>
       )}
+
+      <AlertDialog open={!!confirmTarget} onOpenChange={(open) => !open && setConfirmTarget(null)}>
+        <AlertDialogContent className="max-w-lg">
+          <AlertDialogHeader>
+            <AlertDialogTitle>{t('channelPlan.applyConfirmTitle', { band: confirmTarget?.name ?? '' })}</AlertDialogTitle>
+            <AlertDialogDescription>
+              {t('channelPlan.applyConfirmBody', {
+                band: confirmTarget?.name ?? '',
+                from: confirmTarget?.channel ?? 0,
+                to: confirmTarget?.recommended ?? 0,
+              })}
+            </AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
+            <AlertDialogAction onClick={onConfirmApply}>{t('channelPlan.applyConfirmAction')}</AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
     </div>
   )
 }

+ 8 - 1
server-go/internal/channelplan/store.go

@@ -112,6 +112,9 @@ type Radio struct {
 	Recommended  int    `json:"recommended"` // canal recomendado; 0 = sin datos
 	CurrentScore int    `json:"currentScore"`
 	BestScore    int    `json:"bestScore"`
+	// Section es la sección UCI de la radio ("radio0") reportada por el
+	// agente (#500); vacía con agentes antiguos (la UI deshabilita apply).
+	Section string `json:"section,omitempty"`
 }
 
 // Recommend recibe el estado wireless del router (radios propias) y devuelve
@@ -140,10 +143,14 @@ func (s *Store) Recommend(routerID string, radios []probe.Radio, within time.Dur
 			freq = bandCenter(band, r.Channel)
 		}
 		rec := Radio{
-			Iface:    ifaceForBand(band), // placeholder; el agente no reporta iface por radio
+			Iface:    r.Section, // sección real si el agente la reporta (#500)
 			Name:     r.Name,
 			Channel:  r.Channel,
 			WidthMhz: r.WidthMhz,
+			Section:  r.Section,
+		}
+		if rec.Iface == "" {
+			rec.Iface = ifaceForBand(band) // placeholder; el agente no reporta iface por radio
 		}
 		candidates := candidateChannels(band)
 		bestCh, bestScore := 0, math.MaxInt

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

@@ -150,3 +150,41 @@ func TestPrune(t *testing.T) {
 		t.Fatalf("esperaba 0 tras prune, got %d", len(got))
 	}
 }
+
+func TestRecommendPasaSeccion(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)
+	radios := []probe.Radio{
+		{Name: "2.4 GHz", Channel: 1, WidthMhz: 20, Section: "radio0"},
+		{Name: "5 GHz", Channel: 44, 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))
+	}
+	var sec, nosec *channelplan.Radio
+	for i := range recs {
+		if recs[i].Section != "" {
+			sec = &recs[i]
+		} else {
+			nosec = &recs[i]
+		}
+	}
+	if sec == nil || nosec == nil {
+		t.Fatalf("esperaba una radio con sección y otra sin: %+v", recs)
+	}
+	if sec.Section != "radio0" || sec.Iface != "radio0" {
+		t.Errorf("la sección no pasa al plan: %+v", *sec)
+	}
+	if nosec.Iface == "" {
+		t.Errorf("sin sección el iface debe caer al placeholder: %+v", *nosec)
+	}
+}

+ 64 - 0
server-go/internal/httpapi/orchestr_plans_body_test.go

@@ -0,0 +1,64 @@
+package httpapi_test
+
+import (
+	"encoding/json"
+	"net/http"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/executor"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+)
+
+// TestPlansCreateRespondsWithBody (#500): el POST /api/plans con diff
+// explícito debe devolver el plan serializado (se vio un 201 con body vacío
+// en producción que rompía a los clientes JSON).
+func TestPlansCreateRespondsWithBody(t *testing.T) {
+	ts := makeTestServer(t)
+	defer ts.Close()
+	cookie := adminCookie(t, ts)
+
+	body := `{"routerId":"rt-test","resource":"wireless","diff":[{"kind":"uci_set","args":{"config":"wireless","section":"radio1","option":"channel","value":"1"},"desc":"channel"}]}`
+	req, _ := http.NewRequest("POST", ts.URL+"/api/plans", strings.NewReader(body))
+	req.Header.Set("Cookie", "session="+cookie)
+	req.Header.Set("Content-Type", "application/json")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("post plans: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusCreated {
+		t.Fatalf("expected 201, got %d", res.StatusCode)
+	}
+	var plan map[string]any
+	if err := json.NewDecoder(res.Body).Decode(&plan); err != nil {
+		t.Fatalf("response body is not JSON (regression: empty body): %v", err)
+	}
+	if plan["id"] == nil || plan["status"] != "pending" {
+		t.Fatalf("unexpected plan body: %+v", plan)
+	}
+}
+
+// TestPlanMarshalDirect aísla el problema de serialización: un Plan con el
+// diff que manda la UI del channel plan debe serializar sin error.
+func TestPlanMarshalDirect(t *testing.T) {
+	p := orchestr.Plan{
+		ID:       "p1",
+		RouterID: "rt2",
+		Resource: "wireless",
+		Diff: []executor.Op{
+			{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": "radio1", "option": "channel", "value": "1"}, Desc: "channel radio1 -> 1"},
+			{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "commit"},
+			{Kind: "service", Args: map[string]string{"name": "network", "action": "restart"}, Desc: "reload"},
+		},
+		Status:    "pending",
+		CreatedBy: "admin",
+		CreatedAt: time.Now().UnixMilli(),
+	}
+	b, err := json.Marshal(p)
+	if err != nil {
+		t.Fatalf("marshal plan: %v", err)
+	}
+	t.Logf("plan json: %.200s", b)
+}

+ 5 - 1
server-go/internal/httpapi/server.go

@@ -476,7 +476,11 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
 	var buf bytes.Buffer
 	enc := json.NewEncoder(&buf)
 	enc.SetEscapeHTML(false)
-	_ = enc.Encode(v)
+	if err := enc.Encode(v); err != nil {
+		// Nunca silenciar: un marshal roto dejaría la respuesta sin body
+		// (201 con Content-Length 0 que rompe a los clientes JSON).
+		log.Printf("[netpulse] writeJSON encode error (status %d, %T): %v", status, v, err)
+	}
 	w.Header().Set("Content-Type", "application/json")
 	w.WriteHeader(status)
 	_, _ = w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))

+ 6 - 1
server-go/internal/orchestr/orchestr.go

@@ -79,7 +79,12 @@ func (m *Manager) GetPlan(id string) (*Plan, error) {
 	if err != nil {
 		return nil, err
 	}
-	p.Desired = json.RawMessage(desired)
+	// desired vacío en BD → nil (json.RawMessage("") revienta al serializar
+	// con toolchains recientes: MarshalJSON de un documento vacío es error y
+	// el POST /api/plans respondía 201 sin body).
+	if desired != "" {
+		p.Desired = json.RawMessage(desired)
+	}
 	json.Unmarshal([]byte(diffJSON), &p.Diff)
 	p.Status = status
 	p.CreatedBy = createdBy