From fb8cdc0690cc1e7d1de01ff2fc9cd2576c24afa2 Mon Sep 17 00:00:00 2001 From: Tawhidul Islam <276017696+FhDBro@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:38:18 +0600 Subject: [PATCH 1/2] feat(web): add privacy-redacted diagnostic report to monitor tool Move the diagnostic report generation directly into the browser-based Web Monitor tool per maintainer blueprint. When running diagnostics, the monitor samples four key rates (csi_occupancy, csi_accepted_pps, csi_filtered_pps, and csi_hw_error_pps) over a configurable duration (default 30 seconds) and computes their min, median, and max values. The final report aggregates the rate statistics alongside device capabilities, health, sensing, Wi-Fi, and session SSE fault events, plus client browser context. Identifiers are redacted client-side before export: device names, labels, hostnames, .local domains, SSIDs, and unicast MAC/IPv4 addresses are masked, while credential objects are stripped. Multicast, broadcast, and loopback addresses remain intact for networking diagnosis. The panel provides an in-browser preview, a one-click copy button formatted as fenced JSON for GitHub issues, and a JSON download button. Signed-off-by: Tawhidul Islam <276017696+FhDBro@users.noreply.github.com> --- .github/cla-signatures.json | 4 + docs/TROUBLESHOOTING.md | 5 + docs/web/404.html | 2 +- docs/web/assets/css/styles.css | 99 ++++- docs/web/assets/js/direct-discovery.js | 5 +- docs/web/assets/js/monitor-tool.js | 416 ++++++++++++++++++- docs/web/content/guides/troubleshooting.html | 2 +- docs/web/content/tools/monitor.html | 28 ++ docs/web/index.html | 6 +- test/web/test_site_tools.mjs | 161 +++++++ 10 files changed, 720 insertions(+), 8 deletions(-) diff --git a/.github/cla-signatures.json b/.github/cla-signatures.json index 34fc09d0..aedcda66 100644 --- a/.github/cla-signatures.json +++ b/.github/cla-signatures.json @@ -32,6 +32,10 @@ { "login": "mgoodfellow", "signedAt": "2026-10-28" + }, + { + "login": "FhDBro", + "signedAt": "2026-11-01" } ] } diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 23617e48..9f1ab4f0 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -13,6 +13,7 @@ Most problems can be fixed from the browser: the [troubleshooting guide](https:/ - [Calibration stalls or startup quality is poor](#calibration-stalls-or-startup-quality-is-poor) - [Tuning essentials](#tuning-essentials) - [Device not reachable](#device-not-reachable) +- [Diagnostic report](#diagnostic-report) ## Check the sensing input @@ -132,3 +133,7 @@ From the browser, follow [device not reachable](https://espectre.dev/guides/trou You can connect with the device IP, its name, its 16-character ID, or the last 6 characters of the ID. Names and short IDs rely on mDNS. If discovery fails, run `./espectre devices`, enter the IP, or look it up in your router's DHCP list. See [browser bootstrap](DISCOVERY.md#browser-bootstrap) for how discovery works. Once connected, go back to [Check the sensing input](#check-the-sensing-input). + +## Diagnostic report + +When opening an issue or troubleshooting with maintainers, open [Live motion](https://espectre.dev/tools/monitor/), expand **Diagnostics**, and select **Diagnostic report**. The monitor samples key rates (occupancy, accepted, filtered, and hardware errors) for 30 seconds and bundles device capabilities, health, sensing, Wi-Fi, and session faults. Private network identifiers (passwords, credentials, SSIDs, device names, hostnames, and IP/MAC addresses) are automatically redacted in the browser before generating the report, making the fenced JSON safe to copy directly into GitHub issues. diff --git a/docs/web/404.html b/docs/web/404.html index a46c6f85..426e4d6f 100644 --- a/docs/web/404.html +++ b/docs/web/404.html @@ -10,7 +10,7 @@ Page not found | ESPectre - + diff --git a/docs/web/assets/css/styles.css b/docs/web/assets/css/styles.css index 315bb91c..0179327d 100644 --- a/docs/web/assets/css/styles.css +++ b/docs/web/assets/css/styles.css @@ -2206,6 +2206,99 @@ body.modal-open { overflow: hidden; } .device-live-diagnostics > summary small { margin-left: auto; color: var(--dim); font-size: 11.5px; } .device-live-diagnostics .diag-grid { padding: 0 18px 18px; } .device-live-diagnostics .tool-note { margin: 0; padding: 0 18px 18px; } +.diag-report-panel { + border-top: 1px solid var(--border); + padding: 16px 18px; + display: flex; + flex-direction: column; + gap: 12px; +} +.diag-report-card { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface2); +} +.diag-report-card strong { + display: block; + font-size: 12px; +} +.diag-report-card p { + margin: 2px 0 0; + color: var(--dim); + font-size: 11px; + line-height: 1.4; +} +.diag-report-progress { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface2); +} +.diag-report-progress-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.diag-report-track { + width: 100%; + height: 6px; + background: var(--surface-soft, rgba(0, 0, 0, 0.06)); + border-radius: 999px; + overflow: hidden; +} +.diag-report-bar { + height: 100%; + background: var(--accent); + transition: width 0.3s ease; +} +.diag-report-status { + font-size: 12px; + color: var(--text); +} +.diag-report-result { + display: flex; + flex-direction: column; + gap: 10px; +} +.diag-report-result-header { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 10px; +} +.diag-report-result-title { + font-size: 12px; + font-weight: 600; + color: var(--text); +} +.diag-report-actions { + display: flex; + align-items: center; + gap: 8px; +} +.diag-report-preview { + margin: 0; + padding: 12px; + max-height: 240px; + overflow: auto; + font-family: var(--font-mono, monospace); + font-size: 11px; + line-height: 1.45; + background: var(--surface-soft, rgba(0, 0, 0, 0.04)); + border: 1px solid var(--border); + border-radius: 8px; + white-space: pre; +} /* Theremin */ .theremin-stage { @@ -3928,6 +4021,9 @@ body.modal-open { overflow: hidden; } .live-controls-grid { grid-template-columns: minmax(0, 1fr); } .live-control-wide { grid-column: auto; } .live-calibration { align-items: stretch; flex-direction: column; } + .diag-report-card { align-items: stretch; flex-direction: column; } + .diag-report-result-header { align-items: stretch; flex-direction: column; } + .diag-report-actions { flex-direction: column; } .device-live-diagnostics > summary { align-items: flex-start; flex-direction: column; gap: 4px; position: relative; } .device-live-diagnostics > summary small { margin-left: 0; padding-right: 24px; } .device-live-diagnostics > summary::after { position: absolute; right: 18px; top: 18px; } @@ -3949,7 +4045,8 @@ body.modal-open { overflow: hidden; } .scrolly-caption, .scrolly-nav span, .scrolly-cue, - .scrolly-skip { transition: none; } + .scrolly-skip, + .diag-report-bar { transition: none; } .scene-ui-dot, .pulse, .spinner, diff --git a/docs/web/assets/js/direct-discovery.js b/docs/web/assets/js/direct-discovery.js index d7bf04eb..3f0817e9 100644 --- a/docs/web/assets/js/direct-discovery.js +++ b/docs/web/assets/js/direct-discovery.js @@ -199,7 +199,10 @@ return; } if (name === 'ota') applyOtaStatus(data); - if (name === 'fault') toast(data.message || 'The device reported a runtime fault.'); + if (name === 'fault') { + if (typeof recordMonitorFault === 'function') recordMonitorFault(data); + toast(data.message || 'The device reported a runtime fault.'); + } } const directResourceSessions = new WeakMap(); diff --git a/docs/web/assets/js/monitor-tool.js b/docs/web/assets/js/monitor-tool.js index 107dba32..4329ae69 100644 --- a/docs/web/assets/js/monitor-tool.js +++ b/docs/web/assets/js/monitor-tool.js @@ -51,7 +51,8 @@ calibrating: false, calibrationTimer: null, rawTargetSavePending: null, - rawTargetDiscovery: null + rawTargetDiscovery: null, + sessionFaults: [] }; function monitorStatus(message) { @@ -92,6 +93,7 @@ if (moveEl) moveEl.textContent = '—'; monitorStats({}); monitorDiagStatus(''); + resetMonitorReportView(); conn.movement = 0; conn.motion = false; renderTelemetry(); @@ -268,6 +270,7 @@ duration_seconds: Math.max(0, Math.round((Date.now() - monitor.connectedAt) / 1000)) }); } + resetMonitorReportView(); resetMonitorSession(); } @@ -630,6 +633,413 @@ ); } + /* ============================================== diagnostic report */ + + let monitorReportSampling = null; + let monitorReportJson = ''; + + function recordMonitorFault(data) { + if (!monitor.sessionFaults) monitor.sessionFaults = []; + monitor.sessionFaults.push({ + at: Date.now(), + timestamp: new Date().toISOString(), + fault: data && typeof data === 'object' ? { ...data } : data + }); + } + + function calculateRateStats(values) { + const numbers = (values || []) + .filter((v) => typeof v === 'number' && Number.isFinite(v)) + .sort((a, b) => a - b); + if (!numbers.length) return { min: null, median: null, max: null }; + const min = numbers[0]; + const max = numbers[numbers.length - 1]; + const mid = Math.floor(numbers.length / 2); + const median = numbers.length % 2 !== 0 ? numbers[mid] : (numbers[mid - 1] + numbers[mid]) / 2; + return { + min: Number(min.toFixed(4)), + median: Number(median.toFixed(4)), + max: Number(max.toFixed(4)) + }; + } + + function isMulticastOrBroadcastMac(mac) { + const clean = mac.toLowerCase(); + if (clean === 'ff:ff:ff:ff:ff:ff' || clean === 'ff-ff-ff-ff-ff-ff') return true; + if (clean.startsWith('01:00:5e') || clean.startsWith('01-00-5e') || clean.startsWith('33:33')) return true; + return false; + } + + function isMulticastOrLoopbackIp(ip) { + if (ip === '127.0.0.1' || ip === '::1' || ip === '0.0.0.0' || ip === '255.255.255.255') return true; + const first = parseInt(ip.split('.')[0], 10); + if (first >= 224 && first <= 239) return true; + return false; + } + + function redactMacAddress(value) { + return value.replace(/\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g, (match) => { + if (isMulticastOrBroadcastMac(match)) return match; + const sep = match.includes(':') ? ':' : '-'; + const parts = match.split(sep); + return `${parts[0]}${sep}${parts[1]}${sep}**${sep}**${sep}**${sep}**`; + }); + } + + function redactIpv4Address(value) { + return value.replace(/\b((?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\b/g, (match) => { + if (isMulticastOrLoopbackIp(match)) return match; + const parts = match.split('.'); + return `${parts[0]}.${parts[1]}.x.x`; + }); + } + + function redactDiagnosticReport(data) { + if (!data || typeof data !== 'object') return data; + + const sensitiveTerms = []; + const addTerm = (val, replacement) => { + if (typeof val === 'string' && val.trim().length >= 3) { + const escaped = val.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + sensitiveTerms.push({ pattern: new RegExp(escaped, 'gi'), replacement }); + } + }; + + if (data.wifi && typeof data.wifi === 'object') { + addTerm(data.wifi.ssid, ''); + addTerm(data.wifi.sta_ssid, ''); + addTerm(data.wifi.ap_ssid, ''); + } + if (data.device && typeof data.device === 'object') { + addTerm(data.device.name, ''); + addTerm(data.device.label, ''); + addTerm(data.device.hostname, ''); + } + + const sanitizeText = (str) => { + if (typeof str !== 'string') return str; + let out = str; + for (const { pattern, replacement } of sensitiveTerms) { + out = out.replace(pattern, replacement); + } + out = out.replace(/\b[a-zA-Z0-9][-a-zA-Z0-9]*\.local\b/gi, '.local'); + out = redactMacAddress(out); + out = redactIpv4Address(out); + return out; + }; + + const transform = (key, val) => { + const lowerKey = (key || '').toLowerCase(); + + if (lowerKey === 'credentials' || lowerKey.endsWith('_credentials')) { + return undefined; + } + + if (lowerKey.includes('password') || lowerKey.includes('passphrase') || lowerKey.includes('secret') || lowerKey.includes('token') || lowerKey.includes('api_key') || lowerKey.includes('private_key')) { + if (typeof val === 'boolean') return val; + if (val && typeof val === 'string') return '[REDACTED]'; + if (val && typeof val === 'object') return undefined; + return val; + } + + if (lowerKey === 'name' && typeof val === 'string') return ''; + if (lowerKey === 'label' && typeof val === 'string') return ''; + if (lowerKey === 'hostname' && typeof val === 'string') return ''; + if (lowerKey === 'ssid' && typeof val === 'string') return ''; + + if (lowerKey === 'device_id' && typeof val === 'string' && val.length >= 8) { + return `${val.slice(0, 4)}...${val.slice(-4)}`; + } + + if (typeof val === 'string') { + return sanitizeText(val); + } + + if (Array.isArray(val)) { + return val.map((item) => transform(key, item)).filter((item) => item !== undefined); + } + + if (val && typeof val === 'object') { + const result = {}; + for (const [k, v] of Object.entries(val)) { + const transformed = transform(k, v); + if (transformed !== undefined) result[k] = transformed; + } + return result; + } + + return val; + }; + + return transform('root', data); + } + + function monitorCancelDiagnosticReport({ silent = false } = {}) { + if (!monitorReportSampling) return; + monitorReportSampling.cancel(silent); + } + + function resetMonitorReportView() { + monitorCancelDiagnosticReport({ silent: true }); + monitorReportJson = ''; + const progressEl = $('.js-mon-report-progress'); + const resultEl = $('.js-mon-report-result'); + const previewEl = $('.js-mon-report-preview'); + const startBtn = $('.js-mon-report-start'); + if (progressEl) progressEl.hidden = true; + if (resultEl) resultEl.hidden = true; + if (previewEl) previewEl.textContent = ''; + if (startBtn) startBtn.disabled = false; + } + + function monitorStartDiagnosticReport({ + sampleDurationSec = 30, + sampleIntervalMs = 1000 + } = {}) { + if (monitorReportSampling) return Promise.resolve(null); + const mode = conn.mode; + const direct = mode === 'direct'; + if (!direct && mode !== 'demo') { + toast('Connect to a device before generating a diagnostic report.'); + return Promise.resolve(null); + } + if (direct && !directClient?.connected) { + toast('Direct HTTP connection is not ready. Connect and try again.'); + return Promise.resolve(null); + } + + const startBtn = $('.js-mon-report-start'); + if (startBtn) startBtn.disabled = true; + + const progressEl = $('.js-mon-report-progress'); + const trackEl = $('.js-mon-report-track'); + const barEl = $('.js-mon-report-bar'); + const statusEl = $('.js-mon-report-status'); + const resultEl = $('.js-mon-report-result'); + const previewEl = $('.js-mon-report-preview'); + const copyBtn = $('.js-mon-report-copy'); + + if (progressEl) progressEl.hidden = false; + if (resultEl) resultEl.hidden = true; + if (barEl) barEl.style.width = '0%'; + if (trackEl) trackEl.setAttribute('aria-valuenow', '0'); + if (statusEl) statusEl.textContent = `Sampling diagnostics (0/${sampleDurationSec}s)…`; + + const samples = { + csi_occupancy: [], + csi_accepted_pps: [], + csi_filtered_pps: [], + csi_hw_error_pps: [] + }; + + let elapsedSec = 0; + const controller = new AbortController(); + + return new Promise((resolve) => { + const samplingState = { + controller, + timer: null, + cancel(silent = false) { + if (samplingState.timer) clearInterval(samplingState.timer); + controller.abort(); + monitorReportSampling = null; + if (progressEl) progressEl.hidden = true; + if (startBtn) { + startBtn.disabled = false; + if (typeof startBtn.focus === 'function') startBtn.focus(); + } + if (!silent) toast('Diagnostic report cancelled.'); + resolve(null); + } + }; + monitorReportSampling = samplingState; + + const pollSample = async () => { + if (monitorReportSampling !== samplingState) return; + if (direct && !directClient?.connected) { + samplingState.cancel({ silent: true }); + toast('Device disconnected while sampling diagnostics.'); + return; + } + if (direct && directClient?.connected) { + try { + const res = await directClient.request('get', 'diagnostics', { + fields: ['csi_occupancy', 'csi_accepted_pps', 'csi_filtered_pps', 'csi_hw_error_pps'] + }, { timeoutMs: Math.min(2000, sampleIntervalMs), signal: controller.signal }); + if (res && typeof res === 'object') { + if (typeof res.csi_occupancy === 'number') samples.csi_occupancy.push(res.csi_occupancy); + if (typeof res.csi_accepted_pps === 'number') samples.csi_accepted_pps.push(res.csi_accepted_pps); + if (typeof res.csi_filtered_pps === 'number') samples.csi_filtered_pps.push(res.csi_filtered_pps); + if (typeof res.csi_hw_error_pps === 'number') samples.csi_hw_error_pps.push(res.csi_hw_error_pps); + } + } catch { + // Stale or dropped polling interval sample is ignored + } + } else if (mode === 'demo') { + const targetPps = csiTargetPps(); + samples.csi_accepted_pps.push(Math.max(1, targetPps - 10)); + samples.csi_occupancy.push(Math.max(1, targetPps - 16) / targetPps); + samples.csi_filtered_pps.push(0); + samples.csi_hw_error_pps.push(0); + } + const pct = Math.min(100, Math.round((elapsedSec / sampleDurationSec) * 100)); + if (barEl) barEl.style.width = `${pct}%`; + if (trackEl) trackEl.setAttribute('aria-valuenow', String(pct)); + if (statusEl) statusEl.textContent = `Sampling diagnostics (${Math.min(elapsedSec, sampleDurationSec)}/${sampleDurationSec}s)…`; + + if (elapsedSec >= sampleDurationSec) { + if (samplingState.timer) clearInterval(samplingState.timer); + samplingState.timer = null; + await finishReport(); + return; + } + elapsedSec += Math.round(sampleIntervalMs / 1000) || 1; + }; + + const finishReport = async () => { + if (monitorReportSampling !== samplingState) return; + if (statusEl) statusEl.textContent = 'Reading device resources…'; + + let capabilities = {}; + let device = {}; + let health = {}; + let sensing = {}; + let wifi = {}; + + if (direct && directClient?.connected) { + const readResource = async (name) => { + try { + return await directClient.request('get', name, {}, { + timeoutMs: 5000, + signal: controller.signal + }); + } catch (err) { + return { error: err.message || String(err) }; + } + }; + [capabilities, device, health, sensing, wifi] = await Promise.all([ + readResource('capabilities'), + readResource('device'), + readResource('health'), + readResource('sensing'), + readResource('wifi') + ]); + } else if (mode === 'demo') { + capabilities = { protocol_version: '1.0', resources: ['device', 'health', 'sensing', 'wifi', 'diagnostics'] }; + device = { + name: 'Demo sensor', + device_id: conn.deviceId || '2222222222222222', + chip: 'esp32s3', + firmware_version: '1.0.0' + }; + health = { status: 'healthy', uptime: 3600, free_memory_kb: 161.4 }; + sensing = { detector: 'lightweight', csi_target_pps: csiTargetPps(), motion_on_hits: 3, motion_off_hits: 5 }; + wifi = { ssid: 'DemoNetwork', sta_ip: '192.168.1.50', sta_mac: '30:ae:a4:07:0a:24', wifi_channel: 6, password_configured: true }; + } + + const rawReport = { + timestamp: new Date().toISOString(), + client: { + site: typeof window !== 'undefined' && window.location ? window.location.origin : '', + user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : '' + }, + sampling: { + duration_seconds: sampleDurationSec, + samples_collected: Math.max( + samples.csi_occupancy.length, + samples.csi_accepted_pps.length, + samples.csi_filtered_pps.length, + samples.csi_hw_error_pps.length + ), + rates: { + csi_occupancy: calculateRateStats(samples.csi_occupancy), + csi_accepted_pps: calculateRateStats(samples.csi_accepted_pps), + csi_filtered_pps: calculateRateStats(samples.csi_filtered_pps), + csi_hw_error_pps: calculateRateStats(samples.csi_hw_error_pps) + } + }, + fault_events: monitor.sessionFaults ? monitor.sessionFaults.slice() : [], + capabilities, + device, + health, + sensing, + wifi + }; + + const sanitized = redactDiagnosticReport(rawReport); + monitorReportJson = JSON.stringify(sanitized, null, 2); + + if (previewEl) previewEl.textContent = monitorReportJson; + if (progressEl) progressEl.hidden = true; + if (resultEl) resultEl.hidden = false; + if (startBtn) startBtn.disabled = false; + if (copyBtn && typeof copyBtn.focus === 'function') copyBtn.focus(); + monitorReportSampling = null; + toast('Diagnostic report ready.'); + resolve(sanitized); + }; + + pollSample(); + samplingState.timer = setInterval(pollSample, sampleIntervalMs); + }); + } + + async function monitorCopyDiagnosticReport() { + if (!monitorReportJson) { + toast('No diagnostic report available to copy.'); + return; + } + const fenced = '```json\n' + monitorReportJson + '\n```'; + const copyBtn = $('.js-mon-report-copy'); + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(fenced); + } else if (typeof document !== 'undefined') { + const ta = document.createElement('textarea'); + ta.value = fenced; + ta.style.position = 'fixed'; + ta.style.opacity = '0'; + document.body.appendChild(ta); + ta.select(); + document.execCommand('copy'); + document.body.removeChild(ta); + } + if (copyBtn) { + const prevText = copyBtn.textContent; + copyBtn.textContent = 'Copied!'; + setTimeout(() => { + if (copyBtn.textContent === 'Copied!') copyBtn.textContent = prevText; + }, 2000); + } + toast('Fenced JSON copied to clipboard.'); + } catch (err) { + console.warn('Clipboard write failed:', err); + toast('Failed to copy to clipboard.'); + } + } + + function monitorDownloadDiagnosticReport() { + if (!monitorReportJson) { + toast('No diagnostic report available to download.'); + return; + } + try { + const blob = new Blob([monitorReportJson], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = `espectre-diagnostic-report-${Date.now()}.json`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + setTimeout(() => URL.revokeObjectURL(url), 0); + toast('Diagnostic report downloaded.'); + } catch (err) { + console.warn('Download failed:', err); + toast('Failed to download report.'); + } + } + function monitorInit() { const diagnostics = $('.device-live-diagnostics'); if (diagnostics) { @@ -692,5 +1102,9 @@ document.getElementById('sense-raw-target').addEventListener('change', monitorChangeRawTarget); document.getElementById('sense-raw-target-manual').addEventListener('change', monitorChangeRawTarget); document.getElementById('sense-raw-target-refresh').addEventListener('click', monitorRefreshRawTrafficTargets); + $('.js-mon-report-start')?.addEventListener('click', () => monitorStartDiagnosticReport()); + $('.js-mon-report-cancel')?.addEventListener('click', () => monitorCancelDiagnosticReport()); + $('.js-mon-report-copy')?.addEventListener('click', () => monitorCopyDiagnosticReport()); + $('.js-mon-report-download')?.addEventListener('click', () => monitorDownloadDiagnosticReport()); window.addEventListener('resize', monitorResizeChart); } diff --git a/docs/web/content/guides/troubleshooting.html b/docs/web/content/guides/troubleshooting.html index 1dff7d67..0957d0ad 100644 --- a/docs/web/content/guides/troubleshooting.html +++ b/docs/web/content/guides/troubleshooting.html @@ -92,6 +92,6 @@

Problems covered in other guides

Still stuck?

-

Open an issue on GitHub with your board, firmware, and version, and a screenshot of Diagnostics or a few lines of the device log. The troubleshooting reference explains the log line, the configuration options, and external traffic.

+

Open an issue on GitHub with your board, firmware, and version. You can use Diagnostic report in Live motion to sample key rates and bundle a privacy-redacted diagnostic JSON ready to paste into your issue. The troubleshooting reference explains the log line, the configuration options, and external traffic.

diff --git a/docs/web/content/tools/monitor.html b/docs/web/content/tools/monitor.html index a577c1f6..9b0e6a90 100644 --- a/docs/web/content/tools/monitor.html +++ b/docs/web/content/tools/monitor.html @@ -122,6 +122,34 @@

Motion settings

Loop time
—
+
+
+
+ Diagnostic report +

Sample key rates for 30 s and bundle sanitized device state for bug reports.

+
+ +
+ + +
diff --git a/docs/web/index.html b/docs/web/index.html index 75c4bebc..473925ba 100644 --- a/docs/web/index.html +++ b/docs/web/index.html @@ -24,7 +24,7 @@ - + @@ -34,9 +34,9 @@ - + - + diff --git a/test/web/test_site_tools.mjs b/test/web/test_site_tools.mjs index c5004fa3..843286e2 100644 --- a/test/web/test_site_tools.mjs +++ b/test/web/test_site_tools.mjs @@ -873,6 +873,167 @@ describe('device HTTP request budgets', () => { }); }); +describe('Web Monitor diagnostic report', () => { + it('calculates min, median, and max for sampled rate values', () => { + const runtime = loadDeviceHttpRuntime(); + const calc = runtime.context.calculateRateStats; + assert.deepEqual({ ...calc([10, 20, 30, 40, 50]) }, { min: 10, median: 30, max: 50 }); + assert.deepEqual({ ...calc([10, 20, 30, 40]) }, { min: 10, median: 25, max: 40 }); + assert.deepEqual({ ...calc([5]) }, { min: 5, median: 5, max: 5 }); + assert.deepEqual({ ...calc([]) }, { min: null, median: null, max: null }); + assert.deepEqual({ ...calc([null, undefined, NaN]) }, { min: null, median: null, max: null }); + }); + + it('redacts sensitive identifiers while preserving multicast, loopback, and broadcast', () => { + const runtime = loadDeviceHttpRuntime(); + const redact = runtime.context.redactDiagnosticReport; + const payload = { + device: { + name: 'Living Room ESP32', + label: 'Living Room', + hostname: 'espectre-livingroom', + device_id: '30aea4070a240001', + }, + wifi: { + ssid: 'Home_IoT_5G', + passphrase: 'SuperPassphrase', + private_key: 'MyPrivateKey', + sta_ip: '192.168.1.105', + sta_mac: '30:ae:a4:07:0a:24', + gateway_ip: '192.168.1.1', + bssid: 'aa:bb:cc:dd:ee:ff', + credentials: { username: 'admin', password: 'SecretPassword' }, + password: 'SecretPassword', + password_configured: true, + multicast_ip: '239.255.255.250', + multicast_mac: '01:00:5e:00:00:01', + broadcast_ip: '255.255.255.255', + broadcast_mac: 'ff:ff:ff:ff:ff:ff', + loopback_ip: '127.0.0.1', + apply_message: 'Device Living Room ESP32 connected to Home_IoT_5G at 192.168.1.105 via espectre-livingroom.local' + } + }; + + const result = redact(payload); + assert.equal(result.device.name, ''); + assert.equal(result.device.label, ''); + assert.equal(result.device.hostname, ''); + assert.equal(result.device.device_id, '30ae...0001'); + + assert.equal(result.wifi.ssid, ''); + assert.equal(result.wifi.passphrase, '[REDACTED]'); + assert.equal(result.wifi.private_key, '[REDACTED]'); + assert.equal(result.wifi.credentials, undefined); + assert.equal(result.wifi.password, '[REDACTED]'); + assert.equal(result.wifi.password_configured, true); + assert.equal(result.wifi.sta_ip, '192.168.x.x'); + assert.equal(result.wifi.sta_mac, '30:ae:**:**:**:**'); + assert.equal(result.wifi.gateway_ip, '192.168.x.x'); + assert.equal(result.wifi.bssid, 'aa:bb:**:**:**:**'); + + assert.equal(result.wifi.broadcast_ip, '255.255.255.255'); + assert.equal(result.wifi.broadcast_mac, 'ff:ff:ff:ff:ff:ff'); + assert.equal(result.wifi.multicast_ip, '239.255.255.250'); + assert.equal(result.wifi.multicast_mac, '01:00:5e:00:00:01'); + assert.equal(result.wifi.loopback_ip, '127.0.0.1'); + + assert.equal( + result.wifi.apply_message, + 'Device connected to at 192.168.x.x via .local' + ); + }); + + it('samples diagnostics rates, gathers resources, and exposes copy/download actions', async () => { + const runtime = loadDeviceHttpRuntime(); + const elements = new Map(); + const element = (selector) => { + if (!elements.has(selector)) { + elements.set(selector, { + textContent: '', + style: {}, + hidden: false, + disabled: false, + attributes: new Map(), + setAttribute(name, val) { this.attributes.set(name, String(val)); }, + getAttribute(name) { return this.attributes.get(name); }, + focus() { this.focused = true; } + }); + } + return elements.get(selector); + }; + const prev$ = runtime.context.$; + runtime.context.$ = (selector) => { + if (selector.startsWith('.js-mon-diag-report') || selector.startsWith('.js-mon-report')) { + return element(selector); + } + return prev$(selector); + }; + + const diagnosticsData = { + csi_occupancy: 0.85, + csi_accepted_pps: 98.5, + csi_filtered_pps: 1.2, + csi_hw_error_pps: 0.0 + }; + + const requests = []; + runtime.setClient({ + connected: true, + request: async (method, resource, params) => { + requests.push([method, resource, params]); + if (resource === 'diagnostics') return diagnosticsData; + if (resource === 'device') return { name: 'Sensor 1', device_id: '1122334455667788' }; + if (resource === 'wifi') return { ssid: 'LabWiFi', sta_ip: '10.0.0.45', sta_mac: '12:34:56:78:9a:bc' }; + return {}; + } + }); + + runtime.run("route = 'tool-monitor'"); + runtime.context.recordMonitorFault({ message: 'Synthetic fault', code: 42 }); + + const reportPromise = runtime.context.monitorStartDiagnosticReport({ + sampleDurationSec: 1, + sampleIntervalMs: 1000 + }); + + assert.equal(element('.js-mon-report-start').disabled, true); + assert.equal(element('.js-mon-report-progress').hidden, false); + + await runtime.nextTimer(); + const report = await reportPromise; + + assert.equal(element('.js-mon-report-progress').hidden, true); + assert.equal(element('.js-mon-report-result').hidden, false); + assert.equal(element('.js-mon-report-start').disabled, false); + assert.equal(element('.js-mon-report-track').getAttribute('aria-valuenow'), '100'); + assert.equal(element('.js-mon-report-copy').focused, true); + + const json = element('.js-mon-report-preview').textContent; + assert.ok(json.length > 0); + + assert.equal(report.sampling.duration_seconds, 1); + assert.equal(report.sampling.rates.csi_accepted_pps.min, 98.5); + assert.equal(report.sampling.rates.csi_accepted_pps.max, 98.5); + assert.equal(report.device.name, ''); + assert.equal(report.wifi.ssid, ''); + assert.equal(report.wifi.sta_ip, '10.0.x.x'); + assert.equal(report.fault_events.length, 1); + assert.equal(report.fault_events[0].fault.message, 'Synthetic fault'); + + const pendingPromise = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 5, sampleIntervalMs: 1000 }); + assert.equal(element('.js-mon-report-progress').hidden, false); + runtime.context.monitorCancelDiagnosticReport(); + assert.equal(element('.js-mon-report-progress').hidden, true); + assert.equal(element('.js-mon-report-start').disabled, false); + const cancelled = await pendingPromise; + assert.equal(cancelled, null); + + runtime.context.resetMonitorReportView(); + assert.equal(element('.js-mon-report-result').hidden, true); + assert.equal(element('.js-mon-report-preview').textContent, ''); + }); +}); + let ImprovSerial; let ESPLoader; let Transport; From a8ac26b7174102d83530cfb19046944e249da534 Mon Sep 17 00:00:00 2001 From: Francesco Pace Date: Fri, 27 Nov 2026 18:13:20 +0100 Subject: [PATCH 2/2] feat(web): complete diagnostic reporting over direct http Collect and redact device state, session faults, and sampled CSI rates using the existing API. Include client versions and fix Micro CORS headers for browser reports. Signed-off-by: Francesco Pace --- .github/ISSUE_TEMPLATE/bug_report.yml | 6 + .github/actions/build-pages/action.yml | 2 +- .github/scripts/build_static_pages.py | 13 + docs/CHANGELOG.md | 5 + docs/TROUBLESHOOTING.md | 4 +- docs/web/assets/js/browser-support.js | 12 +- docs/web/assets/js/direct-discovery.js | 14 +- docs/web/assets/js/monitor-tool.js | 354 +++++++++++------- docs/web/content/tools/monitor.html | 2 +- docs/web/index.html | 6 +- .../native_components/native_direct.c | 29 +- test/python/micro/test_micro_protocol.py | 2 +- test/web/test_site_tools.mjs | 136 ++++++- 13 files changed, 409 insertions(+), 176 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9ca2b913..a9ac8454 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -168,6 +168,12 @@ body: # or relevant YAML / sdkconfig lines / collector command + - type: textarea + id: diagnostic_report + attributes: + label: Diagnostic report (optional) + description: In the Web Monitor, connect to the device and select Generate report. Review the preview, then paste the fenced JSON or attach the downloaded file. + - type: textarea id: logs attributes: diff --git a/.github/actions/build-pages/action.yml b/.github/actions/build-pages/action.yml index 1f7c6f5c..1a8673fc 100644 --- a/.github/actions/build-pages/action.yml +++ b/.github/actions/build-pages/action.yml @@ -43,7 +43,7 @@ runs: - name: Build static pages shell: bash - run: python3 .github/scripts/build_static_pages.py + run: python3 .github/scripts/build_static_pages.py --site-revision "$(git rev-parse HEAD)" - uses: ./.github/actions/setup-doxygen diff --git a/.github/scripts/build_static_pages.py b/.github/scripts/build_static_pages.py index a3d7fdef..36e24dcc 100644 --- a/.github/scripts/build_static_pages.py +++ b/.github/scripts/build_static_pages.py @@ -18,6 +18,8 @@ from __future__ import annotations +import argparse +import re import sys from html import escape from html.parser import HTMLParser @@ -315,4 +317,15 @@ def build() -> None: if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--site-revision", help="Git commit to identify a deployed application shell") + args = parser.parse_args() + if args.site_revision and not re.fullmatch(r"[a-f0-9]{40}", args.site_revision): + parser.error("site revision must be a full Git commit hash") build() + if args.site_revision: + # Interactive routes load the root application shell. + shell = WEB_ROOT / "index.html" + marker = f'' + content = re.sub(r'\n', "", shell.read_text()) + shell.write_text(content.replace("", "\n" + marker, 1)) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 19b46458..deb805a0 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to this project will be documented in this file. +## [3.3.0] - Work in progress + +- The Web Monitor can copy or download a local diagnostic report with 30-second CSI and Wi-Fi statistics, recent motion and faults, redacted device state, and browser and site versions. +- **Micro** sends a single valid CORS origin on Direct responses so the Web Monitor can open the event stream and collect a diagnostic report. + --- ## [3.2.2] - 2026-11-25 - Raw Wi-Fi targets and Direct Wi-Fi recovery diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 9f1ab4f0..f808ec0f 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -136,4 +136,6 @@ Once connected, go back to [Check the sensing input](#check-the-sensing-input). ## Diagnostic report -When opening an issue or troubleshooting with maintainers, open [Live motion](https://espectre.dev/tools/monitor/), expand **Diagnostics**, and select **Diagnostic report**. The monitor samples key rates (occupancy, accepted, filtered, and hardware errors) for 30 seconds and bundles device capabilities, health, sensing, Wi-Fi, and session faults. Private network identifiers (passwords, credentials, SSIDs, device names, hostnames, and IP/MAC addresses) are automatically redacted in the browser before generating the report, making the fenced JSON safe to copy directly into GitHub issues. +In [Live motion](https://espectre.dev/tools/monitor/), expand **Diagnostics** and select **Generate report**. The monitor samples CSI occupancy, packet rates, and Wi-Fi signal for 30 seconds. It includes the latest motion observed on this connection and its fault events. The report uses the diagnostic fields advertised by the connected firmware. If no samples arrive, the report still includes device state and marks sampling as `no_samples`. A measured rate of zero is a valid sample. + +The browser masks device and network identifiers before displaying the preview. Review it, then select **Copy fenced JSON** to paste it into an issue, or **Download JSON** to save a file. diff --git a/docs/web/assets/js/browser-support.js b/docs/web/assets/js/browser-support.js index fb6ef64e..3cc6733e 100644 --- a/docs/web/assets/js/browser-support.js +++ b/docs/web/assets/js/browser-support.js @@ -23,11 +23,12 @@ : /Firefox\//i.test(userAgent) ? 'firefox' : /(?:Chrome|CriOS)\//i.test(userAgent) ? 'chrome' : /Safari\//i.test(userAgent) ? 'safari' : 'other'; - const versionMatch = userAgent.match(browser === 'edge' ? /Edg\/(\d+)/i - : browser === 'firefox' ? /Firefox\/(\d+)/i - : browser === 'chrome' ? /(?:Chrome|CriOS)\/(\d+)/i - : browser === 'safari' ? /Version\/(\d+)/i : null); - const browserMajor = versionMatch ? Number(versionMatch[1]) : 0; + const versionMatch = userAgent.match(browser === 'edge' ? /Edg\/(\d+(?:\.\d+)*)/i + : browser === 'firefox' ? /Firefox\/(\d+(?:\.\d+)*)/i + : browser === 'chrome' ? /(?:Chrome|CriOS)\/(\d+(?:\.\d+)*)/i + : browser === 'safari' ? /Version\/(\d+(?:\.\d+)*)/i : null); + const browserVersion = versionMatch?.[1] || null; + const browserMajor = parseInt(browserVersion, 10) || 0; const operatingSystem = ios ? 'ios' : android ? 'android' : /mac/i.test(platform) ? 'macos' @@ -45,6 +46,7 @@ serial, browser, browserMajor, + browserVersion, operatingSystem, hostedDirect, // ESPectre supports browser flashing only on desktop Chrome or Edge. diff --git a/docs/web/assets/js/direct-discovery.js b/docs/web/assets/js/direct-discovery.js index 3f0817e9..bfe801d7 100644 --- a/docs/web/assets/js/direct-discovery.js +++ b/docs/web/assets/js/direct-discovery.js @@ -175,6 +175,13 @@ function ingestDirectEvent(name, data) { if (name === 'motion') { + if (directClient?.connected && Number.isFinite(data.score)) { + directResourceSession(directClient).motion = { + score: data.score, + state: data.state, + timestamp_ms: data.timestamp_ms ?? null + }; + } applySensingCadence(data); applyLiveTelemetry( Number(data.score ?? 0), @@ -200,7 +207,10 @@ } if (name === 'ota') applyOtaStatus(data); if (name === 'fault') { - if (typeof recordMonitorFault === 'function') recordMonitorFault(data); + if (directClient?.connected) { + const at = Date.now(); + directResourceSession(directClient).faults.push({ at, timestamp: new Date(at).toISOString(), fault: data }); + } toast(data.message || 'The device reported a runtime fault.'); } } @@ -209,7 +219,7 @@ function directResourceSession(client) { if (!directResourceSessions.has(client)) { - directResourceSessions.set(client, { snapshots: new Map(), pending: new Map() }); + directResourceSessions.set(client, { snapshots: new Map(), pending: new Map(), faults: [] }); } return directResourceSessions.get(client); } diff --git a/docs/web/assets/js/monitor-tool.js b/docs/web/assets/js/monitor-tool.js index 4329ae69..b35cc019 100644 --- a/docs/web/assets/js/monitor-tool.js +++ b/docs/web/assets/js/monitor-tool.js @@ -51,8 +51,7 @@ calibrating: false, calibrationTimer: null, rawTargetSavePending: null, - rawTargetDiscovery: null, - sessionFaults: [] + rawTargetDiscovery: null }; function monitorStatus(message) { @@ -83,6 +82,11 @@ } function resetMonitorLiveView() { + const session = directResourceSessions.get(directClient); + if (session) { + session.faults.length = 0; + session.motion = null; + } monitorResetChart(); const stateEl = $('.js-mon-state'); if (stateEl) { @@ -270,7 +274,6 @@ duration_seconds: Math.max(0, Math.round((Date.now() - monitor.connectedAt) / 1000)) }); } - resetMonitorReportView(); resetMonitorSession(); } @@ -638,15 +641,6 @@ let monitorReportSampling = null; let monitorReportJson = ''; - function recordMonitorFault(data) { - if (!monitor.sessionFaults) monitor.sessionFaults = []; - monitor.sessionFaults.push({ - at: Date.now(), - timestamp: new Date().toISOString(), - fault: data && typeof data === 'object' ? { ...data } : data - }); - } - function calculateRateStats(values) { const numbers = (values || []) .filter((v) => typeof v === 'number' && Number.isFinite(v)) @@ -664,105 +658,128 @@ } function isMulticastOrBroadcastMac(mac) { - const clean = mac.toLowerCase(); - if (clean === 'ff:ff:ff:ff:ff:ff' || clean === 'ff-ff-ff-ff-ff-ff') return true; - if (clean.startsWith('01:00:5e') || clean.startsWith('01-00-5e') || clean.startsWith('33:33')) return true; - return false; + return (parseInt(mac.slice(0, 2), 16) & 1) === 1; } function isMulticastOrLoopbackIp(ip) { - if (ip === '127.0.0.1' || ip === '::1' || ip === '0.0.0.0' || ip === '255.255.255.255') return true; + if (ip.startsWith('127.') || ip === '::1' || ip === '0.0.0.0' || ip === '255.255.255.255') return true; const first = parseInt(ip.split('.')[0], 10); if (first >= 224 && first <= 239) return true; return false; } - function redactMacAddress(value) { - return value.replace(/\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b/g, (match) => { - if (isMulticastOrBroadcastMac(match)) return match; - const sep = match.includes(':') ? ':' : '-'; - const parts = match.split(sep); - return `${parts[0]}${sep}${parts[1]}${sep}**${sep}**${sep}**${sep}**`; - }); - } - - function redactIpv4Address(value) { - return value.replace(/\b((?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){3}(?:1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)\b/g, (match) => { - if (isMulticastOrLoopbackIp(match)) return match; - const parts = match.split('.'); - return `${parts[0]}.${parts[1]}.x.x`; - }); - } - function redactDiagnosticReport(data) { if (!data || typeof data !== 'object') return data; - const sensitiveTerms = []; - const addTerm = (val, replacement) => { - if (typeof val === 'string' && val.trim().length >= 3) { - const escaped = val.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - sensitiveTerms.push({ pattern: new RegExp(escaped, 'gi'), replacement }); - } - }; - - if (data.wifi && typeof data.wifi === 'object') { - addTerm(data.wifi.ssid, ''); - addTerm(data.wifi.sta_ssid, ''); - addTerm(data.wifi.ap_ssid, ''); - } - if (data.device && typeof data.device === 'object') { - addTerm(data.device.name, ''); - addTerm(data.device.label, ''); - addTerm(data.device.hostname, ''); + const terms = new Map(); + for (const [value, replacement] of [ + [data.wifi?.ssid, ''], + [data.wifi?.sta_ssid, ''], + [data.wifi?.ap_ssid, ''], + [data.device?.name, ''], + [data.device?.label, ''], + [data.device?.hostname, ''], + [data.device?.device_id, ''] + ]) { + if (typeof value !== 'string' || !value.length) continue; + const term = value.toLowerCase(); + if (!terms.has(term)) terms.set(term, replacement); } - const sanitizeText = (str) => { - if (typeof str !== 'string') return str; - let out = str; - for (const { pattern, replacement } of sensitiveTerms) { - out = out.replace(pattern, replacement); + const secretKey = /password|passphrase|secret|token|api_key|private_key|credentials/i; + function collectSecrets(obj, withinSecret = false) { + for (const [key, val] of Object.entries(obj)) { + const secret = withinSecret || secretKey.test(key); + if (secret && typeof val === 'string' && val) terms.set(val.toLowerCase(), '[REDACTED]'); + if (val && typeof val === 'object') collectSecrets(val, secret); + } + } + collectSecrets(data); + + // Match once, longest identity first, so short names cannot alter a longer match or a placeholder. + const identities = [...terms.keys()].sort((a, b) => b.length - a.length) + .map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); + const identityAvailable = Boolean(data.device?.name && (data.wifi?.ssid || data.wifi?.sta_ssid)); + const patterns = [ + /(?(?\b(?:[\da-f]{2}[:-]){5}[\da-f]{2}\b)/.source, + /(?\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b)/.source, + /(?\b(?:[a-z\d][-a-z\d]*\.)+local\b)/.source + ]; + const addresses = new RegExp('^(?:' + patterns.join('|') + ')$', 'i'); + const sensitive = new RegExp([...patterns, ...identities].join('|'), 'gi'); + const replacement = (match, ipv6, mac, ip, hostname) => { + if (ipv6) { + // A colon-separated MAC or timestamp can also match the IPv6 candidate. + if (/^(?:[\da-f]{2}:){5}[\da-f]{2}$/i.test(ipv6)) mac = ipv6; + else { + const address = ipv6.split('%')[0]; + try { + const host = new URL('http://[' + address + ']/').hostname; + return host === '[::1]' || host === '[::]' || host.startsWith('[ff') + ? address : ''; + } catch { + if (address.includes('::') || address.split(':').length >= 8) return ''; + return terms.get(match.toLowerCase()) ?? match; + } + } + } + if (mac) { + if (isMulticastOrBroadcastMac(mac)) return mac; + return mac.slice(0, 5) + (mac[2] + '**').repeat(4); } - out = out.replace(/\b[a-zA-Z0-9][-a-zA-Z0-9]*\.local\b/gi, '.local'); - out = redactMacAddress(out); - out = redactIpv4Address(out); - return out; + if (ip) return isMulticastOrLoopbackIp(ip) ? ip : ip.split('.').slice(0, 2).join('.') + '.x.x'; + if (hostname) return '.local'; + return terms.get(match.toLowerCase()); }; - const transform = (key, val) => { - const lowerKey = (key || '').toLowerCase(); + // These fields contain protocol tokens or report metadata even if a user picks the same name. + const structuredStrings = new Set([ + 'capabilities.resources', 'capabilities.events', 'capabilities.protocol_version', + 'capabilities.operations.name', 'capabilities.operations.method', 'capabilities.operations.path', + 'capabilities.operations.fields', 'sampling.status', 'timestamp', 'fault_events.timestamp', + 'device.firmware_version', 'diagnostics.esp_idf_version', 'diagnostics.firmware_build_date', + 'diagnostics.recent_logs.level', 'last_motion.state', + 'device.chip', 'device.frontend', 'device.firmware', 'device.csi_profile', 'health.status', + 'wifi.band', 'wifi.apply_state', 'sensing.mode', 'sensing.detector', 'sensing.traffic_generator_mode', + 'sensing.csi_sample_spacing' + ]); + + const transform = (key, val, path) => { + const lowerKey = key.toLowerCase(); if (lowerKey === 'credentials' || lowerKey.endsWith('_credentials')) { return undefined; } - if (lowerKey.includes('password') || lowerKey.includes('passphrase') || lowerKey.includes('secret') || lowerKey.includes('token') || lowerKey.includes('api_key') || lowerKey.includes('private_key')) { + if (secretKey.test(lowerKey)) { if (typeof val === 'boolean') return val; - if (val && typeof val === 'string') return '[REDACTED]'; - if (val && typeof val === 'object') return undefined; - return val; + return val == null ? val : '[REDACTED]'; } - if (lowerKey === 'name' && typeof val === 'string') return ''; - if (lowerKey === 'label' && typeof val === 'string') return ''; + if (path === 'device.name' && typeof val === 'string') return ''; + if (path === 'device.label' && typeof val === 'string') return ''; if (lowerKey === 'hostname' && typeof val === 'string') return ''; - if (lowerKey === 'ssid' && typeof val === 'string') return ''; + if (['ssid', 'sta_ssid', 'ap_ssid'].includes(lowerKey) && typeof val === 'string') return ''; - if (lowerKey === 'device_id' && typeof val === 'string' && val.length >= 8) { - return `${val.slice(0, 4)}...${val.slice(-4)}`; + if (lowerKey === 'device_id' && typeof val === 'string') { + return val.length > 8 ? `${val.slice(0, 4)}...${val.slice(-4)}` : ''; } if (typeof val === 'string') { - return sanitizeText(val); + if (structuredStrings.has(path)) return val; + if (!identityAvailable && !addresses.test(val)) return '[REDACTED]'; + return val.replace(sensitive, replacement); } if (Array.isArray(val)) { - return val.map((item) => transform(key, item)).filter((item) => item !== undefined); + return val.map((item) => transform(key, item, path)).filter((item) => item !== undefined); } if (val && typeof val === 'object') { const result = {}; for (const [k, v] of Object.entries(val)) { - const transformed = transform(k, v); + const transformed = transform(k, v, path ? path + '.' + k : k); if (transformed !== undefined) result[k] = transformed; } return result; @@ -771,7 +788,7 @@ return val; }; - return transform('root', data); + return transform('', data, ''); } function monitorCancelDiagnosticReport({ silent = false } = {}) { @@ -799,15 +816,18 @@ if (monitorReportSampling) return Promise.resolve(null); const mode = conn.mode; const direct = mode === 'direct'; + const client = directClient; if (!direct && mode !== 'demo') { toast('Connect to a device before generating a diagnostic report.'); return Promise.resolve(null); } - if (direct && !directClient?.connected) { + if (direct && !client?.connected) { toast('Direct HTTP connection is not ready. Connect and try again.'); return Promise.resolve(null); } + const session = direct ? directResourceSession(client) : null; + monitorReportJson = ''; const startBtn = $('.js-mon-report-start'); if (startBtn) startBtn.disabled = true; @@ -829,18 +849,22 @@ csi_occupancy: [], csi_accepted_pps: [], csi_filtered_pps: [], - csi_hw_error_pps: [] + csi_hw_error_pps: [], + csi_callback_pps: [], + generator_pps: [], + wifi_rssi_dbm: [] }; - let elapsedSec = 0; + let startedAt = Date.now(); + const durationMs = sampleDurationSec * 1000; + let samplesCollected = 0; const controller = new AbortController(); return new Promise((resolve) => { const samplingState = { - controller, timer: null, cancel(silent = false) { - if (samplingState.timer) clearInterval(samplingState.timer); + if (samplingState.timer) clearTimeout(samplingState.timer); controller.abort(); monitorReportSampling = null; if (progressEl) progressEl.hidden = true; @@ -854,46 +878,79 @@ }; monitorReportSampling = samplingState; + const isCurrent = () => { + if (monitorReportSampling !== samplingState) return false; + if (conn.mode === mode && (!direct || (client.connected && directClient === client + && directResourceSessions.get(client) === session))) return true; + samplingState.cancel(true); + toast('Device disconnected while sampling diagnostics.'); + return false; + }; + + let available; + let sampleFields = Object.keys(samples); + const readResource = async (name, params = {}) => { + try { + return await client.request('get', name, params, { + timeoutMs: 5000, + signal: controller.signal + }); + } catch { + return { error: 'unavailable' }; + } + }; + const pollSample = async () => { - if (monitorReportSampling !== samplingState) return; - if (direct && !directClient?.connected) { - samplingState.cancel({ silent: true }); - toast('Device disconnected while sampling diagnostics.'); - return; + if (!isCurrent()) return; + if (direct && !available) { + const catalog = await readResource('diagnostics'); + if (!isCurrent()) return; + available = new Set(Array.isArray(catalog?.fields) ? catalog.fields.map(f => f.name) : []); + sampleFields = available.size ? sampleFields.filter(field => available.has(field)) + : ['csi_occupancy', 'csi_accepted_pps', 'csi_filtered_pps', 'csi_hw_error_pps']; + startedAt = Date.now(); } - if (direct && directClient?.connected) { + const pollStartedAt = Date.now(); + let values; + if (direct) { try { - const res = await directClient.request('get', 'diagnostics', { - fields: ['csi_occupancy', 'csi_accepted_pps', 'csi_filtered_pps', 'csi_hw_error_pps'] - }, { timeoutMs: Math.min(2000, sampleIntervalMs), signal: controller.signal }); - if (res && typeof res === 'object') { - if (typeof res.csi_occupancy === 'number') samples.csi_occupancy.push(res.csi_occupancy); - if (typeof res.csi_accepted_pps === 'number') samples.csi_accepted_pps.push(res.csi_accepted_pps); - if (typeof res.csi_filtered_pps === 'number') samples.csi_filtered_pps.push(res.csi_filtered_pps); - if (typeof res.csi_hw_error_pps === 'number') samples.csi_hw_error_pps.push(res.csi_hw_error_pps); - } + if (sampleFields.length) values = await client.request('get', 'diagnostics', { fields: sampleFields }, { + timeoutMs: Math.min(2000, sampleIntervalMs), signal: controller.signal + }); } catch { - // Stale or dropped polling interval sample is ignored + // Keep sampling after a missed read. } - } else if (mode === 'demo') { + if (!isCurrent()) return; + } else { const targetPps = csiTargetPps(); - samples.csi_accepted_pps.push(Math.max(1, targetPps - 10)); - samples.csi_occupancy.push(Math.max(1, targetPps - 16) / targetPps); - samples.csi_filtered_pps.push(0); - samples.csi_hw_error_pps.push(0); + values = { + csi_accepted_pps: Math.max(1, targetPps - 10), + csi_occupancy: Math.max(1, targetPps - 16) / targetPps, + csi_filtered_pps: 0, + csi_hw_error_pps: 0 + }; } - const pct = Math.min(100, Math.round((elapsedSec / sampleDurationSec) * 100)); + let collected = false; + for (const [field, readings] of Object.entries(samples)) { + if (Number.isFinite(values?.[field])) { + readings.push(values[field]); + if (field.startsWith('csi_')) collected = true; + } + } + if (collected) samplesCollected++; + const elapsedMs = Date.now() - startedAt; + const pct = Math.min(100, Math.round(100 * elapsedMs / durationMs)); if (barEl) barEl.style.width = `${pct}%`; if (trackEl) trackEl.setAttribute('aria-valuenow', String(pct)); - if (statusEl) statusEl.textContent = `Sampling diagnostics (${Math.min(elapsedSec, sampleDurationSec)}/${sampleDurationSec}s)…`; + if (statusEl) statusEl.textContent = `Sampling diagnostics (${Math.min(Math.floor(elapsedMs / 1000), sampleDurationSec)}/${sampleDurationSec}s)…`; - if (elapsedSec >= sampleDurationSec) { - if (samplingState.timer) clearInterval(samplingState.timer); - samplingState.timer = null; + const remainingMs = durationMs - elapsedMs; + if (remainingMs <= 0) { await finishReport(); - return; + } else { + const untilNextPoll = Math.max(0, sampleIntervalMs - (Date.now() - pollStartedAt)); + samplingState.timer = setTimeout(pollSample, Math.min(untilNextPoll, remainingMs)); } - elapsedSec += Math.round(sampleIntervalMs / 1000) || 1; }; const finishReport = async () => { @@ -905,18 +962,14 @@ let health = {}; let sensing = {}; let wifi = {}; - - if (direct && directClient?.connected) { - const readResource = async (name) => { - try { - return await directClient.request('get', name, {}, { - timeoutMs: 5000, - signal: controller.signal - }); - } catch (err) { - return { error: err.message || String(err) }; - } - }; + const diagnostics = {}; + const reportFields = [ + 'wifi_channel', 'free_memory_kb', 'minimum_free_memory_kb', 'loop_time_ms', + 'csi_callbacks_total', 'csi_accepted_total', 'csi_filtered_total', 'csi_hw_error_total', + 'csi_admitted_pps', 'csi_missing_slots_pps', 'csi_excess_pps', 'csi_stale_pps' + ]; + + if (direct) { [capabilities, device, health, sensing, wifi] = await Promise.all([ readResource('capabilities'), readResource('device'), @@ -924,6 +977,14 @@ readResource('sensing'), readResource('wifi') ]); + if (!isCurrent()) return; + const selected = reportFields.filter(field => available.has(field)); + for (let i = 0; i < selected.length; i += 4) { + const fields = selected.slice(i, i + 4); + const values = await readResource('diagnostics', { fields }); + if (!isCurrent()) return; + for (const field of fields) diagnostics[field] = values?.[field] ?? null; + } } else if (mode === 'demo') { capabilities = { protocol_version: '1.0', resources: ['device', 'health', 'sensing', 'wifi', 'diagnostics'] }; device = { @@ -939,26 +1000,18 @@ const rawReport = { timestamp: new Date().toISOString(), - client: { - site: typeof window !== 'undefined' && window.location ? window.location.origin : '', - user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : '' - }, sampling: { duration_seconds: sampleDurationSec, - samples_collected: Math.max( - samples.csi_occupancy.length, - samples.csi_accepted_pps.length, - samples.csi_filtered_pps.length, - samples.csi_hw_error_pps.length - ), - rates: { - csi_occupancy: calculateRateStats(samples.csi_occupancy), - csi_accepted_pps: calculateRateStats(samples.csi_accepted_pps), - csi_filtered_pps: calculateRateStats(samples.csi_filtered_pps), - csi_hw_error_pps: calculateRateStats(samples.csi_hw_error_pps) - } + status: samplesCollected ? 'complete' : 'no_samples', + samples_collected: samplesCollected, + rates: Object.fromEntries(Object.entries(samples) + .filter(([name]) => name !== 'wifi_rssi_dbm') + .map(([name, readings]) => [name, calculateRateStats(readings)])), + wifi_rssi_dbm: calculateRateStats(samples.wifi_rssi_dbm) }, - fault_events: monitor.sessionFaults ? monitor.sessionFaults.slice() : [], + diagnostics, + last_motion: session?.motion ?? null, + fault_events: session ? session.faults.slice() : [], capabilities, device, health, @@ -966,7 +1019,22 @@ wifi }; - const sanitized = redactDiagnosticReport(rawReport); + const browser = window.ESPectreBrowserSupport?.current; + const revision = document.querySelector?.('meta[name="espectre-site-revision"]')?.content; + const asset = document.querySelector?.('script[src*="/assets/js/monitor-tool.js"]')?.src; + const sanitized = { + privacy: 'Generated locally. Network and device identifiers are masked. Review before sharing.', + source: mode, + client: { + site: ['espectre.dev', 'test.espectre.dev'].includes(window.location?.hostname) + ? window.location.hostname : 'local_or_custom', + site_revision: /^[a-f0-9]{40}$/i.test(revision) ? revision : null, + monitor_revision: asset?.match(/[?&]v=([a-f0-9]{12})(?:&|$)/i)?.[1] ?? null, + browser: browser?.browser ?? null, + browser_version: browser?.browserVersion ?? null + }, + ...redactDiagnosticReport(rawReport) + }; monitorReportJson = JSON.stringify(sanitized, null, 2); if (previewEl) previewEl.textContent = monitorReportJson; @@ -975,12 +1043,11 @@ if (startBtn) startBtn.disabled = false; if (copyBtn && typeof copyBtn.focus === 'function') copyBtn.focus(); monitorReportSampling = null; - toast('Diagnostic report ready.'); + toast(samplesCollected ? 'Diagnostic report ready.' : 'No diagnostic samples received. The report contains device state only.'); resolve(sanitized); }; pollSample(); - samplingState.timer = setInterval(pollSample, sampleIntervalMs); }); } @@ -1001,8 +1068,11 @@ ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); - document.execCommand('copy'); - document.body.removeChild(ta); + try { + if (!document.execCommand('copy')) throw new Error('Copy was declined'); + } finally { + document.body.removeChild(ta); + } } if (copyBtn) { const prevText = copyBtn.textContent; diff --git a/docs/web/content/tools/monitor.html b/docs/web/content/tools/monitor.html index 9b0e6a90..a9f1b31f 100644 --- a/docs/web/content/tools/monitor.html +++ b/docs/web/content/tools/monitor.html @@ -126,7 +126,7 @@

Motion settings

Diagnostic report -

Sample key rates for 30 s and bundle sanitized device state for bug reports.

+

Sample CSI rates and Wi-Fi signal for 30 s. Preview the device state and faults observed during this connection before sharing.

diff --git a/docs/web/index.html b/docs/web/index.html index 473925ba..67d7aaae 100644 --- a/docs/web/index.html +++ b/docs/web/index.html @@ -28,15 +28,15 @@ - + - + - + diff --git a/src/python/micro_espectre/firmware/native_components/native_direct.c b/src/python/micro_espectre/firmware/native_components/native_direct.c index 6782a3c3..606fac7b 100644 --- a/src/python/micro_espectre/firmware/native_components/native_direct.c +++ b/src/python/micro_espectre/firmware/native_components/native_direct.c @@ -376,16 +376,13 @@ static bool direct_read_origin(httpd_req_t *request, char *origin, size_t capaci return direct_origin_allowed(origin); } -static bool direct_set_cors(httpd_req_t *request) { - char origin[96]; - if (!direct_read_origin(request, origin, sizeof(origin))) { +static bool direct_set_cors(httpd_req_t *request, char *origin, size_t capacity) { + if (!direct_read_origin(request, origin, capacity)) { return false; } - if (origin[0] != '\0') { - (void) httpd_resp_set_hdr(request, "Access-Control-Allow-Origin", origin); - } - (void) httpd_resp_set_hdr(request, "Vary", "Origin"); - return true; + // HTTPD retains header pointers until the first send in the calling handler. + return httpd_resp_set_hdr(request, "Access-Control-Allow-Origin", origin) == ESP_OK && + httpd_resp_set_hdr(request, "Vary", "Origin") == ESP_OK; } static char *direct_replace_string(char **target, const char *source, size_t length) { @@ -517,10 +514,6 @@ static esp_err_t direct_send_result( if (prefix_length < 0 || (size_t) prefix_length >= sizeof(prefix)) { return ESP_FAIL; } - if (!direct_set_cors(request)) { - httpd_resp_set_status(request, "403 Forbidden"); - return httpd_resp_sendstr(request, "Forbidden"); - } httpd_resp_set_status(request, http_status); httpd_resp_set_type(request, "application/json"); (void) httpd_resp_set_hdr(request, "Cache-Control", "no-store"); @@ -863,7 +856,8 @@ static bool direct_validate_request(httpd_req_t *request, const direct_route_t * } static esp_err_t direct_request_handler(httpd_req_t *request) { - if (!direct_set_cors(request)) { + char origin[96]; + if (!direct_set_cors(request, origin, sizeof(origin))) { httpd_resp_set_status(request, "403 Forbidden"); return httpd_resp_sendstr(request, "Forbidden"); } @@ -925,7 +919,8 @@ static esp_err_t direct_request_handler(httpd_req_t *request) { } static esp_err_t direct_options_handler(httpd_req_t *request) { - if (!direct_set_cors(request)) { + char origin[96]; + if (!direct_set_cors(request, origin, sizeof(origin))) { httpd_resp_set_status(request, "403 Forbidden"); return httpd_resp_sendstr(request, "Forbidden"); } @@ -1023,7 +1018,8 @@ static bool direct_start_heartbeat(void) { } static esp_err_t direct_events_handler(httpd_req_t *request) { - if (!direct_set_cors(request)) { + char origin[96]; + if (!direct_set_cors(request, origin, sizeof(origin))) { httpd_resp_set_status(request, "403 Forbidden"); return httpd_resp_sendstr(request, "Forbidden"); } @@ -1052,8 +1048,7 @@ static esp_err_t direct_events_handler(httpd_req_t *request) { httpd_resp_set_type(async_request, "text/event-stream"); (void) httpd_resp_set_hdr(async_request, "Cache-Control", "no-store"); (void) httpd_resp_set_hdr(async_request, "Connection", "keep-alive"); - if (!direct_set_cors(async_request) || - httpd_resp_send_chunk(async_request, ": connected\n\n", strlen(": connected\n\n")) != ESP_OK) { + if (httpd_resp_send_chunk(async_request, ": connected\n\n", strlen(": connected\n\n")) != ESP_OK) { direct_increment(&direct_state.send_failures); httpd_req_async_handler_complete(async_request); return ESP_FAIL; diff --git a/test/python/micro/test_micro_protocol.py b/test/python/micro/test_micro_protocol.py index 6c61c75a..15eb63a9 100644 --- a/test/python/micro/test_micro_protocol.py +++ b/test/python/micro/test_micro_protocol.py @@ -623,7 +623,7 @@ def test_native_direct_validates_requests_before_dispatch(tmp_path): } #define cJSON_ArrayForEach(entry,array) for (entry=(array) ? (array)->child : NULL; entry; entry=entry->next) #endif -static bool direct_set_cors(httpd_req_t *r) { return true; } +static bool direct_set_cors(httpd_req_t *r, char *origin, size_t capacity) { return true; } static bool direct_request_allowed(void) { return true; } static void direct_increment(unsigned *p) { ++*p; } static void httpd_resp_set_status(httpd_req_t *r, const char *s) { response_status=s; } diff --git a/test/web/test_site_tools.mjs b/test/web/test_site_tools.mjs index 843286e2..5a54a1eb 100644 --- a/test/web/test_site_tools.mjs +++ b/test/web/test_site_tools.mjs @@ -943,6 +943,104 @@ describe('Web Monitor diagnostic report', () => { ); }); + it('masks IPv6 identifiers and suppresses text when an identity read fails', () => { + const { context } = loadDeviceHttpRuntime(); + const report = context.redactDiagnosticReport({ + device: { name: 'Office' }, wifi: { ssid: 'Guest' }, + diagnostics: { recent_logs: [{ message: 'Peers [fe80::1234%en0], ::ffff:10.20.30.40 and ff02::1 via ::1. Peer 2001:db8::2.' }] } + }); + assert.equal(report.diagnostics.recent_logs[0].message, + 'Peers [], and ff02::1 via ::1. Peer .'); + for (const resource of [{ device: {}, wifi: { ssid: 'Guest' } }, { device: { name: 'Office' }, wifi: {} }]) { + const partial = context.redactDiagnosticReport({ + ...resource, fault_events: [{ fault: { message: 'Office failed to join Guest at 10.20.30.40' } }] + }); + assert.equal(partial.fault_events[0].fault.message, '[REDACTED]'); + } + }); + + it('redacts short and overlapping identities in messages while retaining protocol identifiers', () => { + const { context } = loadDeviceHttpRuntime(); + const capabilities = { + resources: ['sensing'], events: ['fault'], + operations: [{ name: 'update_sensing', method: 'PATCH', path: 'sensing', fields: ['threshold'] }] + }; + const report = context.redactDiagnosticReport({ + device: { name: 'TV', label: 'T' }, + wifi: { ssid: 'TV.[1]', apply_message: 'TV / t / tv.[1]' }, + fault_events: [{ fault: { message: 't / TV' } }], + capabilities + }); + assert.equal(report.wifi.apply_message, ' / / '); + assert.equal(report.fault_events[0].fault.message, ' / '); + assert.deepEqual(JSON.parse(JSON.stringify(report.capabilities)), capabilities); + + const collision = context.redactDiagnosticReport({ + device: { name: 'update_sensing' }, wifi: { ssid: 'AB', apply_message: 'Connected to AB' }, capabilities + }); + assert.equal(collision.capabilities.operations[0].name, 'update_sensing'); + assert.equal(collision.wifi.apply_message, 'Connected to '); + }); + + it('exports faults only from the current Direct session', async () => { + const runtime = loadDeviceHttpRuntime(); + runtime.context.$ = () => null; + const client = () => ({ connected: true, request: async (_method, resource) => { + if (resource === 'device') return { name: 'Example' }; + if (resource === 'wifi') return { ssid: 'Guest' }; + return { csi_accepted_pps: 0 }; + } }); + runtime.setClient(client()); + runtime.context.ingestDirectEvent('fault', { code: 'old_device' }); + runtime.setClient(client()); + runtime.context.ingestDirectEvent('fault', { code: 'current_device' }); + const result = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 1 }); + await runtime.nextTimer(); + const report = await result; + assert.deepEqual(Array.from(report.fault_events, event => event.fault.code), ['current_device']); + assert.equal(report.sampling.status, 'complete'); + assert.equal(report.sampling.rates.csi_accepted_pps.median, 0); + }); + + it('keeps a cancelled resource read from publishing over a new report', async () => { + const runtime = loadDeviceHttpRuntime(); + const result = { hidden: true }; + runtime.context.$ = selector => selector === '.js-mon-report-result' ? result : null; + let finishRead; + runtime.setClient({ connected: true, request: async (_method, resource) => { + if (resource === 'device') return new Promise(resolve => { finishRead = resolve; }); + return { csi_accepted_pps: 1 }; + } }); + const first = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 1 }); + await runtime.nextTimer(); + runtime.context.monitorCancelDiagnosticReport(); + assert.equal(await first, null); + const second = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 3 }); + finishRead({ name: 'old device' }); + await runtime.nextTimer(); + assert.equal(result.hidden, true); + runtime.context.monitorCancelDiagnosticReport(); + assert.equal(await second, null); + }); + + it('flags a report with device state but no usable diagnostic samples', async () => { + const runtime = loadDeviceHttpRuntime(); + runtime.context.$ = () => null; + let polls = 0; + runtime.setClient({ connected: true, request: async (_method, resource) => { + if (resource === 'device') return { frontend: 'native' }; + if (resource === 'diagnostics' && ++polls === 1) throw new Error('timeout'); + return { csi_accepted_pps: null }; + } }); + const pending = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 1 }); + await runtime.nextTimer(); + const report = await pending; + assert.equal(report.device.frontend, 'native'); + assert.equal(report.sampling.samples_collected, 0); + assert.equal(report.sampling.status, 'no_samples'); + assert.equal(report.sampling.rates.csi_accepted_pps.median, null); + }); + it('samples diagnostics rates, gathers resources, and exposes copy/download actions', async () => { const runtime = loadDeviceHttpRuntime(); const elements = new Map(); @@ -973,7 +1071,10 @@ describe('Web Monitor diagnostic report', () => { csi_occupancy: 0.85, csi_accepted_pps: 98.5, csi_filtered_pps: 1.2, - csi_hw_error_pps: 0.0 + csi_hw_error_pps: 0.0, + wifi_rssi_dbm: -68, + csi_missing_slots_pps: 0, + wifi_channel: 6 }; const requests = []; @@ -981,7 +1082,11 @@ describe('Web Monitor diagnostic report', () => { connected: true, request: async (method, resource, params) => { requests.push([method, resource, params]); - if (resource === 'diagnostics') return diagnosticsData; + if (resource === 'diagnostics') { + if (!params.fields) return { fields: Object.keys(diagnosticsData).map(name => ({ name })) }; + assert.ok(params.fields.every(field => Object.hasOwn(diagnosticsData, field))); + return Object.fromEntries(params.fields.map(name => [name, diagnosticsData[name]])); + } if (resource === 'device') return { name: 'Sensor 1', device_id: '1122334455667788' }; if (resource === 'wifi') return { ssid: 'LabWiFi', sta_ip: '10.0.0.45', sta_mac: '12:34:56:78:9a:bc' }; return {}; @@ -989,8 +1094,10 @@ describe('Web Monitor diagnostic report', () => { }); runtime.run("route = 'tool-monitor'"); - runtime.context.recordMonitorFault({ message: 'Synthetic fault', code: 42 }); + runtime.context.ingestDirectEvent('fault', { message: 'Synthetic fault', code: 42 }); + runtime.context.window.navigator = { userAgent: 'Chrome/151.0.0.0' }; + runSiteScript('docs/web/assets/js/browser-support.js', runtime.context); const reportPromise = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 1, sampleIntervalMs: 1000 @@ -1011,6 +1118,10 @@ describe('Web Monitor diagnostic report', () => { const json = element('.js-mon-report-preview').textContent; assert.ok(json.length > 0); + assert.equal(report.client.browser_version, '151.0.0.0'); + assert.equal(report.diagnostics.csi_missing_slots_pps, 0); + assert.equal(report.diagnostics.wifi_channel, 6); + assert.equal(report.sampling.wifi_rssi_dbm.min, -68); assert.equal(report.sampling.duration_seconds, 1); assert.equal(report.sampling.rates.csi_accepted_pps.min, 98.5); assert.equal(report.sampling.rates.csi_accepted_pps.max, 98.5); @@ -1020,6 +1131,25 @@ describe('Web Monitor diagnostic report', () => { assert.equal(report.fault_events.length, 1); assert.equal(report.fault_events[0].fault.message, 'Synthetic fault'); + let copied; + runtime.context.navigator = { clipboard: { writeText: async value => { copied = value; } } }; + await runtime.context.monitorCopyDiagnosticReport(); + assert.equal(copied, '```json\n' + json + '\n```'); + + let downloaded; + const link = { click() { this.clicked = true; } }; + runtime.context.Blob = Blob; + runtime.context.URL = class extends URL { + static createObjectURL(blob) { downloaded = blob; return 'blob:report'; } + static revokeObjectURL() {} + }; + runtime.context.document.createElement = () => link; + runtime.context.document.body = { appendChild() {}, removeChild() {} }; + runtime.context.monitorDownloadDiagnosticReport(); + assert.equal(link.clicked, true); + assert.equal(await downloaded.text(), json); + assert.equal(downloaded.type, 'application/json'); + const pendingPromise = runtime.context.monitorStartDiagnosticReport({ sampleDurationSec: 5, sampleIntervalMs: 1000 }); assert.equal(element('.js-mon-report-progress').hidden, false); runtime.context.monitorCancelDiagnosticReport();