Merge pull request #1292 from wger-project/feature/improve-sync-logging-and-reporting

Improve sync logging and reporting
This commit is contained in:
Roland Geider
2026-07-29 17:59:30 +02:00
committed by GitHub
17 changed files with 769 additions and 182 deletions

View File

@@ -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';

View File

@@ -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);

View File

@@ -67,40 +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 String stackTrace,
required List<String> applicationLogs,
String? issueTitle,
String? issueErrorMessage,
String? stackTrace,
String? syncDiagnostics,
}) {
String composeUrl(List<String> 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<String> 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'
'Stack trace:\n```\n$stackTrace\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);
}
}

View File

@@ -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),

View File

@@ -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,24 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget {
icon: Icon(status.icon),
onPressed: () => showDialog<void>(
context: context,
// Like syncState, the stalled flag is a snapshot taken when the dialog opens
// 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(
syncState,
stalled: ref.read(syncWatchdogProvider).stalled.value,
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));
},
),
),
),

View File

@@ -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(

View File

@@ -17,51 +17,20 @@
*/
import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart'
show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus;
import 'package:flutter_riverpod/flutter_riverpod.dart';
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,
@@ -91,118 +60,200 @@ String? _categoriseSyncError(Object error) {
}
}
/// Shows the current powersync status
class SyncStatusDialog extends StatelessWidget {
final SyncStatus _status;
/// 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;
/// 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;
/// Server this app is syncing against. Hidden when null.
final String? serverUrl;
const SyncStatusDialog(this._status, {this.stalled = false, super.key});
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<bool>(
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,
),
),
],
),
),
],
),
// 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?) ...[
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 (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,
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),
),
// 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, s) {
_logger.warning('Error opening issue tracker', e, s);
}
},
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
// 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),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).closeButtonLabel),
),
],
);
}
}

View File

@@ -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<int>((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<SyncStatus?>((ref) {
return Stream.fromFuture(
ref.watch(powerSyncInstanceProvider.future),

View File

@@ -1149,6 +1149,9 @@
"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",
"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",

View File

@@ -1401,6 +1401,23 @@
"@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"
},
"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"

View File

@@ -1186,6 +1186,9 @@
"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",
"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",

View File

@@ -1157,6 +1157,9 @@
"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",
"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",

View File

@@ -0,0 +1,132 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* 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 <http://www.gnu.org/licenses/>.
*/
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) {
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.
///
/// 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<String?> collectSyncDiagnostics({String? serverUrl}) async {
final db = builtPowerSyncInstance;
if (db == null) {
return null;
}
try {
final queue = await db.getUploadQueueStats();
return formatSyncDiagnostics(
db.currentStatus,
pendingUploads: queue.count,
server: serverCategory(serverUrl),
);
} catch (e, s) {
_logger.warning('Could not collect sync diagnostics', e, s);
return null;
}
}

View File

@@ -147,6 +147,63 @@ 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',
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');
@@ -164,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)',
@@ -179,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')));
});
});

View File

@@ -16,9 +16,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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<int>? 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<void> _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<int>();
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();
@@ -174,6 +264,52 @@ 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(onReconnect: () => reconnected = true),
status: buildSyncStatus(connected: true, downloadError: Exception('boom')),
),
);
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(onReconnect: () {}), status: buildSyncStatus(connected: true)),
);
await tester.pumpAndSettle();
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')));
expect(find.text(i18n.syncStatusReconnect), findsNothing);
});
testWidgets('renders the expander with the raw error message when present', (tester) async {
await _pumpDialog(
tester,

View File

@@ -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();
}

View File

@@ -0,0 +1,86 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* 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 <http://www.gnu.org/licenses/>.
*/
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);
});
});
}