Просмотр исходного кода

feat(ui): add a Celsius/Fahrenheit temperature unit preference (#717) (#731)

Temperatures were always shown in Celsius. A display preference now
lets the user pick Celsius or Fahrenheit, applied through a single
formatter across the router cards, fleet table, detail, performance
charts, topology tooltip, SFP panel and the in-app temperature alerts.
The server keeps storing Celsius and the per-router threshold is still
edited in Celsius. The high-temperature alert now carries the router
threshold so its text no longer says 65 C for every router.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
9b07cb5942

+ 2 - 0
CHANGELOG.md

@@ -13,6 +13,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
+- **Unidad de temperatura configurable (Celsius o Fahrenheit) (#717)**: las temperaturas se mostraban siempre en Celsius. Ahora Ajustes → "Datos y umbrales" permite elegir °C o °F, una preferencia de solo presentación que se aplica a tarjetas, tabla comparativa, detalle de router, gráfico de rendimiento, topología y temperatura SFP, así como a las descripciones de las alertas de temperatura en vivo (que ahora muestran el umbral efectivo del router). El servidor y el almacenamiento siguen en Celsius, y los umbrales por router se editan en Celsius con etiqueta explícita. Las notificaciones push y el feed de la demo conservan el Celsius.
+
 - **El umbral de alerta por temperatura alta pasa a ser por router (#716)**: antes era un único valor fijo de 65 °C para todos, así que un router que corre más caliente obligaba a subir el umbral global y ocultaba problemas reales en los más frescos. Ahora cada router puede fijar el suyo (columna `temp_threshold` en `routers`, vacío = 65 °C por defecto); la alerta de temperatura y el estado "hot" del dashboard lo usan. En la UI se configura en Ajustes → Dispositivos, y se retira el slider global de "Datos y umbrales" que no gobernaba la alerta real.
 
 - **El panel WireGuard y la topología ya ven los peers de todos los túneles, no solo `wg0` (#713)**: el servidor sondeaba una única interfaz (`WG_INTERFACE`, por defecto `wg0`), así que un gateway con varios túneles solo mostraba los peers de `wg0`. Ahora `WG_INTERFACE` admite `auto` (nuevo default) o vacío para descubrir y agregar los peers de todas las interfaces del router (`wg show interfaces`), y un valor explícito (una interfaz o una lista separada por comas) sigue actuando como filtro, conservando el comportamiento del caso de un solo túnel.

+ 10 - 7
app/public/locales/en/translation.json

@@ -147,7 +147,8 @@
       },
       "high-temperature": {
         "title": "High temperature on {{router}}",
-        "description": "{{temp}} °C, above the threshold (65 °C)"
+        "description": "{{temp}} °C, above the threshold ({{threshold}} °C)",
+        "descriptionUnit": "{{temp}}, above the threshold ({{threshold}})"
       },
       "link-down": {
         "title": "Link down on {{port}}",
@@ -187,7 +188,8 @@
       },
       "sfp-temp-high": {
         "title": "SFP hot on {{port}}",
-        "description": "Temperature {{temp}} °C (threshold {{threshold}} °C)"
+        "description": "Temperature {{temp}} °C (threshold {{threshold}} °C)",
+        "descriptionUnit": "Temperature {{temp}} (threshold {{threshold}})"
       },
       "ssh-access-lost": {
         "title": "SSH access lost on {{router}}",
@@ -680,7 +682,7 @@
       "viewAllDevices": "View all devices"
     },
     "highTempAdvice": "Improve the device's ventilation.",
-    "highTempBanner": "High temperature — {{temp}} °C. Threshold: 65 °C.",
+    "highTempBanner": "High temperature: {{temp}} (threshold {{threshold}}).",
     "info": {
       "access": "Access",
       "copied": "Command copied",
@@ -709,7 +711,7 @@
     "hostKeyDone": "Key accepted: reconnecting…",
     "perf": {
       "chartAria": "{{label}} of {{name}}, range {{range}}. Current value {{value}} {{unit}}.",
-      "maxTemp": "max {{temp}} °C",
+      "maxTemp": "max {{temp}}",
       "peakCpu": "peak {{pct}} % at {{t}}",
       "ramUsed": "{{used}} MB used of {{total}} MB",
       "tableCaption": "Performance data ({{range}})",
@@ -839,12 +841,12 @@
     "firmwareOutdated": "Outdated",
     "firmwareTargetHint": "Target: {{target}}",
     "gatewayLatency": "Gateway latency",
-    "highTemp": "High temperature: {{temp}} °C · ventilation recommended",
+    "highTemp": "High temperature: {{temp}} · ventilation recommended",
     "mainGateway": "Main gateway",
     "sortBy": "Sort by {{column}}",
     "statusAria": "{{online}} routers online, {{warnings}} with warnings",
     "summary": "{{total}} routers · {{online}} online · {{warnings}} with warnings",
-    "tempThreshold": "Threshold: {{value}} °C",
+    "tempThreshold": "Threshold: {{value}}",
     "traffic24h": "Traffic 24 h",
     "trafficAria": "{{name}} traffic over the last 24 hours",
     "upgradingAll": "Updating…",
@@ -1154,7 +1156,8 @@
       "tempLabel": "Warning temperature",
       "tempNote": "The high-temperature threshold is set per router in \"Devices\" (65 °C by default).",
       "title": "Data & thresholds",
-      "units": "Traffic units"
+      "units": "Traffic units",
+      "tempUnit": "Temperature unit"
     },
     "demo": {
       "caption": "Explore NetPulse with a sample network without touching your routers",

+ 10 - 7
app/public/locales/es/translation.json

@@ -147,7 +147,8 @@
       },
       "high-temperature": {
         "title": "Temperatura alta en {{router}}",
-        "description": "{{temp}} °C, por encima del umbral (65 °C)"
+        "description": "{{temp}} °C, por encima del umbral ({{threshold}} °C)",
+        "descriptionUnit": "{{temp}}, por encima del umbral ({{threshold}})"
       },
       "link-down": {
         "title": "Link caído en {{port}}",
@@ -187,7 +188,8 @@
       },
       "sfp-temp-high": {
         "title": "SFP caliente en {{port}}",
-        "description": "Temperatura {{temp}} °C (umbral {{threshold}} °C)"
+        "description": "Temperatura {{temp}} °C (umbral {{threshold}} °C)",
+        "descriptionUnit": "Temperatura {{temp}} (umbral {{threshold}})"
       },
       "ssh-access-lost": {
         "title": "Acceso SSH perdido en {{router}}",
@@ -680,7 +682,7 @@
       "viewAllDevices": "Ver todos los dispositivos"
     },
     "highTempAdvice": "Mejora la ventilación del equipo.",
-    "highTempBanner": "Temperatura alta — {{temp}} °C. Umbral: 65 °C.",
+    "highTempBanner": "Temperatura alta: {{temp}} (umbral {{threshold}}).",
     "info": {
       "access": "Acceso",
       "copied": "Comando copiado",
@@ -709,7 +711,7 @@
     "hostKeyDone": "Clave aceptada: reconectando…",
     "perf": {
       "chartAria": "{{label}} de {{name}}, rango {{range}}. Valor actual {{value}} {{unit}}.",
-      "maxTemp": "máx {{temp}} °C",
+      "maxTemp": "máx {{temp}}",
       "peakCpu": "pico {{pct}} % a las {{t}}",
       "ramUsed": "{{used}} MB usados de {{total}} MB",
       "tableCaption": "Datos de rendimiento ({{range}})",
@@ -839,12 +841,12 @@
     "firmwareOutdated": "Desactualizado",
     "firmwareTargetHint": "Objetivo: {{target}}",
     "gatewayLatency": "Latencia a la puerta de enlace",
-    "highTemp": "Temperatura alta: {{temp}} °C · ventilación recomendada",
+    "highTemp": "Temperatura alta: {{temp}} · ventilación recomendada",
     "mainGateway": "Puerta de enlace",
     "sortBy": "Ordenar por {{column}}",
     "statusAria": "{{online}} equipos online, {{warnings}} con aviso",
     "summary": "{{total}} equipos · {{online}} online · {{warnings}} con aviso",
-    "tempThreshold": "Umbral: {{value}} °C",
+    "tempThreshold": "Umbral: {{value}}",
     "traffic24h": "Tráfico 24 h",
     "trafficAria": "Tráfico de {{name}} en las últimas 24 horas",
     "upgradingAll": "Actualizando…",
@@ -1154,7 +1156,8 @@
       "tempLabel": "Temperatura de aviso",
       "tempNote": "El umbral de temperatura alta se configura por router en «Dispositivos» (65 °C por defecto).",
       "title": "Datos y umbrales",
-      "units": "Unidades de tráfico"
+      "units": "Unidades de tráfico",
+      "tempUnit": "Unidad de temperatura"
     },
     "demo": {
       "caption": "Explora NetPulse con una red de ejemplo sin tocar tus routers",

+ 3 - 1
app/src/components/RouterCard.tsx

@@ -10,6 +10,7 @@ import { Sparkline } from '@/components/Sparkline'
 import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
 import { useAgentFor } from '@/hooks/useAgentFor'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 
 function MiniMetric({
@@ -40,6 +41,7 @@ interface RouterCardProps {
 /** Tarjeta de router (design.md §10.2): StatusRing, mini-métricas, sparkline, chevron. */
 export function RouterCard({ router, index = 0, className }: RouterCardProps) {
   const { t } = useTranslation()
+  const [tempUnit] = useTempUnit()
   const agent = useAgentFor(router.id)
   const warn = router.status === 'warn'
   const offline = router.status === 'offline'
@@ -96,7 +98,7 @@ export function RouterCard({ router, index = 0, className }: RouterCardProps) {
             <>
               <MiniMetric icon={Cpu} value={`${router.cpu} %`} label="CPU" hot={router.hotMetric === 'cpu'} />
               <MiniMetric icon={MemoryStick} value={`${router.ram} %`} label="RAM" hot={router.hotMetric === 'ram'} />
-              <MiniMetric icon={Thermometer} value={`${router.temp} °C`} label={t('common.temperature')} hot={router.hotMetric === 'temp'} />
+              <MiniMetric icon={Thermometer} value={fmtTemp(router.temp, tempUnit)} label={t('common.temperature')} hot={router.hotMetric === 'temp'} />
             </>
           )}
           <MiniMetric icon={Users} value={String(router.clients)} label={t('common.clients')} />

+ 5 - 3
app/src/components/routers/FleetCard.tsx

@@ -14,6 +14,7 @@ import { AgentBadge } from '@/components/routers/AgentBadge'
 import { useAgentFor } from '@/hooks/useAgentFor'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 
 function MetricRow({
@@ -81,6 +82,7 @@ function TrafficTooltip({
 export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps) {
   const { t } = useTranslation()
   const { isDemo } = useNetPulse()
+  const [tempUnit] = useTempUnit()
   const agent = useAgentFor(router.id)
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
@@ -129,7 +131,7 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
           <div className="mb-4 -mx-6 -mt-6 flex items-center gap-2 border-b border-warn/30 bg-warn/10 px-6 py-2.5">
             <AlertTriangle className="h-4 w-4 shrink-0 text-warn" strokeWidth={1.75} />
             <span className="text-caption font-semibold text-warn">
-              {t('routers.highTemp', { temp: router.temp })}
+              {t('routers.highTemp', { temp: fmtTemp(router.temp, tempUnit) })}
             </span>
           </div>
         )}
@@ -252,10 +254,10 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
               <MetricRow
                 icon={Thermometer}
                 label={t('common.temperature')}
-                value={`${router.temp} °C`}
+                value={fmtTemp(router.temp, tempUnit)}
                 pct={Math.min(100, ((router.temp ?? 0) / 90) * 100)}
                 hot={router.hotMetric === 'temp'}
-                title={router.hotMetric === 'temp' ? t('routers.tempThreshold', { value: router.tempThreshold ?? 65 }) : undefined}
+                title={router.hotMetric === 'temp' ? t('routers.tempThreshold', { value: fmtTemp(router.tempThreshold ?? 65, tempUnit) }) : undefined}
               />
             </>
           )}

+ 7 - 4
app/src/components/routers/FleetTable.tsx

@@ -11,6 +11,7 @@ import { MetricBar } from '@/components/MetricBar'
 import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
 import { getRouterExtras, uptimeHours } from '@/components/routers/routerExtras'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 
 const STATUS_ORDER: Record<Router['status'], number> = { online: 0, warn: 1, offline: 2 }
@@ -59,6 +60,7 @@ function sortValue(r: Router, key: SortKey): string | number {
 
 function TempCell({ router }: { router: Router }) {
   const { t } = useTranslation()
+  const [tempUnit] = useTempUnit()
   const hot = router.hotMetric === 'temp'
   if (router.temp === null) {
     return <span className="font-mono text-mono-sm text-text-faint">—</span>
@@ -69,9 +71,9 @@ function TempCell({ router }: { router: Router }) {
         'inline-flex rounded-md px-1.5 py-0.5 font-mono text-mono-sm',
         hot ? 'bg-warn/10 text-warn' : 'text-text-primary',
       )}
-      title={hot ? t('routers.tempThreshold', { value: router.tempThreshold ?? 65 }) : undefined}
+      title={hot ? t('routers.tempThreshold', { value: fmtTemp(router.tempThreshold ?? 65, tempUnit) }) : undefined}
     >
-      {router.temp} °C
+      {fmtTemp(router.temp, tempUnit)}
     </span>
   )
 }
@@ -95,6 +97,7 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
   const navigate = useNavigate()
   const reduce = useReducedMotion()
   const { routers, agents } = useNetPulse()
+  const [tempUnit] = useTempUnit()
   const [sortKey, setSortKey] = useState<SortKey>('name')
   const [asc, setAsc] = useState(true)
   const [openId, setOpenId] = useState<string | null>(null)
@@ -249,7 +252,7 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                     pulse={r.status !== 'online'}
                   />
                   <span className={cn('font-mono text-mono-sm', r.hotMetric === 'temp' ? 'text-warn' : 'text-text-secondary')}>
-                    {r.temp === null ? '—' : `${r.temp} °C`}
+                    {r.temp === null ? '—' : fmtTemp(r.temp, tempUnit)}
                   </span>
                   <ChevronDown className={cn('h-4 w-4 text-text-muted transition-transform', open && 'rotate-180')} strokeWidth={1.75} />
                 </span>
@@ -266,7 +269,7 @@ export function FleetTable({ refreshKey = 0 }: { refreshKey?: number }) {
                       {[
                         ['CPU', r.cpu === null ? '—' : `${r.cpu} %`],
                         ['RAM', r.ram === null ? '—' : `${r.ram} %`],
-                        [t('routers.colTemp'), r.temp === null ? '—' : `${r.temp} °C`],
+                        [t('routers.colTemp'), r.temp === null ? '—' : fmtTemp(r.temp, tempUnit)],
                         [t('routers.colClients'), String(r.clients)],
                         [t('routers.colTraffic'), `↓ ${fmtEs(extras.trafficNow, 1)} Mbps`],
                         ['Uptime', fmtUptime(r.uptime)],

+ 3 - 1
app/src/components/routers/PortPanel.tsx

@@ -9,6 +9,7 @@ import type { EthPort, RouterExtras, SfpInfo } from '@/components/routers/router
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 import { Activity } from 'lucide-react'
 import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 
 /**
@@ -219,6 +220,7 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
 /** SfpDetail: sección SFP del tooltip (temperatura, potencia óptica, vendor). */
 function SfpDetail({ sfp }: { sfp: SfpInfo }) {
   const { t } = useTranslation()
+  const [tempUnit] = useTempUnit()
   const tempHot = sfp.temperature > 70
   const rxLow = sfp.rxPower < -14
   return (
@@ -230,7 +232,7 @@ function SfpDetail({ sfp }: { sfp: SfpInfo }) {
       <div className="grid grid-cols-2 gap-1.5">
         <MiniStat
           label={t('routerDetail.ports.sfpTemp')}
-          value={`${sfp.temperature.toFixed(1)} °C`}
+          value={fmtTemp(sfp.temperature, tempUnit, 1)}
         />
         <MiniStat
           label={t('routerDetail.ports.sfpRx')}

+ 12 - 9
app/src/components/routers/RouterPerformance.tsx

@@ -10,6 +10,7 @@ import { SectionHeader } from '@/components/SectionHeader'
 import { SegmentedControl } from '@/components/SegmentedControl'
 import type { PerfPoint } from '@/components/routers/routerExtras'
 import { perfCaptions, perfSeries } from '@/components/routers/routerExtras'
+import { fmtTemp, tempUnitSymbol, toTempUnit, useTempUnit } from '@/lib/temperature'
 
 type PerfRange = '1h' | '24h' | '7d'
 
@@ -46,15 +47,17 @@ function PerfTooltip({
   label?: string
 }) {
   const { t } = useTranslation()
+  const [tempUnit] = useTempUnit()
   if (!active || !payload?.length) return null
   const p = payload[0]!
   const def = SERIES.find((s) => s.key === p.dataKey)
+  const display = def?.key === 'temp' ? fmtTemp(Number(p.value), tempUnit) : `${p.value} ${def?.unit}`
   return (
     <div className="rounded-[10px] border border-border-strong bg-elevated px-3 py-2 shadow-lg">
       <div className="mb-0.5 font-mono text-caption text-text-muted">{label}</div>
       <div className="flex items-center gap-2 font-mono text-mono-sm text-text-primary">
         <span className="h-2 w-2 rounded-full" style={{ background: def?.color ?? '#22D3EE' }} />
-        {def ? t(def.labelKey) : ''}: {p.value} {def?.unit}
+        {def ? t(def.labelKey) : ''}: {display}
       </div>
     </div>
   )
@@ -66,6 +69,7 @@ function PerfTooltip({
 export function RouterPerformance({ router, liveSeries, totalRamMb }: { router: Router; liveSeries?: PerfSeriesLive; totalRamMb?: number }) {
   const { t } = useTranslation()
   const { isDemo } = useNetPulse()
+  const [tempUnit] = useTempUnit()
   const [range, setRange] = useState<PerfRange>('24h')
   const reduce = useReducedMotion()
   const data = useMemo(() => {
@@ -77,15 +81,14 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
     return [{ t: '', cpu: router.cpu ?? 0, ram: router.ram ?? 0, temp: router.temp ?? 0 }]
   }, [isDemo, router, range, liveSeries])
   const captions = useMemo(
-    () => perfCaptions(router, data, isDemo ? undefined : totalRamMb),
-    [router, data, isDemo, totalRamMb],
+    () => perfCaptions(router, data, isDemo ? undefined : totalRamMb, tempUnit),
+    [router, data, isDemo, totalRamMb, tempUnit],
   )
 
   // #441: null cuando la fuente no reporta vitals (el panel no se monta,
   // pero el tipo lo exige); se normaliza a 0 para el render defensivo.
   const current: Record<SeriesDef['key'], number> = { cpu: router.cpu ?? 0, ram: router.ram ?? 0, temp: router.temp ?? 0 }
   const captionByKey: Record<SeriesDef['key'], string> = { cpu: captions.cpu, ram: captions.ram, temp: captions.temp }
-
   return (
     <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
       <div className="flex flex-wrap items-center justify-between gap-3">
@@ -112,7 +115,7 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
                 <span className="text-label uppercase text-text-muted">{t(s.labelKey)}</span>
                 <span className="text-caption text-text-muted sm:hidden">{captionByKey[s.key]}</span>
               </div>
-              <div className="h-[90px]" role="img" aria-label={t('routerDetail.perf.chartAria', { label: t(s.labelKey), name: router.name, range, value: current[s.key], unit: s.unit })}>
+              <div className="h-[90px]" role="img" aria-label={t('routerDetail.perf.chartAria', { label: t(s.labelKey), name: router.name, range, value: s.key === 'temp' ? Math.round(toTempUnit(current[s.key], tempUnit)) : current[s.key], unit: s.key === 'temp' ? tempUnitSymbol(tempUnit) : s.unit })}>
                 <ResponsiveContainer width="100%" height="100%">
                   <AreaChart data={data} syncId={SYNC_ID} syncMethod="index" margin={{ top: 4, right: 0, bottom: 0, left: 0 }}>
                     <defs>
@@ -132,7 +135,7 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
                           stroke="#FBBF24"
                           strokeDasharray="4 4"
                           strokeOpacity={0.8}
-                          label={{ value: '65 °C', position: 'insideTopRight', fill: '#FBBF24', fontSize: 9, fontFamily: '"JetBrains Mono", monospace' }}
+                          label={{ value: fmtTemp(TEMP_THRESHOLD, tempUnit), position: 'insideTopRight', fill: '#FBBF24', fontSize: 9, fontFamily: '"JetBrains Mono", monospace' }}
                         />
                       </>
                     )}
@@ -153,8 +156,8 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
             </div>
             <div className="w-20 shrink-0 text-right sm:w-24">
               <div className="kpi-value text-xl font-semibold text-text-primary">
-                <CountUp key={range} value={current[s.key]} />
-                <span className="ml-0.5 text-xs font-medium text-text-secondary">{s.unit}</span>
+                <CountUp key={range} value={s.key === 'temp' ? Math.round(toTempUnit(current[s.key], tempUnit)) : current[s.key]} />
+                <span className="ml-0.5 text-xs font-medium text-text-secondary">{s.key === 'temp' ? tempUnitSymbol(tempUnit) : s.unit}</span>
               </div>
               <div className="mt-0.5 hidden text-caption text-text-muted sm:block">{captionByKey[s.key]}</div>
             </div>
@@ -167,7 +170,7 @@ export function RouterPerformance({ router, liveSeries, totalRamMb }: { router:
       <span className="sr-only">{t('routerDetail.perf.tableCaption', { range })}</span>
       <table className="sr-only">
         <thead>
-          <tr><th>{t('home.traffic.time')}</th><th>CPU (%)</th><th>{t('common.memory')} (%)</th><th>{t('common.temperature')} (°C)</th></tr>
+          <tr><th>{t('home.traffic.time')}</th><th>CPU (%)</th><th>{t('common.memory')} (%)</th><th>{t('common.temperature')} ({tempUnitSymbol(tempUnit)})</th></tr>
         </thead>
         <tbody>
           {data.map((p: PerfPoint) => (

+ 4 - 3
app/src/components/routers/routerExtras.ts

@@ -9,6 +9,7 @@
 import i18n, { dayAbbr } from '@/i18n'
 import type { Router } from '@/data/mock'
 import { adguard, routers } from '@/data/mock'
+import { fmtTemp, type TempUnit } from '@/lib/temperature'
 
 // ---------------------------------------------------------------------------
 // Extras por router
@@ -313,7 +314,7 @@ export function perfSeries(router: Router, range: '1h' | '24h' | '7d'): PerfPoin
   return points
 }
 
-export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number): { cpu: string; ram: string; temp: string } {
+export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number, unit: TempUnit = 'c'): { cpu: string; ram: string; temp: string } {
   // totalMb es la RAM total real (live, del backend). En demo (sin totalMb)
   // se usa el resolver demo, igual que antes.
   const total = totalMb && totalMb > 0 ? totalMb : getRouterExtras(router.id).ramMb
@@ -324,7 +325,7 @@ export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number
     return {
       cpu: i18n.t('routerDetail.perf.peakCpu', { pct: cpu, t: '—' }),
       ram: i18n.t('routerDetail.perf.ramUsed', { used: ramUsed, total }),
-      temp: i18n.t('routerDetail.perf.maxTemp', { temp }),
+      temp: i18n.t('routerDetail.perf.maxTemp', { temp: fmtTemp(temp, unit) }),
     }
   }
   const cpuMax = data.reduce((m, p) => (p.cpu > m.cpu ? p : m), data[0]!)
@@ -333,7 +334,7 @@ export function perfCaptions(router: Router, data: PerfPoint[], totalMb?: number
   return {
     cpu: i18n.t('routerDetail.perf.peakCpu', { pct: cpuMax.cpu, t: cpuMax.t }),
     ram: i18n.t('routerDetail.perf.ramUsed', { used: ramUsed, total }),
-    temp: i18n.t('routerDetail.perf.maxTemp', { temp: tempMax.temp }),
+    temp: i18n.t('routerDetail.perf.maxTemp', { temp: fmtTemp(tempMax.temp, unit) }),
   }
 }
 

+ 3 - 1
app/src/components/topology/TopologyMap.tsx

@@ -17,6 +17,7 @@ import type { Device, DistributionNode, Router, WanInfo, WGPeer } from '@/data/m
 import { fmtEs } from '@/data/mock'
 import { StatusPill } from '@/components/StatusPill'
 import { DEVICE_ICONS } from '@/components/DeviceRow'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { cn } from '@/lib/utils'
 import type { ChipNode, DistNodeView, RouterNode, TopologyModel } from './model'
 import { COLOR, VB_H, VB_W, bandColor, linkColor, statusColor } from './model'
@@ -123,6 +124,7 @@ function TooltipCard({
   onPointerLeave?: () => void
 }) {
   const { t } = useTranslation()
+  const [tempUnit] = useTempUnit()
   return (
     <div
       className={cn(
@@ -156,7 +158,7 @@ function TooltipCard({
             {/* #441: sin vitals (switch SNMP/beacon) se muestra un guion */}
             <MiniStat label="CPU" value={tip.router.cpu === null ? '—' : `${tip.router.cpu} %`} />
             <MiniStat label="RAM" value={tip.router.ram === null ? '—' : `${tip.router.ram} %`} />
-            <MiniStat label={t('routers.colTemp')} value={tip.router.temp === null ? '—' : `${tip.router.temp} °C`} hot={tip.router.hotMetric === 'temp'} />
+            <MiniStat label={t('routers.colTemp')} value={tip.router.temp === null ? '—' : fmtTemp(tip.router.temp, tempUnit)} hot={tip.router.hotMetric === 'temp'} />
             <MiniStat label={t('routers.colClients')} value={String(tip.router.clients)} />
           </div>
           <div className="mt-2 text-caption font-semibold text-accent">

+ 9 - 0
app/src/lib/alerts-i18n.ts

@@ -13,6 +13,7 @@
  */
 import type { TFunction } from 'i18next'
 import type { AlertEvent } from '@/data/types'
+import { formatAlertTempVars, readTempUnit } from '@/lib/temperature'
 
 export function alertTitle(t: TFunction, ev: AlertEvent): string {
   if (!ev.type) return ev.title
@@ -21,6 +22,14 @@ export function alertTitle(t: TFunction, ev: AlertEvent): string {
 
 export function alertDescription(t: TFunction, ev: AlertEvent): string {
   if (!ev.type) return ev.description
+  // Las alertas de temperatura se muestran en la unidad elegida (issue #717):
+  // la clave `descriptionUnit` espera `{{temp}}`/`{{threshold}}` ya formateados
+  // con su unidad (la `description` original, con °C literal, se conserva para
+  // el push del service worker, que no conoce la preferencia).
+  if (ev.type === 'high-temperature' || ev.type === 'sfp-temp-high') {
+    const vars = formatAlertTempVars(ev.type, ev.vars, readTempUnit())
+    return t(`alerts.types.${ev.type}.descriptionUnit`, { defaultValue: ev.description, ...(vars ?? {}) })
+  }
   return t(`alerts.types.${ev.type}.description`, { defaultValue: ev.description, ...(ev.vars ?? {}) })
 }
 

+ 94 - 0
app/src/lib/temperature.ts

@@ -0,0 +1,94 @@
+/**
+ * Preferencia de unidad de temperatura (issue #717).
+ *
+ * El servidor almacena y expone las temperaturas SIEMPRE en Celsius (grados).
+ * Esta preferencia es SOLO de presentación: convierte al formatear para
+ * pintar, sin tocar el dato ni el contrato del servidor.
+ *
+ * Persistencia en localStorage (`netpulse-temp-unit`, 'c' | 'f') con un
+ * evento de cambio (`netpulse-temp-unit-change`) para que los componentes ya
+ * montados se actualicen sin recargar, patrón análogo a `netpulse-refresh-change`.
+ */
+import { useEffect, useState } from 'react'
+import { fmtEs } from '@/data/mock'
+
+export type TempUnit = 'c' | 'f'
+
+const STORAGE_KEY = 'netpulse-temp-unit'
+const CHANGE_EVENT = 'netpulse-temp-unit-change'
+
+/** Lee la unidad guardada; 'c' por defecto (o si el valor no es válido). */
+export function readTempUnit(): TempUnit {
+  try {
+    const raw = localStorage.getItem(STORAGE_KEY)
+    return raw === 'f' ? 'f' : 'c'
+  } catch {
+    return 'c'
+  }
+}
+
+/** Convierte un valor en Celsius al valor en la unidad elegida. */
+export function toTempUnit(celsius: number, unit: TempUnit): number {
+  return unit === 'f' ? (celsius * 9) / 5 + 32 : celsius
+}
+
+/** Símbolo de la unidad. */
+export function tempUnitSymbol(unit: TempUnit): string {
+  return unit === 'f' ? '°F' : '°C'
+}
+
+/**
+ * Formatea una temperatura en Celsius como string con la unidad elegida:
+ * `fmtTemp(65, 'f')` → "149 °F", `fmtTemp(21.1, 'f', 1)` → "70.0 °F".
+ * `celsius === null` → "—".
+ */
+export function fmtTemp(celsius: number | null, unit: TempUnit, decimals = 0): string {
+  if (celsius === null) return '—'
+  const v = toTempUnit(celsius, unit)
+  const rounded = Number(v.toFixed(decimals))
+  return `${fmtEs(rounded, decimals)} ${tempUnitSymbol(unit)}`
+}
+
+/** Escribe la unidad y notifica a los componentes suscritos. */
+export function setTempUnit(unit: TempUnit): void {
+  try {
+    localStorage.setItem(STORAGE_KEY, JSON.stringify(unit))
+  } catch {
+    /* modo privado */
+  }
+  window.dispatchEvent(new Event(CHANGE_EVENT))
+}
+
+/** Hook: unidad actual + setter reactivo a cambios desde Ajustes. */
+export function useTempUnit(): [TempUnit, (u: TempUnit) => void] {
+  const [unit, setUnit] = useState<TempUnit>(readTempUnit)
+  useEffect(() => {
+    const onChange = () => setUnit(readTempUnit())
+    window.addEventListener(CHANGE_EVENT, onChange)
+    return () => window.removeEventListener(CHANGE_EVENT, onChange)
+  }, [])
+  return [unit, setTempUnit]
+}
+
+/**
+ * Formatea las variables de temperatura de una alerta (`temp` y, si existe,
+ * `threshold`) según la unidad elegida. El resto de variables se conserva tal
+ * cual. Solo afecta a los tipos de alerta que llevan temperaturas.
+ */
+export function formatAlertTempVars(
+  type: string | undefined,
+  vars: Record<string, string> | undefined,
+  unit: TempUnit,
+): Record<string, string> | undefined {
+  if (!vars) return vars
+  if (type !== 'high-temperature' && type !== 'sfp-temp-high') return vars
+  const next: Record<string, string> = { ...vars }
+  const fmt = (raw: string) => {
+    const n = Number(raw)
+    if (!Number.isFinite(n)) return raw
+    return fmtTemp(n, unit, raw.includes('.') ? 1 : 0)
+  }
+  if (next.temp !== undefined) next.temp = fmt(next.temp)
+  if (next.threshold !== undefined) next.threshold = fmt(next.threshold)
+  return next
+}

+ 3 - 1
app/src/pages/RouterDetail.tsx

@@ -4,6 +4,7 @@ import { Link, useLocation, useParams } from 'react-router'
 import { AlertTriangle, ArrowLeft, Gauge, Router as RouterIcon, ShieldAlert } from 'lucide-react'
 import { motion, useReducedMotion } from 'framer-motion'
 import { alertRelTime } from '@/i18n'
+import { fmtTemp, useTempUnit } from '@/lib/temperature'
 import { useNetPulse } from '@/data/DataProvider'
 import type { RouterDetailData } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
@@ -29,6 +30,7 @@ export default function RouterDetail() {
   const auth = useAuth()
   const isAdmin = auth?.role === 'admin'
   const { routers, alerts, getRouterDetail, isDemo } = useNetPulse()
+  const [tempUnit] = useTempUnit()
   const router = routers.find((r) => r.id === id)
   const isGateway = router?.roleBadge === 'Principal'
   const [detail, setDetail] = useState<RouterDetailData | null>(null)
@@ -152,7 +154,7 @@ export default function RouterDetail() {
             <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-warn" strokeWidth={1.75} />
             <div className="min-w-0 flex-1">
               <div className="text-sm font-semibold text-warn">
-                {t('routerDetail.highTempBanner', { temp: router.temp })}
+                {t('routerDetail.highTempBanner', { temp: fmtTemp(router.temp, tempUnit), threshold: fmtTemp(router.tempThreshold ?? 65, tempUnit) })}
               </div>
               <p className="mt-0.5 text-sm text-text-secondary">
                 {t('routerDetail.highTempAdvice')}

+ 19 - 0
app/src/pages/Settings.tsx

@@ -64,6 +64,7 @@ import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import type { ServicesVisibility } from '@/hooks/useServicesVisibility'
 import { relTimeFromTs } from '@/i18n'
 import { cn, copyToClipboard, exitDemo } from '@/lib/utils'
+import { useTempUnit } from '@/lib/temperature'
 import { notifyBanner } from '@/lib/update-check'
 import { PALETTES, type PaletteId, type ThemeMode } from '@/lib/theme-boot'
 import TelegramCard from '@/components/TelegramCard'
@@ -3645,6 +3646,7 @@ export default function Settings() {
 
   // ——— Datos y umbrales ———
   const [units, setUnits] = useStoredState<'mbps' | 'mbs'>('netpulse-units', 'mbps')
+  const [tempUnit, setTempUnit] = useTempUnit()
   const [decimalEs, setDecimalEs] = useStoredState('netpulse-decimal-es', true)
   const [refresh, setRefresh] = useStoredState<'3' | '5' | '10' | '0'>('netpulse-refresh', '3')
   const [signalT, setSignalT] = useStoredState('netpulse-th-signal', -70)
@@ -3844,6 +3846,23 @@ export default function Settings() {
                     />
                   </div>
                 </div>
+                <div>
+                  <div className="text-sm font-medium text-text-primary">{t('settings.data.tempUnit')}</div>
+                  <div className="mt-2">
+                    <SegmentedControl
+                      options={[
+                        { value: 'c', label: '°C' },
+                        { value: 'f', label: '°F' },
+                      ]}
+                      value={tempUnit}
+                      onChange={(v) => {
+                        setTempUnit(v)
+                        notify()
+                      }}
+                      ariaLabel={t('settings.data.tempUnit')}
+                    />
+                  </div>
+                </div>
                 <div>
                   <SwitchRow
                     label={t('settings.data.decimalEs')}

+ 1 - 1
server-go/internal/adapters/live.go

@@ -2253,7 +2253,7 @@ func (l *Live) emitTempAlert(cfg RouterConfig, router Router) {
 		Description: fmt.Sprintf("%d °C, por encima del umbral (%d °C)", *router.Temp, thr),
 		Hint:        alerts.HintFor(alerts.HintHighTemp),
 		Type:        alerts.HintHighTemp,
-		Vars:        map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp)},
+		Vars:        map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp), "threshold": strconv.Itoa(thr)},
 		Time:        "ahora mismo", RouterID: cfg.ID,
 	})
 }

+ 3 - 0
server-go/internal/adapters/live_temp_threshold_test.go

@@ -88,6 +88,9 @@ func TestEmitTempAlertUsesPerRouterThreshold(t *testing.T) {
 	if !strings.Contains(list[0].Description, "70 °C") {
 		t.Fatalf("la descripción no refleja el umbral del router: %q", list[0].Description)
 	}
+	if list[0].Vars["threshold"] != "70" {
+		t.Fatalf("Vars.threshold=%q, esperaba 70", list[0].Vars["threshold"])
+	}
 }
 
 func TestEmitTempAlertNoAlertBelowThreshold(t *testing.T) {