From c1241c17c7ac5343c3dcedff0379d4517d06fd18 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 27 Aug 2026 15:49:24 +0200 Subject: [PATCH] Show how far a running health sync has come --- .../account/widgets/settings/health_sync.dart | 23 +++++ .../health/providers/health_importer.dart | 47 +++++++++- .../health/providers/health_repository.dart | 6 ++ .../health/providers/health_sync.dart | 29 +++++- .../health/providers/health_sync.freezed.dart | 45 +++++----- .../health/providers/health_sync.g.dart | 2 +- .../widgets/settings/health_sync_test.dart | 27 ++++++ .../providers/health_importer_test.dart | 89 ++++++++++++++++++- .../providers/health_importer_test.mocks.dart | 2 + .../providers/health_repository_test.dart | 18 ++++ .../health/providers/health_sync_test.dart | 59 ++++++++++++ .../providers/health_sync_test.mocks.dart | 2 + .../screenshots_01_dashboard.mocks.dart | 2 + 13 files changed, 326 insertions(+), 25 deletions(-) diff --git a/lib/features/account/widgets/settings/health_sync.dart b/lib/features/account/widgets/settings/health_sync.dart index ef6c8fe19..ccb2d453a 100644 --- a/lib/features/account/widgets/settings/health_sync.dart +++ b/lib/features/account/widgets/settings/health_sync.dart @@ -19,6 +19,7 @@ import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:intl/intl.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/formatting/formatting.dart'; import 'package:wger/features/health/providers/health_repository.dart'; @@ -150,6 +151,27 @@ class _HealthSyncSettingsTileState extends ConsumerState ); } + /// How far the running import has come, null until it knows. + /// + /// A share of the queries, not an estimate of the time left: an empty window + /// returns in milliseconds and a dense one takes seconds. + Widget? _progressBar(HealthSyncProgress? progress) { + if (progress == null || progress.windowsTotal == 0) { + return null; + } + + final fraction = progress.windowsDone / progress.windowsTotal; + return Row( + children: [ + Expanded(child: LinearProgressIndicator(value: fraction)), + const SizedBox(width: 8), + Text( + NumberFormat.percentPattern(Localizations.localeOf(context).toString()).format(fraction), + ), + ], + ); + } + /// Status line under the toggle: what the last sync did or why it didn't, /// a spinner while one is running, and tapping it syncs (or, when the /// platform withholds the data, asks for access again). @@ -162,6 +184,7 @@ class _HealthSyncSettingsTileState extends ConsumerState child: CircularProgressIndicator(strokeWidth: 2.5), ), title: Text(i18n.healthSyncSyncing), + subtitle: _progressBar(syncState.progress), enabled: false, ); } diff --git a/lib/features/health/providers/health_importer.dart b/lib/features/health/providers/health_importer.dart index a3062b47c..0f2aaf095 100644 --- a/lib/features/health/providers/health_importer.dart +++ b/lib/features/health/providers/health_importer.dart @@ -67,6 +67,12 @@ enum HealthSyncIssue { /// is what tells a caller apart from an import that simply found nothing. typedef HealthImportResult = ({int imported, HealthSyncIssue? issue, bool completed}); +/// How far a run has come, in the platform queries it walks through. +/// +/// Their durations vary by orders of magnitude (an empty window returns in +/// milliseconds), so this says how much is left, not how long it takes. +typedef HealthSyncProgress = ({int windowsDone, int windowsTotal}); + /// Imports body metrics from Apple Health / Health Connect into measurement /// categories. /// @@ -84,6 +90,7 @@ class HealthImporter { required MeasurementRepository measurements, required PreferenceHelper prefs, required AuthCredentialsStorage credentials, + this.onProgress, }) : _health = health, _measurements = measurements, _prefs = prefs, @@ -94,6 +101,10 @@ class HealthImporter { final PreferenceHelper _prefs; final AuthCredentialsStorage _credentials; + /// Reports how far the run has come, after every read window and at the end + /// of every metric. + final void Function(HealthSyncProgress progress)? onProgress; + final _logger = Logger('HealthImporter'); /// How far a read window reaches back before the metric's watermark, to @@ -150,6 +161,7 @@ class HealthImporter { _writer = HealthEntryWriter(_measurements, _health.sourceName); final run = await _prepare(metrics, readable, userId); + _reportProgress(run); for (final metric in metrics) { await _syncMetric(metric, run); } @@ -174,7 +186,7 @@ class HealthImporter { ) async { final categories = await _measurements.getCategoriesOnce(); - return _SyncRun( + final run = _SyncRun( userId: userId, categories: categories, endTime: DateTime.now(), @@ -188,6 +200,12 @@ class HealthImporter { ).map((m) => m.metricType.name).toSet(), newlyReadable: await _newlyReadableTypes(readable), ); + // Only known once the starts are: a metric reading its full history is + // hundreds of windows, one starting at its watermark a handful + run.windowsPerMetric.addEntries( + metrics.map((m) => MapEntry(m.metricType.name, run.windowsFor(m))), + ); + return run; } /// Reads one metric and writes what it delivers, then moves its watermark. @@ -199,6 +217,7 @@ class HealthImporter { final name = metric.metricType.name; final startTime = run.startFor(metric); final readsFullHistory = startTime == _fullHistoryStart; + final windowsBefore = run.windowsDone; // One line per metric would be eight per sync in the exportable log, // where the summary at the end is what a report needs _logger.fine('Syncing $name from $startTime to ${run.endTime}'); @@ -221,6 +240,10 @@ class HealthImporter { start: windowStartFor(startTime, metric), end: run.endTime, window: metric.readWindow, + onWindow: () { + run.windowsDone++; + _reportProgress(run); + }, onBatch: (batch, windowEnd) async { final readings = batch.where((r) => metric.dataTypes.contains(r.type)).toList(); if (readings.isEmpty) { @@ -273,9 +296,17 @@ class HealthImporter { _logger.severe('Importing $name failed', e, s); run.failedMetric = true; } + } finally { + // A metric that stopped early read fewer windows than it was counted + // for, and the progress must not stay short of its share for that + run.windowsDone = windowsBefore + run.windowsPerMetric[name]!; + _reportProgress(run); } } + void _reportProgress(_SyncRun run) => + onProgress?.call((windowsDone: run.windowsDone, windowsTotal: run.windowsTotal)); + /// Writes what the run learned, once every metric has had its turn. Future _persist(_SyncRun run, Set readable) async { // Recorded after the metrics ran, so a sync that died earlier tries @@ -429,10 +460,24 @@ class _SyncRun { /// Type names the platform lets us read but did not last time final Set newlyReadable; + /// How many read windows each metric takes, by metric name + final windowsPerMetric = {}; + + /// Windows read so far, across the metrics that already ran + var windowsDone = 0; + var synced = 0; var failedMetric = false; var permissionsMissing = false; + int get windowsTotal => windowsPerMetric.values.sum; + + /// Into how many windows [HealthRepository.read] slices this metric's span. + int windowsFor(HealthMetric metric) { + final span = endTime.difference(windowStartFor(startFor(metric), metric)); + return span.isNegative ? 0 : (span.inMicroseconds / metric.readWindow.inMicroseconds).ceil(); + } + /// Where the read of [metric] starts. /// /// A metric with nothing imported yet has no watermark to go from, and one diff --git a/lib/features/health/providers/health_repository.dart b/lib/features/health/providers/health_repository.dart index d69849729..6d498f68b 100644 --- a/lib/features/health/providers/health_repository.dart +++ b/lib/features/health/providers/health_repository.dart @@ -199,12 +199,17 @@ class HealthRepository { /// written when a later window fails, so [onBatch] has to be idempotent. /// A failing type is dropped from the remaining windows; the error only /// propagates when every type fails. + /// + /// [onWindow] runs once per window, empty ones included, which is what makes + /// it usable as a progress counter: a full history starts years before the + /// first record, and those windows have no batch to report. Future read({ required List types, required DateTime start, required DateTime end, required Duration window, required Future Function(List batch, DateTime windowEnd) onBatch, + void Function()? onWindow, }) async { final failed = {}; final counts = {for (final type in types) type: 0}; @@ -267,6 +272,7 @@ class HealthRepository { if (batch.isNotEmpty) { await onBatch(batch, windowEnd); } + onWindow?.call(); windowStart = next; } diff --git a/lib/features/health/providers/health_sync.dart b/lib/features/health/providers/health_sync.dart index 5daf62ce9..1b78a4a3a 100644 --- a/lib/features/health/providers/health_sync.dart +++ b/lib/features/health/providers/health_sync.dart @@ -30,7 +30,7 @@ import 'package:wger/features/measurements/providers/measurement_repository.dart /// The importer's outcome is part of what this notifier exposes, so it reads /// as one API from the outside. export 'package:wger/features/health/providers/health_importer.dart' - show HealthSyncIssue, dailyAggregateExternalId; + show HealthSyncIssue, HealthSyncProgress, dailyAggregateExternalId; part 'health_sync.freezed.dart'; part 'health_sync.g.dart'; @@ -48,6 +48,9 @@ sealed class HealthSyncState with _$HealthSyncState { /// What went wrong during the last sync, null when it went through. HealthSyncIssue? issue, + + /// How far the running sync has come, null while none is running. + HealthSyncProgress? progress, }) = _HealthSyncState; } @@ -65,6 +68,9 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { late final HealthRepository _health; late final HealthImporter _importer; + /// Percent the state was last updated for, see [_onProgress]. + int? _reportedPercent; + @override HealthSyncState build() { _health = ref.read(healthRepositoryProvider); @@ -73,6 +79,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { measurements: ref.read(measurementRepositoryProvider), prefs: PreferenceHelper.instance, credentials: ref.read(authCredentialsStorageProvider), + onProgress: _onProgress, ); _loadPersistedState(); @@ -156,6 +163,22 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { await sync(); } + /// Publishes the import's progress, at most once per percent. + /// + /// A full history is thousands of windows, most of them back in + /// milliseconds: every one of them would rebuild the settings for nothing. + void _onProgress(HealthSyncProgress progress) { + if (progress.windowsTotal == 0) { + return; + } + final percent = (100 * progress.windowsDone / progress.windowsTotal).floor(); + if (percent == _reportedPercent) { + return; + } + _reportedPercent = percent; + state = state.copyWith(progress: progress); + } + /// Runs one import and reports it in the state. Returns the number of /// imported entries. A no-op unless the user enabled sync, and while one is /// already running. Triggered on app open, on app resume, and manually from @@ -167,7 +190,8 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { if (state.isSyncing) { return 0; } - state = state.copyWith(isEnabled: true, isSyncing: true, issue: null); + _reportedPercent = null; + state = state.copyWith(isEnabled: true, isSyncing: true, issue: null, progress: null); final result = await _importer.run(); @@ -181,6 +205,7 @@ class HealthSyncNotifier extends _$HealthSyncNotifier { lastSyncCount: result.imported, lastSyncTime: result.completed ? DateTime.now() : state.lastSyncTime, issue: result.issue, + progress: null, ); return result.imported; } diff --git a/lib/features/health/providers/health_sync.freezed.dart b/lib/features/health/providers/health_sync.freezed.dart index 83ec258ae..3d4b50290 100644 --- a/lib/features/health/providers/health_sync.freezed.dart +++ b/lib/features/health/providers/health_sync.freezed.dart @@ -17,7 +17,8 @@ mixin _$HealthSyncState { bool get isEnabled; bool get isSyncing; int get lastSyncCount;/// When the last successful sync finished; null until one succeeded in /// this session. DateTime? get lastSyncTime;/// What went wrong during the last sync, null when it went through. - HealthSyncIssue? get issue; + HealthSyncIssue? get issue;/// How far the running sync has come, null while none is running. + HealthSyncProgress? get progress; /// Create a copy of HealthSyncState /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -28,16 +29,16 @@ $HealthSyncStateCopyWith get copyWith => _$HealthSyncStateCopyW @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)&&(identical(other.lastSyncTime, lastSyncTime) || other.lastSyncTime == lastSyncTime)&&(identical(other.issue, issue) || other.issue == issue)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)&&(identical(other.lastSyncTime, lastSyncTime) || other.lastSyncTime == lastSyncTime)&&(identical(other.issue, issue) || other.issue == issue)&&(identical(other.progress, progress) || other.progress == progress)); } @override -int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount,lastSyncTime,issue); +int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount,lastSyncTime,issue,progress); @override String toString() { - return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount, lastSyncTime: $lastSyncTime, issue: $issue)'; + return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount, lastSyncTime: $lastSyncTime, issue: $issue, progress: $progress)'; } @@ -48,7 +49,7 @@ abstract mixin class $HealthSyncStateCopyWith<$Res> { factory $HealthSyncStateCopyWith(HealthSyncState value, $Res Function(HealthSyncState) _then) = _$HealthSyncStateCopyWithImpl; @useResult $Res call({ - bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue + bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue, HealthSyncProgress? progress }); @@ -65,14 +66,15 @@ class _$HealthSyncStateCopyWithImpl<$Res> /// Create a copy of HealthSyncState /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,Object? lastSyncTime = freezed,Object? issue = freezed,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,Object? lastSyncTime = freezed,Object? issue = freezed,Object? progress = freezed,}) { return _then(_self.copyWith( isEnabled: null == isEnabled ? _self.isEnabled : isEnabled // ignore: cast_nullable_to_non_nullable as bool,isSyncing: null == isSyncing ? _self.isSyncing : isSyncing // ignore: cast_nullable_to_non_nullable as bool,lastSyncCount: null == lastSyncCount ? _self.lastSyncCount : lastSyncCount // ignore: cast_nullable_to_non_nullable as int,lastSyncTime: freezed == lastSyncTime ? _self.lastSyncTime : lastSyncTime // ignore: cast_nullable_to_non_nullable as DateTime?,issue: freezed == issue ? _self.issue : issue // ignore: cast_nullable_to_non_nullable -as HealthSyncIssue?, +as HealthSyncIssue?,progress: freezed == progress ? _self.progress : progress // ignore: cast_nullable_to_non_nullable +as HealthSyncProgress?, )); } @@ -154,10 +156,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue, HealthSyncProgress? progress)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _HealthSyncState() when $default != null: -return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue);case _: +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue,_that.progress);case _: return orElse(); } @@ -175,10 +177,10 @@ return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSy /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue, HealthSyncProgress? progress) $default,) {final _that = this; switch (_that) { case _HealthSyncState(): -return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue);} +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue,_that.progress);} } /// A variant of `when` that fallback to returning `null` /// @@ -192,10 +194,10 @@ return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSy /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue, HealthSyncProgress? progress)? $default,) {final _that = this; switch (_that) { case _HealthSyncState() when $default != null: -return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue);case _: +return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSyncTime,_that.issue,_that.progress);case _: return null; } @@ -207,7 +209,7 @@ return $default(_that.isEnabled,_that.isSyncing,_that.lastSyncCount,_that.lastSy class _HealthSyncState implements HealthSyncState { - const _HealthSyncState({this.isEnabled = false, this.isSyncing = false, this.lastSyncCount = 0, this.lastSyncTime, this.issue}); + const _HealthSyncState({this.isEnabled = false, this.isSyncing = false, this.lastSyncCount = 0, this.lastSyncTime, this.issue, this.progress}); @override@JsonKey() final bool isEnabled; @@ -218,6 +220,8 @@ class _HealthSyncState implements HealthSyncState { @override final DateTime? lastSyncTime; /// What went wrong during the last sync, null when it went through. @override final HealthSyncIssue? issue; +/// How far the running sync has come, null while none is running. +@override final HealthSyncProgress? progress; /// Create a copy of HealthSyncState /// with the given fields replaced by the non-null parameter values. @@ -229,16 +233,16 @@ _$HealthSyncStateCopyWith<_HealthSyncState> get copyWith => __$HealthSyncStateCo @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)&&(identical(other.lastSyncTime, lastSyncTime) || other.lastSyncTime == lastSyncTime)&&(identical(other.issue, issue) || other.issue == issue)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _HealthSyncState&&(identical(other.isEnabled, isEnabled) || other.isEnabled == isEnabled)&&(identical(other.isSyncing, isSyncing) || other.isSyncing == isSyncing)&&(identical(other.lastSyncCount, lastSyncCount) || other.lastSyncCount == lastSyncCount)&&(identical(other.lastSyncTime, lastSyncTime) || other.lastSyncTime == lastSyncTime)&&(identical(other.issue, issue) || other.issue == issue)&&(identical(other.progress, progress) || other.progress == progress)); } @override -int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount,lastSyncTime,issue); +int get hashCode => Object.hash(runtimeType,isEnabled,isSyncing,lastSyncCount,lastSyncTime,issue,progress); @override String toString() { - return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount, lastSyncTime: $lastSyncTime, issue: $issue)'; + return 'HealthSyncState(isEnabled: $isEnabled, isSyncing: $isSyncing, lastSyncCount: $lastSyncCount, lastSyncTime: $lastSyncTime, issue: $issue, progress: $progress)'; } @@ -249,7 +253,7 @@ abstract mixin class _$HealthSyncStateCopyWith<$Res> implements $HealthSyncState factory _$HealthSyncStateCopyWith(_HealthSyncState value, $Res Function(_HealthSyncState) _then) = __$HealthSyncStateCopyWithImpl; @override @useResult $Res call({ - bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue + bool isEnabled, bool isSyncing, int lastSyncCount, DateTime? lastSyncTime, HealthSyncIssue? issue, HealthSyncProgress? progress }); @@ -266,14 +270,15 @@ class __$HealthSyncStateCopyWithImpl<$Res> /// Create a copy of HealthSyncState /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,Object? lastSyncTime = freezed,Object? issue = freezed,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? isEnabled = null,Object? isSyncing = null,Object? lastSyncCount = null,Object? lastSyncTime = freezed,Object? issue = freezed,Object? progress = freezed,}) { return _then(_HealthSyncState( isEnabled: null == isEnabled ? _self.isEnabled : isEnabled // ignore: cast_nullable_to_non_nullable as bool,isSyncing: null == isSyncing ? _self.isSyncing : isSyncing // ignore: cast_nullable_to_non_nullable as bool,lastSyncCount: null == lastSyncCount ? _self.lastSyncCount : lastSyncCount // ignore: cast_nullable_to_non_nullable as int,lastSyncTime: freezed == lastSyncTime ? _self.lastSyncTime : lastSyncTime // ignore: cast_nullable_to_non_nullable as DateTime?,issue: freezed == issue ? _self.issue : issue // ignore: cast_nullable_to_non_nullable -as HealthSyncIssue?, +as HealthSyncIssue?,progress: freezed == progress ? _self.progress : progress // ignore: cast_nullable_to_non_nullable +as HealthSyncProgress?, )); } diff --git a/lib/features/health/providers/health_sync.g.dart b/lib/features/health/providers/health_sync.g.dart index 2fc3e99a8..403aa30d9 100644 --- a/lib/features/health/providers/health_sync.g.dart +++ b/lib/features/health/providers/health_sync.g.dart @@ -56,7 +56,7 @@ final class HealthSyncNotifierProvider } } -String _$healthSyncNotifierHash() => r'16e34d617342221e827eaf521bbfdd3f012a146a'; +String _$healthSyncNotifierHash() => r'b423c6bec19a9481e4d7b22dae0fd5a190e2ead3'; /// Drives the health import: the user's preference, when a run happens, and /// what the settings screen shows about it. diff --git a/test/features/account/widgets/settings/health_sync_test.dart b/test/features/account/widgets/settings/health_sync_test.dart index 0ab813d11..15453a7cb 100644 --- a/test/features/account/widgets/settings/health_sync_test.dart +++ b/test/features/account/widgets/settings/health_sync_test.dart @@ -101,6 +101,7 @@ void main() { healthSyncProvider.overrideWith(() => fake), ], child: const MaterialApp( + locale: Locale('en'), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: Scaffold(body: HealthSyncSettingsTile()), @@ -286,5 +287,31 @@ void main() { expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(find.text('Syncing health data…'), findsOneWidget); expect(tester.widget(find.byType(SwitchListTile)).onChanged, isNull); + // The run has not worked out yet how much there is to read + expect(find.byType(LinearProgressIndicator), findsNothing); + }); + + testWidgets('shows how far a running sync has come', (tester) async { + // A first import reads years of history, which takes long enough that a + // spinner alone leaves the user wondering whether anything happens + await tester.pumpWidget( + createTile( + _FakeHealthSyncNotifier( + null, + initialState: const HealthSyncState( + isEnabled: true, + isSyncing: true, + progress: (windowsDone: 2100, windowsTotal: 5000), + ), + ), + ), + ); + await tester.pump(); + + expect( + tester.widget(find.byType(LinearProgressIndicator)).value, + 0.42, + ); + expect(find.text('42%'), findsOneWidget); }); } diff --git a/test/features/health/providers/health_importer_test.dart b/test/features/health/providers/health_importer_test.dart index d89d2a9ce..72881af08 100644 --- a/test/features/health/providers/health_importer_test.dart +++ b/test/features/health/providers/health_importer_test.dart @@ -107,11 +107,12 @@ void main() { when(measurements.hasEntries(any)).thenAnswer((_) async => false); }); - HealthImporter createImporter() => HealthImporter( + HealthImporter createImporter({void Function(HealthSyncProgress)? onProgress}) => HealthImporter( health: health, measurements: measurements, prefs: PreferenceHelper.instance, credentials: credentials, + onProgress: onProgress, ); /// One run, reduced to the number of entries it wrote. @@ -184,6 +185,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).captured; @@ -201,6 +203,28 @@ void main() { DateTime capturedReadStart([HealthDataType type = HealthDataType.WEIGHT]) => capturedReadStarts()[type]!; + /// How many windows the platform reads the sync asked for add up to, i.e. + /// how often [HealthRepository.read] queries the platform. + int capturedWindowCount() { + final captured = verify( + health.read( + types: anyNamed('types'), + start: captureAnyNamed('start'), + end: captureAnyNamed('end'), + window: captureAnyNamed('window'), + onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), + ), + ).captured; + + var windows = 0; + for (var i = 0; i < captured.length; i += 3) { + final span = (captured[i + 1] as DateTime).difference(captured[i] as DateTime); + windows += (span.inMicroseconds / (captured[i + 2] as Duration).inMicroseconds).ceil(); + } + return windows; + } + /// Every health data type the sync asked the platform for List capturedReadTypes() => verify( health.read( @@ -209,6 +233,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).captured.cast>().expand((types) => types).toList(); @@ -222,6 +247,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).thenAnswer((invocation) async { if (readings.isEmpty) { @@ -245,6 +271,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).thenAnswer((invocation) async { if (!(invocation.namedArguments[#types] as List).contains(type)) { @@ -283,6 +310,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ); }); @@ -377,6 +405,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).thenThrow( PlatformException( @@ -399,6 +428,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).thenThrow(Exception('boom')); @@ -1656,6 +1686,62 @@ void main() { ); }); + test('the progress totals the windows the metrics are read in', () async { + stubReadings([]); + final reports = []; + + await createImporter(onProgress: reports.add).run(); + + // Known before the first read, so the settings show a share of the + // whole run rather than a spinner + expect(reports.first.windowsDone, 0); + expect(reports.first.windowsTotal, capturedWindowCount()); + expect(reports.last.windowsDone, reports.last.windowsTotal); + }); + + test('counts the windows a metric reports while it reads', () async { + when( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), + ), + ).thenAnswer((invocation) async { + final onWindow = invocation.namedArguments[#onWindow] as void Function(); + onWindow(); + onWindow(); + }); + final reports = []; + + await createImporter(onProgress: reports.add).run(); + + expect(reports.take(3).map((r) => r.windowsDone), [0, 1, 2]); + }); + + test('a metric that gave up still hands over its share of the progress', () async { + // Nothing else counts the windows it did not read, and a bar that stops + // at 40% is worse than no bar at all + when( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), + ), + ).thenThrow(Exception('boom')); + final reports = []; + + await createImporter(onProgress: reports.add).run(); + + expect(reports.last.windowsTotal, greaterThan(0)); + expect(reports.last.windowsDone, reports.last.windowsTotal); + }); + test('each metric is read with the window its density affords', () async { // A month of heart rate does not fit into the Android app heap, a month // of scale readings is nothing, so the window comes from the metric @@ -1670,6 +1756,7 @@ void main() { end: anyNamed('end'), window: captureAnyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).captured; final windowByType = { diff --git a/test/features/health/providers/health_importer_test.mocks.dart b/test/features/health/providers/health_importer_test.mocks.dart index c4548cc75..08bce393c 100644 --- a/test/features/health/providers/health_importer_test.mocks.dart +++ b/test/features/health/providers/health_importer_test.mocks.dart @@ -105,6 +105,7 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { required DateTime? end, required Duration? window, required _i4.Future Function(List<_i6.HealthReading>, DateTime)? onBatch, + void Function()? onWindow, }) => (super.noSuchMethod( Invocation.method(#read, [], { @@ -113,6 +114,7 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { #end: end, #window: window, #onBatch: onBatch, + #onWindow: onWindow, }), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), diff --git a/test/features/health/providers/health_repository_test.dart b/test/features/health/providers/health_repository_test.dart index 557179823..184d3899a 100644 --- a/test/features/health/providers/health_repository_test.dart +++ b/test/features/health/providers/health_repository_test.dart @@ -186,6 +186,24 @@ void main() { expect(events, ['read window 1', 'batch of 1', 'read window 2', 'batch of 1']); }); + test('reports every window, empty ones included', () async { + // Most windows of a full history return nothing, so a progress counter + // fed by the batches alone would sit at zero for minutes and then jump + var windows = 0; + + await repository.read( + types: [HealthDataType.WEIGHT], + start: DateTime(2026, 1, 1), + end: DateTime(2026, 4, 1), + window: defaultReadWindow, + onBatch: (batch, _) async {}, + onWindow: () => windows++, + ); + + expect(windows, 3); + expect(windows, capturedWindows().length); + }); + test('a record on the window boundary is delivered once', () async { // Both windows of a contiguous pair contain their shared boundary, so a // record sitting exactly on it comes back from both queries diff --git a/test/features/health/providers/health_sync_test.dart b/test/features/health/providers/health_sync_test.dart index 67635a293..b119a075f 100644 --- a/test/features/health/providers/health_sync_test.dart +++ b/test/features/health/providers/health_sync_test.dart @@ -98,6 +98,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ).thenAnswer((invocation) async { if (readings.isEmpty) { @@ -110,6 +111,30 @@ void main() { }); } + /// Stubs the platform read to walk through the windows its range asks for, + /// the way the repository does, without delivering anything. + void stubEmptyWindows() { + when( + health.read( + types: anyNamed('types'), + start: anyNamed('start'), + end: anyNamed('end'), + window: anyNamed('window'), + onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), + ), + ).thenAnswer((invocation) async { + final span = (invocation.namedArguments[#end] as DateTime).difference( + invocation.namedArguments[#start] as DateTime, + ); + final window = invocation.namedArguments[#window] as Duration; + final onWindow = invocation.namedArguments[#onWindow] as void Function(); + for (var i = 0; i < (span.inMicroseconds / window.inMicroseconds).ceil(); i++) { + onWindow(); + } + }); + } + group('HealthSyncState', () { test('default state has sync disabled', () { const state = HealthSyncState(); @@ -143,6 +168,7 @@ void main() { end: anyNamed('end'), window: anyNamed('window'), onBatch: anyNamed('onBatch'), + onWindow: anyNamed('onWindow'), ), ); }); @@ -231,6 +257,39 @@ void main() { expect(container.read(healthSyncProvider).lastSyncTime, stamped); }); + test('publishes how far the run has come and drops it at the end', () async { + stubEmptyWindows(); + final states = []; + final notifier = createNotifier(); + container.listen(healthSyncProvider, (_, next) => states.add(next)); + + await notifier.sync(); + + final reported = states.map((s) => s.progress).nonNulls.toList(); + expect(reported, isNotEmpty); + expect(reported.every((p) => p.windowsDone <= p.windowsTotal), isTrue); + // Nothing is running anymore, so there is no progress to show either + expect(container.read(healthSyncProvider).progress, isNull); + }); + + test('publishes at most one state per percent', () async { + // A full history is thousands of windows, most of them empty and back + // in milliseconds: the settings must not be rebuilt for every one + stubEmptyWindows(); + final states = []; + final notifier = createNotifier(); + container.listen(healthSyncProvider, (_, next) => states.add(next)); + + await notifier.sync(); + + final percents = states + .map((s) => s.progress) + .nonNulls + .map((p) => (100 * p.windowsDone / p.windowsTotal).floor()) + .toList(); + expect(percents, percents.toSet().toList()); + }); + test('carries the imported count into the state', () async { stubReadings([ HealthReading( diff --git a/test/features/health/providers/health_sync_test.mocks.dart b/test/features/health/providers/health_sync_test.mocks.dart index 2a8381d03..01cd72ecd 100644 --- a/test/features/health/providers/health_sync_test.mocks.dart +++ b/test/features/health/providers/health_sync_test.mocks.dart @@ -105,6 +105,7 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { required DateTime? end, required Duration? window, required _i4.Future Function(List<_i6.HealthReading>, DateTime)? onBatch, + void Function()? onWindow, }) => (super.noSuchMethod( Invocation.method(#read, [], { @@ -113,6 +114,7 @@ class MockHealthRepository extends _i1.Mock implements _i2.HealthRepository { #end: end, #window: window, #onBatch: onBatch, + #onWindow: onWindow, }), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), diff --git a/test/screenshots/screenshots_01_dashboard.mocks.dart b/test/screenshots/screenshots_01_dashboard.mocks.dart index 8fa44e20a..624ee51c6 100644 --- a/test/screenshots/screenshots_01_dashboard.mocks.dart +++ b/test/screenshots/screenshots_01_dashboard.mocks.dart @@ -1179,6 +1179,7 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository { required DateTime? end, required Duration? window, required _i11.Future Function(List<_i45.HealthReading>, DateTime)? onBatch, + void Function()? onWindow, }) => (super.noSuchMethod( Invocation.method(#read, [], { @@ -1187,6 +1188,7 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository { #end: end, #window: window, #onBatch: onBatch, + #onWindow: onWindow, }), returnValue: _i11.Future.value(), returnValueForMissingStub: _i11.Future.value(),