diff --git a/src-tauri/src/desktop/logging.rs b/src-tauri/src/desktop/logging.rs index 088756b08..58c1fee37 100644 --- a/src-tauri/src/desktop/logging.rs +++ b/src-tauri/src/desktop/logging.rs @@ -1,15 +1,34 @@ use tauri::AppHandle; -use tauri_plugin_log::{Builder, FileOpenStrategy, RotationStrategy}; +use tauri_plugin_log::{Builder, FileOpenStrategy, RotationStrategy, Target, TargetKind}; const MAX_LOG_FILE_SIZE: u128 = 5 * 1024 * 1024; const ROTATED_LOG_COUNT: usize = 5; +fn is_reviewed_verbose_target(target: &str) -> bool { + target == "app_lib" + || target.starts_with("app_lib::") + || target == "sable" + || target.starts_with("sable::") + || target == "tauri" + || target.starts_with("tauri::") + || target.starts_with("tauri_runtime_") + || target.starts_with("tauri_plugin_") + || target == tauri_plugin_log::WEBVIEW_TARGET +} + +fn file_log_record_allowed(metadata: &log::Metadata) -> bool { + metadata.level() <= log::Level::Warn || is_reviewed_verbose_target(metadata.target()) +} + fn builder() -> Builder { Builder::default() .level(log::LevelFilter::Info) .max_file_size(MAX_LOG_FILE_SIZE) .rotation_strategy(RotationStrategy::KeepSome(ROTATED_LOG_COUNT)) .file_open_strategy(FileOpenStrategy::Append) + .clear_targets() + .target(Target::new(TargetKind::Stdout)) + .target(Target::new(TargetKind::LogDir { file_name: None }).filter(file_log_record_allowed)) } pub fn setup(app: &AppHandle) -> Result<(), Box> { @@ -27,3 +46,68 @@ pub fn setup(app: &AppHandle) -> Result<(), Box bool { + let metadata = log::Metadata::builder().target(target).level(level).build(); + file_log_record_allowed(&metadata) + } + + #[test] + fn reviewed_targets_keep_verbose_levels() { + for target in [ + "app_lib", + "app_lib::desktop::diagnostics", + "app_lib::network::loopback_http", + "sable", + "tauri", + "tauri::manager", + "tauri_runtime_cef", + "tauri_runtime_cef::cef_impl::ipc", + "tauri_runtime_wry", + "tauri_plugin_updater", + "tauri_plugin_window_state", + tauri_plugin_log::WEBVIEW_TARGET, + ] { + assert!(is_reviewed_verbose_target(target), "expected {target}"); + for level in [log::Level::Info, log::Level::Debug, log::Level::Trace] { + assert!(allowed(target, level), "{level} from {target} dropped"); + } + } + } + + #[test] + fn noisy_dependency_targets_are_suppressed_below_warn() { + for target in [ + "reqwest", + "reqwest::connect", + "hyper::client::pool", + "rustls::client", + "tokio", + "mio", + "tracing", + "cef", + "tao", + "wry", + "webkit2gtk", + "soup3", + "taurine", // similar-looking prefixes must not match + "sablefish::module", + ] { + for level in [log::Level::Info, log::Level::Debug, log::Level::Trace] { + assert!(!allowed(target, level), "{level} from {target} kept"); + } + } + } + + #[test] + fn dependency_warnings_and_errors_are_kept() { + for target in ["reqwest", "hyper::client", "rustls", "cef", "unknown_crate"] { + assert!(allowed(target, log::Level::Warn), "{target} warn dropped"); + assert!(allowed(target, log::Level::Error), "{target} error dropped"); + } + } +} diff --git a/src/app/features/settings/developer-tools/DebugLogViewer.tsx b/src/app/features/settings/developer-tools/DebugLogViewer.tsx index 9d5a1d903..d9846d6aa 100644 --- a/src/app/features/settings/developer-tools/DebugLogViewer.tsx +++ b/src/app/features/settings/developer-tools/DebugLogViewer.tsx @@ -1,5 +1,5 @@ import type { MouseEventHandler } from 'react'; -import { useEffect, useState, useCallback, useMemo } from 'react'; +import { useEffect, useState, useCallback, useMemo, useRef } from 'react'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; import type { RectCords } from 'folds'; import { Box, Text, Button, color, config, Badge, Menu, MenuItem, PopOut } from 'folds'; @@ -138,11 +138,12 @@ export function DebugLogViewer() { const logs = useAtomValue(debugLogsAtom); const clearLogs = useSetAtom(clearDebugLogsAtom); const [autoScroll, setAutoScroll] = useState(true); - const scrollRef = useState(null)[0]; + const scrollRef = useRef(null); const [filterLevel, setFilterLevel] = useState('all'); const [filterCategory, setFilterCategory] = useState('all'); const [categoryAnchor, setCategoryAnchor] = useState(); const [levelAnchor, setLevelAnchor] = useState(); + const refreshLogs = useSetAtom(debugLogsAtom); const handleOpenCategoryMenu: MouseEventHandler = (evt) => { evt.stopPropagation(); @@ -173,19 +174,18 @@ export function DebugLogViewer() { const debugLogger = getDebugLogger(); const unsubscribe = debugLogger.addListener(() => { - // Trigger re-render by refreshing the atom - // This will be handled by the debugLogsAtom's refresh mechanism + refreshLogs(); }); return unsubscribe; - }, [enabled]); + }, [enabled, refreshLogs]); // Auto-scroll to bottom when new logs arrive useEffect(() => { - if (autoScroll && scrollRef) { - scrollRef.scrollTop = scrollRef.scrollHeight; + if (autoScroll && scrollRef.current) { + scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } - }, [filteredLogs, autoScroll, scrollRef]); + }, [filteredLogs, autoScroll]); const handleExportLogs = useCallback( (filtered: boolean) => { @@ -597,6 +597,7 @@ export function DebugLogViewer() { ('idle'); + const [captureActive, setCaptureActive] = useAtom(diagnosticCaptureActiveAtom); + const [captureSince, setCaptureSince] = useState(); + const [captureCompleted, setCaptureCompleted] = useState(false); + const [exportDestination, setExportDestination] = useState(); const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN); @@ -1296,10 +1301,25 @@ function DiagnosticsAndPrivacy() { setNeedsRefresh(true); }; - const handleDiagnosticsExport = async () => { + const handleDiagnosticsCapture = async () => { + if (!captureActive && !captureCompleted) { + const since = getDebugLogger().startCapture(); + setCaptureSince(since); + setCaptureActive(true); + setDiagnosticsState('idle'); + setExportDestination(undefined); + return; + } + setDiagnosticsState('exporting'); try { - const frontendLogs = getDebugLogger().exportLogs(); + const since = captureSince ?? getDebugLogger().getCaptureSince(); + if (captureActive) { + getDebugLogger().stopCapture(); + setCaptureActive(false); + setCaptureCompleted(true); + } + const frontendLogs = getDebugLogger().exportLogs({ since }); if (isDesktopTauri()) { const outputPath = await invoke('export_diagnostics', { frontendLogs, @@ -1308,6 +1328,7 @@ function DiagnosticsAndPrivacy() { setDiagnosticsState('idle'); return; } + setExportDestination(outputPath); } else if (isMobileTauri()) { const zipBytes = await invoke('export_diagnostics', { frontendLogs, @@ -1335,11 +1356,30 @@ function DiagnosticsAndPrivacy() { downloadJsonFile(sanitizedLogs, 'sable-web-diagnostics'); } setDiagnosticsState('success'); + setCaptureCompleted(false); + setCaptureSince(undefined); } catch { setDiagnosticsState('error'); } }; + const handleDiscardCapture = () => { + getDebugLogger().clear(); + setCaptureCompleted(false); + setCaptureSince(undefined); + setExportDestination(undefined); + setDiagnosticsState('idle'); + }; + + const handleStartNewCapture = () => { + const since = getDebugLogger().startCapture(); + setCaptureSince(since); + setCaptureActive(true); + setCaptureCompleted(false); + setDiagnosticsState('idle'); + setExportDestination(undefined); + }; + return ( Diagnostics & Privacy @@ -1402,31 +1442,33 @@ function DiagnosticsAndPrivacy() { gap="300" > {diagnosticsState === 'exporting' ? 'Exporting…' - : isDesktopTauri() || isMobileTauri() - ? 'Export ZIP' - : 'Export JSON'} + : captureActive + ? 'Stop & Export' + : captureCompleted + ? 'Export Capture' + : 'Start Capture'} } @@ -1434,7 +1476,7 @@ function DiagnosticsAndPrivacy() { {diagnosticsState === 'success' && ( {isDesktopTauri() - ? 'Diagnostics ZIP exported with content redacted where possible. Review it before sharing.' + ? `Diagnostics ZIP saved to ${exportDestination ?? 'the selected destination'}. It includes frontend and native logs. Review it before sharing.` : isMobileTauri() ? 'Diagnostics ZIP saved with content redacted where possible. Review it before sharing.' : 'Frontend diagnostics downloaded with content redacted where possible. Review it before sharing.'} @@ -1445,6 +1487,28 @@ function DiagnosticsAndPrivacy() { Could not export diagnostics. Please try again. )} + {captureCompleted && diagnosticsState !== 'exporting' && ( + + + + + )} )} diff --git a/src/app/features/settings/settingsLink.ts b/src/app/features/settings/settingsLink.ts index bb5fd1d6a..ef4d0d1d9 100644 --- a/src/app/features/settings/settingsLink.ts +++ b/src/app/features/settings/settingsLink.ts @@ -51,6 +51,7 @@ export const settingsLinkFocusIdsBySection: Record { + if (active && !debugLogger.isCaptureActive()) debugLogger.startCapture(); + if (!active && debugLogger.isCaptureActive()) debugLogger.stopCapture(); + set(diagnosticCaptureActiveAtom, active); + set(debugLogsAtom); + } +); + /** * Action to clear all debug logs */ diff --git a/src/app/utils/debugLogger.test.ts b/src/app/utils/debugLogger.test.ts index 261d5f283..d3606139c 100644 --- a/src/app/utils/debugLogger.test.ts +++ b/src/app/utils/debugLogger.test.ts @@ -6,6 +6,10 @@ vi.mock('@sentry/react', () => ({ addBreadcrumb: vi.fn<(...args: unknown[]) => void>(), captureException: vi.fn<(...args: unknown[]) => void>(), captureMessage: vi.fn<(...args: unknown[]) => void>(), + getCurrentScope: () => ({ + setExtra: vi.fn(), + addAttachment: vi.fn(), + }), logger: { debug: vi.fn<(...args: unknown[]) => void>(), info: vi.fn<(...args: unknown[]) => void>(), @@ -13,6 +17,7 @@ vi.mock('@sentry/react', () => ({ error: vi.fn<(...args: unknown[]) => void>(), }, metrics: { count: vi.fn<(...args: unknown[]) => void>() }, + setContext: vi.fn(), })); describe('DebugLoggerService', () => { @@ -23,8 +28,8 @@ describe('DebugLoggerService', () => { debugLogger.setEnabled(false); }); - it('stores normal events for local export without sending them to Sentry when disabled', () => { - createDebugLogger('test').info('general', 'normal event'); + it('stores operational warnings for local export without sending them to Sentry when disabled', () => { + createDebugLogger('test').warn('sync', 'normal event'); const exported = JSON.parse(getDebugLogger().exportLogs()) as { logsCount: number; @@ -33,9 +38,86 @@ describe('DebugLoggerService', () => { expect(exported.logsCount).toBe(1); expect(exported.logs).toEqual([ - expect.objectContaining({ level: 'info', message: 'normal event' }), + expect.objectContaining({ level: 'warn', message: 'normal event' }), ]); expect(Sentry.addBreadcrumb).not.toHaveBeenCalled(); - expect(Sentry.logger.info).not.toHaveBeenCalled(); + expect(Sentry.logger.warn).not.toHaveBeenCalled(); + }); +}); + +describe('debug logger diagnostic capture', () => { + const logger = getDebugLogger(); + + beforeEach(() => { + logger.stopCapture(); + logger.setEnabled(false); + logger.clear(); + }); + + it('keeps the default buffer bounded to errors and operational warnings', () => { + logger.log('info', 'general', 'test', 'verbose event'); + logger.log('warn', 'ui', 'test', 'low signal warning'); + logger.log('warn', 'sync', 'test', 'sync warning'); + logger.log('error', 'ui', 'test', 'error event'); + + expect(logger.getLogs().map((entry) => entry.message)).toEqual(['sync warning', 'error event']); + }); + + it('clears old entries and captures verbose events only during an explicit session', () => { + logger.log('error', 'error', 'test', 'before capture'); + const since = logger.startCapture(); + logger.log('info', 'general', 'test', 'during capture'); + logger.stopCapture(); + + expect(logger.getFilteredLogs({ since })).toEqual( + expect.arrayContaining([ + expect.objectContaining({ message: 'Diagnostic capture started' }), + expect.objectContaining({ message: 'during capture' }), + expect.objectContaining({ message: 'Diagnostic capture stopped' }), + ]) + ); + expect(logger.getLogs().some((entry) => entry.message === 'before capture')).toBe(false); + }); + + it('sanitizes entries before storing them in memory', () => { + logger.log('error', 'network', 'test', 'request https://matrix.example/@alice:example.org', { + access_token: 'secret', + data: 'private payload', + }); + + const stored = JSON.stringify(logger.getLogs()); + expect(stored).not.toContain('secret'); + expect(stored).not.toContain('matrix.example'); + expect(stored).not.toContain('private payload'); + expect(logger.getLogs()[0]?.data).toBeUndefined(); + }); + + it.each([ + [ + 'circular values', + () => { + const value: Record = {}; + value.self = value; + return value; + }, + ], + ['BigInts', () => 1n], + ])('does not throw for %s', (_, createValue) => { + expect(() => logger.log('error', 'error', 'test', 'unsafe value', createValue())).not.toThrow(); + expect(logger.getLogs()).toHaveLength(1); + }); + + it('preserves the original Error for Sentry exception capture', async () => { + const Sentry = await import('@sentry/react'); + const error = new Error('original error'); + + logger.log('error', 'error', 'test', 'request failed', error); + + expect(Sentry.captureException).toHaveBeenCalledWith( + error, + expect.objectContaining({ level: 'error' }) + ); + expect(logger.getLogs()[0]?.data).toBe(error); + expect(() => logger.exportLogs()).not.toThrow(); }); }); diff --git a/src/app/utils/debugLogger.ts b/src/app/utils/debugLogger.ts index 55e84420d..568881d3e 100644 --- a/src/app/utils/debugLogger.ts +++ b/src/app/utils/debugLogger.ts @@ -7,7 +7,7 @@ import * as Sentry from '@sentry/react'; import { versionLabel } from '$utils/platform'; -import { sanitizeSentryPayload } from './sentryScrubbers'; +import { sanitizeDiagnosticsLogs, sanitizeSentryPayload } from './sentryScrubbers'; export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; @@ -42,6 +42,10 @@ class DebugLoggerService { private enabled = false; + private captureActive = false; + + private captureSince: number | undefined; + private listeners: Set = new Set(); private disabledBreadcrumbCategories: Set; @@ -75,6 +79,29 @@ class DebugLoggerService { } } + public isCaptureActive(): boolean { + return this.captureActive; + } + + public getCaptureSince(): number | undefined { + return this.captureSince; + } + + public startCapture(): number { + this.clear(); + this.captureActive = true; + this.captureSince = Date.now(); + this.log('info', 'general', 'diagnostics', 'Diagnostic capture started'); + return this.captureSince; + } + + public stopCapture(): number | undefined { + if (!this.captureActive) return this.captureSince; + this.log('info', 'general', 'diagnostics', 'Diagnostic capture stopped'); + this.captureActive = false; + return this.captureSince; + } + public addListener(listener: LogListener): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); @@ -98,7 +125,21 @@ class DebugLoggerService { message: string, data?: unknown ): void { - const entry: LogEntry = { + const operationalCategory = + category === 'sync' || + category === 'network' || + category === 'notification' || + category === 'call' || + category === 'error'; + if ( + !this.enabled && + !this.captureActive && + level !== 'error' && + !(operationalCategory && level === 'warn') + ) + return; + + const rawEntry: LogEntry = { timestamp: Date.now(), level, category, @@ -106,6 +147,16 @@ class DebugLoggerService { message, data, }; + // Omit arbitrary data before serialization; it may be circular or contain BigInts. + const sanitized = sanitizeDiagnosticsLogs( + JSON.stringify({ logs: [{ ...rawEntry, data: undefined }] }) + ); + if (!sanitized) return; + const parsed = JSON.parse(sanitized) as { logs?: LogEntry[] }; + const entry = parsed.logs?.[0]; + if (!entry) return; + // Preserve the original Error for Sentry exception capture. + if (rawEntry.data instanceof Error) entry.data = rawEntry.data; // Add to circular buffer if (this.logs.length >= this.maxLogs) { @@ -162,7 +213,15 @@ class DebugLoggerService { }; const sentryLevel: Sentry.SeverityLevel = sentryLevelMap[entry.level] ?? 'error'; - const sanitizedData = entry.data !== undefined ? sanitizeSentryPayload(entry.data) : undefined; + let sanitizedData: unknown; + if (entry.data !== undefined && !(entry.data instanceof Error)) { + try { + sanitizedData = sanitizeSentryPayload(entry.data); + } catch { + // Sentry data is best-effort and must not break logging. + sanitizedData = undefined; + } + } // Add breadcrumb for all logs (helps with debugging in Sentry), unless category is disabled if (!this.disabledBreadcrumbCategories.has(entry.category)) @@ -289,14 +348,16 @@ class DebugLoggerService { this.logs = []; } - public exportLogs(): string { + public exportLogs(options?: { since?: number }): string { + const logs = options?.since ? this.getFilteredLogs({ since: options.since }) : this.logs; return JSON.stringify( { exportedAt: new Date().toISOString(), build: versionLabel({ includeNightly: false }), - logsCount: this.logs.length, - logs: this.logs.map((log) => ({ + logsCount: logs.length, + logs: logs.map((log) => ({ ...log, + ...(log.data instanceof Error ? { data: undefined } : {}), timestamp: new Date(log.timestamp).toISOString(), })), }, @@ -344,8 +405,8 @@ class DebugLoggerService { // Also add as extra data for better visibility in Sentry UI Sentry.getCurrentScope().setExtra('debugLogs', logsData); - // Add as attachment for download const logsText = JSON.stringify(logsData, null, 2); + // Add as attachment for download Sentry.getCurrentScope().addAttachment({ filename: 'debug-logs.json', data: logsText,