From fe33f693a8c096de9e39de65dca229e1242fade6 Mon Sep 17 00:00:00 2001 From: Ben Tucker Date: Sun, 16 Aug 2026 17:29:43 -0500 Subject: [PATCH] fix(core): make UI side effects and provider reads safe during build Errors handled while the widget tree is building crashed or wedged the app in three related ways: - FlutterError.onError showed dialogs and snackbars synchronously. Pushing a route mid-build trips the navigator's !_debugLocked assertion, and because the one-dialog guard was set before showDialog threw, its release never attached: every later error dialog was then silently suppressed while nothing was on screen, leaving a blank, unresponsive app until restart. Snackbars crashed outright via the messenger's setState. - The sync status and barcode dialogs did ref.read inside their route builders, which run during build. With the provider chain dirty (any token refresh dirties wgerBase -> auth), the read flushed it there and Riverpod scheduled a scope refresh mid-build. The barcode builder also created its search future inline, re-firing the search on every dialog rebuild. - Provider create bodies that widgets watch during build read providers synchronously: the dashboard's routine hydration chain crashed on cold start right after a token refresh, and TrophyStateNotifier.build() has the same shape in the post-login window, where invalidation order left networkStatusProvider dirty while its dependents rebuilt. lib/core/build_safety.dart adds the two idioms as helpers: runAfterFrame defers UI side effects past the build phase, yieldPastBuild yields provider create bodies past their synchronous phase (a microtask, not a timer, since widget tests assert !timersPending at teardown). The error dialog guard is released when the context is gone or the push fails, the snackbar helpers re-resolve the messenger inside the callback, the dialog builders snapshot their providers in the tap handler, and post-login invalidation runs leaf-first. Regression tests cover each shape. --- lib/core/build_safety.dart | 33 ++ lib/core/error_dialogs.dart | 331 ++++++++++-------- lib/core/network/auth_notifier.dart | 7 +- lib/core/widgets/app_bar.dart | 50 +-- lib/features/nutrition/widgets/widgets.dart | 5 +- .../routines/providers/routines_notifier.dart | 11 +- .../routines/widgets/gym_mode/gym_mode.dart | 3 +- .../trophies/providers/trophy_notifier.dart | 16 +- test/core/error_dialogs_test.dart | 92 +++++ test/core/widgets/app_bar_test.dart | 71 ++++ .../providers/routines_notifier_test.dart | 30 ++ 11 files changed, 467 insertions(+), 182 deletions(-) create mode 100644 lib/core/build_safety.dart create mode 100644 test/core/widgets/app_bar_test.dart diff --git a/lib/core/build_safety.dart b/lib/core/build_safety.dart new file mode 100644 index 000000000..fa3659712 --- /dev/null +++ b/lib/core/build_safety.dart @@ -0,0 +1,33 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/widgets.dart'; + +/// Runs [action] on the next frame: UI side effects (dialogs, snackbars, +/// navigation) are illegal during build, but error handlers and provider +/// listeners can fire there. Schedules a frame so idle-time requests run too. +void runAfterFrame(VoidCallback action) { + WidgetsBinding.instance.addPostFrameCallback((_) => action()); + WidgetsBinding.instance.scheduleFrame(); +} + +/// Yields past the synchronous phase of a provider create or widget +/// life-cycle callback: reading a dirty provider there flushes it mid-build +/// and crashes. A microtask, not a timer, since widget tests assert +/// !timersPending at teardown. +Future yieldPastBuild() => Future.microtask(() {}); diff --git a/lib/core/error_dialogs.dart b/lib/core/error_dialogs.dart index 93ce3a7d6..c5be5472d 100644 --- a/lib/core/error_dialogs.dart +++ b/lib/core/error_dialogs.dart @@ -23,6 +23,7 @@ import 'package:flutter_html/flutter_html.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:logging/logging.dart'; import 'package:url_launcher/url_launcher.dart'; +import 'package:wger/core/build_safety.dart'; import 'package:wger/core/errors.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/core/keys.dart'; @@ -36,6 +37,31 @@ import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostic /// modal dialogs on top of each other. bool _errorDialogVisible = false; +/// Shows [dialog] on the next frame, releasing [_errorDialogVisible] when it +/// closes (or when it could not be shown at all). +/// +/// Error handlers can run during build, where pushing a route trips the +/// navigator's !_debugLocked assertion; the secondary exception then wedged +/// the guard flag shut, silently suppressing every later dialog. Deferring +/// to a post-frame callback is legal no matter when the error fired. +void _showErrorDialogNextFrame(BuildContext dialogContext, Future Function() dialog) { + _errorDialogVisible = true; + + runAfterFrame(() { + if (!dialogContext.mounted) { + _errorDialogVisible = false; + Logger('showErrorDialog').info('Dropping deferred error dialog: context unmounted'); + return; + } + try { + dialog().whenComplete(() => _errorDialogVisible = false); + } catch (e) { + _errorDialogVisible = false; + rethrow; + } + }); +} + void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? context}) { final logger = Logger('showHttpExceptionErrorDialog'); @@ -55,34 +81,36 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co logger.info('Suppressing error dialog, one is already visible: $exception'); return; } - _errorDialogVisible = true; - showDialog( - context: dialogContext, - builder: (ctx) => AlertDialog( - title: Text(AppLocalizations.of(ctx).anErrorOccurred), - content: SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - if (exception.type == ErrorType.html) - ServerHtmlError(data: exception.htmlError) - else - ...formatApiErrors(extractErrors(exception.errors)), - ], + _showErrorDialogNextFrame( + dialogContext, + () => showDialog( + context: dialogContext, + builder: (ctx) => AlertDialog( + title: Text(AppLocalizations.of(ctx).anErrorOccurred), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (exception.type == ErrorType.html) + ServerHtmlError(data: exception.htmlError) + else + ...formatApiErrors(extractErrors(exception.errors)), + ], + ), ), + actions: [ + TextButton( + child: Text(MaterialLocalizations.of(ctx).closeButtonLabel), + onPressed: () { + Navigator.of(ctx).pop(); + }, + ), + ], ), - actions: [ - TextButton( - child: Text(MaterialLocalizations.of(ctx).closeButtonLabel), - onPressed: () { - Navigator.of(ctx).pop(); - }, - ), - ], ), - ).whenComplete(() => _errorDialogVisible = false); + ); } /// Flattens a [WgerHttpException]'s context and error map into a readable @@ -112,7 +140,6 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext logger.info('Suppressing error dialog, one is already visible: $error'); return; } - _errorDialogVisible = true; final i18n = AppLocalizations.of(dialogContext); @@ -139,124 +166,127 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext final String fullStackTrace = stackTrace?.toString() ?? 'No stack trace available.'; final applicationLogs = InMemoryLogStore().getFormattedLogs(); - showDialog( - context: dialogContext, - barrierDismissible: false, - builder: (BuildContext context) { - return AlertDialog( - title: Row( - spacing: 8, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.error, color: Theme.of(context).colorScheme.error), - Expanded( - child: Text( - i18n.anErrorOccurred, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - ), - ], - ), - content: SingleChildScrollView( - child: ListBody( + _showErrorDialogNextFrame( + dialogContext, + () => showDialog( + context: dialogContext, + barrierDismissible: false, + builder: (BuildContext context) { + return AlertDialog( + title: Row( + spacing: 8, + mainAxisAlignment: MainAxisAlignment.center, children: [ - Text(i18n.errorInfoDescription), - const SizedBox(height: 8), - Text(i18n.errorInfoDescription2), - const SizedBox(height: 10), - ExpansionTile( - tilePadding: EdgeInsets.zero, - title: Text(i18n.errorViewDetails), - children: [ - Text( - issueErrorMessage, - style: const TextStyle(fontWeight: FontWeight.bold), - ), - Container( - alignment: Alignment.topLeft, - padding: const EdgeInsets.symmetric(vertical: 8.0), - constraints: const BoxConstraints(maxHeight: 250), - child: SingleChildScrollView( - child: Text( - fullStackTrace, - style: TextStyle( - fontSize: 12.0, - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - ), - ), - CopyToClipboardButton( - text: - 'Error Title: $issueTitle\n' - 'Error Message: $issueErrorMessage\n\n' - 'Stack Trace:\n$fullStackTrace', - ), - const SizedBox(height: 8), - Text(i18n.applicationLogs, style: const TextStyle(fontWeight: FontWeight.bold)), - Container( - alignment: Alignment.topLeft, - padding: const EdgeInsets.symmetric(vertical: 8.0), - constraints: const BoxConstraints(maxHeight: 250), - child: SingleChildScrollView( - child: Column( - children: [ - ...applicationLogs.map( - (entry) => Text( - entry, - style: TextStyle( - fontSize: 12.0, - color: Theme.of(context).colorScheme.onSurfaceVariant, - ), - ), - ), - ], - ), - ), - ), - CopyToClipboardButton(text: applicationLogs.join('\n')), - ], + Icon(Icons.error, color: Theme.of(context).colorScheme.error), + Expanded( + child: Text( + i18n.anErrorOccurred, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), ), ], ), - ), - actions: [ - TextButton( - child: const Text('Report issue'), - onPressed: () async { - final githubIssueUrl = buildGithubIssueUrl( - issueTitle: issueTitle, - issueErrorMessage: issueErrorMessage, - stackTrace: fullStackTrace, - applicationLogs: applicationLogs, - syncDiagnostics: await collectSyncDiagnostics(), - ); - final Uri reportUri = Uri.parse(githubIssueUrl); + content: SingleChildScrollView( + child: ListBody( + children: [ + Text(i18n.errorInfoDescription), + const SizedBox(height: 8), + Text(i18n.errorInfoDescription2), + const SizedBox(height: 10), + ExpansionTile( + tilePadding: EdgeInsets.zero, + title: Text(i18n.errorViewDetails), + children: [ + Text( + issueErrorMessage, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + Container( + alignment: Alignment.topLeft, + padding: const EdgeInsets.symmetric(vertical: 8.0), + constraints: const BoxConstraints(maxHeight: 250), + child: SingleChildScrollView( + child: Text( + fullStackTrace, + style: TextStyle( + fontSize: 12.0, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + CopyToClipboardButton( + text: + 'Error Title: $issueTitle\n' + 'Error Message: $issueErrorMessage\n\n' + 'Stack Trace:\n$fullStackTrace', + ), + const SizedBox(height: 8), + Text(i18n.applicationLogs, style: const TextStyle(fontWeight: FontWeight.bold)), + Container( + alignment: Alignment.topLeft, + padding: const EdgeInsets.symmetric(vertical: 8.0), + constraints: const BoxConstraints(maxHeight: 250), + child: SingleChildScrollView( + child: Column( + children: [ + ...applicationLogs.map( + (entry) => Text( + entry, + style: TextStyle( + fontSize: 12.0, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + ), + CopyToClipboardButton(text: applicationLogs.join('\n')), + ], + ), + ], + ), + ), + actions: [ + TextButton( + child: const Text('Report issue'), + onPressed: () async { + final githubIssueUrl = buildGithubIssueUrl( + issueTitle: issueTitle, + issueErrorMessage: issueErrorMessage, + stackTrace: fullStackTrace, + applicationLogs: applicationLogs, + syncDiagnostics: await collectSyncDiagnostics(), + ); + final Uri reportUri = Uri.parse(githubIssueUrl); - try { - await launchUrl(reportUri, mode: LaunchMode.externalApplication); - } catch (e) { - if (kDebugMode) { - logger.warning('Error launching URL: $e'); + try { + await launchUrl(reportUri, mode: LaunchMode.externalApplication); + } catch (e) { + if (kDebugMode) { + logger.warning('Error launching URL: $e'); + } + if (context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e'))); + } } - if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e'))); - } - } - }, - ), - FilledButton( - child: Text(MaterialLocalizations.of(context).okButtonLabel), - onPressed: () { - Navigator.of(context).pop(); - }, - ), - ], - ); - }, - ).whenComplete(() => _errorDialogVisible = false); + }, + ), + FilledButton( + child: Text(MaterialLocalizations.of(context).okButtonLabel), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + ], + ); + }, + ), + ); } /// Routes [error] to the appropriate UI based on its [ErrorSeverity]. @@ -294,11 +324,15 @@ void showTransientErrorSnackbar() { return; } - messenger - ..clearSnackBars() - ..showSnackBar( - SnackBar(content: Text(AppLocalizations.of(context).errorCouldNotConnectToServer)), - ); + // showSnackBar sets state on the messenger, which asserts during build. + // Re-resolved in the callback: the captured messenger can be disposed + // before the frame fires. + final message = AppLocalizations.of(context).errorCouldNotConnectToServer; + runAfterFrame(() { + scaffoldMessengerKey.currentState + ?..clearSnackBars() + ..showSnackBar(SnackBar(content: Text(message))); + }); } /// Shows a brief, non-blocking snackbar telling the user their session is no @@ -311,11 +345,14 @@ void showSessionExpiredSnackbar() { return; } - messenger - ..clearSnackBars() - ..showSnackBar( - SnackBar(content: Text(AppLocalizations.of(context).sessionExpired)), - ); + // Deferred like showTransientErrorSnackbar: auth teardown can coincide + // with a build. + final message = AppLocalizations.of(context).sessionExpired; + runAfterFrame(() { + scaffoldMessengerKey.currentState + ?..clearSnackBars() + ..showSnackBar(SnackBar(content: Text(message))); + }); } /// A widget to render HTML errors returned by the server diff --git a/lib/core/network/auth_notifier.dart b/lib/core/network/auth_notifier.dart index a0ce414a2..7c207d2a9 100644 --- a/lib/core/network/auth_notifier.dart +++ b/lib/core/network/auth_notifier.dart @@ -763,15 +763,16 @@ class AuthNotifier extends _$AuthNotifier { /// with the new token instead of replaying their pre-login error state. void _invalidatePostLoginProviders() { _logger.fine('Invalidating data providers after login'); + // Leaf first: the providers below read reachability as they rebuild, and + // flushing a still-dirty networkStatusProvider from a create during + // widget build crashes. The re-probe also picks up the new server URL. + ref.invalidate(networkStatusProvider); ref.invalidate(accountProvider); ref.invalidate(userProfileProvider); ref.invalidate(routinesRiverpodProvider); ref.invalidate(nutritionProvider); ref.invalidate(trophyStateProvider); ref.invalidate(galleryProvider); - // Re-probe reachability against the new server. NetworkStatus relies on - // this invalidation to pick up the post-login server URL immediately. - ref.invalidate(networkStatusProvider); } /// Exchanges the persisted refresh token for a fresh access/refresh pair. diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 98d51154d..1c218f825 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -54,28 +54,34 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { ), IconButton( icon: Icon(status.icon), - onPressed: () => showDialog( - context: context, - // The dialog watches the sync state itself; only the server URL - // and the offline gate are snapshots taken when it opens. - // No reconnect while offline: the app deliberately disconnects - // there (see powerSyncInstance). The tap-time check covers the - // network dropping while the dialog is open - builder: (_) => SyncStatusDialog( - serverUrl: ref.read(wgerBaseProvider).serverUrl, - onReconnect: !ref.read(networkStatusProvider) - ? null - : () { - final db = builtPowerSyncInstance; - final serverUrl = ref.read(wgerBaseProvider).serverUrl; - if (db == null || serverUrl == null || !ref.read(networkStatusProvider)) { - return; - } - ref.read(syncWatchdogProvider).reset(); - connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider)); - }, - ), - ), + onPressed: () { + // The dialog watches the sync state itself; the server URL and + // offline gate are snapshots. Taken here rather than in the route + // builder, which runs during build where reading a dirty provider + // forces a mid-build refresh. No reconnect while offline: the app + // deliberately disconnects there (see powerSyncInstance); the + // reconnect-time check covers the network dropping while open. + final serverUrl = ref.read(wgerBaseProvider).serverUrl; + final isOnline = ref.read(networkStatusProvider); + + showDialog( + context: context, + builder: (_) => SyncStatusDialog( + serverUrl: serverUrl, + onReconnect: !isOnline + ? null + : () { + final db = builtPowerSyncInstance; + final url = ref.read(wgerBaseProvider).serverUrl; + if (db == null || url == null || !ref.read(networkStatusProvider)) { + return; + } + ref.read(syncWatchdogProvider).reset(); + connectPowerSync(db, url, ref.read(authenticatedHttpClientProvider)); + }, + ), + ); + }, ), IconButton( icon: const Icon(Icons.settings), diff --git a/lib/features/nutrition/widgets/widgets.dart b/lib/features/nutrition/widgets/widgets.dart index 3137d7b32..dc06d18f6 100644 --- a/lib/features/nutrition/widgets/widgets.dart +++ b/lib/features/nutrition/widgets/widgets.dart @@ -278,10 +278,13 @@ class _IngredientTypeaheadState extends ConsumerState { if (!mounted) { return; } + // Started in the tap handler: reading a provider in the route builder + // runs during build, and an inline future re-fires on every rebuild. + final search = ref.read(ingredientRepositoryProvider).searchIngredientByBarcode(barcode); showDialog( context: context, builder: (context) => FutureBuilder( - future: ref.read(ingredientRepositoryProvider).searchIngredientByBarcode(barcode), + future: search, builder: (BuildContext context, AsyncSnapshot snapshot) { return IngredientScanResultDialog(snapshot, barcode, widget.selectIngredient); }, diff --git a/lib/features/routines/providers/routines_notifier.dart b/lib/features/routines/providers/routines_notifier.dart index 56b8d25cd..cc9f16273 100644 --- a/lib/features/routines/providers/routines_notifier.dart +++ b/lib/features/routines/providers/routines_notifier.dart @@ -19,6 +19,7 @@ import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/core/build_safety.dart'; import 'package:wger/core/consts.dart'; import 'package:wger/core/helpers.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; @@ -33,7 +34,6 @@ import 'package:wger/features/routines/models/slot_entry.dart'; import 'package:wger/features/routines/models/weight_unit.dart'; import 'package:wger/features/routines/providers/routines_repository.dart'; import 'package:wger/features/routines/providers/workout_session_notifier.dart'; - part 'routines_notifier.g.dart'; // Reference-data streams: kept alive across the app's lifetime so that @@ -263,6 +263,10 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { } Future _fetchAndSetRoutineFull(int routineId) async { + // Watch-created providers enter here synchronously during widget build, + // where reading a dirty dependency chain forces a mid-build refresh. + await yieldPastBuild(); + final repo = ref.read(routinesRepositoryProvider); // Wait for every reference-data stream to produce its first value before @@ -429,5 +433,10 @@ class RoutinesRiverpod extends _$RoutinesRiverpod { /// lets a reconnect re-create the provider and retry. @riverpod Future routineHydration(Ref ref, int routineId) async { + // Created by a ref.watch during widget build; reading a dirty dependency + // chain there (e.g. auth right after a token refresh) forces a provider + // refresh mid-build. + await yieldPastBuild(); + await ref.read(routinesRiverpodProvider.notifier).fetchAndSetRoutineFull(routineId); } diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 7888972bb..1dbe351ec 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -22,6 +22,7 @@ import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; +import 'package:wger/core/build_safety.dart'; import 'package:wger/core/network/network_provider.dart'; import 'package:wger/core/widgets/error.dart'; import 'package:wger/core/widgets/progress_indicator.dart'; @@ -72,7 +73,7 @@ class _GymModeState extends ConsumerState { // synchronously inside the widget life-cycle: the offline branch reaches // gym-state mutations with no await in between, and modifying a provider // during a life-cycle is not allowed. - await Future.delayed(Duration.zero); + await yieldPastBuild(); final notifier = ref.read(routinesRiverpodProvider.notifier); final routineId = widget._args.routineId; diff --git a/lib/features/trophies/providers/trophy_notifier.dart b/lib/features/trophies/providers/trophy_notifier.dart index 617dd8107..a566ca7af 100644 --- a/lib/features/trophies/providers/trophy_notifier.dart +++ b/lib/features/trophies/providers/trophy_notifier.dart @@ -62,13 +62,15 @@ final class TrophyStateNotifier extends _$TrophyStateNotifier { @override TrophyState build() { - // Trophies are REST-only. Kick off the initial load when the server is - // reachable, and (re)fetch once it becomes reachable again. Skipping the - // fetch while offline keeps the REST calls from hammering an unreachable - // server. - if (ref.read(networkStatusProvider)) { - Future.microtask(_fetchAllSafe); - } + // Trophies are REST-only. Load when reachable, refetch on reconnect, and + // skip while offline so an unreachable server is not hammered. The + // reachability read sits inside the microtask: this build can run during + // widget build with networkStatusProvider dirty (see build_safety.dart). + Future.microtask(() { + if (ref.read(networkStatusProvider)) { + _fetchAllSafe(); + } + }); ref.listen(networkStatusProvider, (previous, next) { if (next && previous == false) { Future.microtask(_fetchAllSafe); diff --git a/test/core/error_dialogs_test.dart b/test/core/error_dialogs_test.dart index 2b072937a..f1a9fff49 100644 --- a/test/core/error_dialogs_test.dart +++ b/test/core/error_dialogs_test.dart @@ -17,9 +17,36 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/core/error_dialogs.dart'; import 'package:wger/core/errors.dart'; +import 'package:wger/core/keys.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Requests an error dialog from *inside* its own build, the situation a +/// FlutterError.onError handler is in when a widget fails to build. +class _ErrorDuringBuild extends StatelessWidget { + const _ErrorDuringBuild(); + + @override + Widget build(BuildContext context) { + showGeneralErrorDialog('boom during build', StackTrace.current, context: context); + return const SizedBox.shrink(); + } +} + +/// Requests the transient-error snackbar from inside a build, where the +/// messenger's setState would otherwise assert. +class _SnackbarDuringBuild extends StatelessWidget { + const _SnackbarDuringBuild(); + + @override + Widget build(BuildContext context) { + showTransientErrorSnackbar(); + return const SizedBox.shrink(); + } +} void main() { group('formatApiErrors', () { @@ -67,4 +94,69 @@ void main() { expect(htmlErrorTitle(''), isNull); }); }); + + group('showGeneralErrorDialog during build', () { + Widget app(Widget home) => MaterialApp( + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ); + + testWidgets('defers the dialog to the next frame instead of asserting', (tester) async { + // Regression: a mid-build route push asserted, and the secondary + // exception wedged the one-dialog guard shut until app restart. + await tester.pumpWidget(app(const _ErrorDuringBuild())); + + // The build itself must not throw... + expect(tester.takeException(), isNull); + + // ...and the dialog appears on the following frame. + await tester.pump(); + expect(find.byType(AlertDialog), findsOneWidget); + + // Dismissing releases the guard: a second dialog can be shown. + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + final context = tester.element(find.byType(SizedBox)); + showGeneralErrorDialog('second error', StackTrace.current, context: context); + // One frame runs the post-frame callback (pushing the route), the next + // builds the dialog. + await tester.pump(); + await tester.pump(); + expect( + find.byType(AlertDialog), + findsOneWidget, + reason: 'the guard flag must not stay wedged after the first dialog', + ); + }); + + testWidgets('snackbar requested during build appears without asserting', (tester) async { + // Same bug class as the dialogs: showSnackBar sets state on the + // messenger, which asserts during build. + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + scaffoldMessengerKey: scaffoldMessengerKey, + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold(body: _SnackbarDuringBuild()), + ), + ); + + expect(tester.takeException(), isNull); + + await tester.pump(); + expect(find.byType(SnackBar), findsOneWidget); + }); + }); } diff --git a/test/core/widgets/app_bar_test.dart b/test/core/widgets/app_bar_test.dart new file mode 100644 index 000000000..534203b86 --- /dev/null +++ b/test/core/widgets/app_bar_test.dart @@ -0,0 +1,71 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; +import 'package:wger/core/widgets/app_bar.dart'; +import 'package:wger/core/widgets/sync_status_dialog.dart'; +import 'package:wger/database/powersync/powersync.dart' show pendingUploadCountProvider, syncStatus; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../helpers/sync_status.dart'; + +void main() { + testWidgets('sync icon snapshots its providers at tap time and opens the dialog', (tester) async { + // Companion to a production crash: reading a dirty provider from the + // route builder forced a mid-build refresh. The exact race needs a + // dependency flip in the same frame and is not deterministically + // reproducible here; this pins the tap-time wiring of the fixed path. + final container = ProviderContainer.test( + overrides: [ + networkStatusProvider.overrideWithValue(true), + pendingUploadCountProvider.overrideWith((ref) => Stream.value(0)), + syncStatus.overrideWithValue(buildSyncStatus(connected: true)), + ], + ); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(appBar: MainAppBar('title')), + ), + ), + ); + await tester.pumpAndSettle(); + + // Dirty the provider the dialog reads, without pumping a frame, so the + // flush happens on the tap itself. + container.invalidate(wgerBaseProvider); + + final syncIcon = find.descendant( + of: find.byType(MainAppBar), + matching: find.byType(IconButton), + ); + await tester.tap(syncIcon.at(1)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.byType(SyncStatusDialog), findsOneWidget); + }); +} diff --git a/test/features/routines/providers/routines_notifier_test.dart b/test/features/routines/providers/routines_notifier_test.dart index b5e9e116d..13edbf2ff 100644 --- a/test/features/routines/providers/routines_notifier_test.dart +++ b/test/features/routines/providers/routines_notifier_test.dart @@ -567,6 +567,36 @@ void main() { }); group('routineHydration family', () { + test('creation defers all provider reads past the synchronous phase', () async { + // Regression: the provider is created by a ref.watch during widget + // build, and a synchronous read of the then-dirty repository chain + // crashed mid-build. No provider may be touched before a yield. + var repoRead = false; + when( + mockRepo.fetchAndSetRoutineFullServer(101), + ).thenAnswer((_) async => Routine(id: 101, name: 'Test routine')); + final container = ProviderContainer.test( + overrides: [ + routinesRepositoryProvider.overrideWith((ref) { + repoRead = true; + return mockRepo; + }), + ...ambientOverrides(), + ], + ); + + container.listen(routineHydrationProvider(101), (_, _) {}); + expect( + repoRead, + false, + reason: 'no provider may be read synchronously during create (build phase)', + ); + + await container.read(routineHydrationProvider(101).future); + expect(repoRead, true); + verify(mockRepo.fetchAndSetRoutineFullServer(101)).called(1); + }); + test('watching the provider triggers a single structure fetch', () async { // Arrange when(