From 3636556ae74f818911b555f8aa0c17bbc59171e0 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sun, 8 Nov 2026 21:34:38 +0200 Subject: [PATCH] feat(devices): clear log view and delete logs from the Health tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../devices/DeleteDeviceLogsModal.jsx | 175 ++++++++++++++++++ .../pages/bellcloud/devices/tabs/LogsTab.jsx | 109 ++++++++--- 2 files changed, 263 insertions(+), 21 deletions(-) create mode 100644 frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx diff --git a/frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx b/frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx new file mode 100644 index 0000000..b0a3534 --- /dev/null +++ b/frontend/src/modals/bellcloud/devices/DeleteDeviceLogsModal.jsx @@ -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 ( + + ) +} + +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 ( + +
+
+ + + Permanently deletes the selected history for {serial} from the console database. The device's own SD-card logs are not affected. This cannot be undone. + +
+ +
+ + Log types + +
+ {TYPES.map(t => ( + setTypes(prev => ({ ...prev, [t.key]: !prev[t.key] }))} + disabled={running} + /> + ))} +
+
+ + {textSources.length > 0 && ( +
+ + Levels (Device Logs & Info) + +
+ {LEVELS.map(l => ( + setLevels(prev => ({ ...prev, [l]: !prev[l] }))} + disabled={running} + /> + ))} +
+
+ )} + +
+ + + {running ? 'Deleting…' : 'Hold to Delete'} + +
+
+
+ ) +} diff --git a/frontend/src/pages/bellcloud/devices/tabs/LogsTab.jsx b/frontend/src/pages/bellcloud/devices/tabs/LogsTab.jsx index d530387..bf72abe 100644 --- a/frontend/src/pages/bellcloud/devices/tabs/LogsTab.jsx +++ b/frontend/src/pages/bellcloud/devices/tabs/LogsTab.jsx @@ -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 }) { - {total > PAGE_SIZE && ( + {total > PAGE_SIZE && !clearedAt && (
@@ -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 }) { - {total > PAGE_SIZE && ( + {total > PAGE_SIZE && !clearedAt && (
@@ -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 }) { - {total > PAGE_SIZE && ( + {total > PAGE_SIZE && !clearedAt && (
@@ -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 ( -
+
+ {sn && ( +
+ {clearedAt ? ( + + View cleared at {fmtTime24(clearedAt)} — showing only newer entries. + + ) : ( + + Clear the view to watch only fresh entries. Nothing is deleted. + + )} +
+ {clearedAt && ( + + )} + + {canEdit && deviceId && ( + + )} +
+ )} + {!sn ? (
No serial number available for this device.
) : channel === 'unified' ? ( - + ) : channel === 'log' ? ( - + ) : channel === 'info' ? ( - + ) : channel === 'alerts' ? ( - + ) : channel === 'heartbeats' ? ( - + ) : ( - + )}
+ {canEdit && deviceId && ( + setShowDelete(false)} + onDeleted={() => setViewEpoch(e => e + 1)} + deviceId={deviceId} + serial={sn} + /> + )} +