From b5701fb3594522136b1a8a7c9912fc20aab80881 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Fri, 11 Sep 2026 12:34:50 +0200 Subject: [PATCH] Sync the NFC tags and home location so a reinstall gets them back Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 4 +- DOCS-phone-alarm.md | 35 +++- phone_app/lib/screens/home_body.dart | 19 +- phone_app/lib/screens/home_screen.dart | 6 + phone_app/lib/services/alarm_publisher.dart | 6 + .../lib/services/alarm_sync_service.dart | 56 ++++-- .../lib/services/home_location_settings.dart | 86 ++++++--- .../lib/services/room_proof_settings.dart | 38 +++- phone_app/lib/services/settings_sync.dart | 121 ++++++++++++ .../test/services/alarm_sync_pull_test.dart | 146 ++++++++++++++ .../test/services/settings_sync_test.dart | 181 ++++++++++++++++++ 11 files changed, 641 insertions(+), 57 deletions(-) create mode 100644 phone_app/lib/services/settings_sync.dart create mode 100644 phone_app/test/services/alarm_sync_pull_test.dart create mode 100644 phone_app/test/services/settings_sync_test.dart diff --git a/AGENTS.md b/AGENTS.md index 476abb7..0f2e346 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,9 @@ passing sent the user back to the start. - **Two *distinct* tags.** The same id in both slots is refused at registration — one tag satisfying both stages removes the walk, which is the entire point. Stored as a JSON list under `roomProof.nfcTagIds`; a legacy - single `roomProof.nfcTagId` migrates into slot 1. + single `roomProof.nfcTagId` migrates into slot 1. **Tags and home location + sync** (`settings_sync.dart`, see `DOCS-phone-alarm.md`) — a reinstall + gets them back; do not make either local-only again. - **Steps are unchanged** (`requiredSteps = 25`, `requiredElapsed = 2 min`), and are counted from ring start, *not* re-baselined at tag 1. Consequence: walking to tag 1 already banks the steps, so only the elapsed floor really diff --git a/DOCS-phone-alarm.md b/DOCS-phone-alarm.md index c176227..0a5f951 100644 --- a/DOCS-phone-alarm.md +++ b/DOCS-phone-alarm.md @@ -178,8 +178,9 @@ phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so `phone_deploy.sh --release --target lib/main_ring_probe.dart` and let it pick. Android compares versionCode only upward, so a hand-picked number puts the phone above what CI will mint and locks CI out until the commit count -catches up — the only other escape is an uninstall, which wipes the NFC tags, -the home location and the sync identity. This happened on 2026-08-31 (probe +catches up — the only other escape is an uninstall, which wipes the sync +identity (the tags and home come back from sync since 2026-09-11, see +below). This happened on 2026-08-31 (probe builds at 200/201 stranded the phone at 207 against a ceiling of 156). `.versioncode-offset` at the repo root is the recovery valve, read by **both** `release-apk.yml` and the local gate so the two can only move together; it is @@ -191,3 +192,33 @@ cannot finish an activity). Without it the dismiss screen stays up over the lockscreen forever — back is disabled by design in both halves — and the live instance would carry a satisfied room proof and the solved answer into the next ring. + +## Tags and home location survive a reinstall + +Both used to live only in SharedPreferences, and a reinstall on 2026-09-11 +lost them. They are properties of the flat, not of one install, so +`lib/services/settings_sync.dart` carries them as two extra per-field entries +on the same `alarm.json` record the PC reads (`nfc_tag_ids`, +`home_location`); the PC parser reads only the hour/minute fields and ignores +the rest. `AlarmSyncService.pushWith` is a real `syncLog` tick now — pull every +device directory, merge per field by HLC, push — and `AlarmPublisher.publish` +wraps it: stage local edits → sync → apply the winners back into prefs. That +last step is the restore. Verified 2026-09-11 on a fresh `wake_alarm_api36` +install: both tags and the home appeared with zero taps after Google sign-in. + +- **Last-writer-wins by wall time, from the local `editedAt`** stamps + (`roomProof.editedAt`, `homeLocation.editedAt`). A value applied *from* the + log is stamped with the log's wall time, and comparisons are on wall time + only — comparing counter/node id on that tie would push the same value + straight back every tick. +- A value from before stamps existed is staged at epoch+1 ms: pushed when + nothing else is known, loses to any real edit. +- **Registering a tag pushes on the Back to the home screen** — the Settings + pop now runs `_syncToPc()`, not just `_loadSyncState()`. Without that the + push waited for the next cold start, which is the same "it vanished" again. +- `setLocal` merges into the existing record; a whole-record upsert there + would drop the settings fields from every push. `HomeBody.syncEpoch` + remounts the presence line after each sync so a restored home shows at once. +- The emulator is a real peer: its device directory outranks the phone by + HLC while it exists. Delete `wake-alarm-sync/devices/` after + a restore test. diff --git a/phone_app/lib/screens/home_body.dart b/phone_app/lib/screens/home_body.dart index ca16cdb..ecb79a6 100644 --- a/phone_app/lib/screens/home_body.dart +++ b/phone_app/lib/screens/home_body.dart @@ -18,6 +18,7 @@ class HomeBody extends StatelessWidget { required this.status, required this.configured, required this.onPickEarlier, + this.syncEpoch = 0, super.key, }); @@ -42,6 +43,11 @@ class HomeBody extends StatelessWidget { /// Called when the user asks to wake earlier tomorrow. final VoidCallback onPickEarlier; + /// Bumped after every sync so the presence line re-reads the home location + /// a pull may just have restored, instead of showing the pre-sync verdict + /// until the next cold start. + final int syncEpoch; + @override Widget build(BuildContext context) { return SafeArea( @@ -51,17 +57,14 @@ class HomeBody extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - const Text( - 'Alarm is armed for', - style: TextStyle(fontSize: 16), - ), - const HomePresenceLine(), + const Text('Alarm is armed for', style: TextStyle(fontSize: 16)), + HomePresenceLine(key: ValueKey(syncEpoch)), const SizedBox(height: 16), Text( time, - style: Theme.of(context).textTheme.displayLarge?.copyWith( - fontWeight: FontWeight.bold, - ), + style: Theme.of( + context, + ).textTheme.displayLarge?.copyWith(fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Text( diff --git a/phone_app/lib/screens/home_screen.dart b/phone_app/lib/screens/home_screen.dart index 5afc496..02af193 100644 --- a/phone_app/lib/screens/home_screen.dart +++ b/phone_app/lib/screens/home_screen.dart @@ -31,6 +31,7 @@ class _HomeScreenState extends State { bool _busy = false; String _status = ''; bool _configured = false; + int _syncEpoch = 0; AlarmSyncService? _service; /// Platform bridge that arms the app's own alarm (item 1). @@ -156,6 +157,7 @@ class _HomeScreenState extends State { setState(() { _status = message; _busy = false; + _syncEpoch++; }); } @@ -182,7 +184,10 @@ class _HomeScreenState extends State { context, MaterialPageRoute(builder: (_) => const SettingsScreen()), ); + // Publish too, not just reload: a tag registered in Settings + // reaches the backend now, not on the next cold start. await _loadSyncState(); + await _syncToPc(); }, ), ], @@ -200,6 +205,7 @@ class _HomeScreenState extends State { busy: _busy, status: _status, configured: _configured, + syncEpoch: _syncEpoch, onPickEarlier: () => unawaited(_pickEarlier()), ), ); diff --git a/phone_app/lib/services/alarm_publisher.dart b/phone_app/lib/services/alarm_publisher.dart index b365e89..e29579e 100644 --- a/phone_app/lib/services/alarm_publisher.dart +++ b/phone_app/lib/services/alarm_publisher.dart @@ -2,6 +2,7 @@ import 'package:wake_alarm_sync/services/alarm_arming.dart'; 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/settings_sync.dart'; import 'package:wake_alarm_sync/services/sync_settings.dart'; /// Publishes the armed alarm to the PC and arms the phone's own alarm. @@ -44,7 +45,12 @@ class AlarmPublisher { } try { await service.setLocal(hour, minute); + // Tags and home ride on the same record: stage local edits, sync + // (pull, merge, push), then take whatever won back into prefs. That + // last step is how a fresh install gets its tags back. + await stageLocalSettings(service); await service.push(settings.token); + await applySyncedSettings(service); final problem = await arming.arm(hour, minute); if (problem != null) return problem; await arming.registerWithClockApp(hour, minute); diff --git a/phone_app/lib/services/alarm_sync_service.dart b/phone_app/lib/services/alarm_sync_service.dart index 60031eb..cea5d94 100644 --- a/phone_app/lib/services/alarm_sync_service.dart +++ b/phone_app/lib/services/alarm_sync_service.dart @@ -29,9 +29,10 @@ typedef Alarm = ({int hour, int minute}); /// regardless of which directory it landed in. /// /// The PC side is read-only (`wake_alarm/_sync.py`, which tries Firebase then -/// GitHub, caching the result for `shutdown-wrapper.sh`). There is no -/// pull/merge here: the phone is the only writer, so its local store is -/// always the source of truth. +/// GitHub). The phone does pull and merge, though — not for the alarm time, +/// which it always owns, but for the NFC tags and home location that ride on +/// the same record (`settings_sync.dart`): a reinstalled phone gets them back +/// from whichever previous install pushed them last. class AlarmSyncService { /// Wraps an already-loaded log store pushing under [deviceId]. AlarmSyncService(this._store, {required this.deviceId}); @@ -66,8 +67,6 @@ class AlarmSyncService { /// whatever uuid this turns out to be. final String deviceId; - String get _remotePath => 'wake-alarm-sync/devices/$deviceId/alarm.json'; - static const _recordId = 'alarm'; static const _hourField = 'alarm_hour'; static const _minuteField = 'alarm_minute'; @@ -122,26 +121,55 @@ class AlarmSyncService { /// /// Both fields share one clock tick — they are always set together, so a /// concurrent per-field merge would never split them. - Future setLocal(int hour, int minute) async { - final hlc = _store.nextHlc(); + Future setLocal(int hour, int minute) => + setFields({_hourField: hour, _minuteField: minute}, _store.nextHlc()); + + /// Upserts [values] onto the alarm record at [hlc], keeping every other + /// field. + /// + /// Preserving is the point: the record also carries the synced settings + /// (`settings_sync.dart`), and a whole-record replace on every publish + /// would silently drop them from the pushed log. + Future setFields(Map values, Hlc hlc) async { + final existing = _store.get(_recordId); await _store.upsert( Record( id: _recordId, - fields: {_hourField: (hour, hlc), _minuteField: (minute, hlc)}, + fields: { + ...?existing?.fields, + for (final e in values.entries) e.key: (e.value, hlc), + }, ), ); } - /// Pushes the local alarm log using [client]. + /// The value and clock of [field] on the alarm record, or null when unset. + (Object?, Hlc)? field(String field) => _store.get(_recordId)?.fields[field]; + + /// Syncs the local alarm log through [client]: pulls every other device's + /// log, merges per field by HLC, then pushes the result. /// /// Takes a [RemoteStore] rather than a `GitHubClient` so the same call /// serves Firebase, GitHub, or the [MirrorStore] that writes both — the /// backend is chosen once, in [syncBackend]. - Future pushWith(RemoteStore client) => client.putFileText( - _remotePath, - logToJson(_store.snapshot()), - message: 'wake_alarm_sync: update alarm', - ); + /// + /// The pull is what brings the tags and home location back to a fresh + /// install. The alarm time itself is unaffected: [setLocal] runs first on + /// every publish, so the local time is always the newest and wins. + Future pushWith(RemoteStore client) async { + final merged = await syncLog( + client: client, + deviceId: deviceId, + pathPrefix: 'wake-alarm-sync/devices', + filename: 'alarm.json', + localLog: _store.snapshot(), + encode: logToJson, + decode: logFromJson, + commitMessage: 'wake_alarm_sync: update alarm', + legacyDeviceId: legacyDeviceId, + ); + await _store.replaceAll(merged); + } /// Pushes to Firebase when this device is set up for it, mirroring to /// GitHub during the cutover; to GitHub alone when it is not. diff --git a/phone_app/lib/services/home_location_settings.dart b/phone_app/lib/services/home_location_settings.dart index 1f62bcb..7b58d60 100644 --- a/phone_app/lib/services/home_location_settings.dart +++ b/phone_app/lib/services/home_location_settings.dart @@ -20,11 +20,34 @@ class HomeLocationSettings { this.lat, this.lon, this.radiusMeters = defaultRadiusMeters, + this.editedAt = '', }); + /// Decodes the JSON shape written by [toJson]; anything malformed reads as + /// unset rather than throwing, matching [load]. + factory HomeLocationSettings.fromJson(Map decoded) { + final bssids = decoded['bssids']; + return HomeLocationSettings( + ssid: decoded['ssid'] as String?, + bssids: bssids is List + ? bssids.whereType().map((b) => b.toLowerCase()).toList() + : const [], + lat: (decoded['lat'] as num?)?.toDouble(), + lon: (decoded['lon'] as num?)?.toDouble(), + radiusMeters: + (decoded['radiusMeters'] as num?)?.toDouble() ?? defaultRadiusMeters, + ); + } + /// SharedPreferences key holding the whole record as JSON. static const String kKey = 'homeLocation.value'; + /// SharedPreferences key holding when home was last captured/cleared (ISO). + /// + /// The cross-device merge compares this stamp (`settings_sync.dart`), so + /// the newest capture on any install wins. Empty means never edited here. + static const String kEditedAtKey = 'homeLocation.editedAt'; + /// How far from the stored coordinate still counts as home. static const double defaultRadiusMeters = 150; @@ -47,6 +70,9 @@ class HomeLocationSettings { /// Radius around ([lat], [lon]) that counts as home. final double radiusMeters; + /// When this record was last captured or cleared, ISO, or '' when never. + final String editedAt; + /// Whether a home has ever been captured. bool get isConfigured => ssid != null || bssids.isNotEmpty || hasCoordinate; @@ -66,27 +92,36 @@ class HomeLocationSettings { static Future load() async { final prefs = await SharedPreferences.getInstance(); final stored = prefs.getString(kKey); - if (stored == null) return const HomeLocationSettings(); + final editedAt = prefs.getString(kEditedAtKey) ?? ''; + if (stored == null) return HomeLocationSettings(editedAt: editedAt); try { final decoded = jsonDecode(stored); if (decoded is! Map) return const HomeLocationSettings(); - final bssids = decoded['bssids']; - return HomeLocationSettings( - ssid: decoded['ssid'] as String?, - bssids: bssids is List - ? bssids.whereType().map((b) => b.toLowerCase()).toList() - : const [], - lat: (decoded['lat'] as num?)?.toDouble(), - lon: (decoded['lon'] as num?)?.toDouble(), - radiusMeters: - (decoded['radiusMeters'] as num?)?.toDouble() ?? - defaultRadiusMeters, - ); + return HomeLocationSettings.fromJson(decoded).withEditedAt(editedAt); } on FormatException { return const HomeLocationSettings(); } } + /// The same location carrying [editedAt]. + HomeLocationSettings withEditedAt(String editedAt) => HomeLocationSettings( + ssid: ssid, + bssids: bssids, + lat: lat, + lon: lon, + radiusMeters: radiusMeters, + editedAt: editedAt, + ); + + /// The wire/storage shape; the inverse of [HomeLocationSettings.fromJson]. + Map toJson() => { + 'ssid': ssid, + 'bssids': bssids, + 'lat': lat, + 'lon': lon, + 'radiusMeters': radiusMeters, + }; + /// Records this place as home, merging [bssid] into any already captured. /// /// Merging rather than replacing is what lets a second press on the other @@ -108,8 +143,9 @@ class HomeLocationSettings { lat: lat ?? current.lat, lon: lon ?? current.lon, radiusMeters: current.radiusMeters, + editedAt: DateTime.now().toIso8601String(), ); - await _save(next); + await applySynced(next); return next; } @@ -117,19 +153,19 @@ class HomeLocationSettings { static Future clear() async { final prefs = await SharedPreferences.getInstance(); await prefs.remove(kKey); + // A clear is an edit too: without a fresh stamp the merge would read the + // still-newer remote copy straight back in. + await prefs.setString(kEditedAtKey, DateTime.now().toIso8601String()); } - static Future _save(HomeLocationSettings value) async { + /// Stores [value] verbatim, including its [editedAt]. + /// + /// The sync merge uses this to apply a winner from another install with + /// that side's real edit time, so re-syncing an unchanged home is a no-op + /// instead of a fresh push every tick. + static Future applySynced(HomeLocationSettings value) async { final prefs = await SharedPreferences.getInstance(); - await prefs.setString( - kKey, - jsonEncode({ - 'ssid': value.ssid, - 'bssids': value.bssids, - 'lat': value.lat, - 'lon': value.lon, - 'radiusMeters': value.radiusMeters, - }), - ); + await prefs.setString(kKey, jsonEncode(value.toJson())); + await prefs.setString(kEditedAtKey, value.editedAt); } } diff --git a/phone_app/lib/services/room_proof_settings.dart b/phone_app/lib/services/room_proof_settings.dart index f0211c9..97e6353 100644 --- a/phone_app/lib/services/room_proof_settings.dart +++ b/phone_app/lib/services/room_proof_settings.dart @@ -10,7 +10,10 @@ import 'package:shared_preferences/shared_preferences.dart'; /// screen drops straight to the bypass when [isComplete] is false. class RoomProofSettings { /// Creates settings from the registered tag ids, one per slot. - const RoomProofSettings({this.nfcTagIds = const ['', '']}); + const RoomProofSettings({ + this.nfcTagIds = const ['', ''], + this.editedAt = '', + }); /// SharedPreferences key holding the tag ids as a JSON list. static const String kNfcTagsKey = 'roomProof.nfcTagIds'; @@ -18,6 +21,13 @@ class RoomProofSettings { /// The pre-two-tag key, migrated into slot 0 on first load. static const String kLegacyNfcTagKey = 'roomProof.nfcTagId'; + /// SharedPreferences key holding when the tags were last changed (ISO). + /// + /// This is the stamp the cross-device merge compares (`settings_sync.dart`), + /// so a registration here beats an older one from a previous install and + /// vice versa. Empty means never edited on this install. + static const String kEditedAtKey = 'roomProof.editedAt'; + /// How many tags the strict sequence needs. static const int requiredTagCount = 2; @@ -26,6 +36,9 @@ class RoomProofSettings { /// Always [requiredTagCount] long, so slot writes never have to grow it. final List nfcTagIds; + /// When [nfcTagIds] was last set, ISO format, or '' when never. + final String editedAt; + /// The tag registered for [slot], or null when that slot is unset. String? tagAt(int slot) { if (slot < 0 || slot >= nfcTagIds.length) return null; @@ -57,15 +70,16 @@ class RoomProofSettings { final prefs = await SharedPreferences.getInstance(); final stored = prefs.getString(kNfcTagsKey); if (stored != null) { - return RoomProofSettings(nfcTagIds: _padded(_decode(stored))); + return RoomProofSettings( + nfcTagIds: _padded(_decode(stored)), + editedAt: prefs.getString(kEditedAtKey) ?? '', + ); } // One-time migration: an existing install has a tag registered under the // old key, and silently losing it would leave the user unable to dismiss // by the normal path on the first morning after the update. final legacy = prefs.getString(kLegacyNfcTagKey); - return RoomProofSettings( - nfcTagIds: _padded([?legacy]), - ); + return RoomProofSettings(nfcTagIds: _padded([?legacy])); } /// Decodes the stored JSON list, treating anything malformed as unset. @@ -79,13 +93,23 @@ class RoomProofSettings { } } - /// Stores [tagId] in [slot], leaving the other slot untouched. + /// Stores [tagId] in [slot], leaving the other slot untouched, stamped now. static Future saveNfcTagAt(int slot, String tagId) async { final current = await load(); final next = List.of(current.nfcTagIds); if (slot < 0 || slot >= next.length) return; next[slot] = tagId; + await replaceAll(next, DateTime.now().toIso8601String()); + } + + /// Stores [tagIds] wholesale with the given [editedAt]. + /// + /// The sync merge uses this to apply a winner from another install, keeping + /// that side's real edit time rather than "now" -- otherwise the next merge + /// would see a fresher local stamp and push the same value straight back. + static Future replaceAll(List tagIds, String editedAt) async { final prefs = await SharedPreferences.getInstance(); - await prefs.setString(kNfcTagsKey, jsonEncode(next)); + await prefs.setString(kNfcTagsKey, jsonEncode(_padded(tagIds))); + await prefs.setString(kEditedAtKey, editedAt); } } diff --git a/phone_app/lib/services/settings_sync.dart b/phone_app/lib/services/settings_sync.dart new file mode 100644 index 0000000..e4ebeab --- /dev/null +++ b/phone_app/lib/services/settings_sync.dart @@ -0,0 +1,121 @@ +/// The NFC tags and home location, carried on the synced alarm record. +/// +/// Both used to live only in SharedPreferences, so a reinstall lost them and +/// the user re-registered two tags and re-captured home by hand (2026-09-11). +/// They are properties of the flat, not of one install, so they ride on the +/// same `alarm.json` record the PC already reads -- as extra per-field +/// entries the PC parser ignores -- and a fresh install gets them back on its +/// first sync with a backend connected. +/// +/// Last-writer-wins per field, by wall time: a registration on any install +/// beats an older one anywhere else. The stamp is the local `editedAt` +/// (`RoomProofSettings` / `HomeLocationSettings`) turned into a deterministic +/// [Hlc], so re-syncing an unchanged value is a no-op rather than a fresh +/// push every tick -- the same trick `diet_guard`'s catering credential uses. +/// Comparisons are on wall time only: a value applied *from* the log gets the +/// log's wall time as its stamp, and comparing counters or node ids on that +/// tie would push the identical value straight back. +library; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; + +/// Field holding the registered tag ids, one string per slot. +const nfcTagsField = 'nfc_tag_ids'; + +/// Field holding [HomeLocationSettings.toJson]; a cleared home is the +/// all-null shape, not an absent field, so clearing propagates too. +const homeLocationField = 'home_location'; + +/// Wall-clock milliseconds of an ISO [editedAt], or 0 when it does not parse. +int _msOf(String editedAt) => + DateTime.tryParse(editedAt)?.toUtc().millisecondsSinceEpoch ?? 0; + +/// The stamp a value applied from the log carries locally. +String _stampOf(Hlc hlc) => DateTime.fromMillisecondsSinceEpoch( + hlc.wallTimeMs, + isUtc: true, +).toIso8601String(); + +/// Copies local edits newer than the log's copy onto the alarm record. +/// +/// Run before every sync so a tag registered a minute ago is in the pushed +/// log. An install that never edited a value (empty `editedAt`) contributes +/// nothing, so it cannot clobber a peer's registration with its own blanks -- +/// unless it holds a value from before stamps existed, which goes in at +/// [_legacyMs] so it is kept when nothing else is known and loses to any +/// stamped peer. +Future stageLocalSettings(AlarmSyncService service) async { + final tags = await RoomProofSettings.load(); + await _stage( + service, + nfcTagsField, + tags.editedAt, + tags.nfcTagIds, + configured: tags.nfcTagIds.any((id) => id.isNotEmpty), + ); + final home = await HomeLocationSettings.load(); + await _stage( + service, + homeLocationField, + home.editedAt, + home.toJson(), + configured: home.isConfigured, + ); +} + +/// The stamp of a pre-stamp value: just above the epoch, so any real edit +/// wins, but present, so it is pushed rather than silently dropped. +const _legacyMs = 1; + +Future _stage( + AlarmSyncService service, + String field, + String editedAt, + Object value, { + required bool configured, +}) async { + if (editedAt.isEmpty && !configured) return; + final localMs = editedAt.isEmpty ? _legacyMs : _msOf(editedAt); + final existing = service.field(field); + if (existing != null && existing.$2.wallTimeMs >= localMs) return; + await service.setFields({ + field: value, + }, Hlc.newTick(service.deviceId, wallTimeMsOverride: localMs)); +} + +/// Writes log values newer than the local copy into SharedPreferences. +/// +/// Run after every sync; this is the restore path for a fresh install. Values +/// that fail to decode are left alone: a peer's malformed push must not wipe +/// a working registration. +Future applySyncedSettings(AlarmSyncService service) async { + final tags = await RoomProofSettings.load(); + final tagField = service.field(nfcTagsField); + if (tagField != null && _newer(tagField.$2, tags.editedAt)) { + final ids = tagField.$1; + if (ids is List) { + await RoomProofSettings.replaceAll( + ids.whereType().toList(), + _stampOf(tagField.$2), + ); + } + } + final home = await HomeLocationSettings.load(); + final homeField = service.field(homeLocationField); + if (homeField != null && _newer(homeField.$2, home.editedAt)) { + final json = homeField.$1; + if (json is Map) { + await HomeLocationSettings.applySynced( + HomeLocationSettings.fromJson( + Map.from(json), + ).withEditedAt(_stampOf(homeField.$2)), + ); + } + } +} + +bool _newer(Hlc remote, String localEditedAt) => + localEditedAt.isEmpty || remote.wallTimeMs > _msOf(localEditedAt); diff --git a/phone_app/test/services/alarm_sync_pull_test.dart b/phone_app/test/services/alarm_sync_pull_test.dart new file mode 100644 index 0000000..f2208fd --- /dev/null +++ b/phone_app/test/services/alarm_sync_pull_test.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart' as http_testing; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; + +const _deviceId = 'this-install'; +const _peerId = 'previous-install'; +const _prefix = 'wake-alarm-sync/devices'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +http.Response _json(Object body, [int status = 200]) => + http.Response(jsonEncode(body), status); + +/// Mock GitHub Contents API with one peer directory holding [peerLog]. +/// +/// The directory GET answers the listing `syncLog` walks, the peer's file GET +/// answers the pull, and every PUT is recorded so the merged push can be +/// inspected. +({http.Client client, List> pushes}) _mockRemote({ + Map? peerLog, +}) { + final pushes = >[]; + final client = http_testing.MockClient((request) async { + final path = request.url.path; + if (!path.contains('/contents/')) return _json({}); + final key = path.split('/contents/').last; + if (request.method == 'PUT') { + final body = jsonDecode(request.body) as Map; + final text = utf8.decode(base64.decode(body['content'] as String)); + pushes.add(jsonDecode(text) as Map); + return _json({}); + } + if (key == _prefix) { + return _json([ + if (peerLog != null) {'name': _peerId, 'type': 'dir'}, + {'name': _deviceId, 'type': 'dir'}, + ]); + } + if (key == '$_prefix/$_peerId/alarm.json' && peerLog != null) { + return _json({ + 'content': base64.encode(utf8.encode(jsonEncode(peerLog))), + 'encoding': 'base64', + }); + } + return _json({}, 404); + }); + return (client: client, pushes: pushes); +} + +Map _peerRecord(Map fields, String hlc) => { + 'alarm': { + 'id': 'alarm', + 'fields': { + for (final e in fields.entries) e.key: [e.value, hlc], + }, + 'deleted': false, + 'deleted_hlc': null, + }, +}; + +void main() { + late AlarmSyncService service; + + setUp(() async { + service = await AlarmSyncService.open( + persistence: _MemPersistence(), + deviceId: _deviceId, + ); + }); + + test('setLocal keeps fields another writer put on the record', () async { + final hlc = Hlc.newTick(_deviceId, wallTimeMsOverride: 1000); + await service.setFields({ + 'nfc_tag_ids': ['a', 'b'], + }, hlc); + await service.setLocal(6, 30); + + expect(service.currentAlarm, (hour: 6, minute: 30)); + final tags = service.field('nfc_tag_ids'); + expect(tags?.$1, ['a', 'b']); + expect(tags?.$2, hlc); + }); + + test('field is null for an unset field or an empty record', () async { + expect(service.field('nfc_tag_ids'), isNull); + await service.setLocal(6, 30); + expect(service.field('nfc_tag_ids'), isNull); + }); + + test('pushWith pulls a previous install and takes its newer field', () async { + await service.setLocal(8, 0); + final (:client, :pushes) = _mockRemote( + peerLog: _peerRecord({ + 'alarm_hour': 7, + 'alarm_minute': 0, + 'nfc_tag_ids': ['x', 'y'], + }, '2026-09-11T10:26:18.254Z-0000-$_peerId'), + ); + final github = GitHubClient( + owner: 'o', + repo: 'r', + token: 't', + httpClient: client, + ); + + await service.pushWith(github); + + // The peer's tags are merged in; the peer's older alarm loses to the + // fresh local one. + expect(service.field('nfc_tag_ids')?.$1, ['x', 'y']); + expect(service.currentAlarm, (hour: 8, minute: 0)); + // And the merged result is what was pushed, under this install's path. + expect(pushes, hasLength(1)); + final fields = (pushes.single['alarm'] as Map)['fields'] as Map; + expect((fields['nfc_tag_ids'] as List).first, ['x', 'y']); + expect((fields['alarm_hour'] as List).first, 8); + }); + + test('pushWith with no peers pushes the local log unchanged', () async { + await service.setLocal(8, 0); + final (:client, :pushes) = _mockRemote(); + final github = GitHubClient( + owner: 'o', + repo: 'r', + token: 't', + httpClient: client, + ); + + await service.pushWith(github); + + expect(pushes, hasLength(1)); + expect(service.field('nfc_tag_ids'), isNull); + }); +} diff --git a/phone_app/test/services/settings_sync_test.dart b/phone_app/test/services/settings_sync_test.dart new file mode 100644 index 0000000..2bc83e1 --- /dev/null +++ b/phone_app/test/services/settings_sync_test.dart @@ -0,0 +1,181 @@ +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; +import 'package:wake_alarm_sync/services/home_location_settings.dart'; +import 'package:wake_alarm_sync/services/room_proof_settings.dart'; +import 'package:wake_alarm_sync/services/settings_sync.dart'; + +const _deviceId = 'this-install'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +Future _open() => + AlarmSyncService.open(persistence: _MemPersistence(), deviceId: _deviceId); + +Hlc _at(String iso) => Hlc.newTick( + 'peer', + wallTimeMsOverride: DateTime.parse(iso).millisecondsSinceEpoch, +); + +const _home = { + 'ssid': 'HomeNet', + 'bssids': ['aa:bb:cc:dd:ee:ff'], + 'lat': 52.2, + 'lon': 20.9, + 'radiusMeters': 150.0, +}; + +void main() { + group('stageLocalSettings', () { + test('an untouched install contributes nothing', () async { + SharedPreferences.setMockInitialValues({}); + final service = await _open(); + await stageLocalSettings(service); + expect(service.field(nfcTagsField), isNull); + expect(service.field(homeLocationField), isNull); + }); + + test('a stamped edit lands on the record at its edit time', () async { + SharedPreferences.setMockInitialValues({}); + await RoomProofSettings.saveNfcTagAt(0, 'tag-a'); + final edited = (await RoomProofSettings.load()).editedAt; + final service = await _open(); + + await stageLocalSettings(service); + + final field = service.field(nfcTagsField); + expect(field?.$1, ['tag-a', '']); + expect( + field?.$2.wallTimeMs, + DateTime.parse(edited).toUtc().millisecondsSinceEpoch, + ); + }); + + test('a pre-stamp value goes in just above the epoch', () async { + SharedPreferences.setMockInitialValues({ + RoomProofSettings.kNfcTagsKey: jsonEncode(['old-a', 'old-b']), + HomeLocationSettings.kKey: jsonEncode(_home), + }); + final service = await _open(); + + await stageLocalSettings(service); + + expect(service.field(nfcTagsField)?.$2.wallTimeMs, 1); + expect(service.field(homeLocationField)?.$2.wallTimeMs, 1); + final home = service.field(homeLocationField)?.$1; + expect(home, isA>()); + expect((home! as Map)['ssid'], 'HomeNet'); + }); + + test('an older local edit does not overwrite a newer field', () async { + SharedPreferences.setMockInitialValues({ + RoomProofSettings.kNfcTagsKey: jsonEncode(['local', '']), + RoomProofSettings.kEditedAtKey: '2026-09-01T00:00:00.000Z', + }); + final service = await _open(); + await service.setFields({ + nfcTagsField: ['remote', 'newer'], + }, _at('2026-09-10T00:00:00.000Z')); + + await stageLocalSettings(service); + + expect(service.field(nfcTagsField)?.$1, ['remote', 'newer']); + }); + }); + + group('applySyncedSettings', () { + test('a fresh install takes the record values with their stamps', () async { + SharedPreferences.setMockInitialValues({}); + final service = await _open(); + await service.setFields({ + nfcTagsField: ['x', 'y'], + homeLocationField: _home, + }, _at('2026-09-11T10:26:18.254Z')); + + await applySyncedSettings(service); + + final tags = await RoomProofSettings.load(); + expect(tags.nfcTagIds, ['x', 'y']); + expect(tags.editedAt, '2026-09-11T10:26:18.254Z'); + final home = await HomeLocationSettings.load(); + expect(home.ssid, 'HomeNet'); + expect(home.bssids, ['aa:bb:cc:dd:ee:ff']); + expect(home.editedAt, '2026-09-11T10:26:18.254Z'); + }); + + test('a newer local edit is kept over an older record', () async { + SharedPreferences.setMockInitialValues({ + RoomProofSettings.kNfcTagsKey: jsonEncode(['mine', 'too']), + RoomProofSettings.kEditedAtKey: '2026-09-12T00:00:00.000Z', + HomeLocationSettings.kKey: jsonEncode(_home), + HomeLocationSettings.kEditedAtKey: '2026-09-12T00:00:00.000Z', + }); + final service = await _open(); + await service.setFields({ + nfcTagsField: ['old', 'old'], + homeLocationField: {'ssid': 'Elsewhere'}, + }, _at('2026-09-01T00:00:00.000Z')); + + await applySyncedSettings(service); + + expect((await RoomProofSettings.load()).nfcTagIds, ['mine', 'too']); + expect((await HomeLocationSettings.load()).ssid, 'HomeNet'); + }); + + test('a malformed value is ignored rather than applied', () async { + SharedPreferences.setMockInitialValues({}); + final service = await _open(); + await service.setFields({ + nfcTagsField: 'not-a-list', + homeLocationField: 42, + }, _at('2026-09-11T00:00:00.000Z')); + + await applySyncedSettings(service); + + expect((await RoomProofSettings.load()).nfcTagIds, ['', '']); + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); + + test('a cleared home on the record clears a stale local one', () async { + SharedPreferences.setMockInitialValues({ + HomeLocationSettings.kKey: jsonEncode(_home), + HomeLocationSettings.kEditedAtKey: '2026-09-01T00:00:00.000Z', + }); + final service = await _open(); + await service.setFields({ + homeLocationField: const HomeLocationSettings().toJson(), + }, _at('2026-09-11T00:00:00.000Z')); + + await applySyncedSettings(service); + + expect((await HomeLocationSettings.load()).isConfigured, isFalse); + }); + + test('apply then stage is a no-op: nothing is pushed back', () async { + SharedPreferences.setMockInitialValues({}); + final service = await _open(); + final hlc = _at('2026-09-11T10:26:18.254Z'); + await service.setFields({ + nfcTagsField: ['x', 'y'], + homeLocationField: _home, + }, hlc); + + await applySyncedSettings(service); + await stageLocalSettings(service); + + expect(service.field(nfcTagsField)?.$2, hlc); + expect(service.field(homeLocationField)?.$2, hlc); + }); + }); +}