diff --git a/frontend/src/lib/deviceCache.js b/frontend/src/lib/deviceCache.js new file mode 100644 index 0000000..65fa8d5 --- /dev/null +++ b/frontend/src/lib/deviceCache.js @@ -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 +} diff --git a/frontend/src/pages/bellcloud/devices/DeviceDetail.jsx b/frontend/src/pages/bellcloud/devices/DeviceDetail.jsx index e036b5d..528b0ac 100644 --- a/frontend/src/pages/bellcloud/devices/DeviceDetail.jsx +++ b/frontend/src/pages/bellcloud/devices/DeviceDetail.jsx @@ -1,9 +1,10 @@ // frontend/src/pages/bellcloud/devices/DeviceDetail.jsx // 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 api from '@/lib/api' +import { getCachedDevice, setCachedDevice, getCachedStatus, setCachedStatus } from '@/lib/deviceCache' import { useAuth } from '@/hooks/useAuth' import { useToast } from '@/components/ui/Toast' import { useDeviceCommand } from '@/hooks/useDeviceCommand' @@ -73,10 +74,19 @@ export default function DeviceDetail() { const canEdit = hasPermission('devices', 'edit') // ── State ────────────────────────────────────────────────────────────────── - const [device, setDevice] = useState(null) - const [loading, setLoading] = useState(true) + // Seeded from the last-known cache (lib/deviceCache — filled by DeviceList + // 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 [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 [deviceUsers, setDeviceUsers] = useState([]) @@ -84,8 +94,11 @@ export default function DeviceDetail() { const [ownerCustomer, setOwnerCustomer] = useState(null) const [assigningCustomer, setAssigningCustomer] = useState(false) - const [tags, setTags] = useState([]) - const [staffNotes, setStaffNotes] = useState('') + const [tags, setTags] = useState(() => { + const t = getCachedDevice(id)?.tags + return Array.isArray(t) ? t : [] + }) + const [staffNotes, setStaffNotes] = useState(() => getCachedDevice(id)?.staffNotes || '') const [showDelete, setShowDelete] = useState(false) const [deleting, setDeleting] = useState(false) @@ -108,8 +121,29 @@ export default function DeviceDetail() { // ── Data fetching ────────────────────────────────────────────────────────── 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('') + + // 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 { const d = await api.get(`/devices/${id}`) setDevice(d) @@ -118,14 +152,8 @@ export default function DeviceDetail() { setLoading(false) const sn = d.serial_number || d.device_id - if (sn) { - api.get('/mqtt/status').then(mqttData => { - if (mqttData?.devices) { - const match = mqttData.devices.find(s => s.device_serial === sn) - setMqttStatus(match || null) - } - }).catch(() => {}) - } + const statusDone = statusPromise || (sn ? fetchStatus(sn) : Promise.resolve()) + statusDone.finally(() => setRefreshing(false)) if (d.customer_id) { api.get(`/devices/${id}/customer`).then(res => { @@ -141,8 +169,10 @@ export default function DeviceDetail() { }).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false)) } 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) + setRefreshing(false) } }, [id]) @@ -187,6 +217,11 @@ export default function DeviceDetail() { 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) => { // Live heartbeat — updates the online dot/RSSI without polling. The device // publishes one every ~30s; we just reflect whatever lands here instead of @@ -418,6 +453,16 @@ export default function DeviceDetail() { } > + {refreshing && ( + + + Syncing… + + )} diff --git a/frontend/src/pages/bellcloud/devices/DeviceList.jsx b/frontend/src/pages/bellcloud/devices/DeviceList.jsx index b8eb325..7b0a9fe 100644 --- a/frontend/src/pages/bellcloud/devices/DeviceList.jsx +++ b/frontend/src/pages/bellcloud/devices/DeviceList.jsx @@ -1,8 +1,13 @@ // 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 api from '@/lib/api' +import { + getCachedDevices, setCachedDevices, + getCachedStatusMap, setCachedStatusMap, + getCachedMetrics, setCachedMetrics, +} from '@/lib/deviceCache' import { useAuth } from '@/hooks/useAuth' import { useMqttWebSocket } from '@/hooks/useMqttWebSocket' import PageHeader from '@/components/ui/PageHeader' @@ -14,6 +19,7 @@ import Pagination from '@/components/ui/Pagination' import SearchBar from '@/components/ui/SearchBar' import RowActions from '@/components/ui/RowActions' import Icon from '@/components/ui/Icon' +import Spinner from '@/components/ui/Spinner' import SegmentedControl from '@/components/ui/SegmentedControl' import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal' import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal' @@ -301,14 +307,18 @@ export default function DeviceList() { const { hasPermission } = useAuth() const canEdit = hasPermission('devices', 'edit') - // Data - const [devices, setDevices] = useState([]) - const [loading, setLoading] = useState(true) + // Data — seeded from the last-known cache so the table paints instantly; + // fetchDevices() then revalidates in the background (see lib/deviceCache). + // 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 [mqttStatusMap, setMqttStatusMap] = useState({}) - const [mqttLoaded, setMqttLoaded] = useState(false) - const [latestDiagMap, setLatestDiagMap] = useState({}) - const [latestPingMap, setLatestPingMap] = useState({}) + const [mqttStatusMap, setMqttStatusMap] = useState(() => getCachedStatusMap() || {}) + const [mqttLoaded, setMqttLoaded] = useState(() => !!getCachedStatusMap()) + const [latestDiagMap, setLatestDiagMap] = useState(() => getCachedMetrics().diagMap || {}) + const [latestPingMap, setLatestPingMap] = useState(() => getCachedMetrics().pingMap || {}) + const fetchSeq = useRef(0) // Server-side filters const [search, setSearch] = useState('') @@ -377,49 +387,71 @@ export default function DeviceList() { }, []) // ── 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 () => { - setLoading(true) - setMqttLoaded(false) - setError('') - try { - const params = new URLSearchParams() - if (search) params.set('search', search) - if (onlineFilter === 'true') params.set('online', 'true') - if (onlineFilter === 'false') params.set('online', 'false') - if (tierFilter) params.set('tier', tierFilter) - // Note: online filter is server-side — we pass it as a query param but - // 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 qs = params.toString() - const data = await api.get(`/devices${qs ? `?${qs}` : ''}`) - 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 { + const seq = ++fetchSeq.current + const params = new URLSearchParams() + if (search) params.set('search', search) + if (onlineFilter === 'true') params.set('online', 'true') + if (onlineFilter === 'false') params.set('online', 'false') + if (tierFilter) params.set('tier', tierFilter) + // Note: online filter is server-side — we pass it as a query param but + // 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 qs = params.toString() + + const cached = getCachedDevices(qs) + if (cached) { + setDevices(cached) 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]) @@ -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(() => { setPage(1) }, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter]) @@ -713,6 +751,16 @@ export default function DeviceList() { : undefined } > + {refreshing && !loading && ( + + + Syncing… + + )} diff --git a/frontend/src/pages/bellcloud/devices/tabs/HealthTab.jsx b/frontend/src/pages/bellcloud/devices/tabs/HealthTab.jsx index 27227f8..99f7854 100644 --- a/frontend/src/pages/bellcloud/devices/tabs/HealthTab.jsx +++ b/frontend/src/pages/bellcloud/devices/tabs/HealthTab.jsx @@ -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 /> - {latestDiag?.ota_current_version ? `v${latestDiag.ota_current_version}` : '—'} + {fw.current ? `v${fw.current}` : '—'} - {latestDiag && ( + {fw.badge && (
- - {latestDiag.ota_update_available ? 'update available' : 'up to date'} - + {fw.badge.label}
)}
@@ -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' && ( )} - {subTab === 'logs' && } + {subTab === 'logs' && } {subTab === 'settings' && ( )}