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:
@@ -0,0 +1,113 @@
|
|||||||
|
// frontend/src/lib/deviceCache.js
|
||||||
|
// Last-known device data for stale-while-revalidate rendering.
|
||||||
|
//
|
||||||
|
// DeviceList and DeviceDetail paint instantly from whatever was fetched last
|
||||||
|
// (in this tab, or earlier in this browser session), then revalidate in the
|
||||||
|
// background and swap in fresh data silently. The backend's MQTT ingest keeps
|
||||||
|
// status current every ~30s, so the cached copy is almost always right; the
|
||||||
|
// background fetch just confirms it.
|
||||||
|
//
|
||||||
|
// Kept in memory (survives in-app navigation) and mirrored to sessionStorage
|
||||||
|
// (survives a page reload in the same tab). Storage can be unavailable or
|
||||||
|
// full — every access is wrapped so the cache silently degrades to memory-only.
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'bs.deviceCache.v1'
|
||||||
|
|
||||||
|
function load() {
|
||||||
|
try {
|
||||||
|
const raw = sessionStorage.getItem(STORAGE_KEY)
|
||||||
|
if (raw) return JSON.parse(raw)
|
||||||
|
} catch { /* unavailable / corrupt — start empty */ }
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
devicesByQuery: {}, // list query string -> devices[]
|
||||||
|
deviceById: {}, // firestore doc id -> device
|
||||||
|
statusMap: null, // serial -> /mqtt/status entry
|
||||||
|
diagMap: null, // serial -> latest diagnostics (list columns)
|
||||||
|
pingMap: null, // serial -> latest ping sample (list columns)
|
||||||
|
healthByKey: {}, // `${sn}|${rangeKey}` -> Health overview datasets
|
||||||
|
...load(),
|
||||||
|
}
|
||||||
|
|
||||||
|
let persistTimer = null
|
||||||
|
function persist() {
|
||||||
|
// Coalesce bursts (e.g. a heartbeat per device) into one write.
|
||||||
|
if (persistTimer) return
|
||||||
|
persistTimer = setTimeout(() => {
|
||||||
|
persistTimer = null
|
||||||
|
try {
|
||||||
|
// Health datasets can be thousands of rows — memory only.
|
||||||
|
const { healthByKey, ...rest } = state
|
||||||
|
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(rest))
|
||||||
|
} catch { /* quota / unavailable — memory cache still works */ }
|
||||||
|
}, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Device list ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevices(query) {
|
||||||
|
return state.devicesByQuery[query] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevices(query, devices) {
|
||||||
|
state.devicesByQuery[query] = devices
|
||||||
|
for (const d of devices) if (d?.id) state.deviceById[d.id] = d
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Single device ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedDevice(id) {
|
||||||
|
return state.deviceById[id] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedDevice(device) {
|
||||||
|
if (!device?.id) return
|
||||||
|
state.deviceById[device.id] = device
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── MQTT status ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedStatusMap() {
|
||||||
|
return state.statusMap
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatusMap(map) {
|
||||||
|
state.statusMap = map
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCachedStatus(serial) {
|
||||||
|
return (serial && state.statusMap?.[serial]) || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedStatus(serial, status) {
|
||||||
|
if (!serial) return
|
||||||
|
state.statusMap = { ...(state.statusMap || {}), [serial]: status }
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Latest metrics (list columns) ────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedMetrics() {
|
||||||
|
return { diagMap: state.diagMap, pingMap: state.pingMap }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedMetrics(diagMap, pingMap) {
|
||||||
|
state.diagMap = diagMap
|
||||||
|
state.pingMap = pingMap
|
||||||
|
persist()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Health overview datasets ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export function getCachedHealth(key) {
|
||||||
|
return state.healthByKey[key] || null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedHealth(key, data) {
|
||||||
|
state.healthByKey[key] = data
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
|
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
|
||||||
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import { getCachedDevice, setCachedDevice, getCachedStatus, setCachedStatus } from '@/lib/deviceCache'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useToast } from '@/components/ui/Toast'
|
import { useToast } from '@/components/ui/Toast'
|
||||||
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
|
import { useDeviceCommand } from '@/hooks/useDeviceCommand'
|
||||||
@@ -73,10 +74,19 @@ export default function DeviceDetail() {
|
|||||||
const canEdit = hasPermission('devices', 'edit')
|
const canEdit = hasPermission('devices', 'edit')
|
||||||
|
|
||||||
// ── State ──────────────────────────────────────────────────────────────────
|
// ── State ──────────────────────────────────────────────────────────────────
|
||||||
const [device, setDevice] = useState(null)
|
// Seeded from the last-known cache (lib/deviceCache — filled by DeviceList
|
||||||
const [loading, setLoading] = useState(true)
|
// and by earlier visits) so the page renders instantly; loadDevice() then
|
||||||
|
// revalidates in the background and `refreshing` drives the Syncing hint.
|
||||||
|
const [device, setDevice] = useState(() => getCachedDevice(id))
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedDevice(id))
|
||||||
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [mqttStatus, setMqttStatus] = useState(null)
|
const [mqttStatus, setMqttStatus] = useState(() => {
|
||||||
|
const d = getCachedDevice(id)
|
||||||
|
return getCachedStatus(d?.serial_number || d?.device_id)
|
||||||
|
})
|
||||||
|
const deviceRef = useRef(device)
|
||||||
|
deviceRef.current = device
|
||||||
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
|
||||||
|
|
||||||
const [deviceUsers, setDeviceUsers] = useState([])
|
const [deviceUsers, setDeviceUsers] = useState([])
|
||||||
@@ -84,8 +94,11 @@ export default function DeviceDetail() {
|
|||||||
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
const [ownerCustomer, setOwnerCustomer] = useState(null)
|
||||||
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
const [assigningCustomer, setAssigningCustomer] = useState(false)
|
||||||
|
|
||||||
const [tags, setTags] = useState([])
|
const [tags, setTags] = useState(() => {
|
||||||
const [staffNotes, setStaffNotes] = useState('')
|
const t = getCachedDevice(id)?.tags
|
||||||
|
return Array.isArray(t) ? t : []
|
||||||
|
})
|
||||||
|
const [staffNotes, setStaffNotes] = useState(() => getCachedDevice(id)?.staffNotes || '')
|
||||||
|
|
||||||
const [showDelete, setShowDelete] = useState(false)
|
const [showDelete, setShowDelete] = useState(false)
|
||||||
const [deleting, setDeleting] = useState(false)
|
const [deleting, setDeleting] = useState(false)
|
||||||
@@ -108,8 +121,29 @@ export default function DeviceDetail() {
|
|||||||
// ── Data fetching ──────────────────────────────────────────────────────────
|
// ── Data fetching ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const loadDevice = useCallback(async () => {
|
const loadDevice = useCallback(async () => {
|
||||||
setLoading(true)
|
// Already showing this device (e.g. reload after a modal save) → refresh
|
||||||
|
// in place. Navigated here → seed from cache if we have it. Only a device
|
||||||
|
// we've never seen shows the full-page spinner.
|
||||||
|
const current = deviceRef.current?.id === id ? deviceRef.current : null
|
||||||
|
const seed = current || getCachedDevice(id)
|
||||||
|
if (!current) {
|
||||||
|
setDevice(seed)
|
||||||
|
setMqttStatus(seed ? getCachedStatus(seed.serial_number || seed.device_id) : null)
|
||||||
|
if (seed?.staffNotes) setStaffNotes(seed.staffNotes)
|
||||||
|
if (Array.isArray(seed?.tags)) setTags(seed.tags)
|
||||||
|
}
|
||||||
|
setLoading(!seed)
|
||||||
|
setRefreshing(true)
|
||||||
setError('')
|
setError('')
|
||||||
|
|
||||||
|
// Live status for just this device. Started right away when the serial
|
||||||
|
// is already known, in parallel with the device fetch.
|
||||||
|
const fetchStatus = sn => api.get(`/mqtt/status/${encodeURIComponent(sn)}`)
|
||||||
|
.then(st => setMqttStatus(st || null))
|
||||||
|
.catch(() => {})
|
||||||
|
const seedSn = seed?.serial_number || seed?.device_id
|
||||||
|
const statusPromise = seedSn ? fetchStatus(seedSn) : null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const d = await api.get(`/devices/${id}`)
|
const d = await api.get(`/devices/${id}`)
|
||||||
setDevice(d)
|
setDevice(d)
|
||||||
@@ -118,14 +152,8 @@ export default function DeviceDetail() {
|
|||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
|
||||||
const sn = d.serial_number || d.device_id
|
const sn = d.serial_number || d.device_id
|
||||||
if (sn) {
|
const statusDone = statusPromise || (sn ? fetchStatus(sn) : Promise.resolve())
|
||||||
api.get('/mqtt/status').then(mqttData => {
|
statusDone.finally(() => setRefreshing(false))
|
||||||
if (mqttData?.devices) {
|
|
||||||
const match = mqttData.devices.find(s => s.device_serial === sn)
|
|
||||||
setMqttStatus(match || null)
|
|
||||||
}
|
|
||||||
}).catch(() => {})
|
|
||||||
}
|
|
||||||
|
|
||||||
if (d.customer_id) {
|
if (d.customer_id) {
|
||||||
api.get(`/devices/${id}/customer`).then(res => {
|
api.get(`/devices/${id}/customer`).then(res => {
|
||||||
@@ -141,8 +169,10 @@ export default function DeviceDetail() {
|
|||||||
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message || 'Failed to load device.')
|
// Cached data on screen → keep it and stay quiet; otherwise show the error.
|
||||||
|
if (!seed) setError(err.message || 'Failed to load device.')
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
}
|
}
|
||||||
}, [id])
|
}, [id])
|
||||||
|
|
||||||
@@ -187,6 +217,11 @@ export default function DeviceDetail() {
|
|||||||
|
|
||||||
const deviceSerial = device?.serial_number || device?.device_id
|
const deviceSerial = device?.serial_number || device?.device_id
|
||||||
|
|
||||||
|
// Write-through: every device / status change (fresh fetch, modal save,
|
||||||
|
// live heartbeat) updates the cache the next visit will paint from.
|
||||||
|
useEffect(() => { if (device) setCachedDevice(device) }, [device])
|
||||||
|
useEffect(() => { if (deviceSerial && mqttStatus) setCachedStatus(deviceSerial, mqttStatus) }, [deviceSerial, mqttStatus])
|
||||||
|
|
||||||
const handleNonAckMessage = useCallback((msg) => {
|
const handleNonAckMessage = useCallback((msg) => {
|
||||||
// Live heartbeat — updates the online dot/RSSI without polling. The device
|
// Live heartbeat — updates the online dot/RSSI without polling. The device
|
||||||
// publishes one every ~30s; we just reflect whatever lands here instead of
|
// publishes one every ~30s; we just reflect whatever lands here instead of
|
||||||
@@ -418,6 +453,16 @@ export default function DeviceDetail() {
|
|||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{refreshing && (
|
||||||
|
<span
|
||||||
|
role="status"
|
||||||
|
title="Fetching fresh data — showing last-known values meanwhile"
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)' }}
|
||||||
|
>
|
||||||
|
<Spinner size="sm" />
|
||||||
|
Syncing…
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<Button variant="ghost" onClick={() => sendMqttCommand('ping')}>
|
<Button variant="ghost" onClick={() => sendMqttCommand('ping')}>
|
||||||
Ping Now
|
Ping Now
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
// frontend/src/pages/devices/DeviceList.jsx
|
// frontend/src/pages/devices/DeviceList.jsx
|
||||||
|
|
||||||
import { useState, useEffect, useCallback } from 'react'
|
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||||
import { useNavigate } from 'react-router-dom'
|
import { useNavigate } from 'react-router-dom'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import {
|
||||||
|
getCachedDevices, setCachedDevices,
|
||||||
|
getCachedStatusMap, setCachedStatusMap,
|
||||||
|
getCachedMetrics, setCachedMetrics,
|
||||||
|
} from '@/lib/deviceCache'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
import { useAuth } from '@/hooks/useAuth'
|
||||||
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
||||||
import PageHeader from '@/components/ui/PageHeader'
|
import PageHeader from '@/components/ui/PageHeader'
|
||||||
@@ -14,6 +19,7 @@ import Pagination from '@/components/ui/Pagination'
|
|||||||
import SearchBar from '@/components/ui/SearchBar'
|
import SearchBar from '@/components/ui/SearchBar'
|
||||||
import RowActions from '@/components/ui/RowActions'
|
import RowActions from '@/components/ui/RowActions'
|
||||||
import Icon from '@/components/ui/Icon'
|
import Icon from '@/components/ui/Icon'
|
||||||
|
import Spinner from '@/components/ui/Spinner'
|
||||||
import SegmentedControl from '@/components/ui/SegmentedControl'
|
import SegmentedControl from '@/components/ui/SegmentedControl'
|
||||||
import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal'
|
import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal'
|
||||||
import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal'
|
import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal'
|
||||||
@@ -301,14 +307,18 @@ export default function DeviceList() {
|
|||||||
const { hasPermission } = useAuth()
|
const { hasPermission } = useAuth()
|
||||||
const canEdit = hasPermission('devices', 'edit')
|
const canEdit = hasPermission('devices', 'edit')
|
||||||
|
|
||||||
// Data
|
// Data — seeded from the last-known cache so the table paints instantly;
|
||||||
const [devices, setDevices] = useState([])
|
// fetchDevices() then revalidates in the background (see lib/deviceCache).
|
||||||
const [loading, setLoading] = useState(true)
|
// The cache key '' matches the initial (unfiltered) query below.
|
||||||
|
const [devices, setDevices] = useState(() => getCachedDevices('') || [])
|
||||||
|
const [loading, setLoading] = useState(() => !getCachedDevices(''))
|
||||||
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
const [error, setError] = useState('')
|
const [error, setError] = useState('')
|
||||||
const [mqttStatusMap, setMqttStatusMap] = useState({})
|
const [mqttStatusMap, setMqttStatusMap] = useState(() => getCachedStatusMap() || {})
|
||||||
const [mqttLoaded, setMqttLoaded] = useState(false)
|
const [mqttLoaded, setMqttLoaded] = useState(() => !!getCachedStatusMap())
|
||||||
const [latestDiagMap, setLatestDiagMap] = useState({})
|
const [latestDiagMap, setLatestDiagMap] = useState(() => getCachedMetrics().diagMap || {})
|
||||||
const [latestPingMap, setLatestPingMap] = useState({})
|
const [latestPingMap, setLatestPingMap] = useState(() => getCachedMetrics().pingMap || {})
|
||||||
|
const fetchSeq = useRef(0)
|
||||||
|
|
||||||
// Server-side filters
|
// Server-side filters
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
@@ -377,49 +387,71 @@ export default function DeviceList() {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
// ── Fetch devices ──────────────────────────────────────────────────────────
|
// ── Fetch devices ──────────────────────────────────────────────────────────
|
||||||
|
// Stale-while-revalidate: if this exact query was fetched before, show it
|
||||||
|
// immediately and refresh silently; only a never-seen query shows the
|
||||||
|
// table's loading state. Status + metrics are fetched in parallel with the
|
||||||
|
// device list (not after it) — they're served from the backend's in-memory
|
||||||
|
// latest-status cache and come back fast.
|
||||||
const fetchDevices = useCallback(async () => {
|
const fetchDevices = useCallback(async () => {
|
||||||
setLoading(true)
|
const seq = ++fetchSeq.current
|
||||||
setMqttLoaded(false)
|
const params = new URLSearchParams()
|
||||||
setError('')
|
if (search) params.set('search', search)
|
||||||
try {
|
if (onlineFilter === 'true') params.set('online', 'true')
|
||||||
const params = new URLSearchParams()
|
if (onlineFilter === 'false') params.set('online', 'false')
|
||||||
if (search) params.set('search', search)
|
if (tierFilter) params.set('tier', tierFilter)
|
||||||
if (onlineFilter === 'true') params.set('online', 'true')
|
// Note: online filter is server-side — we pass it as a query param but
|
||||||
if (onlineFilter === 'false') params.set('online', 'false')
|
// the server returns ALL devices when the param is absent, so we also
|
||||||
if (tierFilter) params.set('tier', tierFilter)
|
// apply a client-side guard to ensure ONLINE-only actually filters.
|
||||||
// Note: online filter is server-side — we pass it as a query param but
|
const qs = params.toString()
|
||||||
// the server returns ALL devices when the param is absent, so we also
|
|
||||||
// apply a client-side guard to ensure ONLINE-only actually filters.
|
const cached = getCachedDevices(qs)
|
||||||
const qs = params.toString()
|
if (cached) {
|
||||||
const data = await api.get(`/devices${qs ? `?${qs}` : ''}`)
|
setDevices(cached)
|
||||||
setDevices(data.devices ?? [])
|
|
||||||
api.get('/mqtt/status').then((mqttData) => {
|
|
||||||
if (mqttData?.devices) {
|
|
||||||
const map = {}
|
|
||||||
for (const s of mqttData.devices) map[s.device_serial] = s
|
|
||||||
setMqttStatusMap(map)
|
|
||||||
}
|
|
||||||
setMqttLoaded(true)
|
|
||||||
}).catch(() => { setMqttLoaded(true) })
|
|
||||||
// Last-known CPU temp + ping RTT — one extra request, fleet-wide,
|
|
||||||
// reading whatever the background MQTT ingestion already stored.
|
|
||||||
// Never triggers a live poll of any device.
|
|
||||||
api.get('/mqtt/latest-metrics').then((metrics) => {
|
|
||||||
if (metrics?.diagnostics) {
|
|
||||||
const dMap = {}
|
|
||||||
for (const d of metrics.diagnostics) dMap[d.device_serial] = d
|
|
||||||
setLatestDiagMap(dMap)
|
|
||||||
}
|
|
||||||
if (metrics?.pings) {
|
|
||||||
const pMap = {}
|
|
||||||
for (const p of metrics.pings) pMap[p.device_serial] = p
|
|
||||||
setLatestPingMap(pMap)
|
|
||||||
}
|
|
||||||
}).catch(() => { /* optional columns — non-fatal if unavailable */ })
|
|
||||||
} catch (err) {
|
|
||||||
setError(err.message || 'Failed to load devices.')
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
} else {
|
||||||
|
setLoading(true)
|
||||||
|
}
|
||||||
|
setRefreshing(true)
|
||||||
|
setError('')
|
||||||
|
|
||||||
|
api.get('/mqtt/status').then((mqttData) => {
|
||||||
|
if (mqttData?.devices) {
|
||||||
|
const map = {}
|
||||||
|
for (const s of mqttData.devices) map[s.device_serial] = s
|
||||||
|
setMqttStatusMap(map)
|
||||||
|
setCachedStatusMap(map)
|
||||||
|
}
|
||||||
|
setMqttLoaded(true)
|
||||||
|
}).catch(() => { setMqttLoaded(true) })
|
||||||
|
|
||||||
|
// Last-known CPU temp + ping RTT — one extra request, fleet-wide,
|
||||||
|
// reading whatever the background MQTT ingestion already stored.
|
||||||
|
// Never triggers a live poll of any device.
|
||||||
|
api.get('/mqtt/latest-metrics').then((metrics) => {
|
||||||
|
const dMap = {}
|
||||||
|
for (const d of metrics?.diagnostics || []) dMap[d.device_serial] = d
|
||||||
|
const pMap = {}
|
||||||
|
for (const p of metrics?.pings || []) pMap[p.device_serial] = p
|
||||||
|
setLatestDiagMap(dMap)
|
||||||
|
setLatestPingMap(pMap)
|
||||||
|
setCachedMetrics(dMap, pMap)
|
||||||
|
}).catch(() => { /* optional columns — non-fatal if unavailable */ })
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await api.get(`/devices${qs ? `?${qs}` : ''}`)
|
||||||
|
const list = data.devices ?? []
|
||||||
|
setCachedDevices(qs, list)
|
||||||
|
// Typing in the search box fires several fetches — only the newest
|
||||||
|
// one may update the table, or an older slow response could win.
|
||||||
|
if (seq === fetchSeq.current) setDevices(list)
|
||||||
|
} catch (err) {
|
||||||
|
// With cached rows on screen a failed revalidation stays silent.
|
||||||
|
if (seq === fetchSeq.current && !cached) setError(err.message || 'Failed to load devices.')
|
||||||
|
} finally {
|
||||||
|
if (seq === fetchSeq.current) {
|
||||||
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [search, onlineFilter, tierFilter])
|
}, [search, onlineFilter, tierFilter])
|
||||||
|
|
||||||
@@ -473,6 +505,12 @@ export default function DeviceList() {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// Keep the cache in step with live heartbeats, so the next visit (or the
|
||||||
|
// detail page) starts from the freshest status this tab has seen.
|
||||||
|
useEffect(() => {
|
||||||
|
if (mqttLoaded) setCachedStatusMap(mqttStatusMap)
|
||||||
|
}, [mqttStatusMap, mqttLoaded])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter])
|
}, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter])
|
||||||
@@ -713,6 +751,16 @@ export default function DeviceList() {
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{refreshing && !loading && (
|
||||||
|
<span
|
||||||
|
role="status"
|
||||||
|
title="Fetching fresh data — showing last-known values meanwhile"
|
||||||
|
style={{ display: 'inline-flex', alignItems: 'center', gap: 'var(--space-2)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-xs)' }}
|
||||||
|
>
|
||||||
|
<Spinner size="sm" />
|
||||||
|
Syncing…
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
<Button variant="secondary" icon={<Icon name="warning" size={14} />} onClick={() => navigate('/devices/crashes')}>
|
<Button variant="secondary" icon={<Icon name="warning" size={14} />} onClick={() => navigate('/devices/crashes')}>
|
||||||
Crash Report
|
Crash Report
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect, useCallback, useMemo } from 'react'
|
import { useState, useEffect, useCallback, useMemo } from 'react'
|
||||||
import api from '@/lib/api'
|
import api from '@/lib/api'
|
||||||
|
import { getCachedHealth, setCachedHealth } from '@/lib/deviceCache'
|
||||||
import Card from '@/components/ui/Card'
|
import Card from '@/components/ui/Card'
|
||||||
import StatusBadge from '@/components/ui/StatusBadge'
|
import StatusBadge from '@/components/ui/StatusBadge'
|
||||||
import Spinner from '@/components/ui/Spinner'
|
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) ───────────────
|
// ─── Health overview sub-tab (stats + charts + boot history) ───────────────
|
||||||
|
|
||||||
function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettings, isOnline, sendMqttCommand }) {
|
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 rangeParams = useMemo(() => {
|
||||||
const p = new URLSearchParams()
|
const p = new URLSearchParams()
|
||||||
if (range.since) p.set('since', range.since.toISOString())
|
if (range.since) p.set('since', range.since.toISOString())
|
||||||
@@ -311,9 +336,33 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
return p.toString()
|
return p.toString()
|
||||||
}, [range])
|
}, [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 () => {
|
const load = useCallback(async () => {
|
||||||
if (!sn) return
|
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('')
|
setError('')
|
||||||
try {
|
try {
|
||||||
const suffix = rangeParams ? `&${rangeParams}` : ''
|
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/ping-samples/${sn}?limit=5000${suffix}`),
|
||||||
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
api.get(`/mqtt/diagnostics-reports/${sn}?limit=5000${suffix}`),
|
||||||
])
|
])
|
||||||
setBootEvents(bootRes.events || [])
|
const next = {
|
||||||
setHeartbeats(hbRes.heartbeats || [])
|
bootEvents: bootRes.events || [],
|
||||||
setPingSamples(pingRes.samples || [])
|
heartbeats: hbRes.heartbeats || [],
|
||||||
setDiagReports(diagRes.reports || [])
|
pingSamples: pingRes.samples || [],
|
||||||
|
diagReports: diagRes.reports || [],
|
||||||
|
}
|
||||||
|
setCachedHealth(cacheKey, next)
|
||||||
|
setBootEvents(next.bootEvents)
|
||||||
|
setHeartbeats(next.heartbeats)
|
||||||
|
setPingSamples(next.pingSamples)
|
||||||
|
setDiagReports(next.diagReports)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message || 'Failed to load device health data.')
|
if (!prior) setError(err.message || 'Failed to load device health data.')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}, [sn, rangeParams])
|
}, [sn, rangeParams, cacheKey])
|
||||||
|
|
||||||
useEffect(() => { load() }, [load])
|
useEffect(() => { load() }, [load])
|
||||||
|
|
||||||
@@ -371,6 +427,7 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
|
|
||||||
const latestBoot = bootEvents[0] || null
|
const latestBoot = bootEvents[0] || null
|
||||||
const latestDiag = diagReports[0] || null
|
const latestDiag = diagReports[0] || null
|
||||||
|
const fw = firmwareSummary(mqttStatus, latestDiag)
|
||||||
const restartsInRange = bootEvents.length
|
const restartsInRange = bootEvents.length
|
||||||
const rangeLabelShort = range.key === 'all' ? 'all-time' : (
|
const rangeLabelShort = range.key === 'all' ? 'all-time' : (
|
||||||
range.key === 'custom' ? 'custom range' :
|
range.key === 'custom' ? 'custom range' :
|
||||||
@@ -513,13 +570,11 @@ function HealthOverview({ sn, mqttStatus, range, offlineTimeoutSec, healthSettin
|
|||||||
/>
|
/>
|
||||||
<MetricTile label="Firmware / OTA">
|
<MetricTile label="Firmware / OTA">
|
||||||
<span style={{ fontFamily: 'var(--font-family-mono)', fontSize: '1rem', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
|
<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>
|
</span>
|
||||||
{latestDiag && (
|
{fw.badge && (
|
||||||
<div style={{ marginTop: 2 }}>
|
<div style={{ marginTop: 2 }}>
|
||||||
<StatusBadge variant={latestDiag.ota_update_available ? 'warning' : 'success'} size="sm">
|
<StatusBadge variant={fw.badge.variant} size="sm">{fw.badge.label}</StatusBadge>
|
||||||
{latestDiag.ota_update_available ? 'update available' : 'up to date'}
|
|
||||||
</StatusBadge>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</MetricTile>
|
</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 [subTab, setSubTab] = useState('overview')
|
||||||
const [range, setRange] = useState(() => resolveRange('7d'))
|
const [range, setRange] = useState(() => resolveRange('7d'))
|
||||||
// Local override after a successful save, so the Settings form and offline-
|
// 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' && (
|
{subTab === 'overview' && (
|
||||||
<HealthOverview sn={sn} mqttStatus={mqttStatus} range={range} offlineTimeoutSec={offlineTimeoutSec} healthSettings={healthSettings} isOnline={isOnline} sendMqttCommand={sendMqttCommand} />
|
<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' && (
|
{subTab === 'settings' && (
|
||||||
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
<HealthSettings deviceId={device?.id} settings={healthSettings} onSaved={setSavedOverride} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
Reference in New Issue
Block a user