From 5e332e18aa7a7f97071ee40cde74dfc163054f7c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 14 Aug 2026 14:52:49 +0200 Subject: [PATCH] Connect PowerSync on the adapter state, not on the reachability probe --- lib/core/network/network_provider.dart | 36 +++++ lib/core/network/network_provider.g.dart | 71 ++++++++++ lib/core/widgets/app_bar.dart | 33 ++--- lib/database/powersync/powersync.dart | 28 ++-- lib/database/powersync/powersync.g.dart | 2 +- lib/powersync/sync_watchdog.dart | 24 +++- test/core/network/network_provider_test.dart | 60 ++++++++ test/core/validators_test.mocks.dart | 129 ++++++++++++++++++ test/core/widgets/app_bar_test.dart | 105 ++++++++++++++ .../routines_repository_test.mocks.dart | 23 ++++ test/powersync/sync_watchdog_test.dart | 41 ++++++ 11 files changed, 523 insertions(+), 29 deletions(-) create mode 100644 test/core/widgets/app_bar_test.dart diff --git a/lib/core/network/network_provider.dart b/lib/core/network/network_provider.dart index fafe56fd3..392369501 100644 --- a/lib/core/network/network_provider.dart +++ b/lib/core/network/network_provider.dart @@ -97,6 +97,42 @@ Future _defaultReachabilityCheck( @visibleForTesting Duration? networkProbeInterval = const Duration(seconds: 30); +/// Whether the device has a network adapter at all (wifi, mobile, ethernet...) +/// +/// This is a platform fact and may therefore gate a connection attempt, unlike +/// the reachability probe behind [NetworkStatus], which is only an indication. +/// Starts out true so nothing waits for the first answer of the platform +/// channel; an adapterless device corrects it a moment later. +@Riverpod(keepAlive: true) +class NetworkAdapterAvailable extends _$NetworkAdapterAvailable { + final _logger = Logger('NetworkStatus'); + + @override + bool build() { + final sub = Connectivity().onConnectivityChanged.listen(_update); + ref.onDispose(sub.cancel); + unawaited(_seed()); + return true; + } + + Future _seed() async { + final conn = await Connectivity().checkConnectivity(); + if (ref.mounted) { + _update(conn); + } + } + + /// An empty list means no connection either, hence [Iterable.any] rather + /// than a check for [ConnectivityResult.none]. + void _update(List conn) { + final available = conn.any((c) => c != ConnectivityResult.none); + if (available != state) { + _logger.info('Network adapter ${available ? 'available' : 'gone'}'); + } + state = available; + } +} + @Riverpod(keepAlive: true) class NetworkStatus extends _$NetworkStatus { final _logger = Logger('NetworkStatus'); diff --git a/lib/core/network/network_provider.g.dart b/lib/core/network/network_provider.g.dart index 77f1b9ed9..c40b34b6b 100644 --- a/lib/core/network/network_provider.g.dart +++ b/lib/core/network/network_provider.g.dart @@ -8,6 +8,77 @@ part of 'network_provider.dart'; // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint, type=warning +/// Whether the device has a network adapter at all (wifi, mobile, ethernet...) +/// +/// This is a platform fact and may therefore gate a connection attempt, unlike +/// the reachability probe behind [NetworkStatus], which is only an indication. +/// Starts out true so nothing waits for the first answer of the platform +/// channel; an adapterless device corrects it a moment later. + +@ProviderFor(NetworkAdapterAvailable) +final networkAdapterAvailableProvider = NetworkAdapterAvailableProvider._(); + +/// Whether the device has a network adapter at all (wifi, mobile, ethernet...) +/// +/// This is a platform fact and may therefore gate a connection attempt, unlike +/// the reachability probe behind [NetworkStatus], which is only an indication. +/// Starts out true so nothing waits for the first answer of the platform +/// channel; an adapterless device corrects it a moment later. +final class NetworkAdapterAvailableProvider + extends $NotifierProvider { + /// Whether the device has a network adapter at all (wifi, mobile, ethernet...) + /// + /// This is a platform fact and may therefore gate a connection attempt, unlike + /// the reachability probe behind [NetworkStatus], which is only an indication. + /// Starts out true so nothing waits for the first answer of the platform + /// channel; an adapterless device corrects it a moment later. + NetworkAdapterAvailableProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'networkAdapterAvailableProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$networkAdapterAvailableHash(); + + @$internal + @override + NetworkAdapterAvailable create() => NetworkAdapterAvailable(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(bool value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$networkAdapterAvailableHash() => r'ba15e4720bf675523b1c5e697ba66e1a3c4e324e'; + +/// Whether the device has a network adapter at all (wifi, mobile, ethernet...) +/// +/// This is a platform fact and may therefore gate a connection attempt, unlike +/// the reachability probe behind [NetworkStatus], which is only an indication. +/// Starts out true so nothing waits for the first answer of the platform +/// channel; an adapterless device corrects it a moment later. + +abstract class _$NetworkAdapterAvailable extends $Notifier { + bool build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element as $ClassProviderElement, bool, Object?, Object?>; + return element.handleCreate(ref, build); + } +} @ProviderFor(NetworkStatus) final networkStatusProvider = NetworkStatusProvider._(); diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 98d51154d..51c132d86 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/core/form_screen.dart'; @@ -56,24 +58,23 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // The dialog watches the sync state itself; only the server URL - // and the offline gate are snapshots taken when it opens. - // No reconnect while offline: the app deliberately disconnects - // there (see powerSyncInstance). The tap-time check covers the - // network dropping while the dialog is open + // The dialog watches the sync state itself; only the server URL is + // a snapshot taken when it opens. The reconnect action is never + // gated on the network status: it exists for the case where that + // status is wrong, so it re-probes instead of trusting it builder: (_) => SyncStatusDialog( serverUrl: ref.read(wgerBaseProvider).serverUrl, - onReconnect: !ref.read(networkStatusProvider) - ? null - : () { - final db = builtPowerSyncInstance; - final serverUrl = ref.read(wgerBaseProvider).serverUrl; - if (db == null || serverUrl == null || !ref.read(networkStatusProvider)) { - return; - } - ref.read(syncWatchdogProvider).reset(); - connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider)); - }, + onReconnect: () { + unawaited(ref.read(networkStatusProvider.notifier).check(optimistic: true)); + + 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/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index ef9b48690..e356aa69e 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -100,28 +100,36 @@ Future powerSyncInstance(Ref ref) async { } }); - // Connect to the sync service only while the device is online. PowerSync's - // own retry loop would otherwise log a credential error on every iteration - // against an unreachable backend - void syncConnection(bool isOnline) { - if (isOnline) { + // Gated on the network adapter only, never on the reachability probe: a + // probe failure is an indication, an unreachable backend is PowerSync's own + // retry loop to handle (the connector throttles its log output while the + // backend does not answer). Reconnecting while already connected is safe and + // doubles as the "retry now" signal when the adapter comes back. + void syncConnection(bool hasAdapter) { + if (hasAdapter) { final serverUrl = ref.read(wgerBaseProvider).serverUrl; if (serverUrl != null) { - _logger.info('Device online, connecting to the sync service'); + _logger.info('Network adapter available, connecting to the sync service'); connectPowerSync(db, serverUrl, client); } else { - _logger.info('Device online, but no server configured: not connecting'); + _logger.info('Network adapter available, but no server configured: not connecting'); } } else { - _logger.info('Device offline, disconnecting from the sync service'); + _logger.info('No network adapter, disconnecting from the sync service'); db.disconnect(); // Deliberate disconnect: an offline device is not a blocked stream. watchdog.reset(); } } - syncConnection(ref.read(networkStatusProvider)); - ref.listen(networkStatusProvider, (_, isOnline) => syncConnection(isOnline)); + syncConnection(ref.read(networkAdapterAvailableProvider)); + ref.listen(networkAdapterAvailableProvider, (_, hasAdapter) => syncConnection(hasAdapter)); + + // The probe stays a diagnostic input for the watchdog: while short REST + // requests fail too, a stream without checkpoints says nothing about the + // blocked middlebox the watchdog looks for. + watchdog.offline = !ref.read(networkStatusProvider); + ref.listen(networkStatusProvider, (_, isOnline) => watchdog.offline = !isOnline); ref.onDispose(() { _builtInstance = null; diff --git a/lib/database/powersync/powersync.g.dart b/lib/database/powersync/powersync.g.dart index 640ad4389..425e243c8 100644 --- a/lib/database/powersync/powersync.g.dart +++ b/lib/database/powersync/powersync.g.dart @@ -46,4 +46,4 @@ final class PowerSyncInstanceProvider } } -String _$powerSyncInstanceHash() => r'83bc0e7e421a0aa82c0ceb2d097367484c9dc87a'; +String _$powerSyncInstanceHash() => r'24189f75fce866ceb03e07a4c5236cdb94b64639'; diff --git a/lib/powersync/sync_watchdog.dart b/lib/powersync/sync_watchdog.dart index 8dbf4a2cf..d4d2c4907 100644 --- a/lib/powersync/sync_watchdog.dart +++ b/lib/powersync/sync_watchdog.dart @@ -55,6 +55,7 @@ class SyncStreamWatchdog { Timer? _timer; DateTime? _lastCheckpoint; bool _sawStatus = false; + bool _offline = false; /// Last error seen since the watchdog was armed, for the warning. Kept /// across status events: a retry loop clears the error while it reconnects @@ -101,14 +102,33 @@ class SyncStreamWatchdog { // already stalled there is nothing new to detect (and no reason to log // the warning again), so the timer stays off until recovery. if (!_disarmed && + !_offline && !stalled.value && (status.connecting || status.connected || _lastError != null)) { _timer ??= Timer(timeout, _onTimeout); } } - /// Call when the app disconnects on purpose (offline gate, logout), so a - /// device that is simply offline is never reported as blocked. + /// Whether the backend is currently unreachable for plain REST requests as + /// well. While set the watchdog stays quiet: a stream that delivers nothing + /// against a backend that answers nothing is not the blocked-stream case. + /// Unlike [reset] this keeps the connection epoch, so a brief false offline + /// does not restart the detection from scratch. + set offline(bool value) { + if (value == _offline) { + return; + } + _offline = value; + if (value) { + _cancelTimer(); + stalled.value = false; + } + } + + /// Call when the app disconnects on purpose (adapter loss, logout, manual + /// reconnect), so a device that is simply not connected is never reported as + /// blocked. Starts a new connection epoch, see [offline] for the softer + /// variant. void reset() { _cancelTimer(); _disarmed = false; diff --git a/test/core/network/network_provider_test.dart b/test/core/network/network_provider_test.dart index 6e97b6ab2..b0caf17d5 100644 --- a/test/core/network/network_provider_test.dart +++ b/test/core/network/network_provider_test.dart @@ -302,6 +302,66 @@ void main() { expect(offline.first.message, contains('no network adapter')); }); + group('networkAdapterAvailableProvider', () { + test('starts available and stays there once the platform confirms an adapter', () async { + final container = makeContainer(); + + // Nothing waits for the platform channel to answer. + expect(container.read(networkAdapterAvailableProvider), isTrue); + + await pumpEventQueue(); + expect(container.read(networkAdapterAvailableProvider), isTrue); + }); + + test('turns false once the platform reports no adapter', () async { + connectivity.current = [ConnectivityResult.none]; + final container = makeContainer(); + container.read(networkAdapterAvailableProvider); + + await pumpEventQueue(); + + expect(container.read(networkAdapterAvailableProvider), isFalse); + }); + + test('an empty result list counts as no adapter', () async { + connectivity.current = []; + final container = makeContainer(); + container.read(networkAdapterAvailableProvider); + + await pumpEventQueue(); + + expect(container.read(networkAdapterAvailableProvider), isFalse); + }); + + test('follows the adapter change events in both directions', () async { + final container = makeContainer(); + container.read(networkAdapterAvailableProvider); + await pumpEventQueue(); + + connectivity.emit([ConnectivityResult.none]); + await pumpEventQueue(); + expect(container.read(networkAdapterAvailableProvider), isFalse); + + connectivity.emit([ConnectivityResult.mobile]); + await pumpEventQueue(); + expect(container.read(networkAdapterAvailableProvider), isTrue); + }); + + test('a failed reachability probe leaves the adapter state alone', () async { + // The whole point of the split: the probe may be wrong, the adapter is + // a platform fact and gates the PowerSync connection. + reachabilityCheck = (_, _, _) async => (reachable: false, reason: 'test'); + final container = makeContainer(serverUrl: 'https://wger.example'); + container.read(networkAdapterAvailableProvider); + + await container.read(networkStatusProvider.notifier).check(); + await pumpEventQueue(); + + expect(container.read(networkStatusProvider), isFalse); + expect(container.read(networkAdapterAvailableProvider), isTrue); + }); + }); + test('periodically re-probes on the configured interval', () async { networkProbeInterval = const Duration(milliseconds: 50); var probeCount = 0; diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index 2df3fa82d..d7cd961db 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -503,6 +503,39 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get allowSelfSignedCertsTitle => + (super.noSuchMethod( + Invocation.getter(#allowSelfSignedCertsTitle), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#allowSelfSignedCertsTitle), + ), + ) + as String); + + @override + String get allowSelfSignedCertsDetail => + (super.noSuchMethod( + Invocation.getter(#allowSelfSignedCertsDetail), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#allowSelfSignedCertsDetail), + ), + ) + as String); + + @override + String get certsNotVerifiedTitle => + (super.noSuchMethod( + Invocation.getter(#certsNotVerifiedTitle), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#certsNotVerifiedTitle), + ), + ) + as String); + @override String get authOptionPasswordTitle => (super.noSuchMethod( @@ -1662,6 +1695,14 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get meal => + (super.noSuchMethod( + Invocation.getter(#meal), + returnValue: _i3.dummyValue(this, Invocation.getter(#meal)), + ) + as String); + @override String get mealLogged => (super.noSuchMethod( @@ -3628,6 +3669,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get settingsVerboseLogging => + (super.noSuchMethod( + Invocation.getter(#settingsVerboseLogging), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#settingsVerboseLogging), + ), + ) + as String); + + @override + String get settingsVerboseLoggingDescription => + (super.noSuchMethod( + Invocation.getter(#settingsVerboseLoggingDescription), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#settingsVerboseLoggingDescription), + ), + ) + as String); + @override String get aboutPageTitle => (super.noSuchMethod( @@ -4250,6 +4313,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get useDynamicColor => + (super.noSuchMethod( + Invocation.getter(#useDynamicColor), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#useDynamicColor), + ), + ) + as String); + @override String get youAreOffline => (super.noSuchMethod( @@ -4492,6 +4566,39 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get syncStatusStalledHint => + (super.noSuchMethod( + Invocation.getter(#syncStatusStalledHint), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#syncStatusStalledHint), + ), + ) + as String); + + @override + String get syncStatusReconnect => + (super.noSuchMethod( + Invocation.getter(#syncStatusReconnect), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#syncStatusReconnect), + ), + ) + as String); + + @override + String get syncStatusNeverSynced => + (super.noSuchMethod( + Invocation.getter(#syncStatusNeverSynced), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#syncStatusNeverSynced), + ), + ) + as String); + @override String get filterNutriscore => (super.noSuchMethod( @@ -4602,6 +4709,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String certsNotVerifiedDetail(String? host) => + (super.noSuchMethod( + Invocation.method(#certsNotVerifiedDetail, [host]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#certsNotVerifiedDetail, [host]), + ), + ) + as String); + @override String exerciseNr(String? nr) => (super.noSuchMethod( @@ -4954,6 +5072,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String syncStatusPendingUploads(int? count) => + (super.noSuchMethod( + Invocation.method(#syncStatusPendingUploads, [count]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#syncStatusPendingUploads, [count]), + ), + ) + as String); + @override String filterNutriscoreOrBetter(String? grade) => (super.noSuchMethod( diff --git a/test/core/widgets/app_bar_test.dart b/test/core/widgets/app_bar_test.dart new file mode 100644 index 000000000..5e0c9ca57 --- /dev/null +++ b/test/core/widgets/app_bar_test.dart @@ -0,0 +1,105 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/core/network/base_provider.dart'; +import 'package:wger/core/network/network_provider.dart'; +import 'package:wger/core/network/wger_base.dart'; +import 'package:wger/core/widgets/app_bar.dart'; +import 'package:wger/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/sync_watchdog.dart'; + +import '../../helpers/sync_status.dart'; + +/// A [NetworkStatus] resolving to a fixed value, recording the re-probes the +/// reconnect action asks for. +class _FakeNetworkStatus extends NetworkStatus { + _FakeNetworkStatus(this._online); + + final bool _online; + final checks = []; + + @override + bool build() => _online; + + @override + Future check({ + Duration timeout = const Duration(seconds: 1), + bool optimistic = false, + }) async { + checks.add(optimistic); + return _online; + } +} + +void main() { + final i18n = AppLocalizationsEn(); + + late _FakeNetworkStatus networkStatus; + + setUp(() => networkStatus = _FakeNetworkStatus(false)); + + Future pumpAppBar(WidgetTester tester) async { + final watchdog = SyncStreamWatchdog(); + addTearDown(watchdog.dispose); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + networkStatusProvider.overrideWith(() => networkStatus), + wgerBaseProvider.overrideWithValue(WgerBaseProvider(serverUrl: 'https://wger.example')), + syncStatus.overrideWithValue(buildSyncStatus()), + syncWatchdogProvider.overrideWithValue(watchdog), + pendingUploadCountProvider.overrideWith((ref) => const Stream.empty()), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: Locale('en'), + home: Scaffold(appBar: MainAppBar('Test')), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.cloud_off)); + await tester.pumpAndSettle(); + } + + testWidgets('offers the reconnect action while the status says offline', (tester) async { + // The status is exactly what the user is trying to override here, so + // gating the button on it would lock them out. + await pumpAppBar(tester); + + expect(find.text(i18n.syncStatusReconnect), findsOneWidget); + }); + + testWidgets('re-probes the network when reconnect is tapped', (tester) async { + await pumpAppBar(tester); + + await tester.tap(find.text(i18n.syncStatusReconnect)); + await tester.pumpAndSettle(); + + expect(networkStatus.checks, [true]); + }); +} diff --git a/test/features/routines/providers/routines_repository_test.mocks.dart b/test/features/routines/providers/routines_repository_test.mocks.dart index 65a35a37c..641d3fc16 100644 --- a/test/features/routines/providers/routines_repository_test.mocks.dart +++ b/test/features/routines/providers/routines_repository_test.mocks.dart @@ -1429,6 +1429,29 @@ class MockDriftPowersyncDatabase extends _i1.Mock implements _i4.DriftPowersyncD ) as _i3.GenerationContext); + @override + _i3.GenerationContext $writeUpdateInsertable( + _i3.TableInfo<_i3.Table, dynamic>? table, + _i3.Insertable? insertable, { + int? startIndex, + }) => + (super.noSuchMethod( + Invocation.method( + #$writeUpdateInsertable, + [table, insertable], + {#startIndex: startIndex}, + ), + returnValue: _FakeGenerationContext_52( + this, + Invocation.method( + #$writeUpdateInsertable, + [table, insertable], + {#startIndex: startIndex}, + ), + ), + ) + as _i3.GenerationContext); + @override String $expandVar(int? start, int? amount) => (super.noSuchMethod( diff --git a/test/powersync/sync_watchdog_test.dart b/test/powersync/sync_watchdog_test.dart index 72221e3e1..9be4987f3 100644 --- a/test/powersync/sync_watchdog_test.dart +++ b/test/powersync/sync_watchdog_test.dart @@ -179,6 +179,47 @@ void main() { }); }); + test('stays quiet while the backend is unreachable for plain requests', () { + fakeAsync((async) { + watchdog.offline = true; + watchdog.onStatus(buildSyncStatus(connecting: true)); + + async.elapse(watchdog.timeout * 2); + + expect(watchdog.stalled.value, isFalse); + expect(records, isEmpty); + }); + }); + + test('going offline cancels a pending timer and clears the flag', () { + fakeAsync((async) { + watchdog.onStatus(buildSyncStatus(connecting: true)); + async.elapse(watchdog.timeout); + expect(watchdog.stalled.value, isTrue); + + watchdog.offline = true; + expect(watchdog.stalled.value, isFalse); + + async.elapse(watchdog.timeout * 2); + expect(watchdog.stalled.value, isFalse); + }); + }); + + test('re-arms on the next status once the backend answers again', () { + fakeAsync((async) { + watchdog.offline = true; + watchdog.onStatus(buildSyncStatus(connecting: true)); + async.elapse(watchdog.timeout); + expect(watchdog.stalled.value, isFalse); + + watchdog.offline = false; + watchdog.onStatus(buildSyncStatus(connecting: true)); + async.elapse(watchdog.timeout); + + expect(watchdog.stalled.value, isTrue); + }); + }); + test('re-arms after reset() for the next connection epoch', () { fakeAsync((async) { watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));