Browse Source

fix(speedtest): reject the ookla-web server url trap, add day+time scheduling and a recent tests list (#744) (#750)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 months ago
parent
commit
c93037ee94

+ 10 - 0
CHANGELOG.md

@@ -9,6 +9,16 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 
 ### Fixed
 ### Fixed
 
 
+- **El test de velocidad ya no mide basura cuando la URL del servidor apunta a la web de Ookla (#744)**: la tarjeta de ajustes traía `https://speedtest.net` como valor por defecto, placeholder y botón "Restaurar" (no es un servidor de pruebas, es la web), y cualquier guardado escribía esa URL en la config: el resultado era una bajada capada, una subida ~0 y un servidor sin nombre. Ahora el campo nace vacío (autoselección), el botón pasa a "Automático", el servidor rechaza la trampa con un mensaje claro, un saneado al arranque limpia la URL trampa de instalaciones existentes, y una medición con bajada o subida <= 0 se descarta con error en vez de ensuciar la serie.
+
+### Added
+
+- **El botón de test de velocidad vive en la tarjeta Tráfico WAN del Overview (#744)**: la franja de velocidad medida (último test, histórico de 7 días, % del plan y botón de ejecutar) pasa del detalle del gateway a la portada, donde ya vive el resto del tráfico.
+- **Lista de últimos tests (#744)**: en la tarjeta del test, un desplegable "Ver últimos tests" con las últimas mediciones (3/5/10, configurable): cuándo, origen (auto/manual), bajada, subida, ping, jitter y servidor.
+- **Programación con día y hora para el test (#744)**: además de cada N horas, se puede elegir semanal (día de la semana + hora) o mensual (día del mes + hora), con el vencimiento derivado del último resultado persistido (reinicios y actualizaciones no resetean el reloj). Las instalaciones con los antiguos "semanal/mensual" por horas (168/720) migran solas al selector nuevo.
+
+### Fixed
+
 - **Los respaldos automáticos ahora se ejecutan de verdad (#741)**: la configuración (activado, frecuencia, retención) existía y se mostraba en la UI, pero nada en el servidor la leía para disparar el respaldo; el único camino que copiaba la base de datos era el botón manual, así que un respaldo inicial y nada más era el comportamiento esperado del código. Ahora un bucle periódico (patrón del scheduler de speedtest) decide en cada pasada si toca, con el vencimiento derivado SIEMPRE del `last_run` persistido: los reinicios y el auto-updater no resetean el reloj. El run manual y el programado comparten el mismo código con exclusión mutua.
 - **Los respaldos automáticos ahora se ejecutan de verdad (#741)**: la configuración (activado, frecuencia, retención) existía y se mostraba en la UI, pero nada en el servidor la leía para disparar el respaldo; el único camino que copiaba la base de datos era el botón manual, así que un respaldo inicial y nada más era el comportamiento esperado del código. Ahora un bucle periódico (patrón del scheduler de speedtest) decide en cada pasada si toca, con el vencimiento derivado SIEMPRE del `last_run` persistido: los reinicios y el auto-updater no resetean el reloj. El run manual y el programado comparten el mismo código con exclusión mutua.
 
 
 ### Added
 ### Added

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

@@ -1502,7 +1502,26 @@
       "invalid": "Invalid values",
       "invalid": "Invalid values",
       "hint": "Each test saturates the link for a few seconds and consumes data: avoid short intervals on capped connections.",
       "hint": "Each test saturates the link for a few seconds and consumes data: avoid short intervals on capped connections.",
       "lastResult": "Last test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "lastResult": "Last test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
-      "unavailable": "Not available in this mode"
+      "unavailable": "Not available in this mode",
+      "kindInterval": "Every N hours",
+      "kindWeekly": "Weekly (day and time)",
+      "kindMonthly": "Monthly (day and time)",
+      "everyLabel": "Every:",
+      "dayLabel": "Day:",
+      "timeLabel": "Time:",
+      "serverPlaceholder": "Empty = closest server automatically",
+      "serverAuto": "Auto",
+      "invalidServer": "That URL is not a valid test server (speedtest.net is the website, not a server): leave it empty to pick the closest one automatically",
+      "invalidSchedule": "The schedule is incomplete (day and time)",
+      "recentShow": "View recent tests",
+      "recentTitle": "Recent tests",
+      "recentCount": "Show:",
+      "colWhen": "When",
+      "colOrigin": "Origin",
+      "originAuto": "Auto",
+      "originManual": "Manual",
+      "colServer": "Server",
+      "noRecent": "No tests recorded yet"
     },
     },
     "proxmox": {
     "proxmox": {
       "title": "Proxmox VE",
       "title": "Proxmox VE",

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

@@ -1502,7 +1502,26 @@
       "invalid": "Valores inválidos",
       "invalid": "Valores inválidos",
       "hint": "Cada test satura el enlace durante unos segundos y consume datos: evita intervalos cortos en líneas con límite de datos.",
       "hint": "Cada test satura el enlace durante unos segundos y consume datos: evita intervalos cortos en líneas con límite de datos.",
       "lastResult": "Último test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "lastResult": "Último test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
-      "unavailable": "No disponible en este modo"
+      "unavailable": "No disponible en este modo",
+      "kindInterval": "Cada N horas",
+      "kindWeekly": "Semanal (día y hora)",
+      "kindMonthly": "Mensual (día y hora)",
+      "everyLabel": "Cada:",
+      "dayLabel": "Día:",
+      "timeLabel": "Hora:",
+      "serverPlaceholder": "Vacío = servidor más cercano automáticamente",
+      "serverAuto": "Automático",
+      "invalidServer": "Esa URL no es un servidor de pruebas válido (speedtest.net es la web, no un servidor): déjalo vacío para elegir el más cercano automáticamente",
+      "invalidSchedule": "La programación está incompleta (día y hora)",
+      "recentShow": "Ver últimos tests",
+      "recentTitle": "Últimos tests",
+      "recentCount": "Mostrar:",
+      "colWhen": "Cuándo",
+      "colOrigin": "Origen",
+      "originAuto": "Auto",
+      "originManual": "Manual",
+      "colServer": "Servidor",
+      "noRecent": "Aún no hay tests registrados"
     },
     },
     "proxmox": {
     "proxmox": {
       "title": "Proxmox VE",
       "title": "Proxmox VE",

+ 1 - 2
app/src/components/routers/WanLatency.tsx

@@ -96,7 +96,6 @@ export function WanLatency() {
             </div>
             </div>
           ))}
           ))}
         </div>
         </div>
-        <SpeedtestStrip contractDown={wan.contractDownMbps} />
       </section>
       </section>
 
 
       {/* 4b. Latencia */}
       {/* 4b. Latencia */}
@@ -203,7 +202,7 @@ function useSpeedtestState() {
   return { running, lastError, last, points, starting, run, reload: load }
   return { running, lastError, last, points, starting, run, reload: load }
 }
 }
 
 
-function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
+export function SpeedtestStrip({ contractDown }: { contractDown?: number }) {
   const { t } = useTranslation()
   const { t } = useTranslation()
   const { running, lastError, last, points, starting, run } = useSpeedtestState()
   const { running, lastError, last, points, starting, run } = useSpeedtestState()
 
 

+ 283 - 28
app/src/pages/Settings.tsx

@@ -44,6 +44,7 @@ import {
    Volume2,
    Volume2,
    Wifi,
    Wifi,
    X,
    X,
+   ChevronUp,
 } from 'lucide-react'
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { HealthRing } from '@/components/HealthRing'
 import { HealthRing } from '@/components/HealthRing'
@@ -58,6 +59,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
 import { Slider } from '@/components/ui/slider'
 import { Slider } from '@/components/ui/slider'
 import { Switch } from '@/components/ui/switch'
 import { Switch } from '@/components/ui/switch'
 import { useNetPulse } from '@/data/DataProvider'
 import { useNetPulse } from '@/data/DataProvider'
+import { fmtEs } from '@/data/mock'
 import { useAuth } from '@/data/AuthContext'
 import { useAuth } from '@/data/AuthContext'
 import { getVapidKey, postPushSubscribe, postPushUnsubscribe, pushContext, urlBase64ToUint8Array } from '@/data/push'
 import { getVapidKey, postPushSubscribe, postPushUnsubscribe, pushContext, urlBase64ToUint8Array } from '@/data/push'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import { useServicesVisibility } from '@/hooks/useServicesVisibility'
@@ -2385,11 +2387,15 @@ function WanSpeedCard({ onSaved, disabled = false }: { onSaved: () => void; disa
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
 function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; disabled?: boolean }) {
 function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; disabled?: boolean }) {
-  const { t } = useTranslation()
+  const { t, i18n } = useTranslation()
   const [enabled, setEnabled] = useState(false)
   const [enabled, setEnabled] = useState(false)
   const [intervalHours, setIntervalHours] = useState(12)
   const [intervalHours, setIntervalHours] = useState(12)
   const [alertPct, setAlertPct] = useState(50)
   const [alertPct, setAlertPct] = useState(50)
-  const [serverUrl, setServerUrl] = useState('https://speedtest.net')
+  const [serverUrl, setServerUrl] = useState('')
+  const [scheduleKind, setScheduleKind] = useState<'interval' | 'weekly' | 'monthly'>('interval')
+  const [dayOfWeek, setDayOfWeek] = useState(1)
+  const [dayOfMonth, setDayOfMonth] = useState(1)
+  const [schedTime, setSchedTime] = useState('01:00')
   const [busy, setBusy] = useState(false)
   const [busy, setBusy] = useState(false)
   const [loading, setLoading] = useState(true)
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState<string | null>(null)
   const [error, setError] = useState<string | null>(null)
@@ -2406,7 +2412,20 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
         setEnabled(!!d.enabled)
         setEnabled(!!d.enabled)
         if (typeof d.intervalHours === 'number') setIntervalHours(d.intervalHours)
         if (typeof d.intervalHours === 'number') setIntervalHours(d.intervalHours)
         if (typeof d.alertPct === 'number') setAlertPct(d.alertPct)
         if (typeof d.alertPct === 'number') setAlertPct(d.alertPct)
-        if (typeof d.serverUrl === 'string' && d.serverUrl) setServerUrl(d.serverUrl)
+        if (typeof d.serverUrl === 'string') setServerUrl(d.serverUrl)
+        // 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') {
+          setScheduleKind(kind)
+        } else if (d.intervalHours === 168) {
+          setScheduleKind('weekly')
+        } else if (d.intervalHours === 720) {
+          setScheduleKind('monthly')
+        }
+        if (typeof d.dayOfWeek === 'number') setDayOfWeek(d.dayOfWeek)
+        if (typeof d.dayOfMonth === 'number') setDayOfMonth(d.dayOfMonth)
+        if (typeof d.time === 'string' && d.time) setSchedTime(d.time)
       })
       })
       .catch(() => undefined)
       .catch(() => undefined)
       .finally(() => {
       .finally(() => {
@@ -2417,10 +2436,36 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     }
     }
   }, [])
   }, [])
 
 
+  const bodyJson = useCallback(
+    () => ({
+      enabled,
+      intervalHours: scheduleKind === 'interval' ? intervalHours : 12,
+      serverUrl,
+      alertPct,
+      scheduleKind,
+      ...(scheduleKind === 'weekly' ? { dayOfWeek } : {}),
+      ...(scheduleKind === 'monthly' ? { dayOfMonth } : {}),
+      ...(scheduleKind !== 'interval' ? { time: schedTime } : {}),
+    }),
+    [enabled, intervalHours, serverUrl, alertPct, scheduleKind, dayOfWeek, dayOfMonth, schedTime],
+  )
+
   const save = useCallback(async () => {
   const save = useCallback(async () => {
     const raw = serverUrl.trim()
     const raw = serverUrl.trim()
     const urlOk = raw === '' || /^https?:\/\/.+\..+/.test(raw)
     const urlOk = raw === '' || /^https?:\/\/.+\..+/.test(raw)
-    if (![12, 24, 168, 720].includes(intervalHours) || !urlOk || alertPct < 0 || alertPct > 90) {
+    if (raw === 'https://speedtest.net' || raw === 'https://www.speedtest.net' || !urlOk) {
+      setError(t('settings.speedtest.invalidServer'))
+      return
+    }
+    if (scheduleKind === 'interval' && ![6, 12, 24, 168, 720].includes(intervalHours)) {
+      setError(t('settings.speedtest.invalid'))
+      return
+    }
+    if (scheduleKind !== 'interval' && !/^\d{2}:\d{2}$/.test(schedTime)) {
+      setError(t('settings.speedtest.invalidSchedule'))
+      return
+    }
+    if (alertPct < 0 || alertPct > 90) {
       setError(t('settings.speedtest.invalid'))
       setError(t('settings.speedtest.invalid'))
       return
       return
     }
     }
@@ -2430,10 +2475,11 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       const res = await fetch('/api/settings/speedtest', {
       const res = await fetch('/api/settings/speedtest', {
         method: 'PUT',
         method: 'PUT',
         headers: { 'Content-Type': 'application/json' },
         headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({ enabled, intervalHours, serverUrl, alertPct }),
+        body: JSON.stringify(bodyJson()),
       })
       })
       if (!res.ok) {
       if (!res.ok) {
-        setError(t('settings.speedtest.saveError'))
+        const d = await res.json().catch(() => null)
+        setError(d?.detail || t('settings.speedtest.saveError'))
         return
         return
       }
       }
       setSaved(true)
       setSaved(true)
@@ -2442,7 +2488,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     } finally {
     } finally {
       setBusy(false)
       setBusy(false)
     }
     }
-  }, [enabled, intervalHours, serverUrl, alertPct, onSaved, t])
+  }, [serverUrl, intervalHours, alertPct, scheduleKind, schedTime, bodyJson, onSaved, t])
 
 
   // «Probar»: guarda la URL del servidor y lanza un test de velocidad
   // «Probar»: guarda la URL del servidor y lanza un test de velocidad
   // inmediato (usa esa URL en el backend).
   // inmediato (usa esa URL en el backend).
@@ -2454,10 +2500,11 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
       const sRes = await fetch('/api/settings/speedtest', {
       const sRes = await fetch('/api/settings/speedtest', {
         method: 'PUT',
         method: 'PUT',
         headers: { 'Content-Type': 'application/json' },
         headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({ enabled, intervalHours, serverUrl, alertPct }),
+        body: JSON.stringify(bodyJson()),
       })
       })
       if (!sRes.ok) {
       if (!sRes.ok) {
-        setError(t('settings.speedtest.saveError'))
+        const d = await sRes.json().catch(() => null)
+        setError(d?.detail || t('settings.speedtest.saveError'))
         return
         return
       }
       }
       const runRes = await fetch('/api/speedtest/run', { method: 'POST' })
       const runRes = await fetch('/api/speedtest/run', { method: 'POST' })
@@ -2473,7 +2520,7 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
     } finally {
     } finally {
       setBusy(false)
       setBusy(false)
     }
     }
-  }, [serverUrl, enabled, intervalHours, alertPct, onSaved, t])
+  }, [serverUrl, bodyJson, onSaved, t])
 
 
   return (
   return (
     <div className="space-y-3">
     <div className="space-y-3">
@@ -2491,24 +2538,92 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
         <label className="block">
         <label className="block">
           <span className="text-label uppercase text-text-muted">{t('settings.speedtest.interval')}</span>
           <span className="text-label uppercase text-text-muted">{t('settings.speedtest.interval')}</span>
           <select
           <select
-            value={intervalHours}
-            onChange={(e) => setIntervalHours(Number(e.target.value))}
+            value={scheduleKind}
+            onChange={(e) => setScheduleKind(e.target.value as 'interval' | 'weekly' | 'monthly')}
             disabled={disabled || loading}
             disabled={disabled || loading}
             aria-label={t('settings.speedtest.interval')}
             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"
             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"
           >
           >
-            {[12, 24, 168, 720].map((h) => (
-              <option key={h} value={h}>
-                {h === 168
-                  ? t('settings.speedtest.intervalWeek')
-                  : h === 720
-                    ? t('settings.speedtest.intervalMonth')
-                    : t('settings.speedtest.intervalH', { hours: h })}
-              </option>
-            ))}
+            <option value="interval">{t('settings.speedtest.kindInterval')}</option>
+            <option value="weekly">{t('settings.speedtest.kindWeekly')}</option>
+            <option value="monthly">{t('settings.speedtest.kindMonthly')}</option>
           </select>
           </select>
         </label>
         </label>
-        <label className="block">
+        {scheduleKind === 'interval' ? (
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.everyLabel')}</span>
+            <select
+              value={intervalHours}
+              onChange={(e) => setIntervalHours(Number(e.target.value))}
+              disabled={disabled || loading}
+              aria-label={t('settings.speedtest.everyLabel')}
+              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"
+            >
+              {[6, 12, 24].map((h) => (
+                <option key={h} value={h}>{t('settings.speedtest.intervalH', { hours: h })}</option>
+              ))}
+            </select>
+          </label>
+        ) : (
+          <label className="block">
+            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.dayLabel')}</span>
+            {scheduleKind === 'weekly' ? (
+              <select
+                value={dayOfWeek}
+                onChange={(e) => setDayOfWeek(Number(e.target.value))}
+                disabled={disabled || loading}
+                aria-label={t('settings.speedtest.dayLabel')}
+                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"
+              >
+                {weekdayNames(i18n.language).map((name, i) => (
+                  <option key={i} value={i}>{name}</option>
+                ))}
+              </select>
+            ) : (
+              <select
+                value={dayOfMonth}
+                onChange={(e) => setDayOfMonth(Number(e.target.value))}
+                disabled={disabled || loading}
+                aria-label={t('settings.speedtest.dayLabel')}
+                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"
+              >
+                {Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
+                  <option key={d} value={d}>{d}</option>
+                ))}
+              </select>
+            )}
+          </label>
+        )}
+      </div>
+      {scheduleKind !== 'interval' && (
+        <div className="flex flex-wrap items-end gap-3">
+          <label className="block max-w-[220px]">
+            <span className="text-label uppercase text-text-muted">{t('settings.speedtest.timeLabel')}</span>
+            <input
+              type="time"
+              value={schedTime}
+              onChange={(e) => setSchedTime(e.target.value)}
+              disabled={disabled || loading}
+              aria-label={t('settings.speedtest.timeLabel')}
+              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>
+            <input
+              type="text"
+              inputMode="numeric"
+              value={alertPct}
+              onChange={(e) => setAlertPct(Number(e.target.value))}
+              disabled={disabled || loading}
+              aria-label={t('settings.speedtest.alertPctLabel')}
+              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>
+        </div>
+      )}
+      {scheduleKind === 'interval' && (
+        <label className="block max-w-[160px]">
           <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
           <span className="text-label uppercase text-text-muted">{t('settings.speedtest.alertPctLabel')}</span>
           <input
           <input
             type="text"
             type="text"
@@ -2520,7 +2635,7 @@ 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"
             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>
-      </div>
+      )}
       <p className="text-caption text-text-muted">{t('settings.speedtest.alertPctHint')}</p>
       <p className="text-caption text-text-muted">{t('settings.speedtest.alertPctHint')}</p>
       <div>
       <div>
         <span className="text-label uppercase text-text-muted">{t('settings.speedtest.serverId')}</span>
         <span className="text-label uppercase text-text-muted">{t('settings.speedtest.serverId')}</span>
@@ -2531,20 +2646,20 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
             value={serverUrl}
             value={serverUrl}
             onChange={(e) => setServerUrl(e.target.value)}
             onChange={(e) => setServerUrl(e.target.value)}
             disabled={disabled || loading}
             disabled={disabled || loading}
-            placeholder="https://speedtest.net"
+            placeholder={t('settings.speedtest.serverPlaceholder')}
             aria-label={t('settings.speedtest.serverId')}
             aria-label={t('settings.speedtest.serverId')}
             className="w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
             className="w-full rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
           />
           />
           <button
           <button
             type="button"
             type="button"
-            onClick={() => setServerUrl('https://speedtest.net')}
+            onClick={() => setServerUrl('')}
             disabled={disabled || loading}
             disabled={disabled || loading}
-            title={t('settings.speedtest.serverRestore')}
-            aria-label={t('settings.speedtest.serverRestore')}
+            title={t('settings.speedtest.serverAuto')}
+            aria-label={t('settings.speedtest.serverAuto')}
             className="flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-border bg-elevated px-3 text-[13px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-60"
             className="flex h-9 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-border bg-elevated px-3 text-[13px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-60"
           >
           >
             <RotateCcw className="h-3.5 w-3.5" strokeWidth={1.75} />
             <RotateCcw className="h-3.5 w-3.5" strokeWidth={1.75} />
-            <span className="hidden sm:inline">{t('settings.speedtest.serverRestore')}</span>
+            <span className="hidden sm:inline">{t('settings.speedtest.serverAuto')}</span>
           </button>
           </button>
           <button
           <button
             type="button"
             type="button"
@@ -2578,6 +2693,146 @@ function SpeedtestCard({ onSaved, disabled = false }: { onSaved: () => void; dis
           </span>
           </span>
         )}
         )}
       </div>
       </div>
+      <SpeedtestRecent disabled={disabled} />
+    </div>
+  )
+}
+
+// weekdayNames: nombres localizados de domingo..sábado (0..6). 2026-09-06 fue
+// domingo; se formatea esa semana completa con el locale activo.
+function weekdayNames(locale: string): string[] {
+  const fmt = new Intl.DateTimeFormat(locale.startsWith('en') ? 'en-GB' : 'es-ES', { weekday: 'long' })
+  return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2026, 8, 6 + i)))
+}
+
+type SpeedtestHistoryItem = {
+  ts: string
+  downMbps: number
+  upMbps: number
+  pingMs?: number
+  jitterMs?: number
+  serverName?: string
+  origin?: string
+}
+
+// SpeedtestRecent (#744): lista de los últimos tests con origen (auto/manual),
+// servidor, ping y jitter. Los datos ya viajan en /api/speedtest/history.
+function SpeedtestRecent({ disabled = false }: { disabled?: boolean }) {
+  const { t, i18n } = useTranslation()
+  const [items, setItems] = useState<SpeedtestHistoryItem[]>([])
+  const [count, setCount] = useState(5)
+  const [open, setOpen] = useState(false)
+
+  useEffect(() => {
+    if (disabled) return
+    let alive = true
+    void fetch('/api/speedtest/history?hours=2160')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (!alive || !d) return
+        const list: SpeedtestHistoryItem[] = d.items ?? []
+        setItems([...list].reverse())
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [disabled])
+
+  const locale = i18n.language?.startsWith('en') ? 'en-GB' : 'es-ES'
+  const fmt = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })
+
+  if (!open) {
+    return (
+      <button
+        type="button"
+        onClick={() => setOpen(true)}
+        disabled={disabled}
+        className="mt-1 text-caption text-accent hover:underline disabled:opacity-50"
+      >
+        {t('settings.speedtest.recentShow')}
+      </button>
+    )
+  }
+
+  return (
+    <div className="mt-3 border-t border-border pt-3">
+      <div className="flex flex-wrap items-center justify-between gap-2">
+        <span className="text-label uppercase text-text-muted">{t('settings.speedtest.recentTitle')}</span>
+        <div className="flex items-center gap-2">
+          <label className="flex items-center gap-1.5 text-caption text-text-muted">
+            <span>{t('settings.speedtest.recentCount')}</span>
+            <select
+              value={count}
+              onChange={(e) => setCount(Number(e.target.value))}
+              aria-label={t('settings.speedtest.recentCount')}
+              className="rounded-lg border border-border bg-elevated px-2 py-1 text-xs text-text-primary"
+            >
+              {[3, 5, 10].map((n) => (
+                <option key={n} value={n}>{n}</option>
+              ))}
+            </select>
+          </label>
+          <button
+            type="button"
+            onClick={() => setOpen(false)}
+            aria-label={t('common.close')}
+            className="text-caption text-text-muted hover:text-text-primary"
+          >
+            <ChevronUp className="h-4 w-4" strokeWidth={1.75} />
+          </button>
+        </div>
+      </div>
+      {items.length === 0 ? (
+        <p className="mt-2 text-caption text-text-muted">{t('settings.speedtest.noRecent')}</p>
+      ) : (
+        <div className="mt-2 overflow-x-auto">
+          <table className="w-full text-caption">
+            <thead>
+              <tr className="text-left text-text-muted">
+                <th className="py-1 pr-3 font-medium">{t('settings.speedtest.colWhen')}</th>
+                <th className="py-1 pr-3 font-medium">{t('settings.speedtest.colOrigin')}</th>
+                <th className="py-1 pr-3 font-medium">↓</th>
+                <th className="py-1 pr-3 font-medium">↑</th>
+                <th className="py-1 pr-3 font-medium">ping</th>
+                <th className="py-1 pr-3 font-medium">jitter</th>
+                <th className="py-1 font-medium">{t('settings.speedtest.colServer')}</th>
+              </tr>
+            </thead>
+            <tbody className="font-mono text-text-secondary">
+              {items.slice(0, count).map((it, idx) => (
+                <tr key={`${it.ts}-${idx}`} className="border-t border-border/60">
+                  <td className="py-1.5 pr-3">
+                    {(() => {
+                      try {
+                        return fmt.format(new Date(it.ts))
+                      } catch {
+                        return it.ts
+                      }
+                    })()}
+                  </td>
+                  <td className="py-1.5 pr-3">
+                    <span
+                      className={`rounded-full border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${
+                        it.origin === 'manual'
+                          ? 'border-accent/40 bg-accent/10 text-accent'
+                          : 'border-border bg-surface text-text-muted'
+                      }`}
+                    >
+                      {it.origin === 'manual' ? t('settings.speedtest.originManual') : t('settings.speedtest.originAuto')}
+                    </span>
+                  </td>
+                  <td className="py-1.5 pr-3 text-accent">{fmtEs(it.downMbps, 1)}</td>
+                  <td className="py-1.5 pr-3 text-tunnel">{fmtEs(it.upMbps, 1)}</td>
+                  <td className="py-1.5 pr-3">{it.pingMs !== undefined ? `${fmtEs(it.pingMs, 0)} ms` : '—'}</td>
+                  <td className="py-1.5 pr-3">{it.jitterMs !== undefined ? `${fmtEs(it.jitterMs, 0)} ms` : '—'}</td>
+                  <td className="py-1.5 truncate">{it.serverName || '—'}</td>
+                </tr>
+              ))}
+            </tbody>
+          </table>
+        </div>
+      )}
     </div>
     </div>
   )
   )
 }
 }

+ 5 - 0
app/src/sections/WanTraffic.tsx

@@ -8,6 +8,7 @@ import { useNetPulse } from '@/data/DataProvider'
 import { SectionHeader } from '@/components/SectionHeader'
 import { SectionHeader } from '@/components/SectionHeader'
 import { SegmentedControl, TIME_RANGE_OPTIONS } from '@/components/SegmentedControl'
 import { SegmentedControl, TIME_RANGE_OPTIONS } from '@/components/SegmentedControl'
 import { StatusPill } from '@/components/StatusPill'
 import { StatusPill } from '@/components/StatusPill'
+import { SpeedtestStrip } from '@/components/routers/WanLatency'
 
 
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 // Tooltip custom (design.md §7): superficie elevated, valores mono con unidad
 // Tooltip custom (design.md §7): superficie elevated, valores mono con unidad
@@ -225,6 +226,10 @@ export function WanTraffic() {
           })}
           })}
         </p>
         </p>
       ) : null}
       ) : null}
+
+      {/* Velocidad medida + botón de test (#511, movido al Overview en
+          #744 a petición del reportero: el gateway ya no la lleva). */}
+      <SpeedtestStrip contractDown={wan.contractDownMbps} />
     </section>
     </section>
   )
   )
 }
 }

+ 237 - 15
server-go/internal/speedtest/scheduler.go

@@ -27,10 +27,13 @@ import (
 // test está en marcha.
 // test está en marcha.
 var ErrAlreadyRunning = errors.New("speedtest already running")
 var ErrAlreadyRunning = errors.New("speedtest already running")
 
 
-// ValidIntervals son los intervalos permitidos (horas). El mínimo de 6 h es
-// deliberado: cada test satura el enlace y consume datos (las notas de la
-// integración de Home Assistant dicen lo mismo).
-var ValidIntervals = []int{6, 12, 24}
+// ValidIntervals son los intervalos permitidos en modo "interval" (horas).
+// El mínimo de 6 h es deliberado: cada test satura el enlace y consume datos
+// (las notas de la integración de Home Assistant dicen lo mismo). 168/720
+// son los "semanal/mensual" históricos pre-#744: se aceptan para no romper
+// instalaciones existentes; la programación con día y hora concretos va por
+// scheduleKind weekly/monthly.
+var ValidIntervals = []int{6, 12, 24, 168, 720}
 
 
 // DefaultSettings: desactivado por defecto (opt-in explícito; un test consume
 // DefaultSettings: desactivado por defecto (opt-in explícito; un test consume
 // datos de la línea y eso lo debe decidir el admin).
 // datos de la línea y eso lo debe decidir el admin).
@@ -47,6 +50,13 @@ type Settings struct {
 	IntervalHours int    `json:"intervalHours"`
 	IntervalHours int    `json:"intervalHours"`
 	ServerURL     string `json:"serverUrl"`
 	ServerURL     string `json:"serverUrl"`
 	AlertPct      int    `json:"alertPct"`
 	AlertPct      int    `json:"alertPct"`
+	// 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).
+	ScheduleKind string `json:"scheduleKind,omitempty"`
+	DayOfWeek    *int   `json:"dayOfWeek,omitempty"`  // 0=domingo..6=sábado (weekly)
+	DayOfMonth   *int   `json:"dayOfMonth,omitempty"` // 1..31 (monthly)
+	Time         string `json:"time,omitempty"`       // "HH:MM" hora local
 }
 }
 
 
 // Claves kv (mismo formato que settings.wan.speed_* de #151).
 // Claves kv (mismo formato que settings.wan.speed_* de #151).
@@ -56,6 +66,11 @@ const (
 	kvServerURL = "settings.speedtest.server_url"
 	kvServerURL = "settings.speedtest.server_url"
 	kvAlertPct  = "settings.speedtest.alert_pct"
 	kvAlertPct  = "settings.speedtest.alert_pct"
 	kvContractD = "settings.wan.speed_down" // del issue #151 (lectura)
 	kvContractD = "settings.wan.speed_down" // del issue #151 (lectura)
+
+	kvScheduleKind = "settings.speedtest.schedule_kind"
+	kvDayOfWeek    = "settings.speedtest.day_of_week"
+	kvDayOfMonth   = "settings.speedtest.day_of_month"
+	kvTime         = "settings.speedtest.time"
 )
 )
 
 
 // AlertEmitter lo cumple *alerts.Engine (emisión por el mismo motor que el
 // AlertEmitter lo cumple *alerts.Engine (emisión por el mismo motor que el
@@ -104,6 +119,7 @@ func (s *Scheduler) SetContractDown(fn func() (float64, bool)) { s.contractDown
 
 
 // Start lanza el bucle periódico (daemon; no retorna).
 // Start lanza el bucle periódico (daemon; no retorna).
 func (s *Scheduler) Start() {
 func (s *Scheduler) Start() {
+	s.sanitizeServerURL()
 	ticker := time.NewTicker(tickEvery)
 	ticker := time.NewTicker(tickEvery)
 	defer ticker.Stop()
 	defer ticker.Stop()
 	for range ticker.C {
 	for range ticker.C {
@@ -123,7 +139,7 @@ func (s *Scheduler) tick() {
 	}
 	}
 	// Sin resultados previos (primera activación) el primer test sale en
 	// Sin resultados previos (primera activación) el primer test sale en
 	// el siguiente tick: el admin activa y ve datos en <30 s.
 	// el siguiente tick: el admin activa y ve datos en <30 s.
-	if last != nil && s.now().Sub(last.TS) < time.Duration(st.IntervalHours)*time.Hour {
+	if !testDue(st, last, s.now()) {
 		return
 		return
 	}
 	}
 	if err := s.tryExecute(st, "scheduled"); err != nil {
 	if err := s.tryExecute(st, "scheduled"); err != nil {
@@ -164,6 +180,14 @@ func (s *Scheduler) executeLocked(st Settings, origin string) error {
 		s.setLastError(err)
 		s.setLastError(err)
 		return err
 		return err
 	}
 	}
+	// Sanity (#744): una medición con bajada o subida <= 0 es la firma del
+	// servidor equivocado (p. ej. la web de Ookla como server_url): se
+	// descarta SIN persistir para no ensuciar la serie ni las gráficas.
+	if res.DownMbps <= 0 || res.UpMbps <= 0 {
+		err := fmt.Errorf("resultado descartado (down %.1f / up %.1f Mbps): servidor de pruebas inválido o inalcanzable, revisa la URL del servidor o déjala vacía para autoselección", res.DownMbps, res.UpMbps)
+		s.setLastError(err)
+		return err
+	}
 	res.Origin = origin
 	res.Origin = origin
 	if res.TS.IsZero() {
 	if res.TS.IsZero() {
 		res.TS = s.now() // runner sin TS (fakes/defensa): la serie exige ts válido
 		res.TS = s.now() // runner sin TS (fakes/defensa): la serie exige ts válido
@@ -200,16 +224,13 @@ func (s *Scheduler) Status() Status {
 	s.mu.Unlock()
 	s.mu.Unlock()
 	if last, err := s.store.Latest(); err == nil {
 	if last, err := s.store.Latest(); err == nil {
 		out.Last = last
 		out.Last = last
-		if st.Enabled && last != nil {
-			next := last.TS.Add(time.Duration(st.IntervalHours) * time.Hour)
+		if st.Enabled {
+			next := nextRunAt(st, last, s.now())
 			if next.Before(s.now()) {
 			if next.Before(s.now()) {
 				next = s.now().Add(tickEvery)
 				next = s.now().Add(tickEvery)
 			}
 			}
 			ms := next.UnixMilli()
 			ms := next.UnixMilli()
 			out.NextRun = &ms
 			out.NextRun = &ms
-		} else if st.Enabled {
-			ms := s.now().Add(tickEvery).UnixMilli()
-			out.NextRun = &ms
 		}
 		}
 	}
 	}
 	return out
 	return out
@@ -261,7 +282,7 @@ func (s *Scheduler) setLastError(err error) {
 // LoadSettings lee la configuración del kv con defaults sanos (valores
 // LoadSettings lee la configuración del kv con defaults sanos (valores
 // inválidos o ausentes → default, nunca error: el test debe poder arrancar).
 // inválidos o ausentes → default, nunca error: el test debe poder arrancar).
 func (s *Scheduler) LoadSettings() Settings {
 func (s *Scheduler) LoadSettings() Settings {
-	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct}
+	st := Settings{IntervalHours: DefaultIntervalHours, AlertPct: DefaultAlertPct, ScheduleKind: "interval"}
 	if s.db == nil {
 	if s.db == nil {
 		return st
 		return st
 	}
 	}
@@ -275,15 +296,55 @@ func (s *Scheduler) LoadSettings() Settings {
 	if v, ok := kvInt(s.db, kvAlertPct); ok && v >= 0 && v <= 90 {
 	if v, ok := kvInt(s.db, kvAlertPct); ok && v >= 0 && v <= 90 {
 		st.AlertPct = v
 		st.AlertPct = v
 	}
 	}
+	if v := kvGet(s.db, kvScheduleKind); validScheduleKind(v) {
+		st.ScheduleKind = v
+	}
+	if v, ok := kvInt(s.db, kvDayOfWeek); ok && v >= 0 && v <= 6 {
+		d := v
+		st.DayOfWeek = &d
+	}
+	if v, ok := kvInt(s.db, kvDayOfMonth); ok && v >= 1 && v <= 31 {
+		d := v
+		st.DayOfMonth = &d
+	}
+	if v := kvGet(s.db, kvTime); validTimeStr(v) {
+		st.Time = v
+	}
 	return st
 	return st
 }
 }
 
 
 // SaveSettings valida y persiste (UPSERT por clave).
 // SaveSettings valida y persiste (UPSERT por clave).
 func (s *Scheduler) SaveSettings(st Settings) error {
 func (s *Scheduler) SaveSettings(st Settings) error {
-	if !validInterval(st.IntervalHours) {
-		return fmt.Errorf("intervalo inválido (%d): permite %v", st.IntervalHours, ValidIntervals)
+	if st.ScheduleKind == "" {
+		st.ScheduleKind = "interval"
+	}
+	if !validScheduleKind(st.ScheduleKind) {
+		return errors.New("scheduleKind debe ser interval, weekly o monthly")
+	}
+	switch st.ScheduleKind {
+	case "weekly":
+		if st.DayOfWeek == nil || *st.DayOfWeek < 0 || *st.DayOfWeek > 6 {
+			return errors.New("weekly exige dayOfWeek 0-6 (0 = domingo)")
+		}
+		if !validTimeStr(st.Time) {
+			return errors.New("weekly exige time HH:MM")
+		}
+	case "monthly":
+		if st.DayOfMonth == nil || *st.DayOfMonth < 1 || *st.DayOfMonth > 31 {
+			return errors.New("monthly exige dayOfMonth 1-31")
+		}
+		if !validTimeStr(st.Time) {
+			return errors.New("monthly exige time HH:MM")
+		}
+	default:
+		if !validInterval(st.IntervalHours) {
+			return fmt.Errorf("intervalo inválido (%d): permite %v", st.IntervalHours, ValidIntervals)
+		}
 	}
 	}
 	if strings.TrimSpace(st.ServerURL) != "" && !validServerURL(st.ServerURL) {
 	if strings.TrimSpace(st.ServerURL) != "" && !validServerURL(st.ServerURL) {
+		if trapServerURL(st.ServerURL) {
+			return errors.New("speedtest.net es la web de Ookla, no un servidor de pruebas: deja el campo vacío para usar el más cercano automáticamente")
+		}
 		return errors.New("serverUrl debe ser una URL http(s) válida")
 		return errors.New("serverUrl debe ser una URL http(s) válida")
 	}
 	}
 	if st.AlertPct < 0 || st.AlertPct > 90 {
 	if st.AlertPct < 0 || st.AlertPct > 90 {
@@ -293,9 +354,28 @@ func (s *Scheduler) SaveSettings(st Settings) error {
 	kvSet(s.db, kvInterval, fmt.Sprintf("%d", st.IntervalHours))
 	kvSet(s.db, kvInterval, fmt.Sprintf("%d", st.IntervalHours))
 	kvSet(s.db, kvServerURL, strings.TrimSpace(st.ServerURL))
 	kvSet(s.db, kvServerURL, strings.TrimSpace(st.ServerURL))
 	kvSet(s.db, kvAlertPct, fmt.Sprintf("%d", st.AlertPct))
 	kvSet(s.db, kvAlertPct, fmt.Sprintf("%d", st.AlertPct))
+	kvSet(s.db, kvScheduleKind, st.ScheduleKind)
+	kvSet(s.db, kvDayOfWeek, intPtrStr(st.DayOfWeek))
+	kvSet(s.db, kvDayOfMonth, intPtrStr(st.DayOfMonth))
+	kvSet(s.db, kvTime, st.Time)
 	return nil
 	return nil
 }
 }
 
 
+// sanitizeServerURL (#744): limpia al arranque el valor trampa conocido
+// (https://speedtest.net guardada cuando el campo se entendía como "la web
+// de Ookla"): produce mediciones basura (subida ~0, sin identidad de
+// servidor). Idempotente; deja cualquier otra URL intacta.
+func (s *Scheduler) sanitizeServerURL() {
+	if s.db == nil {
+		return
+	}
+	v := kvGet(s.db, kvServerURL)
+	if v != "" && trapServerURL(v) {
+		kvSet(s.db, kvServerURL, "")
+		s.logf("server_url trampa (%q) limpiada a autoselección", v)
+	}
+}
+
 func validInterval(v int) bool {
 func validInterval(v int) bool {
 	for _, i := range ValidIntervals {
 	for _, i := range ValidIntervals {
 		if i == v {
 		if i == v {
@@ -305,13 +385,155 @@ func validInterval(v int) bool {
 	return false
 	return false
 }
 }
 
 
-// validServerURL: la URL del servidor de test debe ser http(s) con host.
+// validServerURL: la URL del servidor de test debe ser http(s) con host, y
+// no puede ser la web de Ookla (trampa clásica que mide basura, #744).
 func validServerURL(raw string) bool {
 func validServerURL(raw string) bool {
 	u, err := url.Parse(strings.TrimSpace(raw))
 	u, err := url.Parse(strings.TrimSpace(raw))
 	if err != nil {
 	if err != nil {
 		return false
 		return false
 	}
 	}
-	return (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
+	if !((u.Scheme == "http" || u.Scheme == "https") && u.Host != "") {
+		return false
+	}
+	return !trapServerURL(raw)
+}
+
+// trapServerURL detecta la web de Ookla usada como servidor de pruebas.
+func trapServerURL(raw string) bool {
+	u, err := url.Parse(strings.TrimSpace(raw))
+	if err != nil {
+		return false
+	}
+	host := strings.ToLower(u.Hostname())
+	host = strings.TrimPrefix(host, "www.")
+	return host == "speedtest.net"
+}
+
+func validScheduleKind(v string) bool {
+	return v == "interval" || v == "weekly" || v == "monthly"
+}
+
+func validTimeStr(v string) bool {
+	if v == "" {
+		return false
+	}
+	_, err := time.Parse("15:04", v)
+	return err == nil
+}
+
+func intPtrStr(p *int) string {
+	if p == nil {
+		return ""
+	}
+	return fmt.Sprintf("%d", *p)
+}
+
+// parseTimeHHMM devuelve la hora del día de un "HH:MM" (00:00 si es inválido;
+// el guardado ya valida).
+func parseTimeHHMM(v string) (int, int) {
+	t, err := time.Parse("15:04", v)
+	if err != nil {
+		return 0, 0
+	}
+	return t.Hour(), t.Minute()
+}
+
+// daysInMonth devuelve el último día del mes de t.
+func daysInMonth(t time.Time) int {
+	return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()).Day()
+}
+
+// todaySlot devuelve hoy a la hora programada ("HH:MM", hora local).
+func todaySlot(v string, now time.Time) time.Time {
+	h, m := parseTimeHHMM(v)
+	return time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, now.Location())
+}
+
+// clampDay ajusta el día del mes pedido al último día real del mes de now.
+func clampDay(dom int, now time.Time) int {
+	if dom < 1 {
+		dom = 1
+	}
+	if max := daysInMonth(now); dom > max {
+		dom = max
+	}
+	return dom
+}
+
+// testDue decide si toca medir según la programación (#744). El vencimiento
+// siempre deriva del último resultado persistido: reinicios y updates no
+// resetean el reloj (mismo contrato que los backups automáticos).
+func testDue(st Settings, last *Result, now time.Time) bool {
+	if !st.Enabled {
+		return false
+	}
+	switch st.ScheduleKind {
+	case "weekly":
+		dow := 0
+		if st.DayOfWeek != nil {
+			dow = *st.DayOfWeek
+		}
+		if int(now.Weekday()) != dow {
+			return false
+		}
+		slot := todaySlot(st.Time, now)
+		return !now.Before(slot) && (last == nil || last.TS.Before(slot))
+	case "monthly":
+		dom := 1
+		if st.DayOfMonth != nil {
+			dom = *st.DayOfMonth
+		}
+		dom = clampDay(dom, now)
+		h, m := parseTimeHHMM(st.Time)
+		slot := time.Date(now.Year(), now.Month(), dom, h, m, 0, 0, now.Location())
+		return !now.Before(slot) && (last == nil || last.TS.Before(slot))
+	default: // interval
+		if last == nil {
+			return true
+		}
+		return now.Sub(last.TS) >= time.Duration(st.IntervalHours)*time.Hour
+	}
+}
+
+// nextRunAt calcula el próximo disparo para Status.
+func nextRunAt(st Settings, last *Result, now time.Time) time.Time {
+	h, m := parseTimeHHMM(st.Time)
+	switch st.ScheduleKind {
+	case "weekly":
+		dow := 0
+		if st.DayOfWeek != nil {
+			dow = *st.DayOfWeek
+		}
+		today := todaySlot(st.Time, now)
+		if int(now.Weekday()) == dow && (now.Before(today) || last == nil || last.TS.Before(today)) {
+			return today
+		}
+		days := (dow - int(now.Weekday()) + 7) % 7
+		if days == 0 {
+			days = 7
+		}
+		d := now.AddDate(0, 0, days)
+		return time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, now.Location())
+	case "monthly":
+		dom := 1
+		if st.DayOfMonth != nil {
+			dom = *st.DayOfMonth
+		}
+		dom = clampDay(dom, now)
+		slot := time.Date(now.Year(), now.Month(), dom, h, m, 0, 0, now.Location())
+		if now.Before(slot) || last == nil || last.TS.Before(slot) {
+			return slot
+		}
+		next := now.AddDate(0, 1, 0)
+		domNext := clampDay(dom, next)
+		return time.Date(next.Year(), next.Month(), domNext, h, m, 0, 0, now.Location())
+	default:
+		base := now
+		if last != nil && last.TS.After(base.Add(-time.Duration(st.IntervalHours)*time.Hour)) {
+			base = last.TS
+		}
+		return base.Add(time.Duration(st.IntervalHours) * time.Hour)
+	}
 }
 }
 
 
 func boolStr(b bool) string {
 func boolStr(b bool) string {

+ 146 - 0
server-go/internal/speedtest/scheduler744_test.go

@@ -0,0 +1,146 @@
+// scheduler744_test.go — #744: trampa de server_url (la web de Ookla mide
+// basura), sanity check (no persistir resultados con down/up <= 0) y
+// programación weekly/monthly con vencimiento derivado del último run.
+package speedtest
+
+import (
+	"context"
+	"strings"
+	"testing"
+	"time"
+)
+
+func TestTestDueWeekly(t *testing.T) {
+	dow := 1 // lunes
+	st := Settings{Enabled: true, ScheduleKind: "weekly", DayOfWeek: &dow, Time: "01:00"}
+	at := func(day time.Weekday, h, m int) time.Time {
+		// lunes 2026-09-07; day 0=domingo..6=sábado
+		base := time.Date(2026, 9, 6, 0, 0, 0, 0, time.UTC) // domingo
+		return base.AddDate(0, 0, int(day)).Add(time.Duration(h)*time.Hour + time.Duration(m)*time.Minute)
+	}
+	cases := []struct {
+		name string
+		now  time.Time
+		last *Result
+		want bool
+	}{
+		{"lunes 02:00 sin histórico", at(time.Monday, 2, 0), nil, true},
+		{"lunes 02:00 con run de hoy 01:30", at(time.Monday, 2, 0), &Result{TS: at(time.Monday, 1, 30)}, false},
+		{"lunes 00:30 (antes de la hora)", at(time.Monday, 0, 30), nil, false},
+		{"domingo (no es el día)", at(time.Sunday, 2, 0), nil, false},
+		{"martes ya corrió el lunes", at(time.Tuesday, 2, 0), &Result{TS: at(time.Monday, 1, 5)}, false},
+		{"lunes siguiente sin run", at(time.Monday, 2, 0).AddDate(0, 0, 7), &Result{TS: at(time.Monday, 1, 5)}, 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)
+			}
+		})
+	}
+}
+
+func TestTestDueMonthly(t *testing.T) {
+	dom := 15
+	st := Settings{Enabled: true, ScheduleKind: "monthly", DayOfMonth: &dom, Time: "01:00"}
+	at := func(day, h, m int) time.Time { return time.Date(2026, 9, day, h, m, 0, 0, time.UTC) }
+	cases := []struct {
+		name string
+		now  time.Time
+		last *Result
+		want bool
+	}{
+		{"día 15 tras la hora sin run", at(15, 2, 0), nil, true},
+		{"día 15 tras la hora ya corrido", at(15, 2, 0), &Result{TS: at(15, 1, 30)}, false},
+		{"día 14 (aún no)", at(14, 2, 0), nil, false},
+		{"día 20 con run del 15", at(20, 2, 0), &Result{TS: at(15, 1, 0)}, false},
+	}
+	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)
+			}
+		})
+	}
+	// Clamp a fin de mes: day 31 en febrero (28 días) → slot el 28.
+	d31 := 31
+	stFeb := Settings{Enabled: true, ScheduleKind: "monthly", DayOfMonth: &d31, Time: "23:00"}
+	now := time.Date(2026, 2, 28, 23, 30, 0, 0, time.UTC) // 28-02 23:30
+	if !testDue(stFeb, nil, now) {
+		t.Fatal("day 31 en febrero debe disparar el 28 a las 23:00 (clamp)")
+	}
+}
+
+func TestSaveSettingsValidaTrappaYSchedule(t *testing.T) {
+	_, sched := openStore(t)
+	dow := 3
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, ServerURL: "https://speedtest.net"}); err == nil || !strings.Contains(err.Error(), "Ookla") {
+		t.Fatalf("la trampa speedtest.net debe rechazarse con mensaje claro: %v", err)
+	}
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, ServerURL: "https://www.speedtest.net"}); err == nil {
+		t.Fatal("www.speedtest.net también es trampa")
+	}
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, ScheduleKind: "weekly"}); err == nil {
+		t.Fatal("weekly sin dayOfWeek/time debe rechazarse")
+	}
+	if err := sched.SaveSettings(Settings{Enabled: true, ScheduleKind: "weekly", DayOfWeek: &dow, Time: "01:30"}); err != nil {
+		t.Fatalf("weekly válido: %v", err)
+	}
+	got := sched.LoadSettings()
+	if got.ScheduleKind != "weekly" || got.DayOfWeek == nil || *got.DayOfWeek != 3 || got.Time != "01:30" {
+		t.Fatalf("roundtrip weekly: %+v", got)
+	}
+	d40 := 40
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, ScheduleKind: "monthly", DayOfMonth: &d40}); err == nil {
+		t.Fatal("dayOfMonth 40 debe rechazarse")
+	}
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 3}); err == nil {
+		t.Fatal("intervalo 3h sigue fuera de la allowlist")
+	}
+	// URL legítima de un servidor real pasa.
+	if err := sched.SaveSettings(Settings{Enabled: true, IntervalHours: 6, ServerURL: "http://testvelocidadsev.orange.es:8080/speedtest/upload.php"}); err != nil {
+		t.Fatalf("URL legítima rechazada: %v", err)
+	}
+}
+
+func TestSanitizeServerURL(t *testing.T) {
+	_, sched := openStore(t)
+	kvSet(sched.db, kvServerURL, "https://speedtest.net")
+	sched.sanitizeServerURL()
+	if got := kvGet(sched.db, kvServerURL); got != "" {
+		t.Fatalf("la trampa debía limpiarse, queda %q", got)
+	}
+	// Una URL legítima se conserva.
+	kvSet(sched.db, kvServerURL, "http://mi-servidor.ejemplo:8080/upload.php")
+	sched.sanitizeServerURL()
+	if got := kvGet(sched.db, kvServerURL); got == "" {
+		t.Fatal("la URL legítima no debía tocarse")
+	}
+}
+
+// garbageRunner devuelve la firma exacta del bug: down parcial, up residual.
+type garbageRunner struct{}
+
+func (garbageRunner) Run(ctx context.Context, serverURL string) (Result, error) {
+	return Result{DownMbps: 382.2, UpMbps: -8e-06}, nil
+}
+
+func TestExecuteDiscardsGarbageResult(t *testing.T) {
+	st, sched := openStore(t)
+	sched.runner = garbageRunner{}
+	sched.now = func() time.Time { return time.Unix(1_700_000_000, 0) }
+	stSettings := Settings{Enabled: true, IntervalHours: 6}
+	if err := sched.SaveSettings(stSettings); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	err := sched.executeLocked(stSettings, "manual")
+	if err == nil {
+		t.Fatal("el resultado basura debe devolver error")
+	}
+	if !strings.Contains(err.Error(), "descartado") {
+		t.Fatalf("mensaje inesperado: %v", err)
+	}
+	if last, _ := st.Latest(); last != nil {
+		t.Fatalf("nada debía persistirse, hay %+v", last)
+	}
+}