feat(devices): clear log view and delete logs from the Health tab
Health → Logs gets two actions above the log explorer:
- Clear view (view-only): hides everything received before now so only
fresh entries show. Text channels use it as the server-side `since`
bound; alerts/heartbeats/commands filter client-side. "Show all" undoes
it; nothing is deleted.
- Delete logs… (devices:edit): DeleteDeviceLogsModal permanently deletes
selected history by type — Device Logs and Info (optionally only some
levels) via DELETE /mqtt/logs/{serial}, and alert history / heartbeats /
commands via the existing reset-stats endpoint. Press-and-hold confirm,
like Reset Stats. Device SD-card logs are untouched.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
// frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx
|
||||
// Health tab → Logs → "Delete Logs…". Permanently deletes console-stored log
|
||||
// history for one device, filtered by log type (and by level for the text
|
||||
// channels). Unlike ResetStatsModal this never touches the device itself,
|
||||
// Firestore stats, boot history or ping/diagnostics data — just the log
|
||||
// channels shown in the Logs explorer.
|
||||
//
|
||||
// Device Logs / Info → DELETE /mqtt/logs/{serial}?source=…&level=…
|
||||
// Alerts / Heartbeats / Commands → POST /devices/{id}/reset-stats (existing)
|
||||
|
||||
import { useState } from 'react'
|
||||
import Modal from '@/components/ui/Modal'
|
||||
import Button from '@/components/ui/Button'
|
||||
import PressHoldButton from '@/components/ui/PressHoldButton'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import api from '@/lib/api'
|
||||
import { useToast } from '@/components/ui/Toast'
|
||||
|
||||
const TYPES = [
|
||||
{ key: 'log', label: 'Device Logs', description: 'Debug log lines the firmware streams over MQTT.', leveled: true },
|
||||
{ key: 'info', label: 'Info events', description: 'System info events (playback started, config changes, …).', leveled: true },
|
||||
{ key: 'alert_history', label: 'Alert history', description: 'Past alert transitions. Current active alerts are kept.' },
|
||||
{ key: 'heartbeats', label: 'Heartbeats', description: 'Heartbeat history — also empties the RSSI and free-heap charts on Overview.' },
|
||||
{ key: 'commands', label: 'Commands', description: 'Sent-command history (also shown in the Control tab).' },
|
||||
]
|
||||
|
||||
const LEVELS = ['INFO', 'WARN', 'ERROR']
|
||||
|
||||
function CheckRow({ label, description, checked, onChange, disabled }) {
|
||||
return (
|
||||
<label style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-3)',
|
||||
padding: 'var(--space-2) 0', cursor: disabled ? 'default' : 'pointer',
|
||||
opacity: disabled ? 0.5 : 1,
|
||||
}}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={onChange}
|
||||
disabled={disabled}
|
||||
style={{ accentColor: 'var(--color-danger)', flexShrink: 0, marginTop: 3 }}
|
||||
/>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<p style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
|
||||
{label}
|
||||
</p>
|
||||
{description && (
|
||||
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', marginTop: 2 }}>
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DeleteDeviceLogsModal({ open, onClose, onDeleted, deviceId, serial }) {
|
||||
const { toast } = useToast()
|
||||
const [types, setTypes] = useState({ log: true, info: true, alert_history: false, heartbeats: false, commands: false })
|
||||
const [levels, setLevels] = useState({ INFO: true, WARN: true, ERROR: true })
|
||||
const [running, setRunning] = useState(false)
|
||||
|
||||
const textSources = ['log', 'info'].filter(k => types[k])
|
||||
const selectedLevels = LEVELS.filter(l => levels[l])
|
||||
const allLevels = selectedLevels.length === LEVELS.length
|
||||
const tableKeys = ['alert_history', 'heartbeats', 'commands'].filter(k => types[k])
|
||||
const canRun = (textSources.length > 0 && selectedLevels.length > 0) || tableKeys.length > 0
|
||||
|
||||
const handleClose = () => { if (!running) onClose() }
|
||||
|
||||
const run = async () => {
|
||||
setRunning(true)
|
||||
const done = []
|
||||
const failed = []
|
||||
if (textSources.length > 0 && selectedLevels.length > 0) {
|
||||
const params = new URLSearchParams()
|
||||
textSources.forEach(s => params.append('source', s))
|
||||
if (!allLevels) selectedLevels.forEach(l => params.append('level', l))
|
||||
try {
|
||||
const res = await api.delete(`/mqtt/logs/${encodeURIComponent(serial)}?${params}`)
|
||||
done.push(`${res?.deleted ?? 0} log line(s)`)
|
||||
} catch (err) {
|
||||
failed.push(`logs: ${err.message || 'failed'}`)
|
||||
}
|
||||
}
|
||||
if (tableKeys.length > 0) {
|
||||
const body = Object.fromEntries(tableKeys.map(k => [k, true]))
|
||||
try {
|
||||
const res = await api.post(`/devices/${deviceId}/reset-stats`, body)
|
||||
for (const k of tableKeys) {
|
||||
const label = TYPES.find(t => t.key === k).label.toLowerCase()
|
||||
done.push(`${res?.[k] ?? 0} ${label}`)
|
||||
}
|
||||
} catch (err) {
|
||||
failed.push(`${tableKeys.join(', ')}: ${err.message || 'failed'}`)
|
||||
}
|
||||
}
|
||||
setRunning(false)
|
||||
if (failed.length === 0) {
|
||||
toast.success('Logs deleted', `Removed ${done.join(', ')}.`)
|
||||
} else {
|
||||
toast.danger('Delete incomplete', failed.join(' · '))
|
||||
}
|
||||
onDeleted?.()
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={handleClose} title="Delete Device Logs" size="md" persistent={running}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 'var(--space-2)',
|
||||
padding: 'var(--space-3) var(--space-4)', borderRadius: 'var(--radius-md)',
|
||||
backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)',
|
||||
fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)',
|
||||
}}>
|
||||
<Icon name="warning" size={16} color="var(--color-danger)" style={{ flexShrink: 0, marginTop: 1 }} />
|
||||
<span>
|
||||
Permanently deletes the selected history for <strong>{serial}</strong> from the console database. The device's own SD-card logs are not affected. <strong>This cannot be undone.</strong>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||
Log types
|
||||
</span>
|
||||
<div style={{ borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)' }}>
|
||||
{TYPES.map(t => (
|
||||
<CheckRow
|
||||
key={t.key}
|
||||
label={t.label}
|
||||
description={t.description}
|
||||
checked={!!types[t.key]}
|
||||
onChange={() => setTypes(prev => ({ ...prev, [t.key]: !prev[t.key] }))}
|
||||
disabled={running}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{textSources.length > 0 && (
|
||||
<div>
|
||||
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', letterSpacing: 'var(--tracking-wide)', textTransform: 'uppercase' }}>
|
||||
Levels (Device Logs & Info)
|
||||
</span>
|
||||
<div style={{ display: 'flex', gap: 'var(--space-6)', borderTop: '1px solid var(--color-border)', marginTop: 'var(--space-2)', flexWrap: 'wrap' }}>
|
||||
{LEVELS.map(l => (
|
||||
<CheckRow
|
||||
key={l}
|
||||
label={l}
|
||||
checked={!!levels[l]}
|
||||
onChange={() => setLevels(prev => ({ ...prev, [l]: !prev[l] }))}
|
||||
disabled={running}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)', paddingTop: 'var(--space-2)', borderTop: '1px solid var(--color-border)', flexWrap: 'wrap' }}>
|
||||
<Button variant="ghost" onClick={handleClose} disabled={running}>Cancel</Button>
|
||||
<PressHoldButton
|
||||
variant="danger"
|
||||
holdMs={2000}
|
||||
disabled={running || !canRun}
|
||||
holdingLabel="Keep holding to delete…"
|
||||
onConfirm={run}
|
||||
>
|
||||
{running ? 'Deleting…' : 'Hold to Delete'}
|
||||
</PressHoldButton>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -7,9 +7,15 @@ import api from '@/lib/api'
|
||||
import Spinner from '@/components/ui/Spinner'
|
||||
import StatusBadge from '@/components/ui/StatusBadge'
|
||||
import Pagination from '@/components/ui/Pagination'
|
||||
import { fmtDateTimeMedium, fmtRelative, fmtLogTimestamp } from '@/lib/formatters'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import DeleteDeviceLogsModal from '@/modals/bellcloud/devices/DeleteDeviceLogsModal'
|
||||
import { fmtDateTimeMedium, fmtRelative, fmtLogTimestamp, fmtTime24 } from '@/lib/formatters'
|
||||
import { useMqttWebSocket } from '@/hooks/useMqttWebSocket'
|
||||
|
||||
// Rows timestamped before the "Clear view" point are hidden (view-only).
|
||||
const afterClear = (clearedAt, ts) => !clearedAt || (ts && new Date(ts) >= clearedAt)
|
||||
|
||||
// ─── Glass surface tokens (match Overview / Control tab aesthetic) ────────────
|
||||
|
||||
const GLASS = 'rgba(28, 32, 38, 0.30)'
|
||||
@@ -474,7 +480,7 @@ function TextLogPanel({ sn, source, liveTypes, channel, onChannelChange, range }
|
||||
|
||||
// ─── Unified feed (Device Logs + Info + Alerts merged, chronological) ────────
|
||||
|
||||
function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
||||
function UnifiedPanel({ sn, channel, onChannelChange, range, clearedAt }) {
|
||||
const [logRows, setLogRows] = useState([])
|
||||
const [alertRows, setAlertRows] = useState([])
|
||||
const [initialLoading, setInitialLoading] = useState(true)
|
||||
@@ -559,11 +565,13 @@ function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
||||
|
||||
const merged = useMemo(() => {
|
||||
const logEntries = logRows.map(l => ({ _kind: 'log', source: l.source || 'log', ...l }))
|
||||
const alertEntries = alertRows.map(a => ({ _kind: 'alert', source: 'alert', ...a, received_at: a.occurred_at }))
|
||||
const alertEntries = alertRows
|
||||
.filter(a => afterClear(clearedAt, a.occurred_at))
|
||||
.map(a => ({ _kind: 'alert', source: 'alert', ...a, received_at: a.occurred_at }))
|
||||
const combined = [...logEntries, ...alertEntries]
|
||||
combined.sort((a, b) => new Date(b.received_at) - new Date(a.received_at))
|
||||
return combined
|
||||
}, [logRows, alertRows])
|
||||
}, [logRows, alertRows, clearedAt])
|
||||
|
||||
const liveFiltered = liveRows.filter(l => {
|
||||
if (l._kind === 'alert') return true
|
||||
@@ -678,8 +686,9 @@ function UnifiedPanel({ sn, channel, onChannelChange, range }) {
|
||||
|
||||
// ─── Alerts history panel ─────────────────────────────────────────────────────
|
||||
|
||||
function AlertsPanel({ sn, channel, onChannelChange }) {
|
||||
const [rows, setRows] = useState([])
|
||||
function AlertsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||
const [allRows, setRows] = useState([])
|
||||
const rows = allRows.filter(r => afterClear(clearedAt, r.occurred_at))
|
||||
const [total, setTotal] = useState(0)
|
||||
const [initialLoading, setInitialLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
@@ -750,7 +759,7 @@ function AlertsPanel({ sn, channel, onChannelChange }) {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{total > PAGE_SIZE && (
|
||||
{total > PAGE_SIZE && !clearedAt && (
|
||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||
</div>
|
||||
@@ -761,8 +770,9 @@ function AlertsPanel({ sn, channel, onChannelChange }) {
|
||||
|
||||
// ─── Heartbeats panel ─────────────────────────────────────────────────────────
|
||||
|
||||
function HeartbeatsPanel({ sn, channel, onChannelChange }) {
|
||||
const [rows, setRows] = useState([])
|
||||
function HeartbeatsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||
const [allRows, setRows] = useState([])
|
||||
const rows = allRows.filter(r => afterClear(clearedAt, r.received_at))
|
||||
const [total, setTotal] = useState(0)
|
||||
const [initialLoading, setInitialLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
@@ -835,7 +845,7 @@ function HeartbeatsPanel({ sn, channel, onChannelChange }) {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{total > PAGE_SIZE && (
|
||||
{total > PAGE_SIZE && !clearedAt && (
|
||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||
</div>
|
||||
@@ -853,8 +863,9 @@ const COMMAND_STATUS_VARIANT = {
|
||||
timeout: 'danger',
|
||||
}
|
||||
|
||||
function CommandsPanel({ sn, channel, onChannelChange }) {
|
||||
const [rows, setRows] = useState([])
|
||||
function CommandsPanel({ sn, channel, onChannelChange, clearedAt }) {
|
||||
const [allRows, setRows] = useState([])
|
||||
const rows = allRows.filter(r => afterClear(clearedAt, r.sent_at))
|
||||
const [total, setTotal] = useState(0)
|
||||
const [initialLoading, setInitialLoading] = useState(true)
|
||||
const [page, setPage] = useState(1)
|
||||
@@ -924,7 +935,7 @@ function CommandsPanel({ sn, channel, onChannelChange }) {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{total > PAGE_SIZE && (
|
||||
{total > PAGE_SIZE && !clearedAt && (
|
||||
<div style={{ padding: 'var(--space-4) var(--space-5)', borderTop: '1px solid var(--color-border)' }}>
|
||||
<Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
|
||||
</div>
|
||||
@@ -935,31 +946,87 @@ function CommandsPanel({ sn, channel, onChannelChange }) {
|
||||
|
||||
// ─── LogsTab ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export default function LogsTab({ sn, range }) {
|
||||
export default function LogsTab({ sn, range, deviceId, canEdit }) {
|
||||
const [channel, setChannel] = useState('unified')
|
||||
// "Clear" is view-only: hide everything received before this moment so
|
||||
// only fresh entries show. Nothing is deleted — "Show all" brings it back.
|
||||
const [clearedAt, setClearedAt] = useState(null)
|
||||
// Bumped on clear / show-all / delete to remount the active panel, which
|
||||
// drops its buffered live rows and refetches from scratch.
|
||||
const [viewEpoch, setViewEpoch] = useState(0)
|
||||
const [showDelete, setShowDelete] = useState(false)
|
||||
|
||||
// Text-log channels filter server-side: the clear point simply becomes the
|
||||
// range's lower bound (whichever is later).
|
||||
const effectiveRange = useMemo(() => {
|
||||
if (!clearedAt) return range
|
||||
const since = range?.since && range.since > clearedAt ? range.since : clearedAt
|
||||
return { ...range, since }
|
||||
}, [range, clearedAt])
|
||||
|
||||
const clearView = () => { setClearedAt(new Date()); setViewEpoch(e => e + 1) }
|
||||
const showAll = () => { setClearedAt(null); setViewEpoch(e => e + 1) }
|
||||
|
||||
const panelKey = `${channel}-${viewEpoch}`
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
|
||||
{sn && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
|
||||
{clearedAt ? (
|
||||
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||
View cleared at <span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-secondary)' }}>{fmtTime24(clearedAt)}</span> — showing only newer entries.
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
|
||||
Clear the view to watch only fresh entries. Nothing is deleted.
|
||||
</span>
|
||||
)}
|
||||
<div style={{ flex: 1 }} />
|
||||
{clearedAt && (
|
||||
<Button variant="ghost" size="sm" onClick={showAll}>Show all</Button>
|
||||
)}
|
||||
<Button variant="secondary" size="sm" icon={<Icon name="refresh" size={13} />} onClick={clearView}>
|
||||
{clearedAt ? 'Clear again' : 'Clear view'}
|
||||
</Button>
|
||||
{canEdit && deviceId && (
|
||||
<Button variant="danger" size="sm" icon={<Icon name="delete" size={13} />} onClick={() => setShowDelete(true)}>
|
||||
Delete logs…
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<GlassCard style={{ overflow: 'hidden' }}>
|
||||
{!sn ? (
|
||||
<div style={{ padding: 'var(--space-8)', textAlign: 'center', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', fontStyle: 'italic' }}>
|
||||
No serial number available for this device.
|
||||
</div>
|
||||
) : channel === 'unified' ? (
|
||||
<UnifiedPanel sn={sn} channel={channel} onChannelChange={setChannel} range={range} />
|
||||
<UnifiedPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} range={effectiveRange} clearedAt={clearedAt} />
|
||||
) : channel === 'log' ? (
|
||||
<TextLogPanel sn={sn} source="log" liveTypes={['system/logs']} channel={channel} onChannelChange={setChannel} range={range} />
|
||||
<TextLogPanel key={panelKey} sn={sn} source="log" liveTypes={['system/logs']} channel={channel} onChannelChange={setChannel} range={effectiveRange} />
|
||||
) : channel === 'info' ? (
|
||||
<TextLogPanel sn={sn} source="info" liveTypes={['system/info']} channel={channel} onChannelChange={setChannel} range={range} />
|
||||
<TextLogPanel key={panelKey} sn={sn} source="info" liveTypes={['system/info']} channel={channel} onChannelChange={setChannel} range={effectiveRange} />
|
||||
) : channel === 'alerts' ? (
|
||||
<AlertsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
||||
<AlertsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||
) : channel === 'heartbeats' ? (
|
||||
<HeartbeatsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
||||
<HeartbeatsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||
) : (
|
||||
<CommandsPanel sn={sn} channel={channel} onChannelChange={setChannel} />
|
||||
<CommandsPanel key={panelKey} sn={sn} channel={channel} onChannelChange={setChannel} clearedAt={clearedAt} />
|
||||
)}
|
||||
</GlassCard>
|
||||
|
||||
{canEdit && deviceId && (
|
||||
<DeleteDeviceLogsModal
|
||||
open={showDelete}
|
||||
onClose={() => setShowDelete(false)}
|
||||
onDeleted={() => setViewEpoch(e => e + 1)}
|
||||
deviceId={deviceId}
|
||||
serial={sn}
|
||||
/>
|
||||
)}
|
||||
|
||||
<style>{`
|
||||
@keyframes logstab-pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
|
||||
Reference in New Issue
Block a user