feat(diagnostics): add capture workflow

This commit is contained in:
Erwan Leboucher committed 2026-07-30 08:34:15 +02:00
1 parent d0caffc1a9
commit 09b1430dcb
7 files changed
+340 -37

No files matched your search

+85 -1
View File
@@ -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<crate::BrowserEngine>) -> Result<(), Box<dyn std::error::Error>> {
@@ -27,3 +46,68 @@ pub fn setup(app: &AppHandle<crate::BrowserEngine>) -> Result<(), Box<dyn std::e
Ok(())
}
#[cfg(test)]
mod tests {
use super::{file_log_record_allowed, is_reviewed_verbose_target};
fn allowed(target: &str, level: log::Level) -> 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");
}
}
}
@@ -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<HTMLDivElement | null>(null)[0];
const scrollRef = useRef<HTMLDivElement | null>(null);
const [filterLevel, setFilterLevel] = useState<LogLevel | 'all'>('all');
const [filterCategory, setFilterCategory] = useState<LogCategory | 'all'>('all');
const [categoryAnchor, setCategoryAnchor] = useState<RectCords | undefined>();
const [levelAnchor, setLevelAnchor] = useState<RectCords | undefined>();
const refreshLogs = useSetAtom(debugLogsAtom);
const handleOpenCategoryMenu: MouseEventHandler<HTMLButtonElement> = (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() {
</Box>
<Box
ref={scrollRef}
direction="Column"
gap="200"
style={{
+81 -17
View File
@@ -7,7 +7,7 @@ import type {
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { isTauri, invoke } from '@tauri-apps/api/core';
import dayjs from 'dayjs';
import { useAtomValue, useSetAtom } from 'jotai';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import type { RectCords } from 'folds';
import {
Box,
@@ -64,6 +64,7 @@ import { sessionsAtom, activeSessionIdAtom } from '$state/sessions';
import { isKeyHotkey } from 'is-hotkey';
import { settingsSyncLastSyncedAtom, settingsSyncStatusAtom } from '$hooks/useSettingsSync';
import { sanitizeDiagnosticsLogs } from '$utils/sentryScrubbers';
import { diagnosticCaptureActiveAtom } from '$state/debugLogger';
import { exportSettingsAsJson, importSettingsFromJson } from '$utils/settingsSync';
import { saveFileToDevice } from '$utils/download';
import { CallSoundSettings } from './CallSoundSettings';
@@ -1273,6 +1274,10 @@ function DiagnosticsAndPrivacy() {
const [diagnosticsState, setDiagnosticsState] = useState<
'idle' | 'exporting' | 'success' | 'error'
>('idle');
const [captureActive, setCaptureActive] = useAtom(diagnosticCaptureActiveAtom);
const [captureSince, setCaptureSince] = useState<number>();
const [captureCompleted, setCaptureCompleted] = useState(false);
const [exportDestination, setExportDestination] = useState<string>();
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<string | null | undefined>('export_diagnostics', {
frontendLogs,
@@ -1308,6 +1328,7 @@ function DiagnosticsAndPrivacy() {
setDiagnosticsState('idle');
return;
}
setExportDestination(outputPath);
} else if (isMobileTauri()) {
const zipBytes = await invoke<number[] | Uint8Array>('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 (
<Box direction="Column" gap="100">
<Text size="L400">Diagnostics & Privacy</Text>
@@ -1402,31 +1442,33 @@ function DiagnosticsAndPrivacy() {
gap="300"
>
<SettingTile
title="Export Diagnostics"
focusId="export-diagnostics"
title="Capture Diagnostics"
focusId="capture-diagnostics"
description={
isDesktopTauri()
? 'Export a ZIP containing recent app logs and basic system information, redacted where possible. Review the ZIP before sharing it.'
: isMobileTauri()
? 'Save a ZIP containing recent app logs and basic system information, redacted where possible. Review the ZIP before sharing it.'
: 'Download a frontend-only JSON file containing recent app logs, redacted where possible. Review it before sharing it.'
captureActive
? 'Capture is active. Reproduce the problem, then stop and export the report.'
: captureCompleted
? 'Your completed capture is ready to export. You can retry the export or discard it.'
: 'Start a short, privacy-reviewed capture of errors and useful app activity. Nothing is uploaded automatically.'
}
after={
<Button
variant="Secondary"
variant={captureActive ? 'Critical' : 'Secondary'}
fill="Soft"
size="300"
radii="300"
before={menuIcon(Download)}
onClick={handleDiagnosticsExport}
before={captureActive ? undefined : menuIcon(Download)}
onClick={handleDiagnosticsCapture}
disabled={diagnosticsState === 'exporting'}
>
<Text size="B300">
{diagnosticsState === 'exporting'
? 'Exporting…'
: isDesktopTauri() || isMobileTauri()
? 'Export ZIP'
: 'Export JSON'}
: captureActive
? 'Stop & Export'
: captureCompleted
? 'Export Capture'
: 'Start Capture'}
</Text>
</Button>
}
@@ -1434,7 +1476,7 @@ function DiagnosticsAndPrivacy() {
{diagnosticsState === 'success' && (
<Text size="T200" style={{ color: 'var(--mx-color-positive-container-on)' }}>
{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.
</Text>
)}
{captureCompleted && diagnosticsState !== 'exporting' && (
<Box gap="200" wrap="Wrap">
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={handleStartNewCapture}
>
<Text size="B300">Start New Capture</Text>
</Button>
<Button
variant="Secondary"
fill="Soft"
size="300"
radii="300"
onClick={handleDiscardCapture}
>
<Text size="B300">Discard Capture</Text>
</Button>
</Box>
)}
</SequenceCard>
)}
<Box gap="200" wrap="Wrap" style={{ paddingTop: '4px' }}>
@@ -51,6 +51,7 @@ export const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly s
'right-aligned-bubbles',
'right-swipe-action',
'session-replay',
'capture-diagnostics',
'show-hidden-events',
'hidden-event-edits',
'show-redacted-message-tombstones',
+10
View File
@@ -24,6 +24,16 @@ export const debugLoggerEnabledAtom = atom(
}
);
export const diagnosticCaptureActiveAtom = atom(
debugLogger.isCaptureActive(),
(_, set, active: boolean) => {
if (active && !debugLogger.isCaptureActive()) debugLogger.startCapture();
if (!active && debugLogger.isCaptureActive()) debugLogger.stopCapture();
set(diagnosticCaptureActiveAtom, active);
set(debugLogsAtom);
}
);
/**
* Action to clear all debug logs
*/
+86 -4
View File
@@ -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<string, unknown> = {};
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();
});
});
+68 -7
View File
@@ -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<LogListener> = new Set();
private disabledBreadcrumbCategories: Set<LogCategory>;
@@ -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,