feat(devices): paint list/detail from last-known data, revalidate silently
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>
This commit is contained in:
@@ -10,6 +10,7 @@
|
||||
|
||||
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'
|
||||
@@ -292,18 +293,42 @@ function StatusIcon({ status }) {
|
||||
)
|
||||
}
|
||||
|
||||
// ─── 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 [bootEvents, setBootEvents] = useState([])
|
||||
const [heartbeats, setHeartbeats] = useState([])
|
||||
const [pingSamples, setPingSamples] = useState([])
|
||||
const [diagReports, setDiagReports] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [expandedId, setExpandedId] = useState(null)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
|
||||
const rangeParams = useMemo(() => {
|
||||
const p = new URLSearchParams()
|
||||
if (range.since) p.set('since', range.since.toISOString())
|
||||
@@ -311,9 +336,33 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
||||
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
|
||||
setLoading(true)
|
||||
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}` : ''
|
||||
@@ -323,16 +372,23 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
||||
api.get(`/mqtt/ping-samples/${sn}?limit=5000${suffix}`),
|
||||
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
||||
])
|
||||
setBootEvents(bootRes.events || [])
|
||||
setHeartbeats(hbRes.heartbeats || [])
|
||||
setPingSamples(pingRes.samples || [])
|
||||
setDiagReports(diagRes.reports || [])
|
||||
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) {
|
||||
setError(err.message || 'Failed to load device health data.')
|
||||
if (!prior) setError(err.message || 'Failed to load device health data.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [sn, rangeParams])
|
||||
}, [sn, rangeParams, cacheKey])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
@@ -371,6 +427,7 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
||||
|
||||
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' :
|
||||
@@ -513,13 +570,11 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
||||
/>
|
||||
<MetricTile label="Firmware / OTA">
|
||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
||||
{latestDiag?.ota_current_version ? `v${latestDiag.ota_current_version}` : '—'}
|
||||
{fw.current ? `v${fw.current}` : '—'}
|
||||
</span>
|
||||
{latestDiag && (
|
||||
{fw.badge && (
|
||||
<div style={{ marginTop: 2 }}>
|
||||
<StatusBadge variant={latestDiag.ota_update_available ? 'warning' : 'success'} size="sm">
|
||||
{latestDiag.ota_update_available ? 'update available' : 'up to date'}
|
||||
</StatusBadge>
|
||||
<StatusBadge variant={fw.badge.variant} size="sm">{fw.badge.label}</StatusBadge>
|
||||
</div>
|
||||
)}
|
||||
</MetricTile>
|
||||
@@ -911,7 +966,7 @@ function useHeaderStatus(sn, healthSettings, mqttStatus) {
|
||||
})
|
||||
}
|
||||
|
||||
export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCommand }) {
|
||||
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-
|
||||
@@ -951,7 +1006,7 @@ export default function HealthTab({ device, sn, mqttStatus, isOnline, sendMqttCo
|
||||
{subTab === 'overview' && (
|
||||
<HealthOverview sn={sn} mqttStatus={mqttStatus} range={range} offlineTimeoutSec={offlineTimeoutSec} healthSettings={healthSettings} isOnline={isOnline} sendMqttCommand={sendMqttCommand} />
|
||||
)}
|
||||
{subTab === 'logs' && <LogsTab sn={sn} range={range} />}
|
||||
{subTab === 'logs' && <LogsTab sn={sn} range={range} deviceId={device?.id} canEdit={canEdit} />}
|
||||
{subTab === 'settings' && (
|
||||
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user