Sync the NFC tags and home location so a reinstall gets them back

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-09-11 12:34:50 +02:00
parent c0ed168540
commit b5701fb359
11 changed files with 641 additions and 57 deletions

View File

@ -28,7 +28,9 @@ passing sent the user back to the start.
- **Two *distinct* tags.** The same id in both slots is refused at - **Two *distinct* tags.** The same id in both slots is refused at
registration — one tag satisfying both stages removes the walk, which is the registration — one tag satisfying both stages removes the walk, which is the
entire point. Stored as a JSON list under `roomProof.nfcTagIds`; a legacy 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`), - **Steps are unchanged** (`requiredSteps = 25`, `requiredElapsed = 2 min`),
and are counted from ring start, *not* re-baselined at tag 1. Consequence: 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 walking to tag 1 already banks the steps, so only the elapsed floor really

View File

@ -178,8 +178,9 @@ phone (Pixel 6a, `23181JEGR08034`) holds a **release-signed** build, so
`phone_deploy.sh <app> --release --target lib/main_ring_probe.dart` and let it `phone_deploy.sh <app> --release --target lib/main_ring_probe.dart` and let it
pick. Android compares versionCode only upward, so a hand-picked number puts 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 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, catches up — the only other escape is an uninstall, which wipes the sync
the home location and the sync identity. This happened on 2026-08-31 (probe 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). 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** `.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 `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 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 instance would carry a satisfied room proof and the solved answer into the
next ring. 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/<emulator-uuid>` after
a restore test.

View File

@ -18,6 +18,7 @@ class HomeBody extends StatelessWidget {
required this.status, required this.status,
required this.configured, required this.configured,
required this.onPickEarlier, required this.onPickEarlier,
this.syncEpoch = 0,
super.key, super.key,
}); });
@ -42,6 +43,11 @@ class HomeBody extends StatelessWidget {
/// Called when the user asks to wake earlier tomorrow. /// Called when the user asks to wake earlier tomorrow.
final VoidCallback onPickEarlier; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SafeArea( return SafeArea(
@ -51,17 +57,14 @@ class HomeBody extends StatelessWidget {
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Text( const Text('Alarm is armed for', style: TextStyle(fontSize: 16)),
'Alarm is armed for', HomePresenceLine(key: ValueKey<int>(syncEpoch)),
style: TextStyle(fontSize: 16),
),
const HomePresenceLine(),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
time, time,
style: Theme.of(context).textTheme.displayLarge?.copyWith( style: Theme.of(
fontWeight: FontWeight.bold, context,
), ).textTheme.displayLarge?.copyWith(fontWeight: FontWeight.bold),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(

View File

@ -31,6 +31,7 @@ class _HomeScreenState extends State<HomeScreen> {
bool _busy = false; bool _busy = false;
String _status = ''; String _status = '';
bool _configured = false; bool _configured = false;
int _syncEpoch = 0;
AlarmSyncService? _service; AlarmSyncService? _service;
/// Platform bridge that arms the app's own alarm (item 1). /// Platform bridge that arms the app's own alarm (item 1).
@ -156,6 +157,7 @@ class _HomeScreenState extends State<HomeScreen> {
setState(() { setState(() {
_status = message; _status = message;
_busy = false; _busy = false;
_syncEpoch++;
}); });
} }
@ -182,7 +184,10 @@ class _HomeScreenState extends State<HomeScreen> {
context, context,
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()), MaterialPageRoute<void>(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 _loadSyncState();
await _syncToPc();
}, },
), ),
], ],
@ -200,6 +205,7 @@ class _HomeScreenState extends State<HomeScreen> {
busy: _busy, busy: _busy,
status: _status, status: _status,
configured: _configured, configured: _configured,
syncEpoch: _syncEpoch,
onPickEarlier: () => unawaited(_pickEarlier()), onPickEarlier: () => unawaited(_pickEarlier()),
), ),
); );

View File

@ -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_scheduler.dart';
import 'package:wake_alarm_sync/services/alarm_sync_service.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/firebase_backend.dart';
import 'package:wake_alarm_sync/services/settings_sync.dart';
import 'package:wake_alarm_sync/services/sync_settings.dart'; import 'package:wake_alarm_sync/services/sync_settings.dart';
/// Publishes the armed alarm to the PC and arms the phone's own alarm. /// Publishes the armed alarm to the PC and arms the phone's own alarm.
@ -44,7 +45,12 @@ class AlarmPublisher {
} }
try { try {
await service.setLocal(hour, minute); 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 service.push(settings.token);
await applySyncedSettings(service);
final problem = await arming.arm(hour, minute); final problem = await arming.arm(hour, minute);
if (problem != null) return problem; if (problem != null) return problem;
await arming.registerWithClockApp(hour, minute); await arming.registerWithClockApp(hour, minute);

View File

@ -29,9 +29,10 @@ typedef Alarm = ({int hour, int minute});
/// regardless of which directory it landed in. /// regardless of which directory it landed in.
/// ///
/// The PC side is read-only (`wake_alarm/_sync.py`, which tries Firebase then /// 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 /// GitHub). The phone does pull and merge, though — not for the alarm time,
/// pull/merge here: the phone is the only writer, so its local store is /// which it always owns, but for the NFC tags and home location that ride on
/// always the source of truth. /// the same record (`settings_sync.dart`): a reinstalled phone gets them back
/// from whichever previous install pushed them last.
class AlarmSyncService { class AlarmSyncService {
/// Wraps an already-loaded log store pushing under [deviceId]. /// Wraps an already-loaded log store pushing under [deviceId].
AlarmSyncService(this._store, {required this.deviceId}); AlarmSyncService(this._store, {required this.deviceId});
@ -66,8 +67,6 @@ class AlarmSyncService {
/// whatever uuid this turns out to be. /// whatever uuid this turns out to be.
final String deviceId; final String deviceId;
String get _remotePath => 'wake-alarm-sync/devices/$deviceId/alarm.json';
static const _recordId = 'alarm'; static const _recordId = 'alarm';
static const _hourField = 'alarm_hour'; static const _hourField = 'alarm_hour';
static const _minuteField = 'alarm_minute'; static const _minuteField = 'alarm_minute';
@ -122,26 +121,55 @@ class AlarmSyncService {
/// ///
/// Both fields share one clock tick — they are always set together, so a /// Both fields share one clock tick — they are always set together, so a
/// concurrent per-field merge would never split them. /// concurrent per-field merge would never split them.
Future<void> setLocal(int hour, int minute) async { Future<void> setLocal(int hour, int minute) =>
final hlc = _store.nextHlc(); 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<void> setFields(Map<String, Object?> values, Hlc hlc) async {
final existing = _store.get(_recordId);
await _store.upsert( await _store.upsert(
Record( Record(
id: _recordId, 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 /// Takes a [RemoteStore] rather than a `GitHubClient` so the same call
/// serves Firebase, GitHub, or the [MirrorStore] that writes both — the /// serves Firebase, GitHub, or the [MirrorStore] that writes both — the
/// backend is chosen once, in [syncBackend]. /// backend is chosen once, in [syncBackend].
Future<void> pushWith(RemoteStore client) => client.putFileText( ///
_remotePath, /// The pull is what brings the tags and home location back to a fresh
logToJson(_store.snapshot()), /// install. The alarm time itself is unaffected: [setLocal] runs first on
message: 'wake_alarm_sync: update alarm', /// every publish, so the local time is always the newest and wins.
); Future<void> 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 /// Pushes to Firebase when this device is set up for it, mirroring to
/// GitHub during the cutover; to GitHub alone when it is not. /// GitHub during the cutover; to GitHub alone when it is not.

View File

@ -20,11 +20,34 @@ class HomeLocationSettings {
this.lat, this.lat,
this.lon, this.lon,
this.radiusMeters = defaultRadiusMeters, 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<String, dynamic> decoded) {
final bssids = decoded['bssids'];
return HomeLocationSettings(
ssid: decoded['ssid'] as String?,
bssids: bssids is List
? bssids.whereType<String>().map((b) => b.toLowerCase()).toList()
: const <String>[],
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. /// SharedPreferences key holding the whole record as JSON.
static const String kKey = 'homeLocation.value'; 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. /// How far from the stored coordinate still counts as home.
static const double defaultRadiusMeters = 150; static const double defaultRadiusMeters = 150;
@ -47,6 +70,9 @@ class HomeLocationSettings {
/// Radius around ([lat], [lon]) that counts as home. /// Radius around ([lat], [lon]) that counts as home.
final double radiusMeters; 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. /// Whether a home has ever been captured.
bool get isConfigured => ssid != null || bssids.isNotEmpty || hasCoordinate; bool get isConfigured => ssid != null || bssids.isNotEmpty || hasCoordinate;
@ -66,27 +92,36 @@ class HomeLocationSettings {
static Future<HomeLocationSettings> load() async { static Future<HomeLocationSettings> load() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final stored = prefs.getString(kKey); final stored = prefs.getString(kKey);
if (stored == null) return const HomeLocationSettings(); final editedAt = prefs.getString(kEditedAtKey) ?? '';
if (stored == null) return HomeLocationSettings(editedAt: editedAt);
try { try {
final decoded = jsonDecode(stored); final decoded = jsonDecode(stored);
if (decoded is! Map<String, dynamic>) return const HomeLocationSettings(); if (decoded is! Map<String, dynamic>) return const HomeLocationSettings();
final bssids = decoded['bssids']; return HomeLocationSettings.fromJson(decoded).withEditedAt(editedAt);
return HomeLocationSettings(
ssid: decoded['ssid'] as String?,
bssids: bssids is List
? bssids.whereType<String>().map((b) => b.toLowerCase()).toList()
: const <String>[],
lat: (decoded['lat'] as num?)?.toDouble(),
lon: (decoded['lon'] as num?)?.toDouble(),
radiusMeters:
(decoded['radiusMeters'] as num?)?.toDouble() ??
defaultRadiusMeters,
);
} on FormatException { } on FormatException {
return const HomeLocationSettings(); 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<String, Object?> toJson() => <String, Object?>{
'ssid': ssid,
'bssids': bssids,
'lat': lat,
'lon': lon,
'radiusMeters': radiusMeters,
};
/// Records this place as home, merging [bssid] into any already captured. /// Records this place as home, merging [bssid] into any already captured.
/// ///
/// Merging rather than replacing is what lets a second press on the other /// Merging rather than replacing is what lets a second press on the other
@ -108,8 +143,9 @@ class HomeLocationSettings {
lat: lat ?? current.lat, lat: lat ?? current.lat,
lon: lon ?? current.lon, lon: lon ?? current.lon,
radiusMeters: current.radiusMeters, radiusMeters: current.radiusMeters,
editedAt: DateTime.now().toIso8601String(),
); );
await _save(next); await applySynced(next);
return next; return next;
} }
@ -117,19 +153,19 @@ class HomeLocationSettings {
static Future<void> clear() async { static Future<void> clear() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.remove(kKey); 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<void> _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<void> applySynced(HomeLocationSettings value) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setString( await prefs.setString(kKey, jsonEncode(value.toJson()));
kKey, await prefs.setString(kEditedAtKey, value.editedAt);
jsonEncode(<String, Object?>{
'ssid': value.ssid,
'bssids': value.bssids,
'lat': value.lat,
'lon': value.lon,
'radiusMeters': value.radiusMeters,
}),
);
} }
} }

View File

@ -10,7 +10,10 @@ import 'package:shared_preferences/shared_preferences.dart';
/// screen drops straight to the bypass when [isComplete] is false. /// screen drops straight to the bypass when [isComplete] is false.
class RoomProofSettings { class RoomProofSettings {
/// Creates settings from the registered tag ids, one per slot. /// Creates settings from the registered tag ids, one per slot.
const RoomProofSettings({this.nfcTagIds = const <String>['', '']}); const RoomProofSettings({
this.nfcTagIds = const <String>['', ''],
this.editedAt = '',
});
/// SharedPreferences key holding the tag ids as a JSON list. /// SharedPreferences key holding the tag ids as a JSON list.
static const String kNfcTagsKey = 'roomProof.nfcTagIds'; static const String kNfcTagsKey = 'roomProof.nfcTagIds';
@ -18,6 +21,13 @@ class RoomProofSettings {
/// The pre-two-tag key, migrated into slot 0 on first load. /// The pre-two-tag key, migrated into slot 0 on first load.
static const String kLegacyNfcTagKey = 'roomProof.nfcTagId'; 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. /// How many tags the strict sequence needs.
static const int requiredTagCount = 2; static const int requiredTagCount = 2;
@ -26,6 +36,9 @@ class RoomProofSettings {
/// Always [requiredTagCount] long, so slot writes never have to grow it. /// Always [requiredTagCount] long, so slot writes never have to grow it.
final List<String> nfcTagIds; final List<String> 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. /// The tag registered for [slot], or null when that slot is unset.
String? tagAt(int slot) { String? tagAt(int slot) {
if (slot < 0 || slot >= nfcTagIds.length) return null; if (slot < 0 || slot >= nfcTagIds.length) return null;
@ -57,15 +70,16 @@ class RoomProofSettings {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
final stored = prefs.getString(kNfcTagsKey); final stored = prefs.getString(kNfcTagsKey);
if (stored != null) { 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 // 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 // old key, and silently losing it would leave the user unable to dismiss
// by the normal path on the first morning after the update. // by the normal path on the first morning after the update.
final legacy = prefs.getString(kLegacyNfcTagKey); final legacy = prefs.getString(kLegacyNfcTagKey);
return RoomProofSettings( return RoomProofSettings(nfcTagIds: _padded(<String>[?legacy]));
nfcTagIds: _padded(<String>[?legacy]),
);
} }
/// Decodes the stored JSON list, treating anything malformed as unset. /// 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<void> saveNfcTagAt(int slot, String tagId) async { static Future<void> saveNfcTagAt(int slot, String tagId) async {
final current = await load(); final current = await load();
final next = List<String>.of(current.nfcTagIds); final next = List<String>.of(current.nfcTagIds);
if (slot < 0 || slot >= next.length) return; if (slot < 0 || slot >= next.length) return;
next[slot] = tagId; 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<void> replaceAll(List<String> tagIds, String editedAt) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setString(kNfcTagsKey, jsonEncode(next)); await prefs.setString(kNfcTagsKey, jsonEncode(_padded(tagIds)));
await prefs.setString(kEditedAtKey, editedAt);
} }
} }

View File

@ -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<void> 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<void> _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<void> 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<String>().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<String, dynamic>.from(json),
).withEditedAt(_stampOf(homeField.$2)),
);
}
}
}
bool _newer(Hlc remote, String localEditedAt) =>
localEditedAt.isEmpty || remote.wallTimeMs > _msOf(localEditedAt);

View File

@ -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<String?> read() async => text;
@override
Future<void> 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<Map<String, dynamic>> pushes}) _mockRemote({
Map<String, dynamic>? peerLog,
}) {
final pushes = <Map<String, dynamic>>[];
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<String, dynamic>;
final text = utf8.decode(base64.decode(body['content'] as String));
pushes.add(jsonDecode(text) as Map<String, dynamic>);
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<String, dynamic> _peerRecord(Map<String, Object?> 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': <String>['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);
});
}

View File

@ -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<String?> read() async => text;
@override
Future<void> write(String value) async => text = value;
}
Future<AlarmSyncService> _open() =>
AlarmSyncService.open(persistence: _MemPersistence(), deviceId: _deviceId);
Hlc _at(String iso) => Hlc.newTick(
'peer',
wallTimeMsOverride: DateTime.parse(iso).millisecondsSinceEpoch,
);
const _home = <String, Object?>{
'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<Map<String, Object?>>());
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: <String, Object?>{'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);
});
});
}