// trace.js — Phase 2 Full-Detail Frontend Trace Recorder & Offline IndexedDB Spool // Loaded FIRST before all other scripts. Enabled by default; dynamically synced with backend config. (() => { const nativeFetch = window.fetch ? window.fetch.bind(window) : null; const nativeSendBeacon = navigator.sendBeacon ? navigator.sendBeacon.bind(navigator) : null; const nativeConsoleError = console.error ? console.error.bind(console) : () => {}; const nativeConsoleWarn = console.warn ? console.warn.bind(console) : () => {}; const SESSION_ID = `fe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; const FLUSH_INTERVAL_MS = 2000; const FLUSH_MAX_EVENTS = 50; const FLUSH_MAX_BYTES = 65536; const DB_NAME = 'xjkj_stl_trace_spool'; const DB_STORE = 'batches'; let config = { enabled: true, backend_state_diff: true, backend_rpc_http: true, backend_serial_stream: true, backend_hardware_io: true, frontend_trace: true, compress_rotated: true, volume_mb: 50, retention_days: 30, min_free_gb: 2, }; let diskLowPaused = false; let seq = 0; let buffer = []; let bufferBytes = 0; let flushTimer = null; let flushing = false; let idbPromise = null; let spooledCount = 0; let recentRing = []; const RECENT_RING_MAX = 500; const SECRET_KEY_RE = /^(password|passwd|secret|token|api_token|authorization|cookie|current_password|new_password|bmc_password)$/i; const SECRET_ELEM_RE = /(password|passwd|secret|token|pw-)/i; function isActive() { return !!config.enabled && !!config.frontend_trace && !diskLowPaused; } function sanitize(value, depth = 0) { if (depth > 5) return '[DEPTH_LIMIT]'; if (value === null || value === undefined) return value; if (typeof value === 'string') { return value.length > 512 ? value.slice(0, 512) + `...[+${value.length - 512}B]` : value; } if (typeof value === 'number' || typeof value === 'boolean') return value; if (Array.isArray(value)) { if (value.length > 32) { return { _type: 'array', length: value.length, sample: value.slice(0, 6).map(v => sanitize(v, depth + 1)) }; } return value.map(v => sanitize(v, depth + 1)); } if (typeof value === 'object') { const out = {}; const entries = Object.entries(value); for (let i = 0; i < Math.min(entries.length, 40); i++) { const [k, v] = entries[i]; out[k] = SECRET_KEY_RE.test(k) ? '[REDACTED]' : sanitize(v, depth + 1); } if (entries.length > 40) out._truncated_keys = entries.length - 40; return out; } return String(value); } function elementDescriptor(el) { if (!el || el.nodeType !== 1) return ''; const tag = (el.tagName || '').toLowerCase(); const id = el.id ? `#${el.id}` : ''; const name = el.getAttribute?.('name') ? `[name=${el.getAttribute('name')}]` : ''; const dataPage = el.dataset?.page ? `[data-page=${el.dataset.page}]` : ''; const dataAct = el.dataset?.prodAction ? `[data-prod-action=${el.dataset.prodAction}]` : ''; return `${tag}${id}${name}${dataPage}${dataAct}`; } function safeElementValue(el) { if (!el) return undefined; const type = (el.type || '').toLowerCase(); if (type === 'password' || SECRET_ELEM_RE.test(el.id || '') || SECRET_ELEM_RE.test(el.name || '')) { return '[REDACTED]'; } if (type === 'checkbox' || type === 'radio') return !!el.checked; if (typeof el.value === 'string') { return el.value.length > 200 ? el.value.slice(0, 200) + '...' : el.value; } return undefined; } // ---- Dynamic IndexedDB Offline Spool (zero hardcoded 20MB cap) ---- function openIdb() { if (idbPromise) return idbPromise; if (!window.indexedDB) return Promise.resolve(null); idbPromise = new Promise(resolve => { try { const req = indexedDB.open(DB_NAME, 1); req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(DB_STORE)) { db.createObjectStore(DB_STORE, { keyPath: 'id', autoIncrement: true }); } }; req.onsuccess = () => resolve(req.result); req.onerror = () => resolve(null); } catch (_) { resolve(null); } }); return idbPromise; } async function spoolBatchToIdb(events) { if (!events.length) return; const db = await openIdb(); if (!db) return; try { // Dynamic browser origin quota check (retain up to 25% of available browser storage) let maxBytes = 64 * 1024 * 1024; if (navigator.storage?.estimate) { const est = await navigator.storage.estimate(); if (est && typeof est.quota === 'number' && typeof est.usage === 'number') { const avail = Math.max(0, est.quota - est.usage); maxBytes = Math.max(4 * 1024 * 1024, Math.floor(avail * 0.25)); } } const payloadStr = JSON.stringify(events); if (payloadStr.length > maxBytes) return; await new Promise(resolve => { const tx = db.transaction(DB_STORE, 'readwrite'); tx.objectStore(DB_STORE).add({ ts_ms: Date.now(), bytes: payloadStr.length, events }); tx.oncomplete = () => { spooledCount += 1; resolve(); }; tx.onerror = () => resolve(); }); } catch (_) {} } async function syncSpooledCount() { const db = await openIdb(); if (!db) return; try { spooledCount = await new Promise(resolve => { const tx = db.transaction(DB_STORE, 'readonly'); const req = tx.objectStore(DB_STORE).count(); req.onsuccess = () => resolve(Number(req.result || 0)); req.onerror = () => resolve(0); }); } catch (_) {} } async function drainIdbSpool() { if (!isActive() || !nativeFetch) return; const db = await openIdb(); if (!db) return; try { while (true) { const records = await new Promise(resolve => { const tx = db.transaction(DB_STORE, 'readonly'); const req = tx.objectStore(DB_STORE).getAll(null, 10); req.onsuccess = () => resolve(req.result || []); req.onerror = () => resolve([]); }); if (!records.length) { spooledCount = 0; return; } let stopped = false; for (const rec of records) { const res = await nativeFetch('/api/trace/frontend', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ events: rec.events }), }); if (!res.ok) { stopped = true; break; } await new Promise(resolve => { const tx = db.transaction(DB_STORE, 'readwrite'); tx.objectStore(DB_STORE).delete(rec.id); tx.oncomplete = () => resolve(); tx.onerror = () => resolve(); }); spooledCount = Math.max(0, spooledCount - 1); } if (stopped || records.length < 10) break; } } catch (_) {} } async function exportOfflineJsonl() { const all = []; const seen = new Set(); const pushUnique = ev => { if (!ev || typeof ev !== 'object') return; const key = `${ev.session_id || ''}:${ev.seq || ''}:${ev.ts_ms || ''}`; if (seen.has(key)) return; seen.add(key); all.push(ev); }; const db = await openIdb(); if (db) { const records = await new Promise(resolve => { try { const tx = db.transaction(DB_STORE, 'readonly'); const req = tx.objectStore(DB_STORE).getAll(); req.onsuccess = () => resolve(req.result || []); req.onerror = () => resolve([]); } catch (_) { resolve([]); } }); for (const rec of records) { if (Array.isArray(rec.events)) rec.events.forEach(pushUnique); } } recentRing.forEach(pushUnique); const text = all.map(e => JSON.stringify(e)).join('\n') + '\n'; const url = URL.createObjectURL(new Blob([text], { type: 'application/x-ndjson' })); const a = document.createElement('a'); a.href = url; a.download = `stl_frontend_offline_${SESSION_ID}.jsonl`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 10000); } // ---- Event Recorder & Batch Uploader ---- function record(kind, payload = {}) { if (!isActive()) return; const ev = { kind, session_id: SESSION_ID, seq: ++seq, ts_ms: Date.now(), mono_ms: Math.round((performance.now?.() || 0) * 100) / 100, page: document.body?.dataset?.currentPage || '', ui_mode: document.body?.dataset?.uiMode || '', ...sanitize(payload), }; recentRing.push(ev); if (recentRing.length > RECENT_RING_MAX) recentRing.shift(); let approxLen = 128; try { approxLen = JSON.stringify(ev).length; } catch (_) {} buffer.push(ev); bufferBytes += approxLen; if (buffer.length >= FLUSH_MAX_EVENTS || bufferBytes >= FLUSH_MAX_BYTES) { void flush(false); } else if (!flushTimer) { flushTimer = setTimeout(() => { flushTimer = null; void flush(false); }, FLUSH_INTERVAL_MS); } } async function flush(useBeacon = false) { if (!buffer.length) return; if (flushTimer) { clearTimeout(flushTimer); flushTimer = null; } const batch = buffer; buffer = []; bufferBytes = 0; if (!isActive()) return; const body = JSON.stringify({ events: batch }); if (useBeacon && nativeSendBeacon) { try { const blob = new Blob([body], { type: 'application/json' }); if (nativeSendBeacon('/api/trace/frontend', blob)) return; } catch (_) {} } if (!nativeFetch) return; if (flushing) { await spoolBatchToIdb(batch); return; } flushing = true; try { const res = await nativeFetch('/api/trace/frontend', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body, }); if (!res.ok) { if (res.status !== 401 && res.status !== 403) { await spoolBatchToIdb(batch); } } else { const data = await res.json().catch(() => null); if (data && typeof data.enabled === 'boolean') config.enabled = data.enabled; if (data && typeof data.disk_low_paused === 'boolean') setDiskLowBanner(data.disk_low_paused); if (spooledCount > 0) void drainIdbSpool(); } } catch (_) { await spoolBatchToIdb(batch); } finally { flushing = false; } } // ---- 1. Wrap window.fetch with strict anti-recursion ---- if (nativeFetch) { window.fetch = async function wrappedFetch(input, init) { const urlStr = typeof input === 'string' ? input : (input?.url || ''); const skip = !isActive() || urlStr.includes('/api/trace/frontend') || init?.__stlTraceInternal; if (skip) return nativeFetch(input, init); const t0 = performance.now(); const method = (init?.method || (typeof input === 'object' && input?.method) || 'GET').toUpperCase(); try { const res = await nativeFetch(input, init); record('fe_http', { method, url: urlStr, status: res.status, ok: res.ok, duration_ms: Math.round((performance.now() - t0) * 100) / 100, }); return res; } catch (err) { record('fe_http', { method, url: urlStr, status: 0, ok: false, error: err?.message || String(err), duration_ms: Math.round((performance.now() - t0) * 100) / 100, }); throw err; } }; } // ---- 2. Global Error & Console Interceptors ---- window.addEventListener('error', ev => { record('fe_error', { source: 'window.error', message: ev.message || '', filename: ev.filename || '', lineno: ev.lineno || 0, colno: ev.colno || 0, }); }, true); window.addEventListener('unhandledrejection', ev => { const r = ev.reason; record('fe_error', { source: 'unhandledrejection', message: r?.message || String(r || ''), }); }); console.error = (...args) => { nativeConsoleError(...args); record('fe_error', { source: 'console.error', args: args.map(a => String(a)).slice(0, 6) }); }; console.warn = (...args) => { nativeConsoleWarn(...args); record('fe_error', { source: 'console.warn', args: args.map(a => String(a)).slice(0, 6) }); }; // ---- 3. Capture-Phase UI Action Listeners ---- document.addEventListener('click', ev => { const t = ev.target?.closest?.('button,a,input,select,[role="button"],summary') || ev.target; record('ui_action', { event: 'click', target: elementDescriptor(t), text: (t?.textContent || '').trim().slice(0, 80), value: safeElementValue(t), }); }, true); document.addEventListener('change', ev => { const t = ev.target; record('ui_action', { event: 'change', target: elementDescriptor(t), value: safeElementValue(t), }); }, true); document.addEventListener('submit', ev => { record('ui_action', { event: 'submit', target: elementDescriptor(ev.target), }); }, true); document.addEventListener('keydown', ev => { if (ev.key === 'Enter' || ev.key === 'Escape') { record('ui_action', { event: 'keydown', key: ev.key, target: elementDescriptor(ev.target), }); } }, true); window.addEventListener('hashchange', () => { record('ui_action', { event: 'hashchange', hash: location.hash }); }); document.addEventListener('visibilitychange', () => { record('ui_action', { event: 'visibilitychange', state: document.visibilityState }); if (document.visibilityState === 'hidden') void flush(true); }); window.addEventListener('pagehide', () => { record('ui_action', { event: 'pagehide' }); void flush(true); }); // ---- 4. Disk-Low Alert Banner & Trace Config UI Manager ---- function setDiskLowBanner(paused, message = '') { diskLowPaused = !!paused; const banner = document.getElementById('trace-disk-low-banner'); if (!banner) return; if (diskLowPaused) { banner.textContent = message || `磁盘剩余空间低于 ${config.min_free_gb || 2} GiB,全细节本地日志已自动暂停写入(不影响正常内存测试),清理磁盘空间后自动恢复。`; banner.classList.remove('hidden'); } else { banner.classList.add('hidden'); } } function applyConfig(nextCfg) { if (!nextCfg || typeof nextCfg !== 'object') return; config = { ...config, ...nextCfg }; syncConfigForm(); } function syncConfigForm() { const $ = id => document.getElementById(id); if (!$('trace-enabled-toggle')) return; $('trace-enabled-toggle').checked = !!config.enabled; if ($('trace-sub-state')) $('trace-sub-state').checked = !!config.backend_state_diff; if ($('trace-sub-rpc')) $('trace-sub-rpc').checked = !!config.backend_rpc_http; if ($('trace-sub-serial')) $('trace-sub-serial').checked = !!config.backend_serial_stream; if ($('trace-sub-hw')) $('trace-sub-hw').checked = !!config.backend_hardware_io; if ($('trace-sub-fe')) $('trace-sub-fe').checked = !!config.frontend_trace; if ($('trace-sub-compress')) $('trace-sub-compress').checked = !!config.compress_rotated; if ($('trace-vol-mb')) $('trace-vol-mb').value = String(config.volume_mb ?? 50); if ($('trace-ret-days')) $('trace-ret-days').value = String(config.retention_days ?? 30); if ($('trace-min-free-gb')) $('trace-min-free-gb').value = String(config.min_free_gb ?? 2); const badge = $('trace-status-badge'); if (badge) { badge.textContent = diskLowPaused ? '空间不足暂停' : (config.enabled ? '全细节落盘运行中' : '已关闭'); badge.classList.toggle('connected', !!config.enabled && !diskLowPaused); badge.classList.toggle('error', diskLowPaused); } } async function refreshTraceStatus() { if (!nativeFetch) return; try { const res = await nativeFetch('/api/trace/status', { credentials: 'same-origin', cache: 'no-store' }); if (!res.ok) return; const st = await res.json(); if (st.config) applyConfig(st.config); setDiskLowBanner(!!st.disk_low_paused); const line = document.getElementById('trace-metrics-line'); if (line) { const mb = ((Number(st.written_bytes || 0)) / (1024 * 1024)).toFixed(2); const serMb = ((Number(st.serial_bytes_written || 0)) / (1024 * 1024)).toFixed(2); line.textContent = `当日目录: ${st.today || '-'} · 累计事件 ${st.written_events || 0} 条 · 已落盘 ${mb} MiB (原始串口 ${serMb} MiB) · 前端入库 ${st.frontend_events_ingested || 0} 条 · 丢弃 ${st.dropped_events || 0} · 分区可用 ${st.free_disk_gib ?? '--'} GiB · 浏览器离线队列 ${spooledCount} 批`; } const hwRes = await nativeFetch('/api/hw/info', { credentials: 'same-origin', cache: 'no-store' }); if (hwRes.ok) { const hw = await hwRes.json(); window.stlStore?.set?.('hwInfo', hw, 'hw_poll'); const badge = document.getElementById('hw-tier-badge'); if (badge) badge.textContent = hw.tier_name || `Tier ${hw.isa_tier ?? 0}`; const cpuEl = document.getElementById('hw-cpu-line'); if (cpuEl) { const flags = [ hw.has_ssse3 && 'SSSE3', hw.has_sse42 && 'SSE4.2', hw.has_popcnt && 'POPCNT', hw.has_pclmul && 'PCLMULQDQ', hw.has_aesni && 'AES-NI', hw.has_shani && 'SHA-NI', hw.has_avx2 && 'AVX2', hw.has_bmi2 && 'BMI2', hw.has_vpclmul && 'VPCLMULQDQ', hw.has_gfni && 'GFNI', hw.has_avx512 && 'AVX-512', ].filter(Boolean).join(' · ') || 'SSE2'; cpuEl.textContent = `CPU: ${hw.cpu_brand || 'x86_64'} (${hw.physical_cores || '?'} 线程) · 激活档位: ${hw.tier_name || hw.isa_tier} · 硬件指令集: ${flags}`; } const gpuEl = document.getElementById('hw-gpu-line'); if (gpuEl) { const g = hw.opencl_igpu || {}; const sKb = Math.round(Number(g.break_even_bytes || 524288) / 1024); gpuEl.textContent = g.available ? `OpenCL 核显: ${g.device_name} (${g.compute_units || 0} EU · 零拷贝LLC=${g.zero_copy_llc ? '是' : '否'}) · 标定阈值 S*=${sKb} KiB (GPU ${g.calibrated_gpu_us || 0}us vs CPU ${g.calibrated_cpu_us || 0}us) · GPU 分流 ${g.gpu_offload_count || 0} 次 / CPU SIMD ${g.cpu_fallback_count || 0} 次` : `OpenCL 核显: 未检测到 OpenCL GPU ICD,大批量任务自动走 CPU 多档 SIMD 兜底 (S*=${sKb} KiB · CPU SIMD 执行 ${g.cpu_fallback_count || 0} 次)`; } } } catch (_) {} } async function saveTraceConfigFromUi() { if (!nativeFetch) return; const $ = id => document.getElementById(id); const patch = { enabled: !!$('trace-enabled-toggle')?.checked, backend_state_diff: !!$('trace-sub-state')?.checked, backend_rpc_http: !!$('trace-sub-rpc')?.checked, backend_serial_stream: !!$('trace-sub-serial')?.checked, backend_hardware_io: !!$('trace-sub-hw')?.checked, frontend_trace: !!$('trace-sub-fe')?.checked, compress_rotated: !!$('trace-sub-compress')?.checked, volume_mb: Math.max(1, Number($('trace-vol-mb')?.value || 50)), retention_days: Math.max(1, Number($('trace-ret-days')?.value || 30)), min_free_gb: Math.max(0, Number($('trace-min-free-gb')?.value ?? 2)), }; const res = await nativeFetch('/api/trace/config', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(patch), }); if (res.ok) { const st = await res.json().catch(() => null); if (st?.config) applyConfig(st.config); setDiskLowBanner(!!st?.disk_low_paused); await refreshTraceStatus(); const note = $('trace-save-note'); if (note) note.textContent = `已生效(${patch.enabled ? '开启' : '已关闭'} · 无需重启)`; } } // ---- 5. Hook Store, WebSocket Transport, UI Alert MutationObserver & Periodic Perf ---- function wireRuntimeHooks() { // Store state_diff + initial state_snapshot if (window.stlStore?.subscribe) { let diffCount = 0; record('fe_state_snapshot', { trigger: 'init', uiMode: window.stlStore.get('uiMode'), page: window.stlStore.get('page'), stationId: window.stlStore.get('stationId'), connected: window.stlStore.get('connected'), }); window.stlStore.subscribe(({ path, prev, next, trigger }) => { if (!isActive()) return; const summarizeVal = (p, v) => { if (p === 'stations' && Array.isArray(v)) { return v.map(s => `${s.station_id}:${s.task_status}:${s.verdict}:${s.fault_code || ''}`).join('|'); } if (p.startsWith('controlByStation.')) { return v ? `${v.task_status || ''}:${v.verdict || ''}:${v.firmware?.observed_phase || ''}:${v.watchdog?.fault_code || ''}` : ''; } if (p.startsWith('diagnosticsByStation.')) { return v ? `${v.state || ''}:${v.bytes_received || 0}` : ''; } return sanitize(v); }; const oldS = summarizeVal(path, prev); const newS = summarizeVal(path, next); if (JSON.stringify(oldS) === JSON.stringify(newS)) return; diffCount += 1; record('fe_state_diff', { path, old: oldS, new: newS, trigger }); if (diffCount % 200 === 0) { record('fe_state_snapshot', { trigger: 'periodic', uiMode: window.stlStore.get('uiMode'), page: window.stlStore.get('page'), stationId: window.stlStore.get('stationId'), connected: window.stlStore.get('connected'), stationCount: (window.stlStore.get('stations') || []).length, }); } }); } // Wrap WebSocket RPC calls if (window.stlTransport?.call && !window.stlTransport.__traceWrapped) { const origCall = window.stlTransport.call; window.stlTransport.__traceWrapped = true; window.stlTransport.call = async function tracedCall(method, params, timeoutMs) { const isNoisyPoll = method === 'ReadCleanedUart' || method === 'GetThermalConsole'; const t0 = performance.now(); try { const res = await origCall(method, params, timeoutMs); if (!isNoisyPoll) { record('fe_ws', { method, ok: true, duration_ms: Math.round((performance.now() - t0) * 100) / 100, params: sanitize(params), }); } return res; } catch (err) { record('fe_ws', { method, ok: false, code: err?.code || 'ERR', error: err?.message || String(err), duration_ms: Math.round((performance.now() - t0) * 100) / 100, params: sanitize(params), }); throw err; } }; } window.addEventListener('stl:transport-state', ev => { const d = ev.detail || {}; record('fe_ws', { event: 'transport_state', state: d.state, generation: d.generation, pending: d.pending }); if (d.state === 'open') { void refreshTraceStatus(); void drainIdbSpool(); } }); window.addEventListener('stl:server-event', ev => { const msg = ev.detail || {}; if (msg.event === 'trace_config_changed' && msg.result) { applyConfig(msg.result); return; } if (msg.event === 'trace_disk_low' && msg.result) { setDiskLowBanner(!!msg.result.paused, msg.result.message || ''); return; } if (msg.event === 'task_complete') { record('fe_ws', { event: 'task_complete', result: sanitize(msg.result) }); } }); // UI Alert MutationObserver const obsTargets = ['action-status', 'watchdog-alert-banner', 'dimm-replacement-banner']; const mo = new MutationObserver(muts => { for (const m of muts) { const el = m.target.nodeType === 1 ? m.target : m.target.parentElement; if (!el) continue; const txt = (el.textContent || '').trim().slice(0, 240); record('fe_ui_alert', { target: elementDescriptor(el), hidden: el.classList?.contains('hidden') || false, alert_kind: el.dataset?.alertKind || '', text: txt, }); } }); for (const tid of obsTargets) { const node = document.getElementById(tid); if (node) mo.observe(node, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: ['class', 'data-alert-kind'] }); } // Bind Trace Management Panel buttons in Engineering Records page document.getElementById('btn-trace-save')?.addEventListener('click', () => { void saveTraceConfigFromUi(); }); document.getElementById('btn-trace-refresh')?.addEventListener('click', () => { void refreshTraceStatus(); }); document.getElementById('btn-trace-export-offline')?.addEventListener('click', () => { void exportOfflineJsonl(); }); document.getElementById('btn-trace-download-bundle')?.addEventListener('click', () => { const sid = document.getElementById('trace-bundle-station')?.value || ''; const url = `/api/trace/bundle${sid ? '?station_id=' + encodeURIComponent(sid) : ''}`; const a = document.createElement('a'); a.href = url; a.download = ''; a.click(); }); // Periodic 30s fe_perf snapshot setInterval(() => { if (!isActive()) return; const mem = performance.memory ? { used_mb: Math.round(performance.memory.usedJSHeapSize / 1048576), total_mb: Math.round(performance.memory.totalJSHeapSize / 1048576), } : null; record('fe_perf', { dom_nodes: document.getElementsByTagName('*').length, heap: mem, spooled_batches: spooledCount, station_id: window.stlStore?.get('stationId') || '', }); }, 30000); void syncSpooledCount().then(() => refreshTraceStatus()); } window.stlTrace = { record, flush, refreshStatus: refreshTraceStatus, exportOfflineJsonl, getConfig: () => ({ ...config }), isActive, }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', wireRuntimeHooks); } else { wireRuntimeHooks(); } })();