The device list and detail page showed empty status columns/fields until
every request finished. They now render instantly from the last-known data
and refresh in the background, with a small "Syncing…" spinner in the page
header while fresh data is in flight.
- lib/deviceCache.js: last-known device list (per query), devices by id,
fleet status map, list metrics and Health-overview datasets. In memory
plus sessionStorage (except the large Health datasets); every storage
access is guarded.
- DeviceList: seeded from cache; status + metrics fetched in parallel with
the device list instead of after it; out-of-order search responses are
ignored; live heartbeats are written back to the cache.
- DeviceDetail: seeded from cache (DeviceList already holds the device),
reloads after modal saves refresh in place instead of unmounting the
tab, status comes from the new /mqtt/status/{serial}.
- HealthTab overview: same stale-while-revalidate per device + range.
Health tab firmware lag: the Firmware/OTA tile read the version from the
latest diagnostics report, which the firmware sends only every 5 minutes
(the first 5 minutes after boot), and the tab never re-fetched it while
open — so after an OTA it kept showing the old version. Firmware reports the
same compiled FW_VERSION in heartbeat and diagnostics, so the tile now uses
the heartbeat (30s, pushed live over WebSocket) and only shows the OTA
"update available" badge when the diagnostics report describes the
firmware that is running now. HealthTab also passes deviceId/canEdit down
to LogsTab for the log management actions in the next commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1016 lines
45 KiB
React
1016 lines
45 KiB
React
// frontend/src/pages/bellcloud/devices/tabs/HealthTab.jsx
|
|
// Health tab — stability/diagnostics data derived from firmware boot tracking
|
|
// (F-052/F-053/F-056) and MQTT heartbeat/ping telemetry: lifetime boot count,
|
|
// reset reasons, coredump crash detail, RSSI/ping/heap/temp trends, restart
|
|
// timeline. Sub-tabs: Overview, Logs (full MQTT log explorer), Settings
|
|
// (per-device alert thresholds). A single time-range control in the toolbar
|
|
// scopes every data-fetching section on the page (Overview fully; Logs'
|
|
// Unified/Device Logs/Info channels — Alerts/Heartbeats/Commands panels don't
|
|
// have range support on their endpoints yet).
|
|
|
|
import { useState, useEffect, useCallback, useMemo } from 'react'
|
|
import api from '@/lib/api'
|
|
import { getCachedHealth, setCachedHealth } from '@/lib/deviceCache'
|
|
import Card from '@/components/ui/Card'
|
|
import StatusBadge from '@/components/ui/StatusBadge'
|
|
import Spinner from '@/components/ui/Spinner'
|
|
import Icon from '@/components/ui/Icon'
|
|
import FormField from '@/components/ui/FormField'
|
|
import Button from '@/components/ui/Button'
|
|
import TimeRangeSelect from '@/components/ui/TimeRangeSelect'
|
|
import LineChart from '@/components/ui/LineChart'
|
|
import LogsTab from '@/pages/bellcloud/devices/tabs/LogsTab'
|
|
import { fmtDateTimeMedium, fmtRelative } from '@/lib/formatters'
|
|
import { resolveRange } from '@/lib/timeRange'
|
|
import { useToast } from '@/components/ui/Toast'
|
|
import CrashDetail from '@/components/shared/CrashDetail'
|
|
import { hasCrashDetail, crashHeadline, isHeapExhaustion } from '@/lib/crashReport'
|
|
|
|
// ─── Reset reason → badge variant ──────────────────────────────────────────
|
|
|
|
const FAULT_REASONS = new Set([
|
|
'PANIC', 'TASK_WATCHDOG', 'INTERRUPT_WATCHDOG', 'OTHER_WATCHDOG', 'BROWNOUT',
|
|
])
|
|
|
|
function reasonVariant(reason, isFault) {
|
|
if (isFault ?? FAULT_REASONS.has(reason)) return 'danger'
|
|
if (reason === 'UNKNOWN') return 'warning'
|
|
return 'success'
|
|
}
|
|
|
|
function reasonLabel(reason) {
|
|
if (!reason) return 'Unknown'
|
|
return reason.replace(/_/g, ' ')
|
|
}
|
|
|
|
const DEFAULT_OFFLINE_TIMEOUT_SEC = 90 // matches backend's online = seconds_since_heartbeat < 90
|
|
|
|
// Standard section gap used everywhere on this tab — matches the gap other
|
|
// device-detail tabs (e.g. General) and DESIGN.md's masonry-grid use, so the
|
|
// Health tab doesn't visually stand apart with its own tighter/looser rhythm.
|
|
const SECTION_GAP = 'var(--space-6)'
|
|
|
|
// RSSI color stops — fixed semantic thresholds (not user-configurable, unlike
|
|
// CPU temp): weak/fair/good signal quality. Matches SignalIndicator's own
|
|
// dBm bands so the line chart and the header signal icon never disagree.
|
|
const RSSI_COLOR_STOPS = [
|
|
{ value: -90, color: 'var(--color-danger)' },
|
|
{ value: -70, color: 'var(--color-warning)' },
|
|
{ value: -50, color: 'var(--color-success)' },
|
|
]
|
|
|
|
// ─── Equal-height card grid ─────────────────────────────────────────────────
|
|
// DESIGN.md §11: masonry-grid is for variable-height sections that should
|
|
// auto-flow into balanced columns — it does NOT equalize row heights. Stat
|
|
// tiles and same-shape chart cards must align horizontally, so this uses a
|
|
// real CSS grid instead (masonry would render them at uneven heights).
|
|
|
|
function EqualGrid({ columns, children }) {
|
|
return (
|
|
<div style={{
|
|
display: 'grid',
|
|
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
|
|
gap: SECTION_GAP,
|
|
alignItems: 'stretch',
|
|
}}>
|
|
{children}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ─── Hero KPI tile — uses Card's real title/subtitle so padding matches
|
|
// every other card on the page exactly, per point #1/#8. Content below the
|
|
// title is vertically centered in the remaining body height (#2).
|
|
|
|
function KpiTile({ label, value, unit, sublabel, badge, variant }) {
|
|
const color =
|
|
variant === 'danger' ? 'var(--color-danger)' :
|
|
variant === 'warning' ? 'var(--color-warning)' :
|
|
'var(--color-text-primary)'
|
|
return (
|
|
<Card title={label}>
|
|
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 'var(--space-1)', minHeight: 64 }}>
|
|
{badge ?? (
|
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1.75rem', fontWeight: 'var(--font-weight-bold)', color, lineHeight: 1.15, letterSpacing: '-0.01em' }}>
|
|
{value}
|
|
{unit && <span style={{ fontSize: '1rem', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)', marginLeft: 4 }}>{unit}</span>}
|
|
</span>
|
|
)}
|
|
{sublabel && (
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
|
|
{sublabel}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</Card>
|
|
)
|
|
}
|
|
|
|
// ─── Secondary metric tile (more compact, same Card-title convention) ──────
|
|
|
|
function MetricTile({ label, value, unit, sublabel, children }) {
|
|
return (
|
|
<Card title={label}>
|
|
<div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 2, minHeight: 44 }}>
|
|
{children ?? (
|
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1.15rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
|
{value}
|
|
{unit && <span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginLeft: 3 }}>{unit}</span>}
|
|
</span>
|
|
)}
|
|
{sublabel && (
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
|
{sublabel}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</Card>
|
|
)
|
|
}
|
|
|
|
// ─── Restart timeline — full-width horizontal track, one dot per boot ─────
|
|
// Range-aware per #7: the track always spans [rangeStart, rangeEnd], with
|
|
// dots placed at their real position in that span — a device with only 1
|
|
// day of history inside a 30-day view shows its dots bunched near one edge,
|
|
// not stretched to fill the whole track.
|
|
|
|
function RestartTimeline({ events, rangeStart, rangeEnd }) {
|
|
const tMin = rangeStart
|
|
const tMax = rangeEnd
|
|
const span = Math.max(1, tMax - tMin)
|
|
|
|
return (
|
|
<div style={{ position: 'relative', padding: 'var(--space-4) var(--space-2) var(--space-2)' }}>
|
|
<div style={{
|
|
position: 'relative', height: 8, margin: '32px 4px 8px',
|
|
background: 'var(--color-bg-abyss)', border: '1px solid var(--color-border)',
|
|
borderRadius: 4,
|
|
}}>
|
|
{events.length === 0 && (
|
|
<span style={{
|
|
position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
|
|
fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic',
|
|
whiteSpace: 'nowrap', background: 'var(--color-bg-surface)', padding: '0 var(--space-2)',
|
|
}}>
|
|
No boot events in this range
|
|
</span>
|
|
)}
|
|
{events.map((e, i) => {
|
|
const t = new Date(e.occurred_at).getTime()
|
|
const pct = Math.max(0, Math.min(100, ((t - tMin) / span) * 100))
|
|
const color = e.is_fault ? 'var(--color-danger)' : 'var(--color-success)'
|
|
return (
|
|
<div
|
|
key={e.id ?? i}
|
|
title={`Boot #${e.boot_count ?? '?'} · ${reasonLabel(e.reset_reason)} · ${fmtDateTimeMedium(e.occurred_at)}`}
|
|
style={{
|
|
position: 'absolute', top: '50%', left: `${pct}%`,
|
|
transform: 'translate(-50%, -50%)',
|
|
width: e.is_fault ? 12 : 10, height: e.is_fault ? 12 : 10,
|
|
borderRadius: '50%',
|
|
background: color,
|
|
boxShadow: `0 0 8px ${color}`,
|
|
border: '2px solid var(--color-bg-surface)',
|
|
cursor: 'default',
|
|
}}
|
|
/>
|
|
)
|
|
})}
|
|
</div>
|
|
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
|
|
{fmtDateTimeMedium(new Date(tMin).toISOString())}
|
|
</span>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
|
|
{fmtDateTimeMedium(new Date(tMax).toISOString())}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ─── Boot event row (expandable for crash detail) ──────────────────────────
|
|
|
|
function BootEventRow({ event, expanded, onToggle }) {
|
|
const hasCrash = hasCrashDetail(event)
|
|
const headline = hasCrash ? crashHeadline(event) : null
|
|
const heapLow = isHeapExhaustion(event.pre_crash)
|
|
return (
|
|
<div style={{ borderBottom: '1px solid var(--color-border)' }}>
|
|
<div
|
|
onClick={hasCrash ? onToggle : undefined}
|
|
style={{
|
|
display: 'flex', alignItems: 'center', gap: 'var(--space-4)', flexWrap: 'wrap',
|
|
padding: 'var(--space-3) var(--space-4)',
|
|
cursor: hasCrash ? 'pointer' : 'default',
|
|
}}
|
|
>
|
|
<span style={{ width: 160, flexShrink: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
|
|
{fmtDateTimeMedium(event.occurred_at)}
|
|
</span>
|
|
<StatusBadge variant={reasonVariant(event.reset_reason, event.is_fault)} size="sm">
|
|
{reasonLabel(event.reset_reason)}
|
|
</StatusBadge>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
|
|
boot #{event.boot_count ?? '—'}
|
|
</span>
|
|
{headline && (
|
|
<span style={{
|
|
flex: 1, minWidth: 0, fontSize: 'var(--font-size-xs)', color: 'var(--color-danger)',
|
|
fontFamily: 'var(--font-family-mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
}}>
|
|
{headline}
|
|
</span>
|
|
)}
|
|
{!headline && <span style={{ flex: 1 }} />}
|
|
{heapLow && <StatusBadge variant="warning" size="sm">Low heap</StatusBadge>}
|
|
{event.free_heap != null && (
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>
|
|
{Math.round(event.free_heap / 1024)} KB free at boot
|
|
</span>
|
|
)}
|
|
{hasCrash && (
|
|
<Icon
|
|
name="chevron_down"
|
|
size={14}
|
|
color="var(--color-text-muted)"
|
|
style={{ transform: expanded ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }}
|
|
/>
|
|
)}
|
|
</div>
|
|
{expanded && hasCrash && (
|
|
<div style={{ padding: 'var(--space-2) var(--space-4) var(--space-5)' }}>
|
|
<CrashDetail event={event} />
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ─── Health status icon — computed client-side from Settings thresholds ───
|
|
|
|
function statusFromThresholds({ mqttStatus, latestDiag, restartsInRange, settings }) {
|
|
const w = settings.warning || {}
|
|
const c = settings.critical || {}
|
|
const rssi = mqttStatus?.last_heartbeat?.rssi
|
|
const heapKb = mqttStatus?.last_heartbeat?.free_heap != null ? mqttStatus.last_heartbeat.free_heap / 1024 : null
|
|
const temp = latestDiag?.cpu_temp_avg
|
|
|
|
const checks = [
|
|
[c.restarts_per_week_threshold, restartsInRange],
|
|
[c.rssi_floor_dbm, rssi, true],
|
|
[c.free_heap_floor_kb, heapKb, true],
|
|
[c.cpu_temp_ceiling_c, temp],
|
|
]
|
|
const warnChecks = [
|
|
[w.restarts_per_week_threshold, restartsInRange],
|
|
[w.rssi_floor_dbm, rssi, true],
|
|
[w.free_heap_floor_kb, heapKb, true],
|
|
[w.cpu_temp_ceiling_c, temp],
|
|
]
|
|
|
|
const crossed = (threshold, value, isFloor = false) => {
|
|
if (threshold == null || value == null) return false
|
|
return isFloor ? value < threshold : value > threshold
|
|
}
|
|
|
|
if (checks.some(([t, v, floor]) => crossed(t, v, floor))) return 'critical'
|
|
if (warnChecks.some(([t, v, floor]) => crossed(t, v, floor))) return 'warning'
|
|
return 'ok'
|
|
}
|
|
|
|
function StatusIcon({ status }) {
|
|
const meta = {
|
|
ok: { name: 'check', color: 'var(--color-success)', label: 'All thresholds within range' },
|
|
warning: { name: 'warning', color: 'var(--color-warning)', label: 'A warning threshold has been crossed' },
|
|
critical: { name: 'warning', color: 'var(--color-danger)', label: 'A critical threshold has been crossed' },
|
|
}[status] || { name: 'info', color: 'var(--color-text-muted)', label: 'Status unknown' }
|
|
|
|
return (
|
|
<span title={meta.label} style={{ display: 'inline-flex', alignItems: 'center' }}>
|
|
<Icon name={meta.name} size={16} color={meta.color} />
|
|
</span>
|
|
)
|
|
}
|
|
|
|
// ─── Firmware version + OTA badge ──────────────────────────────────────────
|
|
// The running version comes from the latest HEARTBEAT (every 30s, and pushed
|
|
// live over the WebSocket), not the diagnostics report. Diagnostics arrive
|
|
// only every 5 minutes — the first one 5 min after boot — and this tab
|
|
// doesn't re-fetch them while open, so right after an OTA the report still
|
|
// described the old firmware and the tile lagged behind. Both carry the same
|
|
// compiled FW_VERSION on the device, so the heartbeat is simply fresher.
|
|
// The OTA "update available" flag only exists in diagnostics, so it's shown
|
|
// only when that report describes the firmware that is running now.
|
|
|
|
const normFw = v => (v ? String(v).trim().replace(/^v/i, '') : '')
|
|
|
|
function firmwareSummary(mqttStatus, latestDiag) {
|
|
const hbFw = normFw(mqttStatus?.last_heartbeat?.firmware_version)
|
|
const diagFw = normFw(latestDiag?.ota_current_version)
|
|
const current = hbFw || diagFw
|
|
if (!latestDiag) return { current, badge: null }
|
|
if (!hbFw || !diagFw || hbFw === diagFw) {
|
|
return {
|
|
current,
|
|
badge: latestDiag.ota_update_available
|
|
? { variant: 'warning', label: 'update available' }
|
|
: { variant: 'success', label: 'up to date' },
|
|
}
|
|
}
|
|
// Firmware changed since the last report. If it moved to the version that
|
|
// report said was available, the update has been applied.
|
|
if (normFw(latestDiag.ota_available_version) === hbFw) {
|
|
return { current, badge: { variant: 'success', label: 'up to date' } }
|
|
}
|
|
return { current, badge: { variant: 'neutral', label: 'OTA status pending' } }
|
|
}
|
|
|
|
// ─── Health overview sub-tab (stats + charts + boot history) ───────────────
|
|
|
|
function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettings, isOnline, sendMqttCommand }) {
|
|
const rangeParams = useMemo(() => {
|
|
const p = new URLSearchParams()
|
|
if (range.since) p.set('since', range.since.toISOString())
|
|
if (range.until) p.set('until', range.until.toISOString())
|
|
return p.toString()
|
|
}, [range])
|
|
|
|
// Cache key: presets are relative ("last 7d"), so key them by name — the
|
|
// exact `since` timestamp shifts on every resolve. Custom ranges are exact.
|
|
const cacheKey = `${sn}|${range.key === 'custom' ? rangeParams : range.key}`
|
|
|
|
const [bootEvents, setBootEvents] = useState(() => getCachedHealth(cacheKey)?.bootEvents || [])
|
|
const [heartbeats, setHeartbeats] = useState(() => getCachedHealth(cacheKey)?.heartbeats || [])
|
|
const [pingSamples, setPingSamples] = useState(() => getCachedHealth(cacheKey)?.pingSamples || [])
|
|
const [diagReports, setDiagReports] = useState(() => getCachedHealth(cacheKey)?.diagReports || [])
|
|
const [loading, setLoading] = useState(() => !getCachedHealth(cacheKey))
|
|
const [error, setError] = useState('')
|
|
const [expandedId, setExpandedId] = useState(null)
|
|
const [syncing, setSyncing] = useState(false)
|
|
|
|
// Stale-while-revalidate: last-known datasets for this device + range
|
|
// render immediately; the full-section spinner only shows on a cold load.
|
|
const load = useCallback(async () => {
|
|
if (!sn) return
|
|
const prior = getCachedHealth(cacheKey)
|
|
if (prior) {
|
|
setBootEvents(prior.bootEvents)
|
|
setHeartbeats(prior.heartbeats)
|
|
setPingSamples(prior.pingSamples)
|
|
setDiagReports(prior.diagReports)
|
|
setLoading(false)
|
|
} else {
|
|
setLoading(true)
|
|
}
|
|
setError('')
|
|
try {
|
|
const suffix = rangeParams ? `&${rangeParams}` : ''
|
|
const [bootRes, hbRes, pingRes, diagRes] = await Promise.all([
|
|
api.get(`/mqtt/boot-events/${sn}?limit=2000${suffix}`),
|
|
api.get(`/mqtt/heartbeats/${sn}?limit=5000${suffix}`),
|
|
api.get(`/mqtt/ping-samples/${sn}?limit=5000${suffix}`),
|
|
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
|
])
|
|
const next = {
|
|
bootEvents: bootRes.events || [],
|
|
heartbeats: hbRes.heartbeats || [],
|
|
pingSamples: pingRes.samples || [],
|
|
diagReports: diagRes.reports || [],
|
|
}
|
|
setCachedHealth(cacheKey, next)
|
|
setBootEvents(next.bootEvents)
|
|
setHeartbeats(next.heartbeats)
|
|
setPingSamples(next.pingSamples)
|
|
setDiagReports(next.diagReports)
|
|
} catch (err) {
|
|
if (!prior) setError(err.message || 'Failed to load device health data.')
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}, [sn, rangeParams, cacheKey])
|
|
|
|
useEffect(() => { load() }, [load])
|
|
|
|
// Asks the device for its own SD boot log. The backend merges the reply
|
|
// into boot history as it arrives (fills in crash detail for boots we
|
|
// already have, adds boots the console never saw live), before the ack
|
|
// reaches us — so a reload right after the reply shows the merged result.
|
|
const syncFromDevice = async () => {
|
|
if (!sendMqttCommand) return
|
|
setSyncing(true)
|
|
try {
|
|
await sendMqttCommand('telemetry.get_boot_history')
|
|
await load()
|
|
} catch {
|
|
// the command toast already reports the failure
|
|
} finally {
|
|
setSyncing(false)
|
|
}
|
|
}
|
|
|
|
if (loading) {
|
|
return (
|
|
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-16)' }}>
|
|
<Spinner size="lg" />
|
|
</div>
|
|
)
|
|
}
|
|
|
|
if (error) {
|
|
return (
|
|
<div role="alert" style={{ backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', borderRadius: 'var(--radius-md)', padding: 'var(--space-4)', color: 'var(--color-danger)' }}>
|
|
{error}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
const latestBoot = bootEvents[0] || null
|
|
const latestDiag = diagReports[0] || null
|
|
const fw = firmwareSummary(mqttStatus, latestDiag)
|
|
const restartsInRange = bootEvents.length
|
|
const rangeLabelShort = range.key === 'all' ? 'all-time' : (
|
|
range.key === 'custom' ? 'custom range' :
|
|
{ '10m': '10 min', '1h': '1 hour', '3h': '3 hours', '24h': '24 hours', '3d': '3 days', '7d': '7 days', '30d': '30 days', '3mo': '3 months', '6mo': '6 months' }[range.key] || range.key
|
|
)
|
|
|
|
// Resolved axis bounds for every chart + the restart timeline — the FULL
|
|
// requested range, not just whatever data happens to exist (#7). "all"
|
|
// range has no lower bound, so fall back to the earliest sample actually
|
|
// present (or now-24h if there's nothing at all) purely so the axis has
|
|
// something sensible to show.
|
|
const allTimestamps = [
|
|
...heartbeats.map(h => new Date(h.received_at).getTime()),
|
|
...pingSamples.map(p => new Date(p.sampled_at).getTime()),
|
|
...diagReports.map(d => new Date(d.received_at).getTime()),
|
|
...bootEvents.map(e => new Date(e.occurred_at).getTime()),
|
|
]
|
|
const rangeXMax = range.until ? range.until.getTime() : Date.now()
|
|
const rangeXMin = range.since ? range.since.getTime() : (allTimestamps.length ? Math.min(...allTimestamps) : rangeXMax - 86400000)
|
|
|
|
// ── Offline windows — shared across all four trend charts ────────────────
|
|
// Computed once from heartbeats (the highest-frequency, always-expected
|
|
// signal — every 30s from any online device) and applied identically to
|
|
// RSSI, Heap, Ping, and CPU Temp, rather than each chart inferring gaps
|
|
// from its own series. This matters because ping (every 60s) and
|
|
// diagnostics (every 5min) are naturally sparser than heartbeats, so a gap
|
|
// big enough to mean "offline" on the heartbeat timeline doesn't reliably
|
|
// show up as an anomalous gap in those slower series' own timestamps — and
|
|
// conversely, an outage that also took down the console itself (e.g. a
|
|
// power cut) still shows up as a heartbeat gap even though, from any single
|
|
// series' own perspective, it just looks like "no data for a while," which
|
|
// is indistinguishable from that series' normal sample spacing.
|
|
//
|
|
// Threshold is relative to the visible range (2% of its width) rather than
|
|
// a fixed duration — a 3-minute silence is obviously "offline" when viewing
|
|
// the last hour, but invisible noise when viewing the last 3 months. Floored
|
|
// at the device's own offline-timeout setting so a busy short-range view
|
|
// never flags normal heartbeat jitter as an outage.
|
|
const visibleSpanMs = rangeXMax - rangeXMin
|
|
const offlineWindowThresholdMs = Math.max(offlineTimeoutSec * 1000, visibleSpanMs * 0.02)
|
|
|
|
const offlineWindows = []
|
|
{
|
|
const hbTimes = heartbeats.map(h => new Date(h.received_at).getTime()).sort((a, b) => a - b)
|
|
let cursor = rangeXMin
|
|
for (const t of hbTimes) {
|
|
if (t - cursor > offlineWindowThresholdMs) offlineWindows.push({ start: cursor, end: t })
|
|
cursor = Math.max(cursor, t)
|
|
}
|
|
// Trailing edge: an outage still in progress (no "next" heartbeat yet)
|
|
// has no closing point in the array at all, so it must be checked
|
|
// against the end of the visible range explicitly.
|
|
if (rangeXMax - cursor > offlineWindowThresholdMs) offlineWindows.push({ start: cursor, end: rangeXMax })
|
|
}
|
|
|
|
const rssiSeries = [...heartbeats].reverse().map(h => ({ x: new Date(h.received_at).getTime(), y: h.rssi ?? null }))
|
|
const heapSeries = [...heartbeats].reverse().map(h => ({ x: new Date(h.received_at).getTime(), y: h.free_heap ?? null }))
|
|
const pingSeries = [...pingSamples].reverse().map(p => ({ x: new Date(p.sampled_at).getTime(), y: p.rtt_ms }))
|
|
// cpu_temp_avg is null on reports where no samples were taken yet that
|
|
// window (e.g. the very first report shortly after boot) — rendered as a
|
|
// gap by LineChart, not a false zero.
|
|
const tempSeries = [...diagReports].reverse().map(d => ({ x: new Date(d.received_at).getTime(), y: d.cpu_temp_avg ?? null }))
|
|
|
|
let stackHighWater = {}
|
|
try {
|
|
stackHighWater = latestDiag?.stack_high_water ? JSON.parse(latestDiag.stack_high_water) : {}
|
|
} catch {
|
|
stackHighWater = {}
|
|
}
|
|
const lowestStackEntry = Object.entries(stackHighWater).sort((a, b) => a[1] - b[1])[0]
|
|
const stackWarning = lowestStackEntry && lowestStackEntry[1] < 1024
|
|
|
|
// formatX must be date-aware once the range spans more than a day, or two
|
|
// axis endpoints 24h+ apart can render identical "HH:MM" labels.
|
|
const spanMs = rangeXMax - rangeXMin
|
|
const formatTime = x => spanMs > 36 * 3600000
|
|
? new Date(x).toLocaleString([], { month: 'short', day: 'numeric' })
|
|
: new Date(x).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
|
|
|
// CPU temperature color stops — 3 user-configurable bands from Settings
|
|
// (cool/warn/ceiling), interpolated linearly by LineChart's gradient, not
|
|
// hard-cut.
|
|
const tempCeiling = healthSettings?.warning?.cpu_temp_ceiling_c ?? 65
|
|
const tempCritical = healthSettings?.critical?.cpu_temp_ceiling_c ?? 80
|
|
const tempColorStops = [
|
|
{ value: tempCeiling - 20, color: 'var(--color-info)' },
|
|
{ value: tempCeiling, color: 'var(--color-warning)' },
|
|
{ value: tempCritical, color: 'var(--color-danger)' },
|
|
]
|
|
|
|
return (
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: SECTION_GAP }}>
|
|
|
|
{/* ── Hero KPI row (compact) ───────────────────────────────────────── */}
|
|
<EqualGrid columns={4}>
|
|
<KpiTile
|
|
label="Lifetime Boot Count"
|
|
value={latestBoot?.boot_count ?? '—'}
|
|
/>
|
|
<KpiTile
|
|
label={`Restarts (${rangeLabelShort})`}
|
|
value={restartsInRange}
|
|
variant={restartsInRange > 5 ? 'danger' : restartsInRange > 0 ? 'warning' : undefined}
|
|
sublabel={healthSettings?.warning?.restarts_per_week_threshold != null ? `alert threshold: ${healthSettings.warning.restarts_per_week_threshold} / week` : null}
|
|
/>
|
|
<KpiTile
|
|
label="Device Uptime"
|
|
value={mqttStatus?.last_heartbeat?.uptime_ms != null
|
|
? formatUptimeShort(mqttStatus.last_heartbeat.uptime_ms)
|
|
: '—'}
|
|
sublabel={latestBoot?.boot_count != null ? `since boot #${latestBoot.boot_count}` : null}
|
|
/>
|
|
<KpiTile
|
|
label="Last Boot Reason"
|
|
sublabel={latestBoot ? fmtRelative(latestBoot.occurred_at) : null}
|
|
badge={latestBoot ? (
|
|
<StatusBadge variant={reasonVariant(latestBoot.reset_reason, latestBoot.is_fault)}>
|
|
{reasonLabel(latestBoot.reset_reason)}
|
|
</StatusBadge>
|
|
) : (
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
|
|
No boot data yet
|
|
</span>
|
|
)}
|
|
/>
|
|
</EqualGrid>
|
|
|
|
{/* ── Secondary metrics row (compact) ──────────────────────────────── */}
|
|
<EqualGrid columns={5}>
|
|
<MetricTile
|
|
label="CPU Temperature"
|
|
value={latestDiag?.cpu_temp_avg != null ? latestDiag.cpu_temp_avg.toFixed(1) : '—'}
|
|
unit="°C"
|
|
sublabel={latestDiag?.cpu_temp_max != null ? `peak ${latestDiag.cpu_temp_max.toFixed(1)}°C` : null}
|
|
/>
|
|
<MetricTile
|
|
label="WiFi Reconnects"
|
|
value={latestDiag?.wifi_reconnect_count ?? '—'}
|
|
sublabel={latestDiag?.wifi_last_disconnect_reason ? `last: ${latestDiag.wifi_last_disconnect_reason}` : null}
|
|
/>
|
|
<MetricTile label="Firmware / OTA">
|
|
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
|
{fw.current ? `v${fw.current}` : '—'}
|
|
</span>
|
|
{fw.badge && (
|
|
<div style={{ marginTop: 2 }}>
|
|
<StatusBadge variant={fw.badge.variant} size="sm">{fw.badge.label}</StatusBadge>
|
|
</div>
|
|
)}
|
|
</MetricTile>
|
|
<MetricTile
|
|
label="Signal Strength"
|
|
value={mqttStatus?.last_heartbeat?.rssi ?? '—'}
|
|
unit={mqttStatus?.last_heartbeat?.rssi != null ? 'dBm' : ''}
|
|
sublabel="most recent heartbeat"
|
|
/>
|
|
<MetricTile label="Stack High-Water">
|
|
{lowestStackEntry ? (
|
|
<>
|
|
<span style={{
|
|
fontFamily: 'var(--font-family-mono)', fontSize: '1.15rem', fontWeight: 'var(--font-weight-semibold)',
|
|
color: stackWarning ? 'var(--color-danger)' : 'var(--color-text-primary)',
|
|
}}>
|
|
{lowestStackEntry[1]}<span style={{ fontSize: '0.8rem', color: 'var(--color-text-muted)', marginLeft: 3 }}>B free</span>
|
|
</span>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
|
{lowestStackEntry[0]} (lowest)
|
|
</span>
|
|
</>
|
|
) : (
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>—</span>
|
|
)}
|
|
</MetricTile>
|
|
</EqualGrid>
|
|
|
|
{/* ── Trend graphs ─────────────────────────────────────────────────── */}
|
|
<EqualGrid columns={2}>
|
|
<Card title="Signal Strength (RSSI)" subtitle="From 30s heartbeat — colored by signal quality">
|
|
<LineChart
|
|
data={rssiSeries}
|
|
colorStops={RSSI_COLOR_STOPS}
|
|
unit=" dBm"
|
|
formatValue={v => Math.round(v)}
|
|
formatX={formatTime}
|
|
xMin={rangeXMin}
|
|
xMax={rangeXMax}
|
|
offlineWindows={offlineWindows}
|
|
gapStyle="baseline"
|
|
emptyLabel="No heartbeat data in this range."
|
|
/>
|
|
</Card>
|
|
|
|
<Card
|
|
title="Ping Latency"
|
|
subtitle={pingSeries.length === 0 ? 'RTC-equipped devices only' : 'Round-trip time, sampled every 60s'}
|
|
>
|
|
<LineChart
|
|
data={pingSeries}
|
|
color="var(--color-primary)"
|
|
unit=" ms"
|
|
formatValue={v => Math.round(v)}
|
|
formatX={formatTime}
|
|
xMin={rangeXMin}
|
|
xMax={rangeXMax}
|
|
offlineWindows={offlineWindows}
|
|
gapStyle="baseline"
|
|
emptyLabel="No ping samples in this range — not supported on non-RTC hardware variants."
|
|
/>
|
|
</Card>
|
|
|
|
<Card title="Free Heap" subtitle="From 30s heartbeat">
|
|
<LineChart
|
|
data={heapSeries}
|
|
color="var(--color-success)"
|
|
unit=" KB"
|
|
formatValue={v => Math.round(v / 1024)}
|
|
formatX={formatTime}
|
|
xMin={rangeXMin}
|
|
xMax={rangeXMax}
|
|
offlineWindows={offlineWindows}
|
|
gapStyle="baseline"
|
|
emptyLabel="No heartbeat data in this range."
|
|
/>
|
|
</Card>
|
|
|
|
<Card title="CPU Temperature" subtitle="Min/max/avg sampled every 15s, reported every 5 min">
|
|
<LineChart
|
|
data={tempSeries}
|
|
colorStops={tempColorStops}
|
|
unit="°C"
|
|
formatValue={v => v.toFixed(1)}
|
|
formatX={formatTime}
|
|
xMin={rangeXMin}
|
|
xMax={rangeXMax}
|
|
offlineWindows={offlineWindows}
|
|
gapStyle="baseline"
|
|
emptyLabel="No diagnostics reports in this range."
|
|
/>
|
|
</Card>
|
|
</EqualGrid>
|
|
|
|
{/* ── Restart timeline — full page width ───────────────────────────── */}
|
|
<Card title="Restart Timeline" subtitle="Each dot is one boot — red = fault reset" padding={false}>
|
|
<RestartTimeline events={[...bootEvents].reverse()} rangeStart={rangeXMin} rangeEnd={rangeXMax} />
|
|
</Card>
|
|
|
|
{/* ── Full boot event history ──────────────────────────────────────── */}
|
|
<Card
|
|
title="Boot History"
|
|
subtitle="Reverse-chronological — click a fault row with crash detail to expand"
|
|
padding={false}
|
|
action={sendMqttCommand && (
|
|
<Button variant="secondary" size="sm" icon={<Icon name="refresh" size={14} />} onClick={syncFromDevice} loading={syncing} disabled={!isOnline} title={isOnline ? "Fetch the device's own boot log and merge it into this history" : 'Device is offline'}>
|
|
Sync from device
|
|
</Button>
|
|
)}
|
|
>
|
|
{bootEvents.length === 0 ? (
|
|
<div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontStyle: 'italic' }}>
|
|
No boot events recorded in this range.
|
|
</div>
|
|
) : (
|
|
<div>
|
|
{bootEvents.map(event => (
|
|
<BootEventRow
|
|
key={event.id}
|
|
event={event}
|
|
expanded={expandedId === event.id}
|
|
onToggle={() => setExpandedId(prev => prev === event.id ? null : event.id)}
|
|
/>
|
|
))}
|
|
</div>
|
|
)}
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function formatUptimeShort(ms) {
|
|
const seconds = Math.floor(ms / 1000)
|
|
const d = Math.floor(seconds / 86400)
|
|
const h = Math.floor((seconds % 86400) / 3600)
|
|
const m = Math.floor((seconds % 3600) / 60)
|
|
return [d && `${d}d`, h && `${h}h`, m && `${m}m`].filter(Boolean).join(' ') || '< 1m'
|
|
}
|
|
|
|
// ─── Toggle switch (matches PublicFeaturesSettings' pattern) ──────────────
|
|
|
|
function ToggleSwitch({ enabled, onChange, disabled, id }) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
id={id}
|
|
role="switch"
|
|
aria-checked={enabled}
|
|
disabled={disabled}
|
|
onClick={() => onChange(!enabled)}
|
|
style={{
|
|
flexShrink: 0,
|
|
position: 'relative',
|
|
display: 'inline-flex',
|
|
width: '44px',
|
|
height: '24px',
|
|
borderRadius: 'var(--radius-full)',
|
|
border: 'none',
|
|
cursor: disabled ? 'not-allowed' : 'pointer',
|
|
padding: 0,
|
|
transition: 'background 0.2s',
|
|
background: enabled ? 'var(--color-success)' : 'var(--color-bg-island)',
|
|
boxShadow: enabled
|
|
? 'inset 0 1px 3px rgba(0,0,0,0.2), 0 0 0 1px var(--color-success)'
|
|
: 'inset 0 1px 3px rgba(0,0,0,0.2), 0 0 0 1px var(--color-border-strong)',
|
|
opacity: disabled ? 0.5 : 1,
|
|
}}
|
|
>
|
|
<span
|
|
style={{
|
|
position: 'absolute',
|
|
top: '3px',
|
|
left: enabled ? '23px' : '3px',
|
|
width: '18px',
|
|
height: '18px',
|
|
borderRadius: 'var(--radius-full)',
|
|
background: 'white',
|
|
transition: 'left 0.2s',
|
|
boxShadow: '0 1px 4px rgba(0,0,0,0.3)',
|
|
}}
|
|
aria-hidden="true"
|
|
/>
|
|
</button>
|
|
)
|
|
}
|
|
|
|
// ─── Settings sub-tab — per-device alert thresholds ────────────────────────
|
|
// Each metric gets ONE row with two number inputs — Warning and Critical —
|
|
// rather than the old single-threshold-per-metric layout, so both severity
|
|
// levels driving the header status icon are visible and editable together.
|
|
|
|
const DEFAULT_THRESHOLDS = {
|
|
warning: { restarts_per_week_threshold: 6, rssi_floor_dbm: -80, free_heap_floor_kb: 30, cpu_temp_ceiling_c: 65 },
|
|
critical: { restarts_per_week_threshold: 12, rssi_floor_dbm: -90, free_heap_floor_kb: 15, cpu_temp_ceiling_c: 80 },
|
|
}
|
|
|
|
const THRESHOLD_ROWS = [
|
|
{ key: 'restarts_per_week_threshold', label: 'Restarts per week', unit: '', hint: 'alert if restarts in the selected range exceed this' },
|
|
{ key: 'rssi_floor_dbm', label: 'Signal strength floor', unit: 'dBm', hint: 'alert if RSSI drops below' },
|
|
{ key: 'free_heap_floor_kb', label: 'Free heap floor', unit: 'KB', hint: 'alert if free heap drops below' },
|
|
{ key: 'cpu_temp_ceiling_c', label: 'CPU temperature ceiling', unit: '°C', hint: 'alert if temperature exceeds' },
|
|
]
|
|
|
|
function ThresholdRow({ row, warning, critical, onChange }) {
|
|
return (
|
|
<div style={{
|
|
display: 'grid', gridTemplateColumns: '1fr 140px 140px', gap: 'var(--space-4)', alignItems: 'center',
|
|
padding: 'var(--space-3) 0', borderBottom: '1px solid var(--color-border)',
|
|
}}>
|
|
<div>
|
|
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>{row.label}</p>
|
|
<p style={{ margin: 0, fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>{row.hint}{row.unit ? ` (${row.unit})` : ''}</p>
|
|
</div>
|
|
<FormField
|
|
label="Warning"
|
|
name={`warning_${row.key}`}
|
|
type="number"
|
|
value={warning}
|
|
onChange={e => onChange('warning', row.key, e.target.value)}
|
|
/>
|
|
<FormField
|
|
label="Critical"
|
|
name={`critical_${row.key}`}
|
|
type="number"
|
|
value={critical}
|
|
onChange={e => onChange('critical', row.key, e.target.value)}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
function HealthSettings({ deviceId, settings, onSaved }) {
|
|
const { toast } = useToast()
|
|
const [form, setForm] = useState({
|
|
warning: { ...DEFAULT_THRESHOLDS.warning, ...settings.warning },
|
|
critical: { ...DEFAULT_THRESHOLDS.critical, ...settings.critical },
|
|
offline_timeout_sec: settings.offline_timeout_sec ?? DEFAULT_OFFLINE_TIMEOUT_SEC,
|
|
email_on_threshold: settings.email_on_threshold ?? false,
|
|
push_on_crash_boot: settings.push_on_crash_boot ?? false,
|
|
})
|
|
const [saving, setSaving] = useState(false)
|
|
|
|
useEffect(() => {
|
|
setForm({
|
|
warning: { ...DEFAULT_THRESHOLDS.warning, ...settings.warning },
|
|
critical: { ...DEFAULT_THRESHOLDS.critical, ...settings.critical },
|
|
offline_timeout_sec: settings.offline_timeout_sec ?? DEFAULT_OFFLINE_TIMEOUT_SEC,
|
|
email_on_threshold: settings.email_on_threshold ?? false,
|
|
push_on_crash_boot: settings.push_on_crash_boot ?? false,
|
|
})
|
|
}, [settings])
|
|
|
|
const setThreshold = (severity, key, value) => setForm(prev => ({
|
|
...prev, [severity]: { ...prev[severity], [key]: value },
|
|
}))
|
|
const setField = (key, value) => setForm(prev => ({ ...prev, [key]: value }))
|
|
|
|
const save = async () => {
|
|
setSaving(true)
|
|
try {
|
|
const payload = {
|
|
warning: Object.fromEntries(THRESHOLD_ROWS.map(r => [r.key, Number(form.warning[r.key])])),
|
|
critical: Object.fromEntries(THRESHOLD_ROWS.map(r => [r.key, Number(form.critical[r.key])])),
|
|
offline_timeout_sec: Number(form.offline_timeout_sec),
|
|
email_on_threshold: !!form.email_on_threshold,
|
|
push_on_crash_boot: !!form.push_on_crash_boot,
|
|
}
|
|
const res = await api.put(`/devices/${deviceId}`, { device_health_settings: payload })
|
|
onSaved(res.device_health_settings || payload)
|
|
toast.success('Saved', 'Alert thresholds updated.')
|
|
} catch (err) {
|
|
toast.danger('Error', err.message || 'Failed to save thresholds.')
|
|
} finally {
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div style={{ maxWidth: 'var(--content-max-width-lg)' }}>
|
|
<Card title="Alert Thresholds" subtitle="Warning shows an orange status icon; Critical shows red. Both drive the icon next to the time-range control above.">
|
|
<div style={{
|
|
display: 'grid', gridTemplateColumns: '1fr 140px 140px', gap: 'var(--space-4)',
|
|
paddingBottom: 'var(--space-2)', borderBottom: '1px solid var(--color-border-strong)',
|
|
}}>
|
|
<span />
|
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-warning)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>Warning</span>
|
|
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-danger)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>Critical</span>
|
|
</div>
|
|
{THRESHOLD_ROWS.map(row => (
|
|
<ThresholdRow
|
|
key={row.key}
|
|
row={row}
|
|
warning={form.warning[row.key]}
|
|
critical={form.critical[row.key]}
|
|
onChange={setThreshold}
|
|
/>
|
|
))}
|
|
|
|
<div style={{ marginTop: 'var(--space-6)' }}>
|
|
<FormField
|
|
label="Offline timeout"
|
|
name="offline_timeout_sec"
|
|
type="number"
|
|
value={form.offline_timeout_sec}
|
|
onChange={e => setField('offline_timeout_sec', e.target.value)}
|
|
hint="seconds — no message of any kind for this long ⇒ device considered offline (also controls chart gap detection)"
|
|
/>
|
|
</div>
|
|
|
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 'var(--space-4)', marginTop: 'var(--space-6)' }}>
|
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-3)', padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-md)', background: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
|
|
<div>
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>Email me when a threshold is crossed</span>
|
|
<p style={{ margin: 0, fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>Not yet active — no email infrastructure wired up.</p>
|
|
</div>
|
|
<ToggleSwitch id="email-on-threshold" enabled={!!form.email_on_threshold} onChange={v => setField('email_on_threshold', v)} />
|
|
</div>
|
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-3)', padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-md)', background: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
|
|
<div>
|
|
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)' }}>Push notification on crash boot</span>
|
|
<p style={{ margin: 0, fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>Not yet active — no push infrastructure wired up.</p>
|
|
</div>
|
|
<ToggleSwitch id="push-on-crash" enabled={!!form.push_on_crash_boot} onChange={v => setField('push_on_crash_boot', v)} />
|
|
</div>
|
|
</div>
|
|
|
|
<div style={{ marginTop: 'var(--space-6)' }}>
|
|
<Button variant="primary" loading={saving} onClick={save}>Save Thresholds</Button>
|
|
</div>
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ─── HealthTab ──────────────────────────────────────────────────────────────
|
|
|
|
function SubTabPill({ active, onClick, children }) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={onClick}
|
|
style={{
|
|
display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)',
|
|
padding: 'var(--space-2) var(--space-5)',
|
|
borderRadius: 'var(--radius-full)',
|
|
border: `1px solid ${active ? 'var(--color-border-focus)' : 'var(--color-border)'}`,
|
|
background: active ? 'var(--color-primary-subtle)' : 'var(--color-bg-surface)',
|
|
color: active ? 'var(--color-text-accent)' : 'var(--color-text-muted)',
|
|
fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)',
|
|
fontFamily: 'var(--font-family-base)',
|
|
cursor: 'pointer', whiteSpace: 'nowrap',
|
|
transition: 'background 0.15s, border-color 0.15s, color 0.15s',
|
|
}}
|
|
>
|
|
{children}
|
|
</button>
|
|
)
|
|
}
|
|
|
|
// Reads the header status icon's inputs even while a sub-tab other than
|
|
// Overview is active, so the icon doesn't disappear/reset when you switch
|
|
// to Logs or Settings — it needs its own small, independent fetch of just
|
|
// the latest heartbeat/diagnostics/boot-count, not the full ranged dataset
|
|
// HealthOverview loads.
|
|
function useHeaderStatus(sn, healthSettings, mqttStatus) {
|
|
const [latestDiag, setLatestDiag] = useState(null)
|
|
const [restarts7d, setRestarts7d] = useState(0)
|
|
|
|
useEffect(() => {
|
|
if (!sn) return
|
|
let cancelled = false
|
|
const sevenDaysAgo = new Date(Date.now() - 7 * 86400000).toISOString()
|
|
Promise.all([
|
|
api.get(`/mqtt/diagnostics-reports/${sn}?limit=1`).catch(() => null),
|
|
api.get(`/mqtt/boot-events/${sn}?limit=200&since=${encodeURIComponent(sevenDaysAgo)}`).catch(() => null),
|
|
]).then(([diagRes, bootRes]) => {
|
|
if (cancelled) return
|
|
setLatestDiag(diagRes?.reports?.[0] || null)
|
|
setRestarts7d(bootRes?.total ?? bootRes?.events?.length ?? 0)
|
|
})
|
|
return () => { cancelled = true }
|
|
}, [sn])
|
|
|
|
return statusFromThresholds({
|
|
mqttStatus,
|
|
latestDiag,
|
|
restartsInRange: restarts7d,
|
|
settings: healthSettings,
|
|
})
|
|
}
|
|
|
|
export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCommand, canEdit }) {
|
|
const [subTab, setSubTab] = useState('overview')
|
|
const [range, setRange] = useState(() => resolveRange('7d'))
|
|
// Local override after a successful save, so the Settings form and offline-
|
|
// timeout derivation reflect the new values immediately without waiting on
|
|
// the parent's device prop to re-fetch. Falls back to whatever's on the
|
|
// device doc otherwise — no effect-based sync needed since device updates
|
|
// flow down as a fresh prop value on every render already.
|
|
const [savedOverride, setSavedOverride] = useState(null)
|
|
const healthSettings = savedOverride || device?.device_health_settings || {}
|
|
|
|
const offlineTimeoutSec = healthSettings.offline_timeout_sec || DEFAULT_OFFLINE_TIMEOUT_SEC
|
|
const headerStatus = useHeaderStatus(sn, healthSettings, mqttStatus)
|
|
|
|
return (
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: SECTION_GAP }}>
|
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-4)', flexWrap: 'wrap', minHeight: 38 }}>
|
|
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
|
|
<SubTabPill active={subTab === 'overview'} onClick={() => setSubTab('overview')}>
|
|
<StatusIcon status={headerStatus} />
|
|
Overview
|
|
</SubTabPill>
|
|
<SubTabPill active={subTab === 'logs'} onClick={() => setSubTab('logs')}>Logs</SubTabPill>
|
|
<SubTabPill active={subTab === 'settings'} onClick={() => setSubTab('settings')}>
|
|
<Icon name="settings" size={13} />
|
|
Settings
|
|
</SubTabPill>
|
|
</div>
|
|
{/* Always rendered (Overview + Logs both use it) so the toolbar never
|
|
changes height when switching sub-tabs — only Settings hides it,
|
|
in which case an invisible spacer of the same size holds the row
|
|
height steady. */}
|
|
<div style={{ width: 220, visibility: subTab === 'settings' ? 'hidden' : 'visible' }}>
|
|
<TimeRangeSelect value={range} onChange={setRange} />
|
|
</div>
|
|
</div>
|
|
|
|
{subTab === 'overview' && (
|
|
<HealthOverview sn={sn} mqttStatus={mqttStatus} range={range} offlineTimeoutSec={offlineTimeoutSec} healthSettings={healthSettings} isOnline={isOnline} sendMqttCommand={sendMqttCommand} />
|
|
)}
|
|
{subTab === 'logs' && <LogsTab sn={sn} range={range} deviceId={device?.id} canEdit={canEdit} />}
|
|
{subTab === 'settings' && (
|
|
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
|
)}
|
|
</div>
|
|
)
|
|
}
|