From 19b8da0faccfc4438ed19fbc99d992a6a07af003 Mon Sep 17 00:00:00 2001 From: Agando Date: Wed, 29 Jul 2026 20:46:12 +0200 Subject: auto: 2026-07-29_20:50 changes — gunes sponsorluk page, bunq payment modal, AI platforms, news W30 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/debug/clusters.php | 98 ++++++++++++++++ api/debug/config.php | 59 ++++++++++ api/debug/dashboard.php | 200 ++++++++++++++++++++++++++++++++ api/debug/error.php | 36 ++++++ api/debug/errors.php | 43 +++++++ api/debug/health.php | 20 ++++ api/debug/ingest.php | 117 +++++++++++++++++++ api/debug/stats.php | 55 +++++++++ main.html | 2 +- modules/core/core-bundle.js | 153 ++++++++++++++++++++++-- modules/core/module-debug-supervisor.js | 153 ++++++++++++++++++++++-- review-newos4.html | 20 ++-- 12 files changed, 925 insertions(+), 31 deletions(-) create mode 100644 api/debug/clusters.php create mode 100644 api/debug/config.php create mode 100644 api/debug/dashboard.php create mode 100644 api/debug/error.php create mode 100644 api/debug/errors.php create mode 100644 api/debug/health.php create mode 100644 api/debug/ingest.php create mode 100644 api/debug/stats.php diff --git a/api/debug/clusters.php b/api/debug/clusters.php new file mode 100644 index 0000000..5174317 --- /dev/null +++ b/api/debug/clusters.php @@ -0,0 +1,98 @@ + true, + 'cached' => true, + 'clusters' => $clusters, + 'total_errors' => count($errors), + ]); +} + +// Rebuild clusters +$normalized = []; +foreach ($errors as $e) { + $msg = strtolower($e['message'] ?? ''); + $msg = preg_replace('/\b0x[a-f0-9]+\b/', '0xHEX', $msg); + $msg = preg_replace('/\b\d+\b/', 'N', $msg); + $msg = preg_replace('/["\'].*?["\']/', '"STR"', $msg); + $msg = preg_replace('/[^\w\s]/', ' ', $msg); + $msg = preg_replace('/\s+/', ' ', $msg); + $normalized[] = trim($msg); +} + +$clusters = []; +$assigned = []; +$threshold = CLUSTER_SIMILARITY_THRESHOLD; + +for ($i = 0; $i < count($errors); $i++) { + if (isset($assigned[$i])) continue; + + $cluster = [ + 'errors' => [$i], + 'messages' => [$errors[$i]['message']], + 'count' => $errors[$i]['count'] ?? 1, + 'types' => [$errors[$i]['type'] ?? 'unknown'], + 'categories' => [$errors[$i]['category'] ?? 'runtime'], + 'label' => $errors[$i]['message'] ?? '', + ]; + $assigned[$i] = true; + + for ($j = $i + 1; $j < count($errors); $j++) { + if (isset($assigned[$j])) continue; + + // Jaccard similarity + $tokensA = array_unique(array_filter(explode(' ', $normalized[$i]))); + $tokensB = array_unique(array_filter(explode(' ', $normalized[$j]))); + if (empty($tokensA) && empty($tokensB)) { + $similarity = 1; + } else { + $intersection = count(array_intersect($tokensA, $tokensB)); + $union = count($tokensA) + count($tokensB) - $intersection; + $similarity = $union > 0 ? $intersection / $union : 0; + } + + if ($similarity >= $threshold) { + $cluster['errors'][] = $j; + $cluster['messages'][] = $errors[$j]['message']; + $cluster['count'] += $errors[$j]['count'] ?? 1; + if (!in_array($errors[$j]['type'] ?? 'unknown', $cluster['types'])) { + $cluster['types'][] = $errors[$j]['type'] ?? 'unknown'; + } + if (!in_array($errors[$j]['category'] ?? 'runtime', $cluster['categories'])) { + $cluster['categories'][] = $errors[$j]['category'] ?? 'runtime'; + } + $assigned[$j] = true; + } + } + + // Most frequent message as label + $freq = array_count_values($cluster['messages']); + arsort($freq); + $cluster['label'] = substr(key($freq) ?: $cluster['label'], 0, 200); + $cluster['error_count'] = count($cluster['errors']); + unset($cluster['errors']); + unset($cluster['messages']); + + $clusters[] = $cluster; +} + +usort($clusters, fn($a, $b) => $b['count'] - $a['count']); + +// Cache +save_json(CLUSTERS_FILE, $clusters); +if (file_exists($rebuildFlag)) unlink($rebuildFlag); + +json_response([ + 'success' => true, + 'cached' => false, + 'clusters' => array_slice($clusters, 0, 50), + 'total_errors' => count($errors), + 'total_clusters' => count($clusters), +]); diff --git a/api/debug/config.php b/api/debug/config.php new file mode 100644 index 0000000..4a2bd05 --- /dev/null +++ b/api/debug/config.php @@ -0,0 +1,59 @@ + false, 'error' => $msg], $code); +} diff --git a/api/debug/dashboard.php b/api/debug/dashboard.php new file mode 100644 index 0000000..7a46661 --- /dev/null +++ b/api/debug/dashboard.php @@ -0,0 +1,200 @@ + $hash, 'message' => $e['message'] ?? '', 'count' => 0, 'type' => $t]; + } + $topErrors[$hash]['count'] += $e['count'] ?? 1; + } +} +usort($topErrors, fn($a, $b) => $b['count'] - $a['count']); +$topErrors = array_slice($topErrors, 0, 10); +ksort($byDay); + +$recentSessions = array_slice($sessions, -10, 10, true); +?> + + + + + +newOS4 Debug Dashboard + + + +

🔍 newOS4 Debug Dashboard

+
Server-side error aggregation · · JSON Stats · Clusters · Raw Errors · Health
+ + +
Last sync: UTC
+ + +
+
+

Total Errors

+
+
+
+

Sessions

+
+
+
+

Error Types

+
+
+
+

Modules Affected

+
+
+
+ +
+
+

By Severity

+ + 'error', 'error' => 'error', 'warning' => 'warn'] as $sev => $cls): ?> + + +
+
+
+

By Category

+ + + 0): ?> + + + +
+
+
+

By Module

+ + $count): + if ($i++ > 5) break; + ?> + + +
+
+
+ +
+

Top Errors

+ + + + + + + + + + + + + +
#MessageTypeCount
No errors recorded
+
+ +
+

Daily Trend (last 14 days)

+ + + $count): + $pct = round($count / $maxDay * 100, 0); + ?> + + + + + + +
DayErrors
+
+ +
+

Recent Sessions

+ + + $s): ?> + + + + + + + +
SessionVersionErrorsLast Seen
+
+ +
Auto-refresh every 30s
+ + + diff --git a/api/debug/error.php b/api/debug/error.php new file mode 100644 index 0000000..242dfca --- /dev/null +++ b/api/debug/error.php @@ -0,0 +1,36 @@ + ($e['hash'] ?? '') === $hash); +$matches = array_values($matches); + +if (empty($matches)) { + error_response('Error not found', 404); +} + +$totalCount = array_sum(array_column($matches, 'count')); +$uniqueSessions = array_unique(array_column($matches, 'session_id')); +$firstSeen = min(array_column($matches, 'first_seen')); +$lastSeen = max(array_column($matches, 'last_seen')); + +json_response([ + 'success' => true, + 'hash' => $hash, + 'total_occurrences' => count($matches), + 'total_count' => $totalCount, + 'unique_sessions' => count($uniqueSessions), + 'first_seen' => $firstSeen, + 'last_seen' => $lastSeen, + 'type' => $matches[0]['type'] ?? 'unknown', + 'severity' => $matches[0]['severity'] ?? 'error', + 'category' => $matches[0]['category'] ?? 'runtime', + 'sample_message' => $matches[0]['message'] ?? '', + 'sample_stack' => $matches[0]['stack'] ?? null, + 'occurrences' => array_slice($matches, 0, 20), +]); diff --git a/api/debug/errors.php b/api/debug/errors.php new file mode 100644 index 0000000..1ed9a2f --- /dev/null +++ b/api/debug/errors.php @@ -0,0 +1,43 @@ + $to) return false; + return true; +}); + +$filtered = array_values($filtered); +$total = count($filtered); +$totalPages = max(1, ceil($total / $perPage)); +$offset = ($page - 1) * $perPage; +$pageErrors = array_slice($filtered, $offset, $perPage); + +json_response([ + 'success' => true, + 'total' => $total, + 'page' => $page, + 'per_page' => $perPage, + 'total_pages' => $totalPages, + 'errors' => $pageErrors, +]); diff --git a/api/debug/health.php b/api/debug/health.php new file mode 100644 index 0000000..5a0048f --- /dev/null +++ b/api/debug/health.php @@ -0,0 +1,20 @@ + true, + 'status' => 'ok', + 'uptime' => filemtime(__FILE__) ? (time() - filemtime(__FILE__)) : 0, + 'total_errors' => count($errors), + 'total_sessions' => count($sessions), + 'errors_file_size_kb' => file_exists(ERRORS_FILE) ? round(filesize(ERRORS_FILE) / 1024, 1) : 0, + 'sessions_file_size_kb' => file_exists(SESSIONS_FILE) ? round(filesize(SESSIONS_FILE) / 1024, 1) : 0, + 'last_ingest' => $lastError ? ($lastError['ingested_at'] ?? null) : null, + 'last_ingest_message' => $lastError ? substr($lastError['message'] ?? '', 0, 100) : null, + 'generated_at' => date('c'), +]); diff --git a/api/debug/ingest.php b/api/debug/ingest.php new file mode 100644 index 0000000..363dd09 --- /dev/null +++ b/api/debug/ingest.php @@ -0,0 +1,117 @@ + MAX_ERRORS_PER_BATCH) { + $errors = array_slice($errors, 0, MAX_ERRORS_PER_BATCH); +} +if (strlen($raw) > MAX_BATCH_SIZE_KB * 1024) { + error_response('Payload too large (max ' . MAX_BATCH_SIZE_KB . 'KB)', 413); +} + +// Load existing data +$allErrors = load_json(ERRORS_FILE); +$sessions = load_json(SESSIONS_FILE); + +$sessionId = $session['id'] ?? ('anon_' . bin2hex(random_bytes(4))); +$ingested = 0; +$now = date('c'); + +// Update session metadata +if (!isset($sessions[$sessionId])) { + $sessions[$sessionId] = [ + 'id' => $sessionId, + 'first_seen' => $now, + 'version' => $clientVersion, + 'modules' => $session['modules'] ?? [], + 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', + 'ip' => $_SERVER['REMOTE_ADDR'] ?? '', + 'error_count' => 0, + ]; +} +$sessions[$sessionId]['last_seen'] = $now; +$sessions[$sessionId]['error_count'] += count($errors); +$sessions[$sessionId]['version'] = $clientVersion; + +// Build a lookup of existing hashes for dedup +$existingHashes = []; +foreach ($allErrors as $idx => $existing) { + $h = $existing['hash'] ?? ''; + if ($h) { + $existingHashes[$h] = $idx; + } +} + +// Ingest each error (dedup by hash) +foreach ($errors as $e) { + $hash = $e['hash'] ?? md5(($e['message'] ?? '') . '|' . ($e['source'] ?? '') . '|' . ($e['type'] ?? '')); + + if (isset($existingHashes[$hash])) { + // Update existing entry + $idx = $existingHashes[$hash]; + $allErrors[$idx]['count'] += $e['count'] ?? 1; + $allErrors[$idx]['last_seen'] = $e['lastSeen'] ?? $now; + $allErrors[$idx]['ingested_at'] = $now; + if (!empty($e['stack'])) { + $allErrors[$idx]['stack'] = substr($e['stack'], 0, 2000); + } + $ingested++; + continue; + } + + $entry = [ + 'hash' => $hash, + 'message' => substr($e['message'] ?? '', 0, 500), + 'type' => $e['type'] ?? 'unknown', + 'severity' => $e['severity'] ?? 'error', + 'category' => $e['category'] ?? 'runtime', + 'source' => $e['source'] ?? '', + 'module' => $e['module'] ?? null, + 'stack' => isset($e['stack']) ? substr($e['stack'], 0, 2000) : null, + 'session_id' => $sessionId, + 'count' => $e['count'] ?? 1, + 'first_seen' => $e['firstSeen'] ?? $now, + 'last_seen' => $e['lastSeen'] ?? $now, + 'ingested_at' => $now, + ]; + + $allErrors[] = $entry; + $existingHashes[$hash] = count($allErrors) - 1; + $ingested++; +} + +// Trim to last 10,000 errors (ring buffer) +if (count($allErrors) > 10000) { + $allErrors = array_slice($allErrors, -10000); +} + +save_json(ERRORS_FILE, $allErrors); +save_json(SESSIONS_FILE, $sessions); + +// Rebuild clusters asynchronously (flag file) +$rebuildFlag = DEBUG_DATA_DIR . '/.rebuild_clusters'; +file_put_contents($rebuildFlag, time()); + +json_response([ + 'success' => true, + 'ingested' => $ingested, + 'session_id' => $sessionId, + 'total_errors' => count($allErrors), + 'total_sessions' => count($sessions), +]); diff --git a/api/debug/stats.php b/api/debug/stats.php new file mode 100644 index 0000000..dd0b0db --- /dev/null +++ b/api/debug/stats.php @@ -0,0 +1,55 @@ + $hash, 'message' => $e['message'] ?? '', 'count' => 0, 'type' => $t]; + } + $topErrors[$hash]['count'] += $e['count'] ?? 1; + } +} + +usort($topErrors, fn($a, $b) => $b['count'] - $a['count']); +$topErrors = array_slice($topErrors, 0, 20); +ksort($byDay); + +json_response([ + 'success' => true, + 'total_errors' => $total, + 'total_sessions' => count($sessions), + 'by_type' => $byType, + 'by_severity' => $bySeverity, + 'by_category' => $byCategory, + 'by_module' => $byModule, + 'by_day' => $byDay, + 'top_errors' => $topErrors, + 'generated_at' => date('c'), +]); diff --git a/main.html b/main.html index 1663fc0..feb80f8 100644 --- a/main.html +++ b/main.html @@ -1342,7 +1342,7 @@ - + diff --git a/modules/core/core-bundle.js b/modules/core/core-bundle.js index aab0206..2bb076a 100644 --- a/modules/core/core-bundle.js +++ b/modules/core/core-bundle.js @@ -19164,6 +19164,8 @@ class DebugSupervisorModule { 'debug-trends': 'debug-trends [days] — Error frequency over time (default: 7)', 'debug-fix': 'debug-fix — Suggest and optionally apply fix for an error', 'debug-health': 'debug-health — Check supervisor module health status', + 'debug-sync': 'debug-sync [url] — Sync errors to backend API (or set sync URL)', + 'debug-sync-url': 'debug-sync-url [url] — View or set the backend sync endpoint', }; } @@ -19174,6 +19176,8 @@ class DebugSupervisorModule { this.commands['debug-trends'] = (args) => this._cmdTrends(args); this.commands['debug-fix'] = (args) => this._cmdFix(args); this.commands['debug-health'] = () => this._cmdHealth(); + this.commands['debug-sync'] = (args) => this._cmdSync(args); + this.commands['debug-sync-url'] = (args) => this._cmdSyncUrl(args); } seed() { @@ -19183,6 +19187,36 @@ class DebugSupervisorModule { init() { this._loadDB(); this._installInterceptors(); + // Start periodic sync (every 5 minutes) + this._syncInterval = setInterval(() => this._syncToBackend(), 300000); + // Also sync on first load after a short delay + setTimeout(() => this._syncToBackend(), 5000); + } + + destroy() { + // Clear sync interval + if (this._syncInterval) { + clearInterval(this._syncInterval); + this._syncInterval = null; + } + // Restore original console.error + if (this._originalConsole.error) { + console.error = this._originalConsole.error; + } + // Restore original window.onerror + if (this._originalOnError) { + window.onerror = this._originalOnError; + } + // Restore original fetch + if (this._originalFetch) { + window.fetch = this._originalFetch; + } + // Remove unhandledrejection listener (stored for cleanup) + if (this._rejectionHandler) { + window.removeEventListener('unhandledrejection', this._rejectionHandler); + } + this._interceptorInstalled = false; + this._healthy = false; } // ── Error Database ── @@ -19252,11 +19286,7 @@ class DebugSupervisorModule { _checkQuota() { try { - const total = 0; - for (const key in localStorage) { - // Estimate: key + value length - } - // Simple check: try writing a test key + // Test localStorage is writable const testKey = '__quota_test__'; localStorage.setItem(testKey, '1'); localStorage.removeItem(testKey); @@ -19290,7 +19320,7 @@ class DebugSupervisorModule { _detectSeverity(type, message) { if (type === 'SyntaxError' || type === 'ReferenceError' || type === 'quota') return 'fatal'; - if (type === 'HTTP' && message.includes('5')) return 'error'; + if (type === 'HTTP' && /\b5\d{2}\b/.test(message)) return 'error'; if (type === 'timeout' || type === 'security') return 'error'; if (type === 'tool') return 'warning'; return 'error'; @@ -19347,10 +19377,11 @@ class DebugSupervisorModule { // Unhandled rejections this._originalOnRejection = window.onunhandledrejection; - window.addEventListener('unhandledrejection', function(e) { + this._rejectionHandler = function(e) { const msg = e.reason ? (e.reason.message || String(e.reason)) : 'Unhandled Promise rejection'; self._recordError(msg, 'unhandledrejection', e.reason ? e.reason.stack : null); - }); + }; + window.addEventListener('unhandledrejection', this._rejectionHandler); // Fetch failures this._originalFetch = window.fetch; @@ -19761,9 +19792,11 @@ class DebugSupervisorModule { if (!fix.fixes || fix.fixes.length === 0) return; const firstFix = fix.fixes[0]; try { + // Sanitize params: only allow alphanumeric, hyphens, underscores, dots + const safeParams = (firstFix.params || '').replace(/[^a-zA-Z0-9_\-\.]/g, ''); if (firstFix.action === 'loadmod' && this.terminal) { - this.terminal.executeCommand('loadmod ' + (firstFix.params || '')); - this.terminal.print(' ✅ Applied: loadmod ' + (firstFix.params || ''), 'success'); + this.terminal.executeCommand('loadmod ' + safeParams); + this.terminal.print(' ✅ Applied: loadmod ' + safeParams, 'success'); } else if (firstFix.action === 'test-net' && this.terminal) { this.terminal.executeCommand('test-net'); this.terminal.print(' ✅ Applied: test-net', 'success'); @@ -19788,6 +19821,106 @@ class DebugSupervisorModule { this.terminal.print(' Quota: ' + (this._checkQuota() ? '✅ available' : '🔴 low'), this._checkQuota() ? 'success' : 'error'); } + // ── Sync to Backend ── + + _getSyncUrl() { + try { + return localStorage.getItem('webx11_debug_sync_url') || 'https://webx11.duckdns.org/spaces/newos4/api/debug/ingest.php'; + } catch (e) { + return 'https://webx11.duckdns.org/spaces/newos4/api/debug/ingest.php'; + } + } + + async _syncToBackend() { + if (!this._healthy) return; + const db = this._errorDB.errors; + const keys = Object.keys(db); + if (keys.length === 0) return; + + const payload = { + version: window.NEWOS4_VERSION || 'v4.x', + session: { + id: this._sessionId, + modules: this.terminal?.moduleManager ? Object.keys(this.terminal.moduleManager.modules) : [], + }, + errors: keys.map(k => ({ + hash: k, + message: db[k].message, + type: db[k].type, + severity: db[k].severity, + category: db[k].category, + source: db[k].source, + module: db[k].module, + stack: db[k].stack, + count: db[k].count, + firstSeen: new Date(db[k].firstSeen).toISOString(), + lastSeen: new Date(db[k].lastSeen).toISOString(), + })), + }; + + try { + const resp = await fetch(this._getSyncUrl(), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(10000), + }); + if (resp.ok) { + const result = await resp.json(); + if (result.success) { + const sent = keys.length; + const accepted = result.ingested || 0; + if (accepted < sent) { + console.warn('[DebugSupervisor] Sync truncated: sent ' + sent + ' errors, server accepted ' + accepted + ' (max ' + (result.total_errors || '?') + ' total)'); + } else { + console.log('[DebugSupervisor] Synced ' + accepted + ' errors to backend'); + } + this._lastSyncOk = Date.now(); + return true; + } + } + console.warn('[DebugSupervisor] Sync returned HTTP ' + resp.status); + return false; + } catch (e) { + console.warn('[DebugSupervisor] Sync failed: ' + e.message); + return false; + } + } + + _cmdSync(args) { + const url = (args && args[0]) ? args[0] : null; + if (url) { + try { + localStorage.setItem('webx11_debug_sync_url', url); + this.terminal.print('✅ Sync URL set to: ' + url, 'success'); + } catch (e) { + this.terminal.print('❌ Failed to save sync URL', 'error'); + } + return; + } + this.terminal.print('🔄 Syncing errors to backend...', 'info'); + this._syncToBackend().then(ok => { + if (ok) { + this.terminal.print('✅ Sync complete', 'success'); + } else { + this.terminal.print('❌ Sync failed', 'error'); + } + }); + } + + _cmdSyncUrl(args) { + if (args && args[0]) { + try { + localStorage.setItem('webx11_debug_sync_url', args[0]); + this.terminal.print('✅ Sync URL set to: ' + args[0], 'success'); + } catch (e) { + this.terminal.print('❌ Failed to save sync URL', 'error'); + } + } else { + this.terminal.print('Current sync URL: ' + this._getSyncUrl(), 'info'); + } + } + // ── Dashboard Data ── getDashboardData() { diff --git a/modules/core/module-debug-supervisor.js b/modules/core/module-debug-supervisor.js index 15fe5d4..fc6a919 100644 --- a/modules/core/module-debug-supervisor.js +++ b/modules/core/module-debug-supervisor.js @@ -39,6 +39,8 @@ class DebugSupervisorModule { 'debug-trends': 'debug-trends [days] — Error frequency over time (default: 7)', 'debug-fix': 'debug-fix — Suggest and optionally apply fix for an error', 'debug-health': 'debug-health — Check supervisor module health status', + 'debug-sync': 'debug-sync [url] — Sync errors to backend API (or set sync URL)', + 'debug-sync-url': 'debug-sync-url [url] — View or set the backend sync endpoint', }; } @@ -49,6 +51,8 @@ class DebugSupervisorModule { this.commands['debug-trends'] = (args) => this._cmdTrends(args); this.commands['debug-fix'] = (args) => this._cmdFix(args); this.commands['debug-health'] = () => this._cmdHealth(); + this.commands['debug-sync'] = (args) => this._cmdSync(args); + this.commands['debug-sync-url'] = (args) => this._cmdSyncUrl(args); } seed() { @@ -58,6 +62,36 @@ class DebugSupervisorModule { init() { this._loadDB(); this._installInterceptors(); + // Start periodic sync (every 5 minutes) + this._syncInterval = setInterval(() => this._syncToBackend(), 300000); + // Also sync on first load after a short delay + setTimeout(() => this._syncToBackend(), 5000); + } + + destroy() { + // Clear sync interval + if (this._syncInterval) { + clearInterval(this._syncInterval); + this._syncInterval = null; + } + // Restore original console.error + if (this._originalConsole.error) { + console.error = this._originalConsole.error; + } + // Restore original window.onerror + if (this._originalOnError) { + window.onerror = this._originalOnError; + } + // Restore original fetch + if (this._originalFetch) { + window.fetch = this._originalFetch; + } + // Remove unhandledrejection listener (stored for cleanup) + if (this._rejectionHandler) { + window.removeEventListener('unhandledrejection', this._rejectionHandler); + } + this._interceptorInstalled = false; + this._healthy = false; } // ── Error Database ── @@ -127,11 +161,7 @@ class DebugSupervisorModule { _checkQuota() { try { - const total = 0; - for (const key in localStorage) { - // Estimate: key + value length - } - // Simple check: try writing a test key + // Test localStorage is writable const testKey = '__quota_test__'; localStorage.setItem(testKey, '1'); localStorage.removeItem(testKey); @@ -165,7 +195,7 @@ class DebugSupervisorModule { _detectSeverity(type, message) { if (type === 'SyntaxError' || type === 'ReferenceError' || type === 'quota') return 'fatal'; - if (type === 'HTTP' && message.includes('5')) return 'error'; + if (type === 'HTTP' && /\b5\d{2}\b/.test(message)) return 'error'; if (type === 'timeout' || type === 'security') return 'error'; if (type === 'tool') return 'warning'; return 'error'; @@ -222,10 +252,11 @@ class DebugSupervisorModule { // Unhandled rejections this._originalOnRejection = window.onunhandledrejection; - window.addEventListener('unhandledrejection', function(e) { + this._rejectionHandler = function(e) { const msg = e.reason ? (e.reason.message || String(e.reason)) : 'Unhandled Promise rejection'; self._recordError(msg, 'unhandledrejection', e.reason ? e.reason.stack : null); - }); + }; + window.addEventListener('unhandledrejection', this._rejectionHandler); // Fetch failures this._originalFetch = window.fetch; @@ -636,9 +667,11 @@ class DebugSupervisorModule { if (!fix.fixes || fix.fixes.length === 0) return; const firstFix = fix.fixes[0]; try { + // Sanitize params: only allow alphanumeric, hyphens, underscores, dots + const safeParams = (firstFix.params || '').replace(/[^a-zA-Z0-9_\-\.]/g, ''); if (firstFix.action === 'loadmod' && this.terminal) { - this.terminal.executeCommand('loadmod ' + (firstFix.params || '')); - this.terminal.print(' ✅ Applied: loadmod ' + (firstFix.params || ''), 'success'); + this.terminal.executeCommand('loadmod ' + safeParams); + this.terminal.print(' ✅ Applied: loadmod ' + safeParams, 'success'); } else if (firstFix.action === 'test-net' && this.terminal) { this.terminal.executeCommand('test-net'); this.terminal.print(' ✅ Applied: test-net', 'success'); @@ -663,6 +696,106 @@ class DebugSupervisorModule { this.terminal.print(' Quota: ' + (this._checkQuota() ? '✅ available' : '🔴 low'), this._checkQuota() ? 'success' : 'error'); } + // ── Sync to Backend ── + + _getSyncUrl() { + try { + return localStorage.getItem('webx11_debug_sync_url') || 'https://webx11.duckdns.org/spaces/newos4/api/debug/ingest.php'; + } catch (e) { + return 'https://webx11.duckdns.org/spaces/newos4/api/debug/ingest.php'; + } + } + + async _syncToBackend() { + if (!this._healthy) return; + const db = this._errorDB.errors; + const keys = Object.keys(db); + if (keys.length === 0) return; + + const payload = { + version: window.NEWOS4_VERSION || 'v4.x', + session: { + id: this._sessionId, + modules: this.terminal?.moduleManager ? Object.keys(this.terminal.moduleManager.modules) : [], + }, + errors: keys.map(k => ({ + hash: k, + message: db[k].message, + type: db[k].type, + severity: db[k].severity, + category: db[k].category, + source: db[k].source, + module: db[k].module, + stack: db[k].stack, + count: db[k].count, + firstSeen: new Date(db[k].firstSeen).toISOString(), + lastSeen: new Date(db[k].lastSeen).toISOString(), + })), + }; + + try { + const resp = await fetch(this._getSyncUrl(), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + signal: AbortSignal.timeout(10000), + }); + if (resp.ok) { + const result = await resp.json(); + if (result.success) { + const sent = keys.length; + const accepted = result.ingested || 0; + if (accepted < sent) { + console.warn('[DebugSupervisor] Sync truncated: sent ' + sent + ' errors, server accepted ' + accepted + ' (max ' + (result.total_errors || '?') + ' total)'); + } else { + console.log('[DebugSupervisor] Synced ' + accepted + ' errors to backend'); + } + this._lastSyncOk = Date.now(); + return true; + } + } + console.warn('[DebugSupervisor] Sync returned HTTP ' + resp.status); + return false; + } catch (e) { + console.warn('[DebugSupervisor] Sync failed: ' + e.message); + return false; + } + } + + _cmdSync(args) { + const url = (args && args[0]) ? args[0] : null; + if (url) { + try { + localStorage.setItem('webx11_debug_sync_url', url); + this.terminal.print('✅ Sync URL set to: ' + url, 'success'); + } catch (e) { + this.terminal.print('❌ Failed to save sync URL', 'error'); + } + return; + } + this.terminal.print('🔄 Syncing errors to backend...', 'info'); + this._syncToBackend().then(ok => { + if (ok) { + this.terminal.print('✅ Sync complete', 'success'); + } else { + this.terminal.print('❌ Sync failed', 'error'); + } + }); + } + + _cmdSyncUrl(args) { + if (args && args[0]) { + try { + localStorage.setItem('webx11_debug_sync_url', args[0]); + this.terminal.print('✅ Sync URL set to: ' + args[0], 'success'); + } catch (e) { + this.terminal.print('❌ Failed to save sync URL', 'error'); + } + } else { + this.terminal.print('Current sync URL: ' + this._getSyncUrl(), 'info'); + } + } + // ── Dashboard Data ── getDashboardData() { diff --git a/review-newos4.html b/review-newos4.html index 975a0e8..deff556 100644 --- a/review-newos4.html +++ b/review-newos4.html @@ -3,7 +3,7 @@ - + ChatStudio newOS4 - Review