Selaa lähdekoodia

fix: links table parents, dialog polish, auto speedtest schedule (#1067)

* fix(topology): name the dist node as uplink parent in the links table (#1063)

The backhauls table hardcoded the gateway as column A for every uplink
row, but the server semantics anchor uplinks to a dist node when the FDB
evidence says so. Resolve the parent name from sem.links (router or dist
node, name/ip/id), falling back to the gateway when there is no
semantics or no match, keeping demo behavior unchanged.

* fix(settings): collapse long config dialog hints into InfoTips (#1064)

The WAN speedtest dialog rendered the alertPct explanation as an
always-visible paragraph. Move it into the existing click-to-reveal
InfoTip next to the field label, and audit the other config dialogs
(ntfy, Telegram, Proxmox, AdGuard, MQTT): their long hints already live
in InfoTips, so no further conversion was needed. Reuses existing i18n
keys, no new text.

* fix(settings): close config dialogs on successful save (#1065)

Saving from the WAN speedtest config dialog left it open, and the same
happened with the ntfy, Telegram and MQTT dialogs. Close the containing
dialog when the save succeeds (the parent toast already confirms it);
failed saves keep the dialog open with the error. Proxmox and AdGuard
already close their editing form on success; wrapping their onSaved
closes the containing dialog too, and the WireGuard section has no save
dialog.

* feat(speedtest): auto schedule at the quietest traffic hour (#1066)

Add an "auto" scheduleKind: the scheduler picks the hour of day with
the lowest average traffic (down+up) from its own metrics history over
the last 7 days, falling back to 03:00 when there is no data, and
re-evaluates it on each tick. The default scheduled time moves from
01:00 to 03:00. Status exposes the chosen hour and the settings UI gets
an "auto" option with a read-only time field. Interval/weekly/monthly
behavior is unchanged.
Nacho 2 kuukautta sitten
vanhempi
sitoutus
73c614641e

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

@@ -1697,6 +1697,7 @@
       "lastResult": "Last test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "Not available in this mode",
       "kindInterval": "Every N hours",
+      "kindAuto": "Automatic (quietest hour)",
       "kindWeekly": "Weekly (day and time)",
       "kindMonthly": "Monthly (day and time)",
       "everyLabel": "Every:",

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

@@ -1697,6 +1697,7 @@
       "lastResult": "Último test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "No disponible en este modo",
       "kindInterval": "Cada N horas",
+      "kindAuto": "Automático (hora de menos tráfico)",
       "kindWeekly": "Semanal (día y hora)",
       "kindMonthly": "Mensual (día y hora)",
       "everyLabel": "Cada:",

+ 22 - 1
app/src/components/topology/model.ts

@@ -1556,6 +1556,27 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     return mbps >= 1000 ? `${(mbps / 1000).toFixed(mbps % 1000 === 0 ? 0 : 1)} Gbps` : `${mbps} Mbps`
   }
   const backhauls: BackhaulRow[] = []
+  // #1063: la columna A de un uplink debe nombrar al padre REAL que dice la
+  // semántica server-side (sem.links kind 'uplink': from = id de router o de
+  // distnode, p. ej. el padre aprendido por FDB #1047/#1060), no siempre el
+  // gateway. Sin semántica o sin match → gateway (comportamiento de siempre,
+  // demo incluido).
+  const uplinkFromByNodeId = new Map<string, string>()
+  if (sem) {
+    for (const sl of sem.links) {
+      if (sl.kind === 'uplink') uplinkFromByNodeId.set(sl.to, sl.from)
+    }
+  }
+  const uplinkParentName = (nodeId: string): string => {
+    const fromId = uplinkFromByNodeId.get(nodeId)
+    if (fromId) {
+      const rn = routerById.get(fromId)
+      if (rn) return rn.router.name
+      const dn = distById.get(fromId) ?? distNodes.find((n) => n.id === fromId)?.node
+      if (dn) return dn.name ?? dn.ip ?? dn.id
+    }
+    return gatewayNode?.router.name ?? ''
+  }
   if (gatewayNode) {
     backhauls.push({
       id: 'wan', a: gatewayNode.router.name, b: 'Internet', kind: 'wan',
@@ -1567,7 +1588,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   for (const node of apNodes) {
     const isWifi = node.router.backhaul === 'wifi'
     backhauls.push({
-      id: `uplink-${node.id}`, a: gatewayNode?.router.name ?? '', b: node.router.name, kind: 'uplink',
+      id: `uplink-${node.id}`, a: uplinkParentName(node.id), b: node.router.name, kind: 'uplink',
       type: isWifi ? 'topology.links.wifiUplink' : 'common.cable',
       // El contrato no trae ni tasa PHY ni señal del backhaul de un AP, así
       // que no se afirma ninguna. El tono sí es información real: un enlace

+ 57 - 14
app/src/pages/Settings.tsx

@@ -3189,10 +3189,14 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
   // endpoint HTTP libre cuya URL completa escribe el usuario) + ndt (#1037,
   // M-Lab NDT con autodetección de servidor).
   const [provider, setProvider] = useState<'ookla' | 'cloudflare' | 'librespeed' | 'custom' | 'ndt'>('ndt')
-  const [scheduleKind, setScheduleKind] = useState<'interval' | 'weekly' | 'monthly'>('interval')
+  const [scheduleKind, setScheduleKind] = useState<'interval' | 'auto' | 'weekly' | 'monthly'>('interval')
   const [dayOfWeek, setDayOfWeek] = useState(1)
   const [dayOfMonth, setDayOfMonth] = useState(1)
-  const [schedTime, setSchedTime] = useState('01:00')
+  // Hora por defecto 03:00 (#1066): valle típico del tráfico residencial.
+  const [schedTime, setSchedTime] = useState('03:00')
+  // #1066: con kind "auto" la hora la elige el server (la de menos tráfico
+  // de su histórico) y la expone en /status: el UI la muestra solo lectura.
+  const [autoTime, setAutoTime] = useState('')
   const [busy, setBusy] = useState(false)
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState<string | null>(null)
@@ -3218,7 +3222,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
         // Migración visual de los "semanal/mensual" históricos (#744):
         // 168h/720h sin scheduleKind pasan a weekly/monthly con día y hora.
         const kind = typeof d.scheduleKind === 'string' ? d.scheduleKind : ''
-        if (kind === 'weekly' || kind === 'monthly') {
+        if (kind === 'interval' || kind === 'auto' || kind === 'weekly' || kind === 'monthly') {
           setScheduleKind(kind)
         } else if (d.intervalHours === 168) {
           setScheduleKind('weekly')
@@ -3238,6 +3242,22 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     }
   }, [])
 
+  // #1066: la hora elegida por kind "auto" la calcula el server; se lee al
+  // abrir el diálogo y se refresca al cambiar a "auto".
+  useEffect(() => {
+    if (scheduleKind !== 'auto') return
+    let alive = true
+    void fetch('/api/speedtest/status')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (alive && d && typeof d.autoTime === 'string' && d.autoTime) setAutoTime(d.autoTime)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [scheduleKind, cfgOpen])
+
   const bodyJson = useCallback(
     () => ({
       enabled,
@@ -3248,7 +3268,8 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       scheduleKind,
       ...(scheduleKind === 'weekly' ? { dayOfWeek } : {}),
       ...(scheduleKind === 'monthly' ? { dayOfMonth } : {}),
-      ...(scheduleKind !== 'interval' ? { time: schedTime } : {}),
+      // "auto" no envía time: la hora la deriva el server del histórico.
+      ...(scheduleKind === 'weekly' || scheduleKind === 'monthly' ? { time: schedTime } : {}),
     }),
     [enabled, intervalHours, serverUrl, provider, alertPct, scheduleKind, dayOfWeek, dayOfMonth, schedTime],
   )
@@ -3295,7 +3316,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       setError(t('settings.speedtest.invalid'))
       return
     }
-    if (scheduleKind !== 'interval' && !/^\d{2}:\d{2}$/.test(schedTime)) {
+    if ((scheduleKind === 'weekly' || scheduleKind === 'monthly') && !/^\d{2}:\d{2}$/.test(schedTime)) {
       setError(t('settings.speedtest.invalidSchedule'))
       return
     }
@@ -3319,6 +3340,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       setSaved(true)
       window.setTimeout(() => setSaved(false), 2000)
       onSaved()
+      setCfgOpen(false) // #1065: guardar con éxito cierra el diálogo
     } finally {
       setBusy(false)
     }
@@ -3434,12 +3456,13 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           </span>
           <select
             value={scheduleKind}
-            onChange={(e) => setScheduleKind(e.target.value as 'interval' | 'weekly' | 'monthly')}
+            onChange={(e) => setScheduleKind(e.target.value as 'interval' | 'auto' | 'weekly' | 'monthly')}
             disabled={disabled || loading}
             aria-label={t('settings.speedtest.interval')}
             className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
           >
             <option value="interval">{t('settings.speedtest.kindInterval')}</option>
+            <option value="auto">{t('settings.speedtest.kindAuto')}</option>
             <option value="weekly">{t('settings.speedtest.kindWeekly')}</option>
             <option value="monthly">{t('settings.speedtest.kindMonthly')}</option>
           </select>
@@ -3459,6 +3482,19 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
               ))}
             </select>
           </label>
+        ) : scheduleKind === 'auto' ? (
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.timeLabel')}</span>
+            <input
+              type="time"
+              value={autoTime}
+              readOnly
+              disabled={disabled || loading}
+              aria-label={t('settings.speedtest.timeLabel')}
+              title={t('settings.speedtest.kindAuto')}
+              className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-muted focus:outline-none"
+            />
+          </label>
         ) : (
           <label className="block">
             <span className="text-label uppercase text-text-muted">{t('settings.speedtest.dayLabel')}</span>
@@ -3492,6 +3528,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       </div>
       {scheduleKind !== 'interval' && (
         <div className="flex flex-wrap items-end gap-3">
+          {(scheduleKind === 'weekly' || scheduleKind === 'monthly') && (
           <label className="block max-w-[220px]">
             <span className="text-label uppercase text-text-muted">{t('settings.speedtest.timeLabel')}</span>
             <input
@@ -3503,8 +3540,12 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
               className="mt-1 w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
             />
           </label>
+          )}
           <label className="block max-w-[160px]">
-            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
+            <span className="flex items-center gap-1 text-label uppercase text-text-muted">
+              {t('settings.speedtest.alertPctLabel')}
+              <InfoTip text={t('settings.speedtest.alertPctHint')} />
+            </span>
             <input
               type="text"
               inputMode="numeric"
@@ -3519,7 +3560,10 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       )}
       {scheduleKind === 'interval' && (
         <label className="block max-w-[160px]">
-          <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
+          <span className="flex items-center gap-1 text-label uppercase text-text-muted">
+            {t('settings.speedtest.alertPctLabel')}
+            <InfoTip text={t('settings.speedtest.alertPctHint')} />
+          </span>
           <input
             type="text"
             inputMode="numeric"
@@ -3531,7 +3575,6 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           />
         </label>
       )}
-      <p className="text-caption text-text-muted">{t('settings.speedtest.alertPctHint')}</p>
       {/* URL del servidor/instancia/endpoint: no aplica a Cloudflare
           (endpoints fijos); opcional en Ookla, obligatoria en LibreSpeed
           (#976) y en custom (#1001, donde es la URL completa del endpoint
@@ -3945,7 +3988,7 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.adguard.title')}</DialogTitle>
           </DialogHeader>
-          <AdGuardManager reduce={reduce} onSaved={onSaved} />
+          <AdGuardManager reduce={reduce} onSaved={() => { onSaved(); setDialog(null) }} />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'proxmox'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -3953,7 +3996,7 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.proxmox.title')}</DialogTitle>
           </DialogHeader>
-          <ProxmoxManager reduce={reduce} onSaved={onSaved} />
+          <ProxmoxManager reduce={reduce} onSaved={() => { onSaved(); setDialog(null) }} />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'mqtt'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -3961,7 +4004,7 @@ function ServicesCard({
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.mqtt.title')}</DialogTitle>
           </DialogHeader>
-          <MqttCard onSaved={onSaved} bare />
+          <MqttCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
     </Card>
@@ -4038,7 +4081,7 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.ntfy.title')}</DialogTitle>
           </DialogHeader>
-          <NtfyCard onSaved={onSaved} bare />
+          <NtfyCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
       <Dialog open={dialog === 'telegram'} onOpenChange={(o) => { if (!o) setDialog(null) }}>
@@ -4046,7 +4089,7 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
           <DialogHeader>
             <DialogTitle className="sr-only">{t('settings.telegram.title')}</DialogTitle>
           </DialogHeader>
-          <TelegramCard onSaved={onSaved} bare />
+          <TelegramCard onSaved={() => { onSaved(); setDialog(null) }} bare />
         </DialogContent>
       </Dialog>
     </div>

+ 113 - 7
server-go/internal/speedtest/scheduler.go

@@ -40,8 +40,21 @@ var ValidIntervals = []int{6, 12, 24, 168, 720}
 const (
 	DefaultIntervalHours = 12
 	DefaultAlertPct      = 50
-	testTimeout          = 3 * time.Minute
-	tickEvery            = 30 * time.Second
+	// DefaultSchedTime (#1066): hora por defecto de la programación. Era
+	// 01:00; a las 03:00 local el tráfico residencial suele estar en su
+	// mínimo, así el test no compite con el uso real de la línea.
+	DefaultSchedTime = "03:00"
+	testTimeout      = 3 * time.Minute
+	tickEvery        = 30 * time.Second
+)
+
+// #1066: programación "auto": el scheduler elige la hora de menos tráfico
+// de su propio histórico (tabla metrics, últimos 7 días); sin datos, cae a
+// la hora por defecto (03:00).
+const (
+	scheduleKindAuto  = "auto"
+	defaultQuietHour  = 3
+	quietHourLookback = 7 * 24 * time.Hour
 )
 
 // Settings persistidas en kv (claves settings.speedtest.*).
@@ -57,7 +70,9 @@ type Settings struct {
 	Provider string `json:"provider,omitempty"`
 	// Programación (#744): "interval" (cada IntervalHours, comportamiento
 	// histórico) | "weekly" (DayOfWeek a la Time local) | "monthly"
-	// (DayOfMonth a la Time local; si el mes no tiene ese día, el último).
+	// (DayOfMonth a la Time local; si el mes no tiene ese día, el último) |
+	// "auto" (#1066: diaria a la hora de menos tráfico del histórico propio;
+	// Time la deriva el scheduler y se ignora el valor persistido).
 	ScheduleKind string `json:"scheduleKind,omitempty"`
 	DayOfWeek    *int   `json:"dayOfWeek,omitempty"`  // 0=domingo..6=sábado (weekly)
 	DayOfMonth   *int   `json:"dayOfMonth,omitempty"` // 1..31 (monthly)
@@ -111,7 +126,8 @@ type Scheduler struct {
 	running  atomic.Bool
 	mu       sync.Mutex
 	lastErr  string
-	belowPln bool // debounce de la alerta: true hasta que un test recupere
+	belowPln bool   // debounce de la alerta: true hasta que un test recupere
+	autoTime string // #1066: última hora elegida por kind "auto" ("HH:MM")
 }
 
 func NewScheduler(store *Store, db *sql.DB, runner Runner) *Scheduler {
@@ -169,6 +185,11 @@ func (s *Scheduler) Start() {
 
 func (s *Scheduler) tick() {
 	st := s.LoadSettings()
+	if st.ScheduleKind == scheduleKindAuto {
+		// #1066: la hora se reevalúa en cada tick (el patrón de consumo
+		// cambia: findes, vacaciones) y queda cacheada para Status.
+		st.Time = s.resolveAutoTime()
+	}
 	if !st.Enabled || s.running.Load() {
 		return
 	}
@@ -252,6 +273,9 @@ type Status struct {
 	LastError string  `json:"lastError,omitempty"`
 	Last      *Result `json:"last,omitempty"`
 	NextRun   *int64  `json:"nextRunMs,omitempty"` // unix ms; nil = sin programar
+	// AutoTime (#1066): hora elegida por la programación "auto" ("HH:MM",
+	// hora local); solo presente con scheduleKind "auto".
+	AutoTime string `json:"autoTime,omitempty"`
 }
 
 // Status compone la foto actual (running, último error, último resultado y
@@ -259,6 +283,18 @@ type Status struct {
 func (s *Scheduler) Status() Status {
 	st := s.LoadSettings()
 	out := Status{Running: s.running.Load()}
+	if st.ScheduleKind == scheduleKindAuto {
+		// La hora la conoce el tick; si aún no ha pasado ninguno (server
+		// recién arrancado), se calcula ahora para que la UI pueda enseñarla.
+		s.mu.Lock()
+		auto := s.autoTime
+		s.mu.Unlock()
+		if auto == "" {
+			auto = s.resolveAutoTime()
+		}
+		st.Time = auto
+		out.AutoTime = auto
+	}
 	s.mu.Lock()
 	out.LastError = s.lastErr
 	s.mu.Unlock()
@@ -319,10 +355,56 @@ func (s *Scheduler) setLastError(err error) {
 	s.lastErr = err.Error()
 }
 
+// resolveAutoTime (#1066) calcula la hora elegida por la programación "auto"
+// (la de menos tráfico medio del histórico) y la cachea para Status.
+func (s *Scheduler) resolveAutoTime() string {
+	tm := fmt.Sprintf("%02d:00", s.quietHour(s.now()))
+	s.mu.Lock()
+	s.autoTime = tm
+	s.mu.Unlock()
+	return tm
+}
+
+// quietHour devuelve la hora del día (local) con menor tráfico medio
+// (bajada+subida) de los últimos 7 días según la tabla metrics; sin datos
+// suficientes devuelve defaultQuietHour (03:00). La hora se agrupa en la
+// zona horaria local del server (misma referencia que el resto del
+// scheduler), corrigiendo el epoch con el offset activo en `now`.
+func (s *Scheduler) quietHour(now time.Time) int {
+	if s.db == nil {
+		return defaultQuietHour
+	}
+	_, off := now.Zone()
+	rows, err := s.db.Query(
+		`SELECT ((ts/1000 + ?) % 86400) / 3600 AS h,
+		        AVG(COALESCE(rx_bps, 0) + COALESCE(tx_bps, 0)), COUNT(*)
+		 FROM metrics WHERE ts >= ? GROUP BY h`,
+		off, now.Add(-quietHourLookback).UnixMilli())
+	if err != nil {
+		return defaultQuietHour
+	}
+	defer rows.Close()
+	best, bestAvg, seen := 0, 0.0, false
+	for rows.Next() {
+		var h, n int
+		var avg float64
+		if err := rows.Scan(&h, &avg, &n); err != nil {
+			continue
+		}
+		if !seen || avg < bestAvg {
+			best, bestAvg, seen = h, avg, true
+		}
+	}
+	if !seen {
+		return defaultQuietHour
+	}
+	return best
+}
+
 // LoadSettings lee la configuración del kv con defaults sanos (valores
 // inválidos o ausentes → default, nunca error: el test debe poder arrancar).
 func (s *Scheduler) LoadSettings() Settings {
-	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct, ScheduleKind: "interval"}
+	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct, ScheduleKind: "interval", Time: DefaultSchedTime}
 	if s.db == nil {
 		return st
 	}
@@ -365,7 +447,7 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 		st.ScheduleKind = "interval"
 	}
 	if !validScheduleKind(st.ScheduleKind) {
-		return errors.New("scheduleKind debe ser interval, weekly o monthly")
+		return errors.New("scheduleKind debe ser interval, auto, weekly o monthly")
 	}
 	switch st.ScheduleKind {
 	case "weekly":
@@ -382,6 +464,9 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 		if !validTimeStr(st.Time) {
 			return errors.New("monthly exige time HH:MM")
 		}
+	case scheduleKindAuto:
+		// sin campos extra: la hora la deriva el scheduler del histórico y
+		// lo que llegue en Time se ignora (no se afirma una hora concreta).
 	default:
 		if !validInterval(st.IntervalHours) {
 			return fmt.Errorf("intervalo inválido (%d): permite %v", st.IntervalHours, ValidIntervals)
@@ -474,7 +559,7 @@ func trapServerURL(raw string) bool {
 }
 
 func validScheduleKind(v string) bool {
-	return v == "interval" || v == "weekly" || v == "monthly"
+	return v == "interval" || v == "weekly" || v == "monthly" || v == scheduleKindAuto
 }
 
 func validTimeStr(v string) bool {
@@ -532,6 +617,15 @@ func testDue(st Settings, last *Result, now time.Time) bool {
 		return false
 	}
 	switch st.ScheduleKind {
+	case scheduleKindAuto:
+		// Diario a la hora elegida. El tick resuelve st.Time con la hora de
+		// menos tráfico; el fallback cubre llamadas directas con Time vacío.
+		tm := st.Time
+		if !validTimeStr(tm) {
+			tm = DefaultSchedTime
+		}
+		slot := todaySlot(tm, now)
+		return !now.Before(slot) && (last == nil || last.TS.Before(slot))
 	case "weekly":
 		dow := 0
 		if st.DayOfWeek != nil {
@@ -563,6 +657,18 @@ func testDue(st Settings, last *Result, now time.Time) bool {
 func nextRunAt(st Settings, last *Result, now time.Time) time.Time {
 	h, m := parseTimeHHMM(st.Time)
 	switch st.ScheduleKind {
+	case scheduleKindAuto:
+		tm := st.Time
+		if !validTimeStr(tm) {
+			tm = DefaultSchedTime
+		}
+		ah, am := parseTimeHHMM(tm)
+		slot := todaySlot(tm, now)
+		if now.Before(slot) || last == nil || last.TS.Before(slot) {
+			return slot
+		}
+		d := now.AddDate(0, 0, 1)
+		return time.Date(d.Year(), d.Month(), d.Day(), ah, am, 0, 0, now.Location())
 	case "weekly":
 		dow := 0
 		if st.DayOfWeek != nil {

+ 150 - 0
server-go/internal/speedtest/scheduler1066_test.go

@@ -0,0 +1,150 @@
+// scheduler1066_test.go — #1066: programación "auto" (diaria a la hora de
+// menos tráfico del histórico propio), hora por defecto 03:00 y picker de
+// hora valle sobre la tabla metrics (misma BD que el scheduler).
+package speedtest
+
+import (
+	"testing"
+	"time"
+)
+
+// seedMetrics inserta filas en la tabla metrics del scheduler (ts epoch ms).
+func seedMetrics(t *testing.T, sched *Scheduler, rows [][3]int64) {
+	t.Helper()
+	for _, r := range rows {
+		if _, err := sched.db.Exec(
+			"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES ('rt1', ?, 0, 0, 0, 0, ?, ?)",
+			r[0], r[1], r[2]); err != nil {
+			t.Fatalf("seed metrics: %v", err)
+		}
+	}
+}
+
+// atLocal construye el ts epoch ms de una fecha en la zona local del test.
+func atLocal(y int, m time.Month, day, h, min int) int64 {
+	return time.Date(y, m, day, h, min, 0, 0, time.Local).UnixMilli()
+}
+
+func TestDefaultSchedTime0300(t *testing.T) {
+	if DefaultSchedTime != "03:00" {
+		t.Fatalf("DefaultSchedTime = %q, want 03:00", DefaultSchedTime)
+	}
+	// LoadSettings con kv vacío debe traer la hora por defecto nueva (era 01:00).
+	_, sched := openStore(t)
+	if got := sched.LoadSettings().Time; got != "03:00" {
+		t.Fatalf("LoadSettings().Time = %q, want 03:00", got)
+	}
+}
+
+func TestQuietHourPicksArgmin(t *testing.T) {
+	_, sched := openStore(t)
+	// Junio (sin DST en Europa): 7 días con tráfico alto de 12:00 a 14:00
+	// y un valle claro a las 04:00. El picker debe elegir el valle.
+	now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local)
+	sched.now = func() time.Time { return now }
+	var rows [][3]int64
+	for d := 0; d < 7; d++ {
+		day := now.AddDate(0, 0, -d)
+		y, m, dd := day.Date()
+		for _, h := range []int{12, 13, 14} {
+			rows = append(rows, [3]int64{atLocal(y, m, dd, h, 0), 80_000_000, 20_000_000})
+		}
+		rows = append(rows, [3]int64{atLocal(y, m, dd, 4, 0), 100_000, 50_000})
+		rows = append(rows, [3]int64{atLocal(y, m, dd, 22, 0), 30_000_000, 5_000_000})
+	}
+	seedMetrics(t, sched, rows)
+	if got := sched.quietHour(now); got != 4 {
+		t.Fatalf("quietHour = %d, want 4 (el valle del histórico)", got)
+	}
+	// resolveAutoTime expone la hora elegida en formato HH:00 para Status.
+	if got := sched.resolveAutoTime(); got != "04:00" {
+		t.Fatalf("resolveAutoTime = %q, want 04:00", got)
+	}
+}
+
+func TestQuietHourFallbackSinDatos(t *testing.T) {
+	_, sched := openStore(t)
+	now := time.Date(2026, 6, 15, 12, 0, 0, 0, time.Local)
+	if got := sched.quietHour(now); got != defaultQuietHour {
+		t.Fatalf("quietHour sin datos = %d, want %d (fallback)", got, defaultQuietHour)
+	}
+	// Datos fuera de la ventana de 7 días tampoco sirven.
+	_, sched2 := openStore(t)
+	seedMetrics(t, sched2, [][3]int64{{atLocal(2026, 5, 1, 4, 0), 1000, 1000}})
+	if got := sched2.quietHour(now); got != defaultQuietHour {
+		t.Fatalf("quietHour con datos antiguos = %d, want %d (fallback)", got, defaultQuietHour)
+	}
+}
+
+func TestSaveSettingsAutoRoundtrip(t *testing.T) {
+	_, sched := openStore(t)
+	if err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "auto"}); err != nil {
+		t.Fatalf("auto debe aceptarse sin day/time: %v", err)
+	}
+	if got := sched.LoadSettings().ScheduleKind; got != "auto" {
+		t.Fatalf("roundtrip scheduleKind = %q, want auto", got)
+	}
+	err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "diario"})
+	if err == nil {
+		t.Fatal("scheduleKind inválido debe rechazarse")
+	}
+}
+
+func TestTestDueAutoDiario(t *testing.T) {
+	st := Settings{Enabled: true, ScheduleKind: "auto", Time: "04:00"}
+	at := func(h, m int) time.Time { return time.Date(2026, 6, 15, h, m, 0, 0, time.Local) }
+	cases := []struct {
+		name string
+		now  time.Time
+		last *Result
+		want bool
+	}{
+		{"05:00 sin histórico", at(5, 0), nil, true},
+		{"05:00 con run de hoy 04:30", at(5, 0), &Result{TS: at(4, 30)}, false},
+		{"03:59 (antes de la hora)", at(3, 59), nil, false},
+		{"04:00 en punto", at(4, 0), nil, true},
+		{"día siguiente con run de ayer", at(5, 0).AddDate(0, 0, 1), &Result{TS: at(4, 30)}, true},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			if got := testDue(st, tc.last, tc.now); got != tc.want {
+				t.Fatalf("testDue = %v, want %v", got, tc.want)
+			}
+		})
+	}
+	// Time vacío cae al default (03:00).
+	stEmpty := Settings{Enabled: true, ScheduleKind: "auto"}
+	if !testDue(stEmpty, nil, at(3, 30)) {
+		t.Fatal("auto sin Time debe usar el default 03:00")
+	}
+}
+
+func TestStatusAutoExponeHoraElegida(t *testing.T) {
+	_, sched := openStore(t)
+	// 02:00 local: antes del slot elegido (04:00), así nextRun cae hoy a esa
+	// hora en vez de al clamp genérico de Status.
+	now := time.Date(2026, 6, 15, 2, 0, 0, 0, time.Local)
+	sched.now = func() time.Time { return now }
+	var rows [][3]int64
+	for d := 0; d < 7; d++ {
+		day := now.AddDate(0, 0, -d)
+		y, m, dd := day.Date()
+		rows = append(rows, [3]int64{atLocal(y, m, dd, 12, 0), 80_000_000, 20_000_000})
+		rows = append(rows, [3]int64{atLocal(y, m, dd, 4, 0), 100_000, 50_000})
+	}
+	seedMetrics(t, sched, rows)
+	if err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "auto"}); err != nil {
+		t.Fatalf("save auto: %v", err)
+	}
+	st := sched.Status()
+	if st.AutoTime != "04:00" {
+		t.Fatalf("Status.AutoTime = %q, want 04:00", st.AutoTime)
+	}
+	if st.NextRun == nil {
+		t.Fatal("Status.NextRun no debe ser nil con auto activado")
+	}
+	next := time.UnixMilli(*st.NextRun).In(time.Local)
+	if next.Hour() != 4 {
+		t.Fatalf("nextRun debe caer a las 04:xx local, cayó a las %02d:%02d", next.Hour(), next.Minute())
+	}
+}