From b544fcea4a4a5e7b2c4e3e7803289dac233de500 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 14:48:25 -0800 Subject: [PATCH] feat(mobile): add a diagnostics test report and test crash to Settings (#9676) A way to check that a build's diagnostic reporting works end to end, per [mobile diagnostic reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md). A build with a reporting destination shows a Diagnostics card in Settings with **Send test report** and **Test crash**. A build without one, which includes every build from this repository alone, never shows it and still reports nothing. | Before | After | | --- | --- | | ![Settings bottom, before](https://github.com/user-attachments/assets/92fdef05-8d63-43db-8df1-32ccb92105c8) | ![Settings bottom with the Diagnostics card](https://github.com/user-attachments/assets/a205ab18-ed1e-49d5-8e34-88e29e4c91fa) | ![Test crash confirmation](https://github.com/user-attachments/assets/335eb362-3a61-4c8c-8b32-44de548cf788) ### What's in it - The reporter gains `reporting` (whether the build has a destination), `sendTestReport()` and `crashForTest()`. The do-nothing reporter returns false and does nothing. - **Send test report** sends a fixed `DiagnosticTestError` tagged with a new `testReport` operation. It passes through the same filter as every report. - **Test crash** asks for confirmation, then crashes in native code through the SDK, so native crash reports can be checked too. The report goes out the next time the app opens. - The spec gains a "A way to check a build" decision. ### Regressions None expected: builds without a destination render Settings exactly as before. ### Validation Added widget tests for the card being absent without reporting, sending a test report, and the crash happening only once confirmed, plus a test of what a sent test report contains and one that a second tap sends a second report. The screenshots come from simulator builds of main and this branch, both with the same placeholder destination. A full-app simulator run at dec267f (placeholder destination) passed: channel list, opening and scrolling a channel, search, the other Settings sections, two test reports (a toast each time), cancelling Test crash, confirming it (a native crash in the Sentry SDK) and relaunching signed in. --------- Signed-off-by: Tom Brow Co-authored-by: studio --- docs/mobile-diagnostic-reporting.md | 1 + .../lib/features/settings/settings_page.dart | 5 + .../settings_page/diagnostics_section.dart | 44 ++++++++ .../diagnostics/diagnostic_reporter.dart | 31 ++++++ .../sentry_diagnostic_reporter.dart | 13 +++ .../settings/settings_diagnostics_test.dart | 101 ++++++++++++++++++ .../diagnostic_reporting_test.dart | 32 +++++- 7 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 mobile/lib/features/settings/settings_page/diagnostics_section.dart create mode 100644 mobile/test/features/settings/settings_diagnostics_test.dart diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index bb38d8d4a9..12bbf69cd7 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -52,6 +52,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - **Main-thread hangs** are captured by the SDK's own hang detection, at the SDK's default thresholds. The app's Dart code runs on the platform's main thread, so Dart work that blocks it shows up here. On iOS, the SDK reports the main thread being blocked, fully or mostly, for 2 seconds or more while the app is active, with the main thread's stack taken during the hang, including freezes the app recovers from. A hang that is still going when the app is killed, for example by the system watchdog, is sent on the next launch as a fatal hang. The SDK's separate watchdog-termination tracking also reports, on the next launch, a run that ended while the app was in the foreground with nothing else to explain it; it never reports on simulators or for kills in the background. App hang detection is off while a debugger is attached ([sentry-cocoa 9.35.0](https://github.com/getsentry/sentry-cocoa/blob/9.35.0/Sources/Swift/Integrations/AppHangTracking/SentryHangTrackingIntegration.swift)). On Android the SDK reports only freezes the system itself declared "app not responding". On Android 11 and later it reports only one that ended the process, read from the system's exit records on the next launch: the most recent unreported one, and only when the system kept a usable thread dump. Before Android 11 it reports when the main thread has been blocked for 5 seconds and the system has marked the app not responding, never with a debugger attached ([sentry-java 8.64.0](https://github.com/getsentry/sentry-java/blob/8.64.0/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegrationFactory.java)). So with these defaults, a freeze the app recovers from is reported on iOS, and on Android only before Android 11 and only once the system has marked the app not responding. Dart frames in a hang's stack are readable only with the Dart code's debug symbols at the destination, the same as for crashes. - **Native reports skip that filter.** Native crashes and app hangs are captured and sent by the native SDKs, which never call the Dart filter. They carry stack traces and, for a native exception, its reason text. No app code puts content in a native exception today, and the SDK's native network breadcrumbs, which would carry request addresses, are off. - **Readable stack traces** need the build's debug symbols at the destination. Uploading them belongs to the release process of whoever distributes the build; this repository documents the requirement and adds nothing organization-specific. +- **A way to check a build.** A build that reports shows a Diagnostics card in Settings with two actions: send a test report (a fixed test error with its own operation, through the same filter as every report) and a test crash in native code, behind a confirmation. A build without a destination never shows it. Whoever distributes a reporting build can then confirm, before relying on it, that reports arrive with readable stack traces. - **Both platforms.** Step one covers the main app on iOS and Android. Background work that runs the app's Dart code in its own engine, as decided for Android push handling in [ADR 0006](adr/0006-android-notifications-run-app-dart-code.md), starts the reporting module the same way once it exists. Dart errors are captured in the main app's Flutter engine only: the iOS sheets that start their own engine (channel settings and the profile photo editor) are not covered, though native crashes while they are open still are. - **Reporting never blocks the app.** A call into the reporting module returns at once and nothing waits on the destination. A failure inside reporting is dropped and never reaches the code that made the call. diff --git a/mobile/lib/features/settings/settings_page.dart b/mobile/lib/features/settings/settings_page.dart index ef3c680932..44428df9f0 100644 --- a/mobile/lib/features/settings/settings_page.dart +++ b/mobile/lib/features/settings/settings_page.dart @@ -18,6 +18,8 @@ import 'package:url_launcher/url_launcher.dart'; import '../../shared/auth/auth.dart'; import '../../shared/identity_transfer/nsec_export_sheet.dart'; import '../../shared/clipboard_utils.dart'; +import '../../shared/diagnostics/diagnostic_reporter.dart'; +import '../../shared/widgets/confirmation_dialog.dart'; import '../../shared/hosted/hosted_environment.dart'; import '../../shared/hosted/sign_out.dart'; import '../../shared/push/push_relay_capability_provider.dart'; @@ -40,6 +42,7 @@ part 'settings_page/status_section.dart'; part 'settings_page/connection_section.dart'; part 'settings_page/notifications_section.dart'; part 'settings_page/builderlab_account_section.dart'; +part 'settings_page/diagnostics_section.dart'; Widget _emptyProfileEditPage(BuildContext context) => const SizedBox.shrink(); @@ -245,6 +248,8 @@ class SettingsPage extends HookConsumerWidget { ], if (!wide && HostedEnvironment.enabled) const _BuilderlabAccountSection(), + if (ref.watch(diagnosticReporterProvider).reporting) + const _DiagnosticsSection(), // Rarely needed, so it sits last. AppListCard( verticalPadding: Grid.twelve, diff --git a/mobile/lib/features/settings/settings_page/diagnostics_section.dart b/mobile/lib/features/settings/settings_page/diagnostics_section.dart new file mode 100644 index 0000000000..4818794638 --- /dev/null +++ b/mobile/lib/features/settings/settings_page/diagnostics_section.dart @@ -0,0 +1,44 @@ +part of '../settings_page.dart'; + +/// Checks that a build's diagnostic reporting works end to end. Shown only +/// in builds with a reporting destination, the internal dogfood builds. +class _DiagnosticsSection extends ConsumerWidget { + const _DiagnosticsSection(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final reporter = ref.watch(diagnosticReporterProvider); + return AppListCard( + verticalPadding: Grid.twelve, + children: [ + AppListRow( + key: const Key('settings-send-test-report'), + title: 'Send test report', + onTap: () { + reporter.sendTestReport(); + ScaffoldMessenger.of(context).showFeedbackSnackBar( + const SnackBar(content: Text('Test report sent.')), + kind: ToastKind.success, + ); + }, + ), + AppListRow( + key: const Key('settings-test-crash'), + title: 'Test crash', + titleColor: context.colors.error, + onTap: () async { + final confirmed = await showDestructiveConfirmation( + context: context, + title: 'Crash Buzz?', + message: + 'Buzz closes at once. The crash report is sent the next ' + 'time you open it.', + confirmLabel: 'Crash', + ); + if (confirmed) reporter.crashForTest(); + }, + ), + ], + ); + } +} diff --git a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart index 61a2c40794..5b43be168c 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart @@ -22,6 +22,27 @@ abstract interface class DiagnosticReporter { /// Attributes later reports and counts to [pubkey], or to no one. void setMember(String? pubkey); + + /// Whether this build has a reporting destination. Only then does Settings + /// offer the checks below. + bool get reporting; + + /// Sends a [DiagnosticTestError], to check a build's reporting end to end. + void sendTestReport(); + + /// Crashes the app in native code, to check native crash reports. + void crashForTest(); +} + +/// The error a test report carries, so it is easy to tell apart. +/// +/// Not const: each report needs its own instance, or the destination's +/// deduplication drops every report after the first. +class DiagnosticTestError implements Exception { + DiagnosticTestError(); + + @override + String toString() => 'DiagnosticTestError'; } /// Where an explicit error report comes from. @@ -33,6 +54,7 @@ enum DiagnosticOperation { pushGatewayResponse, storedData, eventSubscriber, + testReport, } /// The operation a networking event belongs to. @@ -99,6 +121,15 @@ class NoopDiagnosticReporter implements DiagnosticReporter { @override void setMember(String? pubkey) {} + + @override + bool get reporting => false; + + @override + void sendTestReport() {} + + @override + void crashForTest() {} } /// The reporter chosen at startup. The root scope overrides it; tests diff --git a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart index e82a1b41a4..9e90ea3f80 100644 --- a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart @@ -73,6 +73,19 @@ class SentryDiagnosticReporter implements DiagnosticReporter { ), ); + @override + bool get reporting => true; + + @override + void sendTestReport() => reportError( + DiagnosticTestError(), + StackTrace.current, + operation: DiagnosticOperation.testReport, + ); + + @override + void crashForTest() => _drop(SentryFlutter.nativeCrash); + static Map _attributes(NetworkEvent event) => { 'backend': SentryAttribute.string(event.backend), 'endpoint': SentryAttribute.string(event.endpoint.name), diff --git a/mobile/test/features/settings/settings_diagnostics_test.dart b/mobile/test/features/settings/settings_diagnostics_test.dart new file mode 100644 index 0000000000..ee74c07899 --- /dev/null +++ b/mobile/test/features/settings/settings_diagnostics_test.dart @@ -0,0 +1,101 @@ +import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/shared/community/community_membership_provider.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + Future pumpSettings( + WidgetTester tester, + DiagnosticReporter reporter, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 1400); + addTearDown(tester.view.reset); + PackageInfo.setMockInitialValues( + appName: 'Buzz', + packageName: 'xyz.block.buzz', + version: '0.16.0', + buildNumber: '432', + buildSignature: '', + ); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + currentCommunityRoleProvider.overrideWithValue( + const AsyncData(CommunityMemberRole.member), + ), + diagnosticReporterProvider.overrideWithValue(reporter), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: SettingsPage( + profileHeader: const SizedBox.shrink(), + identityRecoveryPageBuilder: (_) => const SizedBox.shrink(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + final sendRow = find.byKey(const Key('settings-send-test-report')); + final crashRow = find.byKey(const Key('settings-test-crash')); + + testWidgets('a build without reporting offers no checks', (tester) async { + await pumpSettings(tester, const NoopDiagnosticReporter()); + + expect(sendRow, findsNothing); + expect(crashRow, findsNothing); + }); + + testWidgets('a reporting build sends a test report', (tester) async { + final reporter = _RecordingReporter(); + await pumpSettings(tester, reporter); + + await tester.ensureVisible(sendRow); + await tester.tap(sendRow); + await tester.pump(); + + expect(reporter.calls, ['sendTestReport']); + expect(find.text('Test report sent.'), findsOneWidget); + }); + + testWidgets('a test crash happens only once confirmed', (tester) async { + final reporter = _RecordingReporter(); + await pumpSettings(tester, reporter); + + await tester.ensureVisible(crashRow); + await tester.tap(crashRow); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(reporter.calls, isEmpty); + + await tester.tap(crashRow); + await tester.pumpAndSettle(); + await tester.tap(find.text('Crash')); + await tester.pumpAndSettle(); + expect(reporter.calls, ['crashForTest']); + }); +} + +class _RecordingReporter extends NoopDiagnosticReporter { + final calls = []; + + @override + bool get reporting => true; + + @override + void sendTestReport() => calls.add('sendTestReport'); + + @override + void crashForTest() => calls.add('crashForTest'); +} diff --git a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart index e01284d71c..9d57b00891 100644 --- a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart +++ b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart @@ -14,6 +14,8 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:nostr/nostr.dart' as nostr; +// ignore: depend_on_referenced_packages, implementation_imports +import 'package:sentry/src/deduplication/deduplication_event_processor.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; // The SDK's own processors and integrations, so tests see what it really // sends rather than hand-built events. @@ -154,10 +156,11 @@ void main() { transport = _MemoryTransport(); options = SentryFlutterOptions(); configureDiagnostics(options, 'https://key@example.org/1'); - // The processors SentryFlutter.init installs, in its order. + // The processors Sentry.init and SentryFlutter.init install. options ..transport = transport ..sendClientReports = false + ..addEventProcessor(DeduplicationEventProcessor(options)) ..addEventProcessor(FlutterExceptionEventProcessor()) ..addEventProcessor(FlutterEnricherEventProcessor(options)) ..addEventProcessor(WidgetEventProcessor()) @@ -206,6 +209,26 @@ void main() { expect(transport.events.single['user']['id'], 'a' * 64); }); + test('a test report is a test error from the test operation', () async { + SentryDiagnosticReporter(hub: hub).sendTestReport(); + await transport.first(); + + final sent = transport.events.single; + final exception = (sent['exception']['values'] as List).last as Map; + expect(exception['type'], 'DiagnosticTestError'); + expect(exception['stacktrace'], isNotNull); + expect(sent['tags']['operation'], 'testReport'); + }); + + test('every test report is sent, not only the first', () async { + SentryDiagnosticReporter(hub: hub) + ..sendTestReport() + ..sendTestReport(); + await transport.count(2); + + expect(transport.events, hasLength(2)); + }); + testWidgets('sends only the allowed contexts', (tester) async { tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(accessibleNavigation: true); @@ -447,9 +470,15 @@ class _ReleaseChecker extends RuntimeChecker { class _MemoryTransport implements Transport { final events = >[]; final _first = Completer(); + final _added = StreamController.broadcast(); Future first() => _first.future; + Future count(int n) async { + if (events.length >= n) return; + await _added.stream.firstWhere((_) => events.length >= n); + } + @override Future send(SentryEnvelope envelope) async { for (final item in envelope.items) { @@ -457,6 +486,7 @@ class _MemoryTransport implements Transport { final bytes = await item.dataFactory(); events.add(jsonDecode(utf8.decode(bytes)) as Map); if (!_first.isCompleted) _first.complete(); + _added.add(null); } return envelope.header.eventId; }