From 60f79774c997bd61431b7d8ce3d72b5564f68932 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Sun, 30 Aug 2026 16:28:20 +0200 Subject: [PATCH] Fix the race that stopped the phone publishing at all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PC has been firing the morning routine at 07:00 instead of 08:00, off a record the phone published on 2026-08-09 and never superseded. The phone was connected to Firebase the whole time and the home screen still said "Connect a sync backend in Settings first." initState fired three futures concurrently and the last one read what the first two were still writing: unawaited(_applyPolicy()); // sets _hour/_minute unawaited(_loadSyncState()); // sets _service unawaited(_syncToPc()); // reads BOTH `publish` takes the service as a *parameter*, so it captured `_service` by value while it was still null. Assigning it moments later could never reach the call. The startup publish therefore passed null every time and bailed out before touching the network -- and `_syncToPc` had exactly one call site, that one, so nothing published, ever. `_applyPolicy` has the same shape: a publish that did win the race would have sent the baseline instead of an active override. The bootstrap is now strictly sequential. Three things conspired to hide it for three weeks: - `publish` returned "Connect a sync backend in Settings first." for BOTH a missing backend and a null service, so a broken store looked like a setup step the user had never done. The advice pointed at something that was not broken. The two causes now report differently, with a regression test. - `_loadSyncState` swallowed its exception with `on Exception catch (_)`, so if the store genuinely failed to open there was no trace anywhere. It logs now. - `_pickEarlier` never published at all, so "Wake me earlier tomorrow" -- the one schedule edit the app offers -- never reached the PC either. It does now. home_screen.dart went over the 250-line cap, so its body moves to `screens/home_body.dart` as a stateless widget taking plain values. The screen keeps the state and the ordering rules, which is where the bugs lived. Verified on the Pixel 6a: home screen now reads "Synced to PC ✓", and the PC's `_sync --show --no-cache` returns `08:00 (remote)` stamped seconds earlier, against `07:00` from 2026-08-09 before. The phone had also minted a new device id, so both records exist in Firebase and the HLC ranking picks the newer -- which is exactly why that reader ranks by HLC and not by listing order. 104 Dart tests pass; analyzer clean. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN --- phone_app/lib/screens/home_body.dart | 123 +++++++++++++++++ phone_app/lib/screens/home_screen.dart | 124 ++++++------------ phone_app/lib/services/alarm_publisher.dart | 9 +- .../test/services/alarm_publisher_test.dart | 41 ++++++ 4 files changed, 213 insertions(+), 84 deletions(-) create mode 100644 phone_app/lib/screens/home_body.dart create mode 100644 phone_app/test/services/alarm_publisher_test.dart diff --git a/phone_app/lib/screens/home_body.dart b/phone_app/lib/screens/home_body.dart new file mode 100644 index 0000000..fe20c5a --- /dev/null +++ b/phone_app/lib/screens/home_body.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/ui/theme.dart'; + +/// The home screen's body: the armed time, the earlier-only control and the +/// status line. +/// +/// Split out of `home_screen.dart` for the 250-line cap. Deliberately +/// stateless, taking plain values -- the screen keeps the state and the +/// ordering rules, which is where the bugs lived. +class HomeBody extends StatelessWidget { + /// Creates the body from already-resolved state. + const HomeBody({ + required this.time, + required this.baseline, + required this.isOverridden, + required this.busy, + required this.status, + required this.configured, + required this.onPickEarlier, + super.key, + }); + + /// The armed time, preformatted. + final String time; + + /// The baseline time, shown while an override is active. + final String baseline; + + /// Whether a one-shot earlier start is in force. + final bool isOverridden; + + /// Whether an operation is in flight. + final bool busy; + + /// The status line; may be a raw exception string. + final String status; + + /// Whether a sync backend is connected. + final bool configured; + + /// Called when the user asks to wake earlier tomorrow. + final VoidCallback onPickEarlier; + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'Alarm is armed for', + style: TextStyle(fontSize: 16), + ), + const SizedBox(height: 16), + Text( + time, + style: Theme.of(context).textTheme.displayLarge?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + isOverridden + ? 'One-shot early start — back to $baseline ' + 'after it rings' + : 'Every day. It cannot be turned off.', + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 13), + ), + const SizedBox(height: 32), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: busy ? null : onPickEarlier, + icon: const Icon(Icons.arrow_upward), + label: const Text('Wake me earlier tomorrow'), + style: OutlinedButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 16), + ), + ), + ), + const SizedBox(height: 24), + if (status.isNotEmpty) + Text( + status, + textAlign: TextAlign.center, + // Bounded: status can be a raw `'Error: $e'`, i.e. an + // arbitrarily long exception toString(). Unbounded, that + // alone added 100-150px and pushed this column past the + // viewport even in portrait. The scroll view above makes + // the overflow recoverable; this keeps it from happening. + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: status.contains('Error') + ? Theme.of(context).colorScheme.error + : Theme.of( + context, + ).extension()!.success, + ), + ), + if (!configured) ...[ + const SizedBox(height: 16), + Text( + 'Open Settings (gear icon) to connect Firebase.', + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of( + context, + ).extension()!.warning, + ), + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/phone_app/lib/screens/home_screen.dart b/phone_app/lib/screens/home_screen.dart index 3d6f371..5afc496 100644 --- a/phone_app/lib/screens/home_screen.dart +++ b/phone_app/lib/screens/home_screen.dart @@ -1,7 +1,9 @@ import 'dart:async'; +import 'dart:developer' as developer; import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/home_body.dart'; import 'package:wake_alarm_sync/screens/settings_screen.dart'; import 'package:wake_alarm_sync/services/alarm_policy.dart'; import 'package:wake_alarm_sync/services/alarm_publisher.dart'; @@ -9,7 +11,6 @@ import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; import 'package:wake_alarm_sync/services/firebase_backend.dart'; import 'package:wake_alarm_sync/services/sync_settings.dart'; -import 'package:wake_alarm_sync/ui/theme.dart'; /// Main screen: displays the current alarm time and syncs it to the PC via /// the shared crdt_sync transport. @@ -41,11 +42,23 @@ class _HomeScreenState extends State { @override void initState() { super.initState(); - unawaited(_applyPolicy()); - unawaited(_loadSyncState()); - // Publishing to the PC is automatic too: it used to require the same tap - // that armed the alarm, so a forgotten tap left the PC on its fallback. - unawaited(_syncToPc()); + // STRICTLY SEQUENTIAL. These three used to run concurrently, and the + // last one reads what the first two write: `publish` takes the service as + // a *parameter*, so it captured `_service` while it was still null and + // every startup publish returned "connect a backend" while a backend was + // connected. `_applyPolicy` has the same shape -- publishing before it + // resolves would send the baseline instead of an active override. + unawaited(_bootstrapSync()); + } + + /// Resolves the policy and the sync store, then publishes -- in that order. + /// + /// Publishing to the PC is automatic: it used to require the same tap that + /// armed the alarm, so a forgotten tap left the PC on its fallback. + Future _bootstrapSync() async { + await _applyPolicy(); + await _loadSyncState(); + await _syncToPc(); } /// Opens the sync store and records whether a backend is connected. @@ -60,9 +73,17 @@ class _HomeScreenState extends State { try { settings = await SyncSettings.load(); service = await AlarmSyncService.open(); - } on Exception catch (_) { + } on Exception catch (e, stack) { // Storage/plugins unavailable (e.g. under a widget test, or a keystore - // hiccup): keep the on-screen defaults rather than crashing. + // hiccup): keep the on-screen defaults rather than crashing. Logged + // rather than swallowed -- silence here is what made a broken store + // look like an unconfigured backend for weeks. + developer.log( + 'sync store unavailable: $e', + name: 'WakeAlarmSync', + error: e, + stackTrace: stack, + ); return; } // Either backend counts: a device connected only to Firebase is fully @@ -103,6 +124,10 @@ class _HomeScreenState extends State { await _applyPolicy(); if (!mounted) return; setState(() => _status = 'Armed for ${_fmt(_hour, _minute)} tomorrow.'); + // The PC has to learn about the new time too. Without this the only + // publish attempt was the one at startup, so an alarm moved earlier here + // never reached the PC at all. + await _syncToPc(); } /// Re-reads the policy and arms the alarm to match it. @@ -168,81 +193,14 @@ class _HomeScreenState extends State { // happened: phone landscape leaves only ~360px of body height for ~405px // of content, and the status line renders an unbounded raw // `'Error: \$e'` with no maxLines, which overflows even in portrait. - body: SafeArea( - child: Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(32), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Text( - 'Alarm is armed for', - style: TextStyle(fontSize: 16), - ), - const SizedBox(height: 16), - Text( - _fmt(_hour, _minute), - style: Theme.of(context).textTheme.displayLarge?.copyWith( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 8), - Text( - _isOverridden - ? 'One-shot early start — back to $_baseline ' - 'after it rings' - : 'Every day. It cannot be turned off.', - textAlign: TextAlign.center, - style: const TextStyle(fontSize: 13), - ), - const SizedBox(height: 32), - SizedBox( - width: double.infinity, - child: OutlinedButton.icon( - onPressed: _busy ? null : _pickEarlier, - icon: const Icon(Icons.arrow_upward), - label: const Text('Wake me earlier tomorrow'), - style: OutlinedButton.styleFrom( - padding: const EdgeInsets.symmetric(vertical: 16), - ), - ), - ), - const SizedBox(height: 24), - if (_status.isNotEmpty) - Text( - _status, - textAlign: TextAlign.center, - // Bounded: _status can be a raw `'Error: $e'`, i.e. an - // arbitrarily long exception toString(). Unbounded, that - // alone added 100-150px and pushed this column past the - // viewport even in portrait. The scroll view above makes - // the overflow recoverable; this keeps it from happening. - maxLines: 4, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: _status.contains('Error') - ? Theme.of(context).colorScheme.error - : Theme.of( - context, - ).extension()!.success, - ), - ), - if (!_configured) ...[ - const SizedBox(height: 16), - Text( - 'Open Settings (gear icon) to connect Firebase.', - textAlign: TextAlign.center, - style: TextStyle( - color: Theme.of( - context, - ).extension()!.warning, - ), - ), - ], - ], - ), - ), - ), + body: HomeBody( + time: _fmt(_hour, _minute), + baseline: _baseline, + isOverridden: _isOverridden, + busy: _busy, + status: _status, + configured: _configured, + onPickEarlier: () => unawaited(_pickEarlier()), ), ); } diff --git a/phone_app/lib/services/alarm_publisher.dart b/phone_app/lib/services/alarm_publisher.dart index 80df408..b365e89 100644 --- a/phone_app/lib/services/alarm_publisher.dart +++ b/phone_app/lib/services/alarm_publisher.dart @@ -32,9 +32,16 @@ class AlarmPublisher { // syncBackend() falls back to GitHub alone, or pushes to Firebase alone // via the mirror, so either credential is enough to proceed. final hasFirebase = await loadAccount() != null; - if ((!settings.isConfigured && !hasFirebase) || service == null) { + if (!settings.isConfigured && !hasFirebase) { return 'Connect a sync backend in Settings first.'; } + // Distinct from the above on purpose. Both used to report "connect a + // backend", so a store that failed to open looked like a configuration + // the user had never done -- and the advice was to fix something that + // was not broken. + if (service == null) { + return 'Sync store unavailable — reopen the app.'; + } try { await service.setLocal(hour, minute); await service.push(settings.token); diff --git a/phone_app/test/services/alarm_publisher_test.dart b/phone_app/test/services/alarm_publisher_test.dart new file mode 100644 index 0000000..371ce98 --- /dev/null +++ b/phone_app/test/services/alarm_publisher_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/alarm_publisher.dart'; + +import '../fake_secure_storage.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + installFakeSecureStorage(); + SharedPreferences.setMockInitialValues({}); + }); + + test('an unconfigured install is told to connect a backend', () async { + final message = await AlarmPublisher().publish( + service: null, + hour: 8, + minute: 0, + ); + expect(message, contains('Connect a sync backend')); + }); + + test('a missing store is not reported as a missing backend', () async { + // The regression this guards. Both causes used to return the same + // "connect a backend" line, so a store that failed to open looked like a + // setup step the user had never done — while Firebase was connected the + // whole time and the real fault was a null service. The advice pointed at + // something that was not broken, and nothing published for weeks. + SharedPreferences.setMockInitialValues({ + 'github_token': 'ghp_configured', + }); + final message = await AlarmPublisher().publish( + service: null, + hour: 8, + minute: 0, + ); + expect(message, isNot(contains('Connect a sync backend'))); + expect(message, contains('Sync store unavailable')); + }); +}