diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index 48c2d46571..478269972b 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -20,7 +20,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat 4. As a developer, I want a report when the relay rejects something the app sent as invalid, so that client bugs in what we send are found. 5. As a developer, I want a report when a Builderlab or push gateway response cannot be understood, so that contract drift is caught. 6. As a developer, I want a report when data saved on the device cannot be read back, so that storage corruption and migration bugs surface. -7. As a developer, I want each report to carry the trail of recent networking events, so that I can see what the connection was doing before the fault. +7. As a developer, I want each report to carry the trail of recent networking events and the screens the person was on, so that I can see what the connection was doing and where the person was before the fault. 8. As a developer, I want each report to carry the member's public key, so that I can follow up with the person who hit it. 9. As a developer, I want timeouts, disconnects, being offline, rate limits and refused sign-ins counted and not reported as errors, so that the error list contains only bugs someone can fix. 10. As a developer, I want every network request and relay connection event counted with its backend, endpoint, outcome and kind of failure, so that I can see which backend and which operation is failing. @@ -46,7 +46,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - **Networking measurements.** Every request through the app's shared HTTP client and every relay connection event (connected, disconnected, reconnect attempt, request timed out, subscription closed by the relay) is counted with four attributes: backend, endpoint, outcome and kind of failure. The backend is the host name of the server the app was talking to. Endpoints are names from a fixed list, never raw paths. Durations are recorded for requests and for time to connect. HTTP is measured where the app's shared HTTP client already classifies transport failures; relay connections are measured by hand in the relay session, since the SDK documents no WebSocket instrumentation. - **Counts are handed to the SDK as they happen**, including while the network is down. The app does no buffering of its own, and the SDK's default limit on unsent data is kept. Accepted consequence: in a long outage the oldest unsent reports can be dropped. - **No log lines in step one.** The counts carry the member and the time. The first implementation task confirms that the destination can filter counts by member; if it cannot, the fallback is one log line per outage, sent after it ends. -- **Breadcrumbs come from a fixed list:** networking events, written by the app, and the app moving to the foreground or background, written by the SDK. The SDK's other automatic breadcrumbs, which could carry content or addresses, are turned off or filtered. +- **Breadcrumbs come from a fixed list:** networking events and screen names, written by the app, and the app moving to the foreground or background, written by the SDK. A screen name comes from the app's own list of screens (such as the channel list, a channel, a thread or settings), with any other page called "other". It is never a channel or community name, an ID, a route's settings or anything a screen shows, so a report shows which screens the person was on and not what they were looking at. A breadcrumb is left when the person moves to a page or back to one. Dialogs, sheets and menus leave none. The SDK's other automatic breadcrumbs, which could carry content or addresses, are turned off or filtered. - **Who a report is about.** The member's public key is set as the report's user when a session starts and cleared when it ends. When the session is a Builderlab account, the Builderlab's origin and the account's subject identifier are added, never its email address. Every report also carries the app's own random per-install identifier, created on first launch and kept in a file that device backups and transfers skip, so a phone restored from another gets its own, as a separate field, signed in or not, so reports from one device can be matched to the members who used it, and a member's reports to the devices they used. With no member set, for example before sign-in, the SDK fills the report's user with its own random per-install identifier, on Dart and native reports alike. On iOS, native crash and hang reports also carry the SDK's device app hash: a hash of the identifier iOS gives the app's vendor, the hardware model and the bundle identifier, stable across launches and across a reinstall while another app from the same vendor stays installed. The Dart filter drops it, so Dart reports don't carry it. The SDK also sends session records, so the destination can show a crash-free rate. A session begins each time the app starts or returns after 30 seconds or more in the background. The SDK sends a record when it begins, an update each time an error is counted, and a last record when it ends. Together they carry when the session started, how many errors it had, how it ended (normally, crashed or abnormally), the time from start to end (not time in active use), the release, the environment and the SDK's identifier. - **One filter before anything leaves.** Errors, breadcrumbs and counts from Dart all pass through a single filter that removes URL query strings and fragments, drops any attribute not on the allowed list, replaces every error's own text with fixed wording, drops what the SDK adds about the failing widget or platform call, and keeps only the app, operating system, device and runtime details among the report's contexts, so the SDK's accessibility settings, locale and the device's own name stay on the device. An error keeps its type and stack trace. The SDK's options for sending personal data, screenshots, view hierarchies and session recordings stay off. - **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. @@ -74,7 +74,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - Requests that bypass the shared HTTP client, such as those made by native media players and image loaders. - Alert rules, dashboards and the destination's own configuration, which belong to whoever owns the destination. - Diagnostic reporting in a [public build](../CONTEXT.md#public-build). Nothing prevents it, but what a report carries was chosen for internal builds. Turning it on there first needs the member's public key and the server host names removed, the rest of the list reviewed, and a way to tell people ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)). Because identity and every attribute pass through one module, that is a small code change. -- Usage or behavior data of any kind, beyond the SDK's session records described above. +- Usage or behavior data of any kind, beyond the SDK's session records described above and the trail of screens in a report. - Fixing the bugs the reports will reveal, including one found while planning: a catch-all in account requests presents every error as an outage. ## Further notes diff --git a/mobile/lib/app.dart b/mobile/lib/app.dart index fb9b1e2160..6bf94344aa 100644 --- a/mobile/lib/app.dart +++ b/mobile/lib/app.dart @@ -54,6 +54,8 @@ import 'shared/auth/auth.dart'; import 'shared/deeplink/pending_deep_link_provider.dart'; import 'shared/emoji/emoji_burst.dart'; import 'shared/relay/relay.dart'; +import 'shared/diagnostics/diagnostic_navigation_observer.dart'; +import 'shared/diagnostics/diagnostic_reporter.dart'; import 'shared/theme/theme.dart'; import 'shared/widgets/buzz_loading_indicator.dart'; import 'shared/read_state/failed_clear_notice.dart'; @@ -476,10 +478,13 @@ class App extends HookConsumerWidget { }, ); final latestHome = useRef(null)..value = home; + final screenObserver = useMemoized( + () => DiagnosticNavigationObserver(ref.read(diagnosticReporterProvider)), + ); return MaterialApp( navigatorKey: _mobileRootNavigatorKey, - navigatorObservers: [appRouteObserver], + navigatorObservers: [appRouteObserver, screenObserver], title: 'Buzz', debugShowCheckedModeBanner: false, theme: lightTheme, diff --git a/mobile/lib/shared/diagnostics/diagnostic_filter.dart b/mobile/lib/shared/diagnostics/diagnostic_filter.dart index 8006aa1806..6c62b144a2 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_filter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_filter.dart @@ -1,5 +1,7 @@ import 'package:sentry_flutter/sentry_flutter.dart'; +import 'diagnostic_reporter.dart'; + /// The one filter every Dart report, breadcrumb and count passes through /// before it leaves the device. Reports the native SDKs capture themselves /// (native crashes, app hangs) do not pass through it. @@ -12,6 +14,12 @@ abstract final class DiagnosticFilter { /// Breadcrumb category the app writes for networking events. static const networkCategory = 'network'; + /// Breadcrumb category the app writes for the screen the person moved to. + static const navigationCategory = 'navigation'; + + /// The one data key of a navigation breadcrumb: a `DiagnosticScreen` name. + static const screenKey = 'screen'; + /// Breadcrumb category of the SDK's foreground/background entries. static const lifecycleCategory = 'app.lifecycle'; @@ -28,7 +36,11 @@ abstract final class DiagnosticFilter { /// Fixed wording that replaces an error's own text. static const removedText = 'Error text removed before sending.'; - static const _breadcrumbCategories = {networkCategory, lifecycleCategory}; + static const _breadcrumbCategories = { + networkCategory, + navigationCategory, + lifecycleCategory, + }; /// Device fields that may leave: the hardware and its state, never the /// name a person gave it or its locale and timezone. @@ -185,6 +197,7 @@ abstract final class DiagnosticFilter { if (crumb == null || !_breadcrumbCategories.contains(crumb.category)) { return null; } + if (crumb.category == navigationCategory) return _screenCrumb(crumb); crumb.message = switch (crumb.message) { final message? => stripUrlTails(message), null => null, @@ -195,6 +208,18 @@ abstract final class DiagnosticFilter { return crumb; } + /// A navigation breadcrumb leaves as its screen name and nothing else, and + /// only when that name is on the app's list. + static Breadcrumb? _screenCrumb(Breadcrumb crumb) { + final screen = crumb.data?[screenKey]; + if (!DiagnosticScreen.values.any((value) => value.name == screen)) { + return null; + } + crumb.message = null; + crumb.data = {screenKey: screen}; + return crumb; + } + /// Filters a count. static SentryMetric filterMetric(SentryMetric metric) { metric.attributes.removeWhere((key, _) => !allowsAttribute(key)); diff --git a/mobile/lib/shared/diagnostics/diagnostic_navigation_observer.dart b/mobile/lib/shared/diagnostics/diagnostic_navigation_observer.dart new file mode 100644 index 0000000000..da51e3d2e9 --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_navigation_observer.dart @@ -0,0 +1,67 @@ +import 'package:flutter/widgets.dart'; + +import 'diagnostic_reporter.dart'; +import 'diagnostic_screens.dart'; + +/// Leaves a breadcrumb for each screen the person moves to or back to, so a +/// report shows which screens they were on. +/// +/// Attach one to each navigator that holds screens: the app's root navigator +/// and the pane navigator that holds an open conversation. Only pages +/// ([PageRoute]) count. Dialogs, sheets and menus are popup routes with no +/// screen of their own, so opening or closing one leaves nothing. A build +/// without a reporting destination does nothing, not even looking at routes. +class DiagnosticNavigationObserver extends NavigatorObserver { + DiagnosticNavigationObserver(this._reporter); + + final DiagnosticReporter _reporter; + + @override + void didPush(Route route, Route? previousRoute) => + _arrived(route); + + @override + void didReplace({Route? newRoute, Route? oldRoute}) => + _arrived(newRoute); + + @override + void didPop(Route route, Route? previousRoute) => + _revealed(route, previousRoute); + + @override + void didRemove(Route route, Route? previousRoute) => + _revealed(route, previousRoute); + + void _arrived(Route? route) { + if (route is PageRoute) _announce(route); + } + + void _revealed(Route left, Route? revealed) { + if (left is PageRoute && revealed is PageRoute) { + _announce(revealed); + } + } + + /// Names [route] once the frame has built it, if it is then what the person + /// sees. Several pops in one go, or a route replaced at once, leave only the + /// screen they end on. + void _announce(PageRoute route) { + if (!_reporter.reporting) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!_shown(route)) return; + _reporter.leaveBreadcrumb( + DiagnosticBreadcrumb.screen(DiagnosticScreens.of(route)), + ); + }); + } + + /// Whether [route] is current on its navigator and every navigator hosting + /// it. + static bool _shown(Route route) { + if (!route.isCurrent) return false; + final navigator = route.navigator; + if (navigator == null) return false; + final host = ModalRoute.of(navigator.context); + return host == null || _shown(host); + } +} diff --git a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart index 43e5a1e1e6..18dbcbb8f5 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart @@ -99,14 +99,56 @@ class NetworkEvent { final Duration? duration; } -/// One entry in the trail of recent networking events. -class DiagnosticBreadcrumb { - const DiagnosticBreadcrumb(this.event); +/// A screen the person can be on, from a fixed list the app writes. Only +/// these names ever leave the device for navigation, never a channel or +/// community name, an ID, or anything else a route could carry. +enum DiagnosticScreen { + channelList, + channel, + thread, + forumPost, + channelDetails, + search, + activity, + settings, + appearance, + profile, + agents, + invites, + communitySwitcher, + addCommunity, + mediaViewer, + onboarding, + + /// Any page the app does not name. + other, +} + +/// One entry in the trail of recent events: a networking event or the screen +/// the person moved to. +sealed class DiagnosticBreadcrumb { + const DiagnosticBreadcrumb._(); + + /// A networking event. + const factory DiagnosticBreadcrumb(NetworkEvent event) = NetworkBreadcrumb; + + /// The person moved to [screen]. + const factory DiagnosticBreadcrumb.screen(DiagnosticScreen screen) = + ScreenBreadcrumb; +} + +class NetworkBreadcrumb extends DiagnosticBreadcrumb { + const NetworkBreadcrumb(this.event) : super._(); - /// Breadcrumbs from the fixed list are networking events. final NetworkEvent event; } +class ScreenBreadcrumb extends DiagnosticBreadcrumb { + const ScreenBreadcrumb(this.screen) : super._(); + + final DiagnosticScreen screen; +} + /// Used when the build has no reporting destination. class NoopDiagnosticReporter implements DiagnosticReporter { const NoopDiagnosticReporter(); diff --git a/mobile/lib/shared/diagnostics/diagnostic_screens.dart b/mobile/lib/shared/diagnostics/diagnostic_screens.dart new file mode 100644 index 0000000000..b1a5afedfd --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_screens.dart @@ -0,0 +1,86 @@ +import 'package:flutter/widgets.dart'; + +import '../../features/activity/activity_page.dart'; +import '../../features/agents/agents_page.dart'; +import '../../features/channels/channel_actions_sheet.dart'; +import '../../features/channels/channel_detail_page.dart'; +import '../../features/channels/channels_page.dart'; +import '../../features/channels/media_viewer_page.dart'; +import '../../features/channels/thread_detail_page.dart'; +import '../../features/forum/forum_thread_page.dart'; +import '../../features/home/home_page.dart'; +import '../../features/invites/invite_create_page.dart'; +import '../../features/onboarding/hosted_connect_page.dart'; +import '../../features/pairing/add_community_page.dart'; +import '../../features/pairing/pairing_page.dart'; +import '../../features/profile/profile_edit_page.dart'; +import '../../features/search/search_page.dart'; +import '../../features/settings/settings_page.dart'; +import '../../features/settings/theme_picker_page.dart'; +import '../../onboarding_app_entry.dart'; +import '../../organization_app_entry.dart'; +import 'diagnostic_reporter.dart'; + +/// Names the screen a route shows, for the trail of screens in a report. +/// +/// A route has no name of its own here: the app pushes page widgets without +/// route settings, and where settings exist they can carry IDs. So a route is +/// named by the first page widget below it that is on this list, and a route +/// showing none is [DiagnosticScreen.other]. Nothing is read from a route's +/// settings, its arguments or what the page shows. +abstract final class DiagnosticScreens { + /// The app's pages that have a name. Add a page here to name it; an unlisted + /// page is reported as [DiagnosticScreen.other], never by its own type name, + /// which release builds can obfuscate. + static const pages = { + HomePage: DiagnosticScreen.channelList, + ChannelDetailPage: DiagnosticScreen.channel, + ThreadDetailPage: DiagnosticScreen.thread, + ForumThreadPage: DiagnosticScreen.forumPost, + ChannelDetailsPage: DiagnosticScreen.channelDetails, + SearchPage: DiagnosticScreen.search, + ActivityPage: DiagnosticScreen.activity, + SettingsPage: DiagnosticScreen.settings, + ThemePickerPage: DiagnosticScreen.appearance, + ProfileEditPage: DiagnosticScreen.profile, + AgentsPage: DiagnosticScreen.agents, + CommunityInvitePage: DiagnosticScreen.invites, + CommunitySwitcherPage: DiagnosticScreen.communitySwitcher, + AddCommunityPage: DiagnosticScreen.addCommunity, + MediaImageViewerPage: DiagnosticScreen.mediaViewer, + MediaVideoViewerPage: DiagnosticScreen.mediaViewer, + OnboardingAppEntry: DiagnosticScreen.onboarding, + OrganizationAppEntry: DiagnosticScreen.onboarding, + PairingPage: DiagnosticScreen.onboarding, + HostedConnectPage: DiagnosticScreen.onboarding, + }; + + /// How many elements a search below a route may look at. A page sits near + /// the top of its route; this keeps an unlisted page from costing a walk of + /// everything it shows. + static const _searchBudget = 3000; + + /// The screen [route] shows, once it has been built. + static DiagnosticScreen of(ModalRoute route) { + if (route.subtreeContext case final BuildContext context) { + var budget = _searchBudget; + DiagnosticScreen? found; + void visit(Element element) { + if (found != null || budget-- <= 0) return; + found = pages[element.widget.runtimeType]; + if (found == null) element.visitChildElements(visit); + } + + (context as Element).visitChildElements(visit); + if (found != null) return found!; + } + // The first route of a nested navigator is its container, such as the + // empty list side of a pane, and shows whatever hosts that navigator. + if (route.isFirst) { + final navigator = route.navigator; + final host = navigator == null ? null : ModalRoute.of(navigator.context); + if (host != null) return of(host); + } + return DiagnosticScreen.other; + } +} diff --git a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart index edcb2b72f1..1521fbb414 100644 --- a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart @@ -52,18 +52,22 @@ class SentryDiagnosticReporter implements DiagnosticReporter { @override void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb) => _drop( - () => _hub.addBreadcrumb( - Breadcrumb( + () => _hub.addBreadcrumb(switch (breadcrumb) { + NetworkBreadcrumb(:final event) => Breadcrumb( category: DiagnosticFilter.networkCategory, - level: breadcrumb.event.outcome == NetworkOutcome.failure + level: event.outcome == NetworkOutcome.failure ? SentryLevel.warning : SentryLevel.info, data: { - for (final entry in _attributes(breadcrumb.event).entries) + for (final entry in _attributes(event).entries) entry.key: entry.value.value, }, ), - ), + ScreenBreadcrumb(:final screen) => Breadcrumb( + category: DiagnosticFilter.navigationCategory, + data: {DiagnosticFilter.screenKey: screen.name}, + ), + }), ); @override diff --git a/mobile/lib/shared/widgets/adaptive_conversation_pane.dart b/mobile/lib/shared/widgets/adaptive_conversation_pane.dart index 6183754b14..a681fd0fb2 100644 --- a/mobile/lib/shared/widgets/adaptive_conversation_pane.dart +++ b/mobile/lib/shared/widgets/adaptive_conversation_pane.dart @@ -4,6 +4,8 @@ import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:duo_kit/duo_kit.dart'; +import '../diagnostics/diagnostic_navigation_observer.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import 'duo_toolbar.dart'; import 'app_route_observer.dart'; import 'covered_route_keyboard_insets.dart'; @@ -206,6 +208,9 @@ class AdaptiveConversationPane extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final routeObserver = useMemoized(appRouteObserver.createNestedObserver); + final screenObserver = useMemoized( + () => DiagnosticNavigationObserver(ref.read(diagnosticReporterProvider)), + ); final navigator = useMemoized(() => GlobalKey()); final ownerRoute = ModalRoute.of(context); useEffect(() { @@ -369,7 +374,10 @@ class AdaptiveConversationPane extends HookConsumerWidget { child: Navigator( requestFocus: selected != null, key: navigator, - observers: [routeObserver], + observers: [ + routeObserver, + screenObserver, + ], pages: [ if (!(wide && persistentSelection && diff --git a/mobile/test/shared/diagnostics/diagnostic_navigation_test.dart b/mobile/test/shared/diagnostics/diagnostic_navigation_test.dart new file mode 100644 index 0000000000..8fc774d4e7 --- /dev/null +++ b/mobile/test/shared/diagnostics/diagnostic_navigation_test.dart @@ -0,0 +1,136 @@ +import 'package:buzz/features/channels/channel_detail_page.dart'; +import 'package:buzz/features/channels/thread_detail_page.dart'; +import 'package:buzz/features/home/home_page.dart'; +import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/features/settings/theme_picker_page.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_navigation_observer.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_screens.dart'; +import 'package:buzz/shared/hosted/known_community_sync_provider.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:shared_preferences/shared_preferences.dart'; + +void main() { + group('the screen a page is named', () { + final rows = <(Type, DiagnosticScreen)>[ + (HomePage, DiagnosticScreen.channelList), + (ChannelDetailPage, DiagnosticScreen.channel), + (ThreadDetailPage, DiagnosticScreen.thread), + (SettingsPage, DiagnosticScreen.settings), + (ThemePickerPage, DiagnosticScreen.appearance), + // Not on the list: never named by its own type. + (Text, DiagnosticScreen.other), + ]; + for (final (page, screen) in rows) { + test('$screen for $page', () { + expect(DiagnosticScreens.pages[page] ?? DiagnosticScreen.other, screen); + }); + } + }); + + group('screen breadcrumbs', () { + const channelId = 'c0ffee-secret-channel-id'; + late _RecordingReporter reporter; + + Future pumpApp(WidgetTester tester, {bool reporting = true}) async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + reporter = _RecordingReporter(reporting: reporting); + await tester.pumpWidget( + ProviderScope( + overrides: [ + knownCommunitySyncProvider.overrideWithValue(null), + savedPrefsProvider.overrideWithValue(prefs), + ], + child: MaterialApp( + theme: AppTheme.light(), + navigatorObservers: [DiagnosticNavigationObserver(reporter)], + home: const Scaffold(body: Text('start')), + ), + ), + ); + await tester.pump(); + } + + NavigatorState navigator(WidgetTester tester) => + tester.state(find.byType(Navigator)); + + List trail() => [ + for (final screen in reporter.screens) screen.name, + ]; + + testWidgets('a push and a pop leave the screens the person was on', ( + tester, + ) async { + await pumpApp(tester); + + // A route whose settings carry an ID is still named by its page. + navigator(tester).push( + MaterialPageRoute( + settings: const RouteSettings(name: '/channels/$channelId'), + builder: (_) => const ThemePickerPage(), + ), + ); + await tester.pumpAndSettle(); + // An unlisted page is "other", whatever its settings say. + navigator(tester).push( + MaterialPageRoute( + settings: const RouteSettings(name: '/channels/$channelId'), + builder: (_) => const Scaffold(body: Text('unlisted')), + ), + ); + await tester.pumpAndSettle(); + // A dialog is not a screen: opening and closing it leaves nothing. + final dialog = showDialog( + context: navigator(tester).context, + builder: (_) => const AlertDialog(content: Text('dialog')), + ); + await tester.pumpAndSettle(); + navigator(tester).pop(); + await dialog; + await tester.pumpAndSettle(); + // Two pops at once leave only the screen they end on. + navigator(tester).popUntil((route) => route.isFirst); + await tester.pumpAndSettle(); + + expect(trail(), ['other', 'appearance', 'other', 'other']); + expect( + reporter.crumbs.map((crumb) => crumb.toString()).join(), + isNot(contains(channelId)), + ); + }); + + testWidgets('a build without a destination looks at nothing', ( + tester, + ) async { + await pumpApp(tester, reporting: false); + navigator( + tester, + ).push(MaterialPageRoute(builder: (_) => const ThemePickerPage())); + await tester.pumpAndSettle(); + navigator(tester).pop(); + await tester.pumpAndSettle(); + + expect(reporter.crumbs, isEmpty); + }); + }); +} + +class _RecordingReporter extends NoopDiagnosticReporter { + _RecordingReporter({required this.reporting}); + + @override + final bool reporting; + + final crumbs = []; + + Iterable get screens => + crumbs.whereType().map((crumb) => crumb.screen); + + @override + void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb) => + crumbs.add(breadcrumb); +} diff --git a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart index 5e54121a01..130b194a14 100644 --- a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart +++ b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart @@ -67,10 +67,28 @@ void main() { null, ), ( - 'a navigation breadcrumb is dropped', + 'a navigation breadcrumb that names no app screen is dropped', () async => crumb(Breadcrumb(category: 'navigation', message: 'Chat')), null, ), + ( + 'a navigation breadcrumb with an unlisted screen name is dropped', + () async => crumb( + Breadcrumb(category: 'navigation', data: {'screen': 'secret-room'}), + ), + null, + ), + ( + 'a navigation breadcrumb keeps only its screen name', + () async => crumb( + Breadcrumb( + category: 'navigation', + message: 'secret-room', + data: {'screen': 'channel', 'route': '/channels/secret-id'}, + ), + )?.data, + {'screen': 'channel'}, + ), ( 'a lifecycle breadcrumb is kept', () async => crumb(