feat(devices): add Health tab, log explorer, and fleet health indicators

Surfaces the new device-health telemetry (boot events, ping RTT,
diagnostics reports, alert events) across the console:

- HealthTab: boot/diagnostics timeline, CPU temp and RSSI charts
  (LineChart), current alert status, and a Settings sub-tab for
  DeviceHealthSettings thresholds
- LogsTab: dedicated log explorer embedded in the Health tab, with
  level/source filtering and fmtLogTimestamp for dense timestamp rows
- OverviewTab: a "Latest Device Issue" card showing the most recent
  alert event, colour-coded by severity and fading with age, plus a
  modal to inspect the surrounding log lines
- DeviceList/DeviceListCardView/DeviceListMapView: fleet list gains a
  SignalIndicator-based RSSI display in place of the plain online dot

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 18:32:06 +03:00
co-authored by Claude Sonnet 5
parent 0d79a9f72c
commit acd1896788
7 changed files with 2395 additions and 94 deletions
@@ -10,7 +10,8 @@ import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'
import { fmtDateMedium, fmtRelative } from '@/lib/formatters'
import Modal from '@/components/ui/Modal'
import { fmtDateMedium, fmtDateTimeMedium, fmtRelative, fmtLogTimestamp } from '@/lib/formatters'
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
import {
parseFirestoreDate,
@@ -52,6 +53,23 @@ function subscrDurationLabel(days) {
return `${days}d`
}
// Latest Device Issue color: severity sets the base hue, age controls intensity.
// today = full opacity, fading out toward ~1 week, capped at a dim floor beyond that.
const ALERT_SEVERITY_HUE = {
CRITICAL: 'var(--color-danger)',
FAILED: 'var(--color-danger)',
WARNING: 'var(--color-warning)',
}
function alertEventStyle(occurredAtIso) {
const hue = ALERT_SEVERITY_HUE[occurredAtIso.state] || 'var(--color-warning)'
const ageMs = Date.now() - new Date(occurredAtIso.occurred_at).getTime()
const ageDays = ageMs / 86400000
// 1.0 opacity at "today", fading linearly to a 0.35 floor by 7 days out.
const opacity = Math.max(0.35, 1 - (ageDays / 7) * 0.65)
return { color: hue, opacity }
}
// ─── Sub-components ───────────────────────────────────────────────────────────
function GlassCard({ children, style = {}, className = '' }) {
@@ -146,6 +164,14 @@ const LOG_COLORS = {
INFO: { text: 'var(--color-info)', bg: 'var(--color-info-bg)' },
}
// Message text colour — INFO stays neutral/white, only WARN/ERROR get coloured
// so problem lines are the ones that visually stand out.
const MESSAGE_TEXT_COLOR = {
ERROR: 'var(--color-danger)',
WARN: 'var(--color-warning)',
INFO: 'var(--color-text-primary)',
}
// Level slider steps: 0=All, 1=INFO, 2=WARN, 3=ERROR
const LEVEL_STEPS = [
{ value: '', label: 'ALL', color: 'var(--color-text-muted)' },
@@ -265,6 +291,24 @@ export default function OverviewTab({
const [issueModal, setIssueModal] = useState({ open: false, entry: null })
const [viewNote, setViewNote] = useState(null)
// ── Latest device issue detail modal ─────────────────────────────────────
const [alertModalOpen, setAlertModalOpen] = useState(false)
const [alertLogs, setAlertLogs] = useState([])
const [alertLogsLoading, setAlertLogsLoading] = useState(false)
const openAlertModal = useCallback(() => {
setAlertModalOpen(true)
if (!sn) return
setAlertLogsLoading(true)
api.get(`/mqtt/logs/${sn}?limit=20&offset=0`)
.then(data => {
const rows = (data.logs || []).filter(l => l.level === 'ERROR' || l.level === 'WARN')
setAlertLogs(rows)
})
.catch(() => setAlertLogs([]))
.finally(() => setAlertLogsLoading(false))
}, [sn])
const handleNoteSaved = () => {
setNoteModal({ open: false })
loadNotes()
@@ -277,43 +321,52 @@ export default function OverviewTab({
// ── Live logs ─────────────────────────────────────────────────────────────
const [logs, setLogs] = useState([])
const [logsLoading, setLogsLoading] = useState(false)
const [logsInitialLoading, setLogsInitialLoading] = useState(true)
const [levelStep, setLevelStep] = useState(0) // index into LEVEL_STEPS
const [searchText, setSearchText] = useState('')
const [autoScroll, setAutoScroll] = useState(true)
const [autoRefresh, setAutoRefresh] = useState(false)
const [autoRefresh, setAutoRefresh] = useState(true)
const [liveLogs, setLiveLogs] = useState([])
const logsContainerRef = useRef(null)
const logsHasLoadedOnce = useRef(false)
const LIMIT = 50
const levelFilter = LEVEL_STEPS[levelStep].value
// Stepped severity order: a level also matches everything more severe than it
// (ALL < INFO < WARN < ERROR), so picking WARN also shows WARN and ERROR.
const LEVEL_RANK = { INFO: 0, WARN: 1, ERROR: 2 }
const meetsLevelFloor = lvl => !levelFilter || (LEVEL_RANK[lvl] ?? 0) >= LEVEL_RANK[levelFilter]
const fetchLogs = useCallback(async () => {
// `background` fetches (polling / manual refresh) never toggle a loading
// flag — only the very first load shows a spinner, so auto-sync and the
// REFRESH button stay seamless instead of flickering every few seconds.
const fetchLogs = useCallback(async (background = false) => {
if (!sn) return
setLogsLoading(true)
if (!background && !logsHasLoadedOnce.current) setLogsInitialLoading(true)
try {
const params = new URLSearchParams({ limit: LIMIT, offset: 0 })
if (levelFilter) params.set('level', levelFilter)
if (levelFilter) { params.set('level', levelFilter); params.set('min_level', 'true') }
if (searchText) params.set('search', searchText)
const data = await api.get(`/mqtt/logs/${sn}?${params}`)
setLogs(data.logs || [])
} catch {
// silent
} finally {
setLogsLoading(false)
logsHasLoadedOnce.current = true
setLogsInitialLoading(false)
}
}, [sn, levelFilter, searchText])
useEffect(() => { if (sn) fetchLogs() }, [sn, fetchLogs])
useEffect(() => { if (sn) fetchLogs(false) }, [sn, fetchLogs])
useEffect(() => {
if (!autoRefresh || !sn) return
const t = setInterval(fetchLogs, 5000)
const t = setInterval(() => fetchLogs(true), 5000)
return () => clearInterval(t)
}, [autoRefresh, sn, fetchLogs])
const handleWsMessage = useCallback((data) => {
if (data.type === 'logs' && data.device_serial === sn) {
if (data.type === 'system/logs' && data.device_serial === sn) {
const entry = {
id: Date.now(),
level: data.payload?.level?.includes('EROR') ? 'ERROR' :
@@ -330,18 +383,24 @@ export default function OverviewTab({
const allLogs = [
...liveLogs.filter(l => {
if (levelFilter && l.level !== levelFilter) return false
if (!meetsLevelFloor(l.level)) return false
if (searchText && !l.message.toLowerCase().includes(searchText.toLowerCase())) return false
return true
}),
...logs,
]
// Only auto-scroll to top when a genuinely NEW live log arrives — not when
// the level filter / search changes the visible set (that should update
// the list in place, without yanking the scroll position).
const liveLogCount = liveLogs.length
const prevLiveLogCount = useRef(liveLogCount)
useEffect(() => {
if (autoScroll && logsContainerRef.current) {
if (liveLogCount > prevLiveLogCount.current && autoScroll && logsContainerRef.current) {
logsContainerRef.current.scrollTop = 0
}
}, [allLogs.length, autoScroll])
prevLiveLogCount.current = liveLogCount
}, [liveLogCount, autoScroll])
// ── Service lifecycle ─────────────────────────────────────────────────────
const subscrStart = parseFirestoreDate(sub?.subscrStart)
@@ -429,68 +488,93 @@ export default function OverviewTab({
</div>
{/* ── Section B: Hardware info ── */}
{/* ── Section B+D: Device info grid (Serial/HW/Uptime/Location/Rev/Issue) ── */}
<div style={{
flex: 1,
flex: 2,
padding: 'var(--space-6)',
marginLeft: 'var(--space-4)',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
gap: 'var(--space-4)',
alignItems: 'center',
minWidth: 0,
}}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-5) var(--space-8)', maxWidth: 480 }}>
}} className="overview-hero-grid-wrap">
<div className="overview-hero-grid" style={{
display: 'grid',
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gridAutoRows: 'auto',
columnGap: 'var(--space-8)',
rowGap: 'var(--space-5)',
width: '100%',
}}>
<InfoField label="Serial Number" mono>{sn || '—'}</InfoField>
<InfoField label="Hardware Family">{hwVariant}</InfoField>
<InfoField label="Device Uptime">
{mqttStatus?.last_heartbeat?.uptime_ms != null
? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-base)' }}>{formatUptime(Math.floor(mqttStatus.last_heartbeat.uptime_ms / 1000))}</span>
: <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic', fontWeight: 'var(--font-weight-normal)' }}>Unavailable</span>}
</InfoField>
<InfoField label="Location">{device.device_location || '—'}</InfoField>
<InfoField label="Hardware Revision">{hwRevision || device.device_attributes?.firmwareVersion || '—'}</InfoField>
</div>
</div>
{/* ── Section D: Uptime + Latest Issue ── */}
<div style={{
width: 220,
flexShrink: 0,
padding: 'var(--space-6)',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
gap: 'var(--space-5)',
minWidth: 0,
}}>
<InfoField label="Device Uptime">
{mqttStatus?.uptime_seconds != null
? <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-base)' }}>{formatUptime(mqttStatus.uptime_seconds)}</span>
: <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic', fontWeight: 'var(--font-weight-normal)' }}>Unavailable</span>}
</InfoField>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-more-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>Latest Device Issue</span>
{mqttStatus?.last_warn_message ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-warning)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
MQTT · WARN · Health Monitor
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-secondary)',
lineHeight: 1.5,
}}>
{mqttStatus.last_warn_message}
</span>
</div>
) : (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No recent issues
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', minWidth: 0 }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-more-muted)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
Latest Device Issue
</span>
)}
{mqttStatus?.last_alert_event ? (
<div
onClick={openAlertModal}
role="button"
tabIndex={0}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openAlertModal() } }}
style={{
display: 'flex',
flexDirection: 'column',
gap: 2,
cursor: 'pointer',
borderRadius: 'var(--radius-sm)',
marginInline: -4,
paddingInline: 4,
transition: 'background 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.background = GLASS_INNER}
onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
...alertEventStyle(mqttStatus.last_alert_event),
}}>
{mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem} · {fmtRelative(mqttStatus.last_alert_event.occurred_at)}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-secondary)',
lineHeight: 1.4,
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: 1,
WebkitBoxOrient: 'vertical',
textOverflow: 'ellipsis',
}}>
{mqttStatus.last_alert_event.message || 'No details provided.'}
</span>
</div>
) : (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No recent issues
</span>
)}
</div>
</div>
</div>
@@ -930,7 +1014,7 @@ export default function OverviewTab({
{LEVEL_STEPS.map((step, idx) => (
<button
key={step.value}
onClick={() => { setLevelStep(idx); setLogs([]) }}
onClick={() => setLevelStep(idx)}
title={step.label}
style={{
height: 24,
@@ -1020,10 +1104,10 @@ export default function OverviewTab({
AUTO-SYNC
</button>
{/* Refresh — same visual style as the toggle buttons */}
{/* Refresh — same visual style as the toggle buttons. No spinner/dim-out:
a background sync must stay seamless, not flicker every few seconds. */}
<button
onClick={fetchLogs}
disabled={logsLoading}
onClick={() => fetchLogs(true)}
style={{
height: 28,
paddingInline: 'var(--space-3)',
@@ -1033,24 +1117,19 @@ export default function OverviewTab({
color: 'var(--color-text-secondary)',
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
cursor: logsLoading ? 'not-allowed' : 'pointer',
cursor: 'pointer',
letterSpacing: 'var(--tracking-wide)',
fontFamily: 'var(--font-family-base)',
opacity: logsLoading ? 0.5 : 1,
flexShrink: 0,
display: 'flex',
alignItems: 'center',
gap: 'var(--space-1)',
}}
>
{logsLoading ? <Spinner size="sm" /> : null}
REFRESH
</button>
</div>
{/* Log rows */}
<div ref={logsContainerRef} style={{ maxHeight: 320, overflowY: 'auto', fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)' }}>
{logsLoading && allLogs.length === 0 ? (
{logsInitialLoading && allLogs.length === 0 ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
<Spinner size="sm" />
</div>
@@ -1095,7 +1174,7 @@ export default function OverviewTab({
}}
>
<td style={{ padding: 'var(--space-2) var(--space-4)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap' }}>
{log.received_at?.replace('T', ' ').substring(0, 19)}
{fmtLogTimestamp(log.received_at)}
{log._live && (
<span style={{ marginLeft: 'var(--space-2)', fontSize: 'var(--font-size-xs)', color: 'var(--color-success)', fontWeight: 'var(--font-weight-semibold)' }}>LIVE</span>
)}
@@ -1114,7 +1193,7 @@ export default function OverviewTab({
{log.level}
</span>
</td>
<td style={{ padding: 'var(--space-2) var(--space-4)', color: 'var(--color-text-primary)' }}>
<td style={{ padding: 'var(--space-2) var(--space-4)', color: MESSAGE_TEXT_COLOR[log.level] || 'var(--color-text-primary)' }}>
{log.message}
</td>
</tr>
@@ -1134,6 +1213,12 @@ export default function OverviewTab({
@media (max-width: 900px) {
.overview-row2 { grid-template-columns: 1fr !important; }
}
@media (max-width: 1100px) {
.overview-hero-grid { grid-template-columns: repeat(2, minmax(0, 1fr)) !important; }
}
@media (max-width: 640px) {
.overview-hero-grid { grid-template-columns: 1fr !important; }
}
@keyframes ov-pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.35; }
@@ -1160,8 +1245,8 @@ export default function OverviewTab({
open={issueModal.open}
entry={issueModal.entry}
defaultType="issue"
prefilledLinks={issueModal.entry ? undefined : [{ entity_type: 'device', entity_id: id, display_name: device?.device_name || sn, locked: true }]}
knownEntities={id ? { [id]: device?.device_name || sn } : undefined}
prefilledLinks={issueModal.entry ? undefined : [{ entity_type: 'device', entity_id: id, display_name: device?.console_name || device?.device_name || sn, locked: true }]}
knownEntities={id ? { [id]: device?.console_name || device?.device_name || sn } : undefined}
onClose={() => setIssueModal({ open: false, entry: null })}
onSaved={handleIssueSaved}
/>
@@ -1224,6 +1309,92 @@ export default function OverviewTab({
</div>
</div>
)}
{/* ── Latest Device Issue detail modal ──────────────────────────────── */}
<Modal
open={alertModalOpen}
onClose={() => setAlertModalOpen(false)}
title="Latest Device Issue"
size="md"
>
{mqttStatus?.last_alert_event && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
...alertEventStyle(mqttStatus.last_alert_event),
opacity: 1,
}}>
{mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{fmtDateTimeMedium(mqttStatus.last_alert_event.occurred_at)}
</span>
</div>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>
{mqttStatus.last_alert_event.message || 'No details provided.'}
</p>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', borderTop: '1px solid var(--color-border)', paddingTop: 'var(--space-4)' }}>
<SectionLabel>Recent Error &amp; Warning Logs</SectionLabel>
{alertLogsLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-4)' }}>
<Spinner size="sm" />
</div>
) : alertLogs.length === 0 ? (
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No recent error or warning logs.
</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', maxHeight: 280, overflowY: 'auto' }}>
{alertLogs.map((log, i) => {
const s = LOG_COLORS[log.level] || LOG_COLORS.INFO
return (
<div
key={log.id || i}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
}}
>
<span style={{
display: 'inline-block',
padding: '1px var(--space-2)',
borderRadius: 'var(--radius-sm)',
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
background: s.bg,
color: s.text,
letterSpacing: 'var(--tracking-wide)',
flexShrink: 0,
}}>
{log.level}
</span>
<span style={{ flex: 1, fontSize: 'var(--font-size-sm)', color: MESSAGE_TEXT_COLOR[log.level] || 'var(--color-text-primary)', fontFamily: 'var(--font-family-mono)' }}>
{log.message}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }}>
{fmtLogTimestamp(log.received_at)}
</span>
</div>
)
})}
</div>
)}
</div>
</div>
)}
</Modal>
</div>
)
}