From d72a0ccf93c4974985607fe4f9525093d5ff773d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 16:22:30 +0200 Subject: [PATCH 1/6] Allow users to force-reconnect to the powersync service --- lib/core/widgets/app_bar.dart | 20 ++++++++++-- lib/core/widgets/sync_status_dialog.dart | 18 ++++++++++- lib/l10n/app_de.arb | 1 + lib/l10n/app_en.arb | 4 +++ lib/l10n/app_es.arb | 1 + lib/l10n/app_fr.arb | 1 + .../core/widgets/sync_status_dialog_test.dart | 32 +++++++++++++++++++ 7 files changed, 74 insertions(+), 3 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 9713f86e5..350260967 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -19,12 +19,15 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/core/form_screen.dart'; +import 'package:wger/core/network/auth_http_client.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; import 'package:wger/core/settings_dashboard_widgets_screen.dart'; import 'package:wger/core/widgets/about.dart'; import 'package:wger/core/widgets/sync_status_dialog.dart'; -import 'package:wger/database/powersync/powersync.dart' show syncStatus, syncWatchdogProvider; +import 'package:wger/database/powersync/powersync.dart' + show builtPowerSyncInstance, connectPowerSync, syncStatus, syncWatchdogProvider; import 'package:wger/features/account/providers/account_notifier.dart'; import 'package:wger/features/account/widgets/forms.dart'; import 'package:wger/features/account/widgets/settings.dart'; @@ -53,10 +56,23 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // Like syncState, the stalled flag is a snapshot taken when the dialog opens + // Like syncState, the stalled and offline flags are snapshots + // taken when the dialog opens. No reconnect action while offline: + // the app deliberately disconnects there (see powerSyncInstance) builder: (_) => SyncStatusDialog( syncState, stalled: ref.read(syncWatchdogProvider).stalled.value, + onReconnect: !ref.read(networkStatusProvider) + ? null + : () { + final db = builtPowerSyncInstance; + final serverUrl = ref.read(wgerBaseProvider).serverUrl; + if (db == null || serverUrl == null) { + return; + } + ref.read(syncWatchdogProvider).reset(); + connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider)); + }, ), ), ), diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 3f362bab9..3fa41ab10 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -100,7 +100,11 @@ class SyncStatusDialog extends StatelessWidget { /// case, so the dialog adds a hint about likely network-side blockers. final bool stalled; - const SyncStatusDialog(this._status, {this.stalled = false, super.key}); + /// Drops the current sync connection and opens a fresh one. When null, + /// the reconnect action is not shown. + final VoidCallback? onReconnect; + + const SyncStatusDialog(this._status, {this.stalled = false, this.onReconnect, super.key}); @override Widget build(BuildContext context) { @@ -198,6 +202,18 @@ class SyncStatusDialog extends StatelessWidget { }, child: Text(i18n.applicationLogs), ), + // A stuck stream (firewall, VPN, flaky DNS) often recovers on a + // fresh connection and can look healthy here while hanging, so the + // action is not gated on an error. Absent only while offline, where + // reconnecting would just spin against an unreachable backend. + if (onReconnect != null) + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onReconnect!(); + }, + child: Text(i18n.syncStatusReconnect), + ), TextButton( onPressed: () => Navigator.of(context).pop(), child: Text(MaterialLocalizations.of(context).closeButtonLabel), diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index cde9d0198..33b8c4f7e 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1149,6 +1149,7 @@ "syncStatusLastSynced": "Letzte Synchronisierung", "syncStatusErrorDetails": "Fehlerdetails", "syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.", + "syncStatusReconnect": "Neu verbinden", "sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an", "endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen", "minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c8026edc9..6c6564e35 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1401,6 +1401,10 @@ "@syncStatusStalledHint": { "description": "Hint shown in the sync status dialog when the app keeps connecting but never receives any sync data, which usually means something on the network is blocking the connection" }, + "syncStatusReconnect": "Reconnect", + "@syncStatusReconnect": { + "description": "Button in the sync status dialog that drops the stuck connection to the sync service and opens a fresh one" + }, "filterNutriscore": "Nutri-Score filter", "@filterNutriscore": { "description": "Heading for the Nutri-Score slider in the ingredient search filter dialog" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 16cc2d7e5..e02a5d948 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1186,6 +1186,7 @@ "syncStatusLastSynced": "Última sincronización", "syncStatusErrorDetails": "Detalles del error", "syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.", + "syncStatusReconnect": "Reconectar", "sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo", "weightOrRepsRequired": "Introduce un peso, repeticiones o ambos", "timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 51a7e989a..f6f259e2b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1157,6 +1157,7 @@ "syncStatusLastSynced": "Dernière synchronisation", "syncStatusErrorDetails": "Détails de l'erreur", "syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.", + "syncStatusReconnect": "Reconnecter", "sessionExpired": "Votre session a expiré, veuillez vous reconnecter", "weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux", "timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides", diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index 76c4985f1..e0b499cd2 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -174,6 +174,38 @@ void main() { expect(find.text(i18n.syncStatusError), findsOneWidget); }); + testWidgets('shows the reconnect action on error and fires the callback', (tester) async { + var reconnected = false; + await tester.pumpWidget( + _wrap( + SyncStatusDialog( + buildSyncStatus(connected: true, downloadError: Exception('boom')), + onReconnect: () => reconnected = true, + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text(i18n.syncStatusReconnect)); + await tester.pumpAndSettle(); + expect(reconnected, isTrue); + }); + + testWidgets('shows the reconnect action even while the sync looks healthy', (tester) async { + await tester.pumpWidget( + _wrap(SyncStatusDialog(buildSyncStatus(connected: true), onReconnect: () {})), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.syncStatusReconnect), findsOneWidget); + }); + + testWidgets('omits the reconnect action without a callback', (tester) async { + await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); + + expect(find.text(i18n.syncStatusReconnect), findsNothing); + }); + testWidgets('renders the expander with the raw error message when present', (tester) async { await _pumpDialog( tester, From 30f44ad4713f229a35ec8d70f81285b25f9a12a3 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 16:50:14 +0200 Subject: [PATCH 2/6] Show more sync information on the sync status dialog Also, make it stateful so it shows live data for sync queue size, etc. --- lib/core/widgets/app_bar.dart | 10 +- lib/core/widgets/sync_status_dialog.dart | 259 ++++++++++-------- lib/database/powersync/powersync.dart | 9 + lib/l10n/app_de.arb | 2 + lib/l10n/app_en.arb | 13 + lib/l10n/app_es.arb | 2 + lib/l10n/app_fr.arb | 2 + .../core/widgets/sync_status_dialog_test.dart | 126 +++++++-- test/helpers/sync_status.dart | 7 + 9 files changed, 297 insertions(+), 133 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 350260967..d32b7e396 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -56,12 +56,12 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // Like syncState, the stalled and offline flags are snapshots - // taken when the dialog opens. No reconnect action while offline: - // the app deliberately disconnects there (see powerSyncInstance) + // The dialog watches the sync state itself; only the server URL + // and the offline gate are snapshots taken when it opens. + // No reconnect action while offline: the app deliberately + // disconnects there (see powerSyncInstance) builder: (_) => SyncStatusDialog( - syncState, - stalled: ref.read(syncWatchdogProvider).stalled.value, + serverUrl: ref.read(wgerBaseProvider).serverUrl, onReconnect: !ref.read(networkStatusProvider) ? null : () { diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 3fa41ab10..f41796a31 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -17,10 +17,13 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:powersync/powersync.dart' show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage; +import 'package:wger/database/powersync/powersync.dart' + show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/powersync/connector.dart' show RetryableUploadException; @@ -91,134 +94,172 @@ String? _categoriseSyncError(Object error) { } } -/// Shows the current powersync status -class SyncStatusDialog extends StatelessWidget { - final SyncStatus _status; - - /// True when the sync stream keeps reconnecting without ever receiving - /// data (see SyncStreamWatchdog). There is no error to show in that - /// case, so the dialog adds a hint about likely network-side blockers. - final bool stalled; - +/// Shows the current powersync status. Watches the status, the upload queue +/// and the watchdog, so the content keeps updating while the dialog is open. +class SyncStatusDialog extends ConsumerWidget { /// Drops the current sync connection and opens a fresh one. When null, /// the reconnect action is not shown. final VoidCallback? onReconnect; - const SyncStatusDialog(this._status, {this.stalled = false, this.onReconnect, super.key}); + /// Server this app is syncing against. Hidden when null. + final String? serverUrl; + + const SyncStatusDialog({this.onReconnect, this.serverUrl, super.key}); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final i18n = AppLocalizations.of(context); final theme = Theme.of(context); - final status = syncStatusIconAndLabel(_status, i18n); - final lastSynced = _status.lastSyncedAt; - final errorCategory = _status.anyError == null ? null : _categoriseSyncError(_status.anyError!); + final syncState = ref.watch(syncStatus); + // The queue count loads async for a moment; treat that as an empty queue + final pendingUploads = ref.watch(pendingUploadCountProvider).value ?? 0; + final status = syncStatusIconAndLabel(syncState, i18n); + final lastSynced = syncState.lastSyncedAt; + final errorCategory = syncState.anyError == null + ? null + : _categoriseSyncError(syncState.anyError!); - return AlertDialog( - title: Text(i18n.syncStatusDialogTitle), - content: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Icon(status.icon, size: 28), - const SizedBox(width: 12), - Expanded( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(status.label, style: theme.textTheme.titleMedium), - if (errorCategory != null) - Text( - errorCategory, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, + // stalled: the sync stream keeps reconnecting without ever receiving + // data (see SyncStreamWatchdog). There is no error to show in that + // case, so the dialog adds a hint about likely network-side blockers. + return ValueListenableBuilder( + valueListenable: ref.watch(syncWatchdogProvider).stalled, + builder: (context, stalled, _) => AlertDialog( + title: Text(i18n.syncStatusDialogTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon(status.icon, size: 28), + const SizedBox(width: 12), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(status.label, style: theme.textTheme.titleMedium), + if (errorCategory != null) + Text( + errorCategory, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), ), + ], + ), + ), + ], + ), + // Progress through the running download, so a long initial sync + // is visibly moving instead of sitting on a static label. + if (syncState.downloadProgress case final progress?) ...[ + const SizedBox(height: 12), + LinearProgressIndicator(value: progress.downloadedFraction), + const SizedBox(height: 4), + Text( + '${progress.downloadedOperations} / ${progress.totalOperations}', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + if (stalled && syncState.anyError == null) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusStalledHint, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + if (pendingUploads > 0) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusPendingUploads(pendingUploads), + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 16), + + // Last sync timestamp if available + Text(i18n.syncStatusLastSynced, style: theme.textTheme.labelMedium), + const SizedBox(height: 4), + Text( + lastSynced != null + ? localizedDate(context).add_Hms().format(lastSynced.toLocal()) + : syncState.hasSynced == false + ? i18n.syncStatusNeverSynced + : '-/-', + ), + if (serverUrl != null) ...[ + const SizedBox(height: 16), + Text(i18n.serverSectionLabel, style: theme.textTheme.labelMedium), + const SizedBox(height: 4), + Text(serverUrl!), + ], + + // Raw error in an expandable section. Only shown when an error + // actually exists; otherwise we don't render the tile at all, + // so the dialog stays compact in the happy case. + if (syncState.anyError != null) ...[ + const SizedBox(height: 8), + Theme( + // ExpansionTile draws its own dividers; suppress the default + // divider colour so the tile blends with the dialog content. + data: theme.copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + tilePadding: EdgeInsets.zero, + childrenPadding: const EdgeInsets.only(bottom: 8), + title: Text(i18n.syncStatusErrorDetails), + children: [ + SelectableText( + syncState.anyError!.toString(), + style: theme.textTheme.bodySmall?.copyWith( + fontFamily: 'monospace', + color: theme.colorScheme.error, ), + ), ], ), ), ], - ), - if (stalled && _status.anyError == null) ...[ - const SizedBox(height: 8), - Text( - i18n.syncStatusStalledHint, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), ], - const SizedBox(height: 16), - - // Last sync timestamp if available - Text(i18n.syncStatusLastSynced, style: theme.textTheme.labelMedium), - const SizedBox(height: 4), - Text( - lastSynced == null - ? '-/-' - : localizedDate(context).add_Hms().format(lastSynced.toLocal()), - ), - - // Raw error in an expandable section. Only shown when an error - // actually exists; otherwise we don't render the tile at all, - // so the dialog stays compact in the happy case. - if (_status.anyError != null) ...[ - const SizedBox(height: 8), - Theme( - // ExpansionTile draws its own dividers; suppress the default - // divider colour so the tile blends with the dialog content. - data: theme.copyWith(dividerColor: Colors.transparent), - child: ExpansionTile( - tilePadding: EdgeInsets.zero, - childrenPadding: const EdgeInsets.only(bottom: 8), - title: Text(i18n.syncStatusErrorDetails), - children: [ - SelectableText( - _status.anyError!.toString(), - style: theme.textTheme.bodySmall?.copyWith( - fontFamily: 'monospace', - color: theme.colorScheme.error, - ), - ), - ], - ), + ), + actions: [ + // The stalled hint and the WARNING land in the application logs; + // give the user a direct path to them. + if (stalled && syncState.anyError == null) + TextButton( + onPressed: () { + final navigator = Navigator.of(context); + navigator.pop(); + navigator.pushNamed(LogOverviewPage.routeName); + }, + child: Text(i18n.applicationLogs), ), - ], + // A stuck stream (firewall, VPN, flaky DNS) often recovers on a + // fresh connection and can look healthy here while hanging, so the + // action is not gated on an error. Absent only while offline, where + // reconnecting would just spin against an unreachable backend. + if (onReconnect != null) + TextButton( + onPressed: () { + Navigator.of(context).pop(); + onReconnect!(); + }, + child: Text(i18n.syncStatusReconnect), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(MaterialLocalizations.of(context).closeButtonLabel), + ), ], ), - actions: [ - // The stalled hint and the WARNING land in the application logs; - // give the user a direct path to them. - if (stalled && _status.anyError == null) - TextButton( - onPressed: () { - final navigator = Navigator.of(context); - navigator.pop(); - navigator.pushNamed(LogOverviewPage.routeName); - }, - child: Text(i18n.applicationLogs), - ), - // A stuck stream (firewall, VPN, flaky DNS) often recovers on a - // fresh connection and can look healthy here while hanging, so the - // action is not gated on an error. Absent only while offline, where - // reconnecting would just spin against an unreachable backend. - if (onReconnect != null) - TextButton( - onPressed: () { - Navigator.of(context).pop(); - onReconnect!(); - }, - child: Text(i18n.syncStatusReconnect), - ), - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: Text(MaterialLocalizations.of(context).closeButtonLabel), - ), - ], ); } } diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index 1349c9c99..09d508a85 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -192,6 +192,15 @@ void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client) ); } +/// Number of local changes still waiting in the upload queue. Emits again +/// whenever the queue changes, so consumers can show a live count. +final pendingUploadCountProvider = StreamProvider.autoDispose((ref) async* { + final db = await ref.watch(powerSyncInstanceProvider.future); + yield* db + .watch('SELECT count(*) AS count FROM ps_crud', triggerOnTables: ['ps_crud']) + .map((rows) => rows.first['count'] as int); +}); + final _syncStatusInternal = StreamProvider((ref) { return Stream.fromFuture( ref.watch(powerSyncInstanceProvider.future), diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 33b8c4f7e..37f3cc372 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1150,6 +1150,8 @@ "syncStatusErrorDetails": "Fehlerdetails", "syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.", "syncStatusReconnect": "Neu verbinden", + "syncStatusPendingUploads": "{count, plural, =1{Eine lokale Änderung wartet auf den Upload} other{{count} lokale Änderungen warten auf den Upload}}", + "syncStatusNeverSynced": "Noch nie synchronisiert", "sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an", "endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen", "minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 6c6564e35..1b3ebcd57 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1405,6 +1405,19 @@ "@syncStatusReconnect": { "description": "Button in the sync status dialog that drops the stuck connection to the sync service and opens a fresh one" }, + "syncStatusPendingUploads": "{count, plural, =1{One local change waiting for upload} other{{count} local changes waiting for upload}}", + "@syncStatusPendingUploads": { + "description": "Line in the sync status dialog showing how many local changes have not reached the server yet", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "syncStatusNeverSynced": "Not yet synchronised", + "@syncStatusNeverSynced": { + "description": "Shown in the sync status dialog instead of the last-sync timestamp when this device has never completed a synchronisation" + }, "filterNutriscore": "Nutri-Score filter", "@filterNutriscore": { "description": "Heading for the Nutri-Score slider in the ingredient search filter dialog" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index e02a5d948..82fe3fc47 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1187,6 +1187,8 @@ "syncStatusErrorDetails": "Detalles del error", "syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.", "syncStatusReconnect": "Reconectar", + "syncStatusPendingUploads": "{count, plural, =1{Un cambio local pendiente de subir} other{{count} cambios locales pendientes de subir}}", + "syncStatusNeverSynced": "Aún no sincronizado", "sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo", "weightOrRepsRequired": "Introduce un peso, repeticiones o ambos", "timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index f6f259e2b..469adaca9 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1158,6 +1158,8 @@ "syncStatusErrorDetails": "Détails de l'erreur", "syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.", "syncStatusReconnect": "Reconnecter", + "syncStatusPendingUploads": "{count, plural, =1{Une modification locale en attente d'envoi} other{{count} modifications locales en attente d'envoi}}", + "syncStatusNeverSynced": "Pas encore synchronisé", "sessionExpired": "Votre session a expiré, veuillez vous reconnecter", "weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux", "timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides", diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index e0b499cd2..f123fb4d4 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -16,9 +16,11 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:io' show SocketException; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:powersync/powersync.dart' show @@ -28,24 +30,43 @@ import 'package:powersync/powersync.dart' SyncStatus, UpdateType; import 'package:wger/core/widgets/sync_status_dialog.dart'; +import 'package:wger/database/powersync/powersync.dart' + show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/l10n/generated/app_localizations_en.dart'; import 'package:wger/powersync/connector.dart' show RetryableUploadException; +import 'package:wger/powersync/sync_watchdog.dart'; import '../../helpers/sync_status.dart'; -Widget _wrap(Widget child) { - return MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - locale: const Locale('en'), - home: Scaffold(body: child), +/// Wraps [child] in a MaterialApp with the providers the dialog watches +/// overridden to fixed test values. +Widget _wrap( + Widget child, { + required SyncStatus status, + bool stalled = false, + Stream? pendingUploads, +}) { + final watchdog = SyncStreamWatchdog(); + watchdog.stalled.value = stalled; + return ProviderScope( + overrides: [ + syncStatus.overrideWithValue(status), + syncWatchdogProvider.overrideWithValue(watchdog), + pendingUploadCountProvider.overrideWith((ref) => pendingUploads ?? const Stream.empty()), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: Scaffold(body: child), + ), ); } -/// Renders [SyncStatusDialog] inside a minimal MaterialApp + Scaffold. +/// Renders a plain [SyncStatusDialog] for the given status. Future _pumpDialog(WidgetTester tester, SyncStatus status) async { - await tester.pumpWidget(_wrap(SyncStatusDialog(status))); + await tester.pumpWidget(_wrap(const SyncStatusDialog(), status: status)); await tester.pumpAndSettle(); } @@ -118,13 +139,83 @@ void main() { }); group('SyncStatusDialog rendering', () { - testWidgets('renders title, status label, and "never synced" placeholder', (tester) async { + testWidgets('renders title, status label, and the never-synced text', (tester) async { + // Without a lastSyncedAt the status derives hasSynced == false await _pumpDialog(tester, buildSyncStatus(connected: true)); expect(find.text(i18n.syncStatusDialogTitle), findsOneWidget); expect(find.text(i18n.syncStatusConnected), findsOneWidget); expect(find.text(i18n.syncStatusLastSynced), findsOneWidget); + expect(find.text(i18n.syncStatusNeverSynced), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsNothing); + }); + + testWidgets('renders the placeholder while the sync state is still unknown', (tester) async { + await _pumpDialog(tester, buildUninitializedSyncStatus()); + expect(find.text('-/-'), findsOneWidget); + expect(find.text(i18n.syncStatusNeverSynced), findsNothing); + }); + + testWidgets('shows the pending-upload count when changes are waiting', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: Stream.value(3), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.syncStatusPendingUploads(3)), findsOneWidget); + }); + + testWidgets('omits the pending-upload line when the queue is empty', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: Stream.value(0), + ), + ); + await tester.pumpAndSettle(); + + expect(find.textContaining('upload'), findsNothing); + }); + + testWidgets('updates the pending-upload count while the dialog is open', (tester) async { + final queue = StreamController(); + addTearDown(queue.close); + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(), + status: buildSyncStatus(connected: true), + pendingUploads: queue.stream, + ), + ); + await tester.pumpAndSettle(); + + queue.add(2); + await tester.pumpAndSettle(); + expect(find.text(i18n.syncStatusPendingUploads(2)), findsOneWidget); + + // The queue drained: the line disappears without reopening the dialog + queue.add(0); + await tester.pumpAndSettle(); + expect(find.textContaining('upload'), findsNothing); + }); + + testWidgets('shows the server URL when provided', (tester) async { + await tester.pumpWidget( + _wrap( + const SyncStatusDialog(serverUrl: 'https://wger.example'), + status: buildSyncStatus(connected: true), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text(i18n.serverSectionLabel), findsOneWidget); + expect(find.text('https://wger.example'), findsOneWidget); }); testWidgets('formats the last-sync timestamp when set', (tester) async { @@ -144,7 +235,7 @@ void main() { testWidgets('shows the blocked-connection hint when stalled without an error', (tester) async { await tester.pumpWidget( - _wrap(SyncStatusDialog(buildSyncStatus(connecting: true), stalled: true)), + _wrap(const SyncStatusDialog(), status: buildSyncStatus(connecting: true), stalled: true), ); await tester.pumpAndSettle(); @@ -162,10 +253,9 @@ void main() { testWidgets('prefers the real error over the stalled hint', (tester) async { await tester.pumpWidget( _wrap( - SyncStatusDialog( - buildSyncStatus(connecting: true, downloadError: Exception('boom')), - stalled: true, - ), + const SyncStatusDialog(), + status: buildSyncStatus(connecting: true, downloadError: Exception('boom')), + stalled: true, ), ); await tester.pumpAndSettle(); @@ -178,10 +268,8 @@ void main() { var reconnected = false; await tester.pumpWidget( _wrap( - SyncStatusDialog( - buildSyncStatus(connected: true, downloadError: Exception('boom')), - onReconnect: () => reconnected = true, - ), + SyncStatusDialog(onReconnect: () => reconnected = true), + status: buildSyncStatus(connected: true, downloadError: Exception('boom')), ), ); await tester.pumpAndSettle(); @@ -193,7 +281,7 @@ void main() { testWidgets('shows the reconnect action even while the sync looks healthy', (tester) async { await tester.pumpWidget( - _wrap(SyncStatusDialog(buildSyncStatus(connected: true), onReconnect: () {})), + _wrap(SyncStatusDialog(onReconnect: () {}), status: buildSyncStatus(connected: true)), ); await tester.pumpAndSettle(); diff --git a/test/helpers/sync_status.dart b/test/helpers/sync_status.dart index b8220687a..b64546907 100644 --- a/test/helpers/sync_status.dart +++ b/test/helpers/sync_status.dart @@ -44,3 +44,10 @@ SyncStatus buildSyncStatus({ streamSubscriptions: null, ); } + +/// Builds the status used before the sync state has been loaded from the +/// database (`hasSynced` still null). +SyncStatus buildUninitializedSyncStatus() { + // ignore: invalid_use_of_internal_member + return const SyncStatus.uninitialized(); +} From 718fa05d1b6f7174b02bd6057ff892586a478168 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:06:05 +0200 Subject: [PATCH 3/6] Add sync diagnostics to the "submit to github" error dialog --- lib/core/error_dialogs.dart | 2 + lib/core/errors.dart | 6 +- lib/core/widgets/sync_status_dialog.dart | 98 +++++++------- lib/powersync/sync_diagnostics.dart | 120 ++++++++++++++++++ test/core/errors_test.dart | 42 ++++++ .../core/widgets/sync_status_dialog_test.dart | 16 +++ test/powersync/sync_diagnostics_test.dart | 86 +++++++++++++ 7 files changed, 316 insertions(+), 54 deletions(-) create mode 100644 lib/powersync/sync_diagnostics.dart create mode 100644 test/powersync/sync_diagnostics_test.dart diff --git a/lib/core/error_dialogs.dart b/lib/core/error_dialogs.dart index 4105e2209..2a6869e6a 100644 --- a/lib/core/error_dialogs.dart +++ b/lib/core/error_dialogs.dart @@ -28,6 +28,7 @@ import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/core/keys.dart'; import 'package:wger/core/logs.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; /// Whether an error dialog is currently on screen. /// @@ -222,6 +223,7 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext issueErrorMessage: issueErrorMessage, stackTrace: fullStackTrace, applicationLogs: applicationLogs, + syncDiagnostics: await collectSyncDiagnostics(), ); final Uri reportUri = Uri.parse(githubIssueUrl); diff --git a/lib/core/errors.dart b/lib/core/errors.dart index 07a2ac8bb..14457f7a6 100644 --- a/lib/core/errors.dart +++ b/lib/core/errors.dart @@ -74,8 +74,9 @@ bool isNetworkError(Object e) { String buildGithubIssueUrl({ required String issueTitle, required String issueErrorMessage, - required String stackTrace, required List applicationLogs, + String? stackTrace, + String? syncDiagnostics, }) { String composeUrl(List logs) { final logText = logs.isEmpty ? '-- No logs available --' : logs.join('\n'); @@ -85,7 +86,8 @@ String buildGithubIssueUrl({ '## Error details\n\n' 'Error title: $issueTitle\n' 'Error message: $issueErrorMessage\n' - 'Stack trace:\n```\n$stackTrace\n```\n\n' + '${stackTrace != null ? 'Stack trace:\n```\n$stackTrace\n```\n\n' : ''}' + '${syncDiagnostics != null ? 'Sync status:\n```\n$syncDiagnostics\n```\n\n' : ''}' 'App logs (last ${logs.length} entries):\n```\n$logText\n```'; return '$GITHUB_ISSUES_BUG_URL' '&title=${Uri.encodeComponent(issueTitle)}' diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index f41796a31..28efa616c 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -18,53 +18,19 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:powersync/powersync.dart' - show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; +import 'package:logging/logging.dart'; +import 'package:powersync/powersync.dart' show SyncStatus; +import 'package:url_launcher/url_launcher.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; import 'package:wger/core/formatting/formatting.dart'; +import 'package:wger/core/logs.dart'; import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage; import 'package:wger/database/powersync/powersync.dart' show pendingUploadCountProvider, syncStatus, syncWatchdogProvider; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/powersync/connector.dart' show RetryableUploadException; +import 'package:wger/powersync/sync_diagnostics.dart'; -/// Maps an HTTP status code to a short English category label. -String _categoriseHttpStatus(int statusCode) { - if (statusCode == 401 || statusCode == 403) { - return 'Authentication error'; - } - if (statusCode >= 500) { - return 'Server error'; - } - return 'HTTP $statusCode'; -} - -/// Classifies a sync error into a short English category label -String? _categoriseSyncError(Object error) { - if (error is CredentialsException) { - return 'Authentication error'; - } - - if (error is PowerSyncProtocolException) { - return 'Protocol error'; - } - - if (error is SyncResponseException) { - return _categoriseHttpStatus(error.statusCode); - } - if (error is RetryableUploadException) { - return _categoriseHttpStatus(error.statusCode); - } - - final typeName = error.runtimeType.toString(); - if (typeName.endsWith('SocketException') || - typeName == 'WebSocketChannelException' || - typeName == 'ClientException' || - typeName == 'HttpException') { - return 'Connection error'; - } - - return null; -} +final _logger = Logger('SyncStatusDialog'); ({IconData icon, String label}) syncStatusIconAndLabel( SyncStatus status, @@ -117,7 +83,7 @@ class SyncStatusDialog extends ConsumerWidget { final lastSynced = syncState.lastSyncedAt; final errorCategory = syncState.anyError == null ? null - : _categoriseSyncError(syncState.anyError!); + : categoriseSyncError(syncState.anyError!); // stalled: the sync stream keeps reconnecting without ever receiving // data (see SyncStreamWatchdog). There is no error to show in that @@ -153,6 +119,18 @@ class SyncStatusDialog extends ConsumerWidget { ), ], ), + + // Stalled or errored sync + if (stalled && syncState.anyError == null) ...[ + const SizedBox(height: 8), + Text( + i18n.syncStatusStalledHint, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + // Progress through the running download, so a long initial sync // is visibly moving instead of sitting on a static label. if (syncState.downloadProgress case final progress?) ...[ @@ -166,15 +144,6 @@ class SyncStatusDialog extends ConsumerWidget { ), ), ], - if (stalled && syncState.anyError == null) ...[ - const SizedBox(height: 8), - Text( - i18n.syncStatusStalledHint, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], if (pendingUploads > 0) ...[ const SizedBox(height: 8), Text( @@ -205,7 +174,6 @@ class SyncStatusDialog extends ConsumerWidget { // Raw error in an expandable section. Only shown when an error // actually exists; otherwise we don't render the tile at all, - // so the dialog stays compact in the happy case. if (syncState.anyError != null) ...[ const SizedBox(height: 8), Theme( @@ -242,6 +210,32 @@ class SyncStatusDialog extends ConsumerWidget { }, child: Text(i18n.applicationLogs), ), + // Pre-filled bug report including the sync snapshot. Sync problems + // usually never raise the fatal error dialog, so this is their + // report path. + if (stalled || syncState.anyError != null) + TextButton( + onPressed: () async { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: + syncState.anyError?.toString() ?? + 'Sync stream stalled (connects but receives no data)', + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: formatSyncDiagnostics( + syncState, + pendingUploads: pendingUploads, + server: serverCategory(serverUrl), + ), + ); + try { + await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); + } catch (e) { + _logger.warning('Error opening issue tracker: $e'); + } + }, + child: const Text('Report issue'), + ), // A stuck stream (firewall, VPN, flaky DNS) often recovers on a // fresh connection and can look healthy here while hanging, so the // action is not gated on an error. Absent only while offline, where diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart new file mode 100644 index 000000000..8c02fdcd1 --- /dev/null +++ b/lib/powersync/sync_diagnostics.dart @@ -0,0 +1,120 @@ +/* + * 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:powersync/powersync.dart' + show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; +import 'package:wger/core/consts.dart'; +import 'package:wger/database/powersync/powersync.dart' show builtPowerSyncInstance; +import 'package:wger/powersync/connector.dart' show RetryableUploadException; + +/// Maps an HTTP status code to a short English category label. +String _categoriseHttpStatus(int statusCode) { + if (statusCode == 401 || statusCode == 403) { + return 'Authentication error'; + } + if (statusCode >= 500) { + return 'Server error'; + } + return 'HTTP $statusCode'; +} + +/// Classifies a sync error into a short English category label +String? categoriseSyncError(Object error) { + if (error is CredentialsException) { + return 'Authentication error'; + } + + if (error is PowerSyncProtocolException) { + return 'Protocol error'; + } + + if (error is SyncResponseException) { + return _categoriseHttpStatus(error.statusCode); + } + if (error is RetryableUploadException) { + return _categoriseHttpStatus(error.statusCode); + } + + final typeName = error.runtimeType.toString(); + if (typeName.endsWith('SocketException') || + typeName == 'WebSocketChannelException' || + typeName == 'ClientException' || + typeName == 'HttpException') { + return 'Connection error'; + } + + return null; +} + +/// Reduces [serverUrl] to a category for bug reports, so self-hosted URLs +/// stay private. Null when the URL is unknown. +String? serverCategory(String? serverUrl) { + return switch (serverUrl) { + null => null, + DEFAULT_SERVER_PROD => 'wger.de', + DEFAULT_SERVER_TEST => 'dev.wger.de', + _ => 'self-hosted', + }; +} + +/// Renders a compact sync-state summary for bug reports. +String formatSyncDiagnostics( + SyncStatus status, { + required int pendingUploads, + String? server, +}) { + final buffer = StringBuffer(); + if (server != null) { + buffer.writeln('server: $server'); + } + buffer + ..writeln( + 'connected: ${status.connected}, connecting: ${status.connecting}, ' + 'downloading: ${status.downloading}, uploading: ${status.uploading}', + ) + ..writeln('last successful sync: ${status.lastSyncedAt?.toUtc().toIso8601String() ?? 'never'}') + ..writeln('pending uploads: $pendingUploads'); + if (status.downloadProgress case final progress?) { + buffer.writeln( + 'download progress: ${progress.downloadedOperations} / ${progress.totalOperations}', + ); + } + if (status.anyError case final error?) { + // Clamped: some exception toStrings embed whole response bodies, and + // the report has to fit into a GitHub issue URL. + final text = error.toString(); + final clamped = text.length <= 300 ? text : '${text.substring(0, 300)}…'; + buffer.writeln('error (${categoriseSyncError(error) ?? 'Uncategorised'}): $clamped'); + } + return buffer.toString().trimRight(); +} + +/// Snapshot of the current sync state for bug reports, or null when the +/// PowerSync database has not been initialised. +Future collectSyncDiagnostics({String? serverUrl}) async { + final db = builtPowerSyncInstance; + if (db == null) { + return null; + } + final queue = await db.getUploadQueueStats(); + return formatSyncDiagnostics( + db.currentStatus, + pendingUploads: queue.count, + server: serverCategory(serverUrl), + ); +} diff --git a/test/core/errors_test.dart b/test/core/errors_test.dart index 780efbff7..78318e58d 100644 --- a/test/core/errors_test.dart +++ b/test/core/errors_test.dart @@ -147,6 +147,48 @@ void main() { expect(description, contains('log line 1')); }); + test('Includes the sync status section when diagnostics are passed', () { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: 'boom', + applicationLogs: ['log line'], + syncDiagnostics: 'connected: false\npending uploads: 3', + ); + + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('Sync status:')); + expect(description, contains('pending uploads: 3')); + // No stack trace was passed, so the section is omitted entirely + expect(description, isNot(contains('Stack trace:'))); + }); + + test('Keeps the sync status section and drops logs instead', () { + final url = buildGithubIssueUrl( + issueTitle: 'Sync error', + issueErrorMessage: 'boom', + applicationLogs: List.generate(3000, (i) => 'log entry number $i'), + syncDiagnostics: 'connected: false\npending uploads: 3', + ); + + expect(url.length, lessThanOrEqualTo(GITHUB_ISSUES_MAX_URL_LENGTH)); + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('pending uploads: 3')); + expect(description, isNot(contains('log entry number 2999'))); + }); + + test('Omits the sync status section without diagnostics', () { + final url = buildGithubIssueUrl( + issueTitle: 'An error occurred', + issueErrorMessage: 'boom', + stackTrace: 'trace', + applicationLogs: ['log line'], + ); + + final description = Uri.parse(url).queryParameters['description']!; + expect(description, isNot(contains('Sync status:'))); + expect(description, contains('Stack trace:')); + }); + test('Drops the oldest log entries, keeps the newest', () { // Logs come newest-first, so index 0 is the most recent entry. final logs = List.generate(3000, (i) => 'log entry $i'); diff --git a/test/core/widgets/sync_status_dialog_test.dart b/test/core/widgets/sync_status_dialog_test.dart index f123fb4d4..1b22fc200 100644 --- a/test/core/widgets/sync_status_dialog_test.dart +++ b/test/core/widgets/sync_status_dialog_test.dart @@ -288,6 +288,22 @@ void main() { expect(find.text(i18n.syncStatusReconnect), findsOneWidget); }); + testWidgets('offers the report action on error and when stalled, not while healthy', ( + tester, + ) async { + await _pumpDialog(tester, buildSyncStatus(connected: true)); + expect(find.text('Report issue'), findsNothing); + + await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); + expect(find.text('Report issue'), findsOneWidget); + + await tester.pumpWidget( + _wrap(const SyncStatusDialog(), status: buildSyncStatus(connecting: true), stalled: true), + ); + await tester.pumpAndSettle(); + expect(find.text('Report issue'), findsOneWidget); + }); + testWidgets('omits the reconnect action without a callback', (tester) async { await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: Exception('boom'))); diff --git a/test/powersync/sync_diagnostics_test.dart b/test/powersync/sync_diagnostics_test.dart new file mode 100644 index 000000000..4ef0de2c6 --- /dev/null +++ b/test/powersync/sync_diagnostics_test.dart @@ -0,0 +1,86 @@ +/* + * 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 'dart:io' show SocketException; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/consts.dart'; +import 'package:wger/powersync/sync_diagnostics.dart'; + +import '../helpers/sync_status.dart'; + +void main() { + group('serverCategory', () { + test('maps the known servers and hides self-hosted URLs', () { + expect(serverCategory(null), isNull); + expect(serverCategory(DEFAULT_SERVER_PROD), 'wger.de'); + expect(serverCategory(DEFAULT_SERVER_TEST), 'dev.wger.de'); + expect(serverCategory('https://wger.my-private-nas.example'), 'self-hosted'); + }); + }); + + group('formatSyncDiagnostics', () { + test('renders the healthy state', () { + final text = formatSyncDiagnostics( + buildSyncStatus(connected: true, lastSyncedAt: DateTime.utc(2026, 7, 29, 10, 30)), + pendingUploads: 0, + server: 'wger.de', + ); + + expect(text, contains('server: wger.de')); + expect(text, contains('connected: true, connecting: false')); + expect(text, contains('last successful sync: 2026-07-29T10:30:00.000Z')); + expect(text, contains('pending uploads: 0')); + expect(text, isNot(contains('error'))); + }); + + test('reports a never-completed sync and the pending queue', () { + final text = formatSyncDiagnostics(buildSyncStatus(connecting: true), pendingUploads: 3); + + expect(text, contains('last successful sync: never')); + expect(text, contains('pending uploads: 3')); + expect(text, isNot(contains('server:'))); + }); + + test('includes the categorised error', () { + final text = formatSyncDiagnostics( + buildSyncStatus(downloadError: const SocketException('no route to host')), + pendingUploads: 0, + ); + + expect(text, contains('error (Connection error): SocketException')); + }); + + test('clamps oversized error messages', () { + final text = formatSyncDiagnostics( + buildSyncStatus(downloadError: Exception('x' * 5000)), + pendingUploads: 0, + ); + + final errorLine = text.split('\n').firstWhere((line) => line.startsWith('error')); + expect(errorLine.length, lessThan(350)); + expect(errorLine, endsWith('…')); + }); + }); + + group('collectSyncDiagnostics', () { + test('returns null while the PowerSync database is not initialised', () async { + expect(await collectSyncDiagnostics(), isNull); + }); + }); +} From 9e446e0b94d82ca29d0d477af90322bd8a9c4b20 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:23:09 +0200 Subject: [PATCH 4/6] Allow users to submit issues to github with full stackstrace and sync debug info --- lib/core/consts.dart | 6 ++- lib/core/errors.dart | 63 +++++++++++++++++++----------- lib/core/widgets/about.dart | 19 ++++++++- lib/core/widgets/log_overview.dart | 24 +++++++++++- test/core/errors_test.dart | 23 +++++++++-- 5 files changed, 106 insertions(+), 29 deletions(-) diff --git a/lib/core/consts.dart b/lib/core/consts.dart index 30136fdd7..449f43d6c 100644 --- a/lib/core/consts.dart +++ b/lib/core/consts.dart @@ -161,8 +161,10 @@ const GITHUB_ISSUES_URL = '$GITHUB_REPO_URL/issues/new/choose'; const GITHUB_ISSUES_BUG_URL = '$GITHUB_REPO_URL/issues/new?template=1_bug.yml'; const GITHUB_SPONSORS_URL = 'https://github.com/sponsors/wger-project'; -/// Maximum length for a pre-filled GitHub issue URL -const GITHUB_ISSUES_MAX_URL_LENGTH = 8000; +/// Maximum length for a pre-filled GitHub issue URL. GitHub starts answering +/// issues/new with an error page at roughly 7050 characters (measured 2026-07), +/// so stay well below that. +const GITHUB_ISSUES_MAX_URL_LENGTH = 6500; const DISCORD_URL = 'https://discord.gg/rPWFv6W'; const MASTODON_URL = 'https://fosstodon.org/@wger'; const READTHEDOCS_URL = 'https://wger.readthedocs.io'; diff --git a/lib/core/errors.dart b/lib/core/errors.dart index 14457f7a6..df7b06467 100644 --- a/lib/core/errors.dart +++ b/lib/core/errors.dart @@ -67,42 +67,61 @@ bool isNetworkError(Object e) { /// Builds the URL that opens a pre-filled GitHub bug report. /// -/// The error details are passed to GitHub as query parameters and since -/// GitHub rejects URLs longer than [GITHUB_ISSUES_MAX_URL_LENGTH], when -/// the report would exceed that limit, the oldest log entries are pruned -/// until the URL fits. +/// All error-related parameters are optional so user-initiated reports (no +/// crash, just logs and diagnostics) render without empty error sections. +/// The details are passed to GitHub as query parameters and since GitHub +/// rejects URLs longer than [GITHUB_ISSUES_MAX_URL_LENGTH], an oversized +/// report first drops the oldest log entries and then, if still too long, +/// trims the stack trace from the bottom until the URL fits. String buildGithubIssueUrl({ - required String issueTitle, - required String issueErrorMessage, required List applicationLogs, + String? issueTitle, + String? issueErrorMessage, String? stackTrace, String? syncDiagnostics, }) { - String composeUrl(List logs) { + final descriptionPrompt = issueErrorMessage != null + ? '[Please describe what you were doing when the error occurred.]' + : '[Please describe the problem you are seeing.]'; + + String composeUrl(List logs, String? trace) { final logText = logs.isEmpty ? '-- No logs available --' : logs.join('\n'); - final description = - '## Description\n\n' - '[Please describe what you were doing when the error occurred.]\n\n' - '## Error details\n\n' - 'Error title: $issueTitle\n' - 'Error message: $issueErrorMessage\n' - '${stackTrace != null ? 'Stack trace:\n```\n$stackTrace\n```\n\n' : ''}' - '${syncDiagnostics != null ? 'Sync status:\n```\n$syncDiagnostics\n```\n\n' : ''}' - 'App logs (last ${logs.length} entries):\n```\n$logText\n```'; + final errorDetails = issueErrorMessage == null + ? null + : '## Error details\n\n' + '${issueTitle != null ? 'Error title: $issueTitle\n' : ''}' + 'Error message: $issueErrorMessage' + '${trace != null ? '\nStack trace:\n```\n$trace\n```' : ''}'; + final sections = [ + '## Description\n\n$descriptionPrompt', + ?errorDetails, + if (syncDiagnostics != null) 'Sync status:\n```\n$syncDiagnostics\n```', + 'App logs (last ${logs.length} entries):\n```\n$logText\n```', + ]; + final description = sections.join('\n\n'); return '$GITHUB_ISSUES_BUG_URL' - '&title=${Uri.encodeComponent(issueTitle)}' + '${issueTitle != null ? '&title=${Uri.encodeComponent(issueTitle)}' : ''}' '&description=${Uri.encodeComponent(description)}'; } - // The logs come newest-first, so the oldest entry is the last one. Drop it - // and retry until the URL fits within the limit. + // The logs come newest-first, so the oldest entry is the last one. Once + // all logs are gone, drop stack frames starting from the outermost one; + // the top of the trace is where the error actually happened. var logs = applicationLogs; + var trace = stackTrace; while (true) { - final url = composeUrl(logs); - if (url.length <= GITHUB_ISSUES_MAX_URL_LENGTH || logs.isEmpty) { + final url = composeUrl(logs, trace); + if (url.length <= GITHUB_ISSUES_MAX_URL_LENGTH) { + return url; + } + if (logs.isNotEmpty) { + logs = logs.sublist(0, logs.length - 1); + } else if (trace != null && trace.contains('\n')) { + trace = trace.substring(0, trace.lastIndexOf('\n')); + } else { + // Nothing left to trim return url; } - logs = logs.sublist(0, logs.length - 1); } } diff --git a/lib/core/widgets/about.dart b/lib/core/widgets/about.dart index 87a7de5a0..144308fa0 100644 --- a/lib/core/widgets/about.dart +++ b/lib/core/widgets/about.dart @@ -22,12 +22,16 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:wger/core/consts.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; +import 'package:wger/core/logs.dart'; import 'package:wger/core/misc.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/features/exercises/screens/add_exercise_screen.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; import 'log_overview.dart'; @@ -113,7 +117,20 @@ class AboutPage extends ConsumerWidget { trailing: const Icon(Icons.arrow_outward), title: Text(i18n.aboutBugsListTitle), contentPadding: EdgeInsets.zero, - onTap: () => launchURL(GITHUB_ISSUES_URL, context), + // Pre-fill the report with the app logs and the sync + // snapshot, so user-initiated issues carry the same context + // as crash reports + onTap: () async { + final url = buildGithubIssueUrl( + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: await collectSyncDiagnostics( + serverUrl: ref.read(wgerBaseProvider).serverUrl, + ), + ); + if (context.mounted) { + launchURL(url, context); + } + }, ), ListTile( leading: const Icon(Icons.translate), diff --git a/lib/core/widgets/log_overview.dart b/lib/core/widgets/log_overview.dart index 61c128b82..9894c76e0 100644 --- a/lib/core/widgets/log_overview.dart +++ b/lib/core/widgets/log_overview.dart @@ -18,8 +18,11 @@ import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; +import 'package:wger/core/errors.dart' show buildGithubIssueUrl; import 'package:wger/core/logs.dart'; +import 'package:wger/core/misc.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/powersync/sync_diagnostics.dart' show collectSyncDiagnostics; class LogOverviewPage extends StatelessWidget { static String routeName = '/LogOverviewPage'; @@ -32,7 +35,26 @@ class LogOverviewPage extends StatelessWidget { final logs = InMemoryLogStore().logs.reversed.toList(); return Scaffold( - appBar: AppBar(title: Text(i18n.applicationLogs)), + appBar: AppBar( + title: Text(i18n.applicationLogs), + actions: [ + // Opens a pre-filled GitHub issue with these logs and the current + // sync snapshot + IconButton( + icon: const Icon(Icons.bug_report), + tooltip: 'Report issue', + onPressed: () async { + final url = buildGithubIssueUrl( + applicationLogs: InMemoryLogStore().getFormattedLogs(), + syncDiagnostics: await collectSyncDiagnostics(), + ); + if (context.mounted) { + launchURL(url, context); + } + }, + ), + ], + ), body: logs.isEmpty ? const Center(child: Text('No logs available.')) : ListView.builder( diff --git a/test/core/errors_test.dart b/test/core/errors_test.dart index 78318e58d..b1b3cf3db 100644 --- a/test/core/errors_test.dart +++ b/test/core/errors_test.dart @@ -147,6 +147,21 @@ void main() { expect(description, contains('log line 1')); }); + test('Builds a user-initiated report without error sections', () { + final url = buildGithubIssueUrl( + applicationLogs: ['log line'], + syncDiagnostics: 'connected: true', + ); + + expect(url, startsWith(GITHUB_ISSUES_BUG_URL)); + expect(url, isNot(contains('&title='))); + final description = Uri.parse(url).queryParameters['description']!; + expect(description, contains('[Please describe the problem you are seeing.]')); + expect(description, isNot(contains('Error details'))); + expect(description, contains('Sync status:')); + expect(description, contains('log line')); + }); + test('Includes the sync status section when diagnostics are passed', () { final url = buildGithubIssueUrl( issueTitle: 'Sync error', @@ -206,7 +221,7 @@ void main() { expect(description, isNot(contains('log entry 2999'))); // oldest dropped }); - test('Keeps the full stack trace and drops logs instead', () { + test('Drops logs first, then trims the stack trace from the bottom', () { final longTrace = List.generate( 80, (i) => '#$i SomeClass.someMethod (package:wger/some/file.dart:$i:11)', @@ -221,9 +236,11 @@ void main() { expect(url.length, lessThanOrEqualTo(GITHUB_ISSUES_MAX_URL_LENGTH)); final description = Uri.parse(url).queryParameters['description']!; - // The stack trace is never trimmed: first and last frame survive. + // The trace alone exceeds the limit here, so the logs are gone and + // the outermost frames were dropped; the top of the trace survives. expect(description, contains('#0 SomeClass.someMethod')); - expect(description, contains('#79 SomeClass.someMethod')); + expect(description, isNot(contains('#79 SomeClass.someMethod'))); + expect(description, isNot(contains('log entry number'))); }); }); From 630d4864d8a1e65c89a6cd7a08a6566b3f3f407d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:28:47 +0200 Subject: [PATCH 5/6] Cleanup --- lib/core/widgets/app_bar.dart | 7 ++++--- lib/powersync/sync_diagnostics.dart | 24 ++++++++++++++++++------ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index d32b7e396..98d51154d 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -58,8 +58,9 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { 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 action while offline: the app deliberately - // disconnects there (see powerSyncInstance) + // 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) @@ -67,7 +68,7 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { : () { final db = builtPowerSyncInstance; final serverUrl = ref.read(wgerBaseProvider).serverUrl; - if (db == null || serverUrl == null) { + if (db == null || serverUrl == null || !ref.read(networkStatusProvider)) { return; } ref.read(syncWatchdogProvider).reset(); diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart index 8c02fdcd1..cff4da5bd 100644 --- a/lib/powersync/sync_diagnostics.dart +++ b/lib/powersync/sync_diagnostics.dart @@ -16,12 +16,15 @@ * along with this program. If not, see . */ +import 'package:logging/logging.dart'; import 'package:powersync/powersync.dart' show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus; import 'package:wger/core/consts.dart'; import 'package:wger/database/powersync/powersync.dart' show builtPowerSyncInstance; import 'package:wger/powersync/connector.dart' show RetryableUploadException; +final _logger = Logger('sync_diagnostics'); + /// Maps an HTTP status code to a short English category label. String _categoriseHttpStatus(int statusCode) { if (statusCode == 401 || statusCode == 403) { @@ -106,15 +109,24 @@ String formatSyncDiagnostics( /// Snapshot of the current sync state for bug reports, or null when the /// PowerSync database has not been initialised. +/// +/// Never throws: this runs on report paths where the app may already be in +/// a broken state (e.g. the DB is closing down), and a missing sync section +/// must not prevent the report itself. Future collectSyncDiagnostics({String? serverUrl}) async { final db = builtPowerSyncInstance; if (db == null) { return null; } - final queue = await db.getUploadQueueStats(); - return formatSyncDiagnostics( - db.currentStatus, - pendingUploads: queue.count, - server: serverCategory(serverUrl), - ); + try { + final queue = await db.getUploadQueueStats(); + return formatSyncDiagnostics( + db.currentStatus, + pendingUploads: queue.count, + server: serverCategory(serverUrl), + ); + } catch (e) { + _logger.warning('Could not collect sync diagnostics: $e'); + return null; + } } From 30cc2fc9595c1ac34039caa90d8d9e93016babfd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Wed, 29 Jul 2026 17:42:31 +0200 Subject: [PATCH 6/6] Improve logging --- lib/core/widgets/sync_status_dialog.dart | 4 ++-- lib/powersync/sync_diagnostics.dart | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index 28efa616c..baa878410 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -230,8 +230,8 @@ class SyncStatusDialog extends ConsumerWidget { ); try { await launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication); - } catch (e) { - _logger.warning('Error opening issue tracker: $e'); + } catch (e, s) { + _logger.warning('Error opening issue tracker', e, s); } }, child: const Text('Report issue'), diff --git a/lib/powersync/sync_diagnostics.dart b/lib/powersync/sync_diagnostics.dart index cff4da5bd..27a389e2f 100644 --- a/lib/powersync/sync_diagnostics.dart +++ b/lib/powersync/sync_diagnostics.dart @@ -125,8 +125,8 @@ Future collectSyncDiagnostics({String? serverUrl}) async { pendingUploads: queue.count, server: serverCategory(serverUrl), ); - } catch (e) { - _logger.warning('Could not collect sync diagnostics: $e'); + } catch (e, s) { + _logger.warning('Could not collect sync diagnostics', e, s); return null; } }