diff --git a/AGENTS.md b/AGENTS.md index 0f2e346..9423712 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,11 @@ can reach the two-minute floor or the five-minute bypass. More, including everything that is a hard crash or a silent no-ring: **`DOCS-phone-alarm.md`**. +**Free days.** On a day in the shared pool (`~/utils/freedays`) the phone +does not ring at all: `AlarmReceiver` checks a native cache Dart rewrites +after every mark/release/sync. Picker, cache and its fail-closed contract: +**`DOCS-free-days.md`**. + ## Scheduling — a per-minute timer `wake-alarm-trigger.timer` ticks every minute (`OnCalendar=*:*:00`, diff --git a/DOCS-free-days.md b/DOCS-free-days.md new file mode 100644 index 0000000..e953c59 --- /dev/null +++ b/DOCS-free-days.md @@ -0,0 +1,65 @@ +# Free days — the phone picker for the shared pool + +The pool itself is `~/utils/freedays` (Python): one global set of days on +which every gate app stands down, 35 per calendar year, declared for today or +later, never backdated, refunded only while still in the future. Read its +README for the rules. This file covers the phone half, which lives in this +repo because the alarm is the one gate where standing down is a physical +event — the phone stays silent — rather than an absent dialog. + +## Where things are + +| | | +|---|---| +| Picker | `phone_app/lib/screens/free_days_screen.dart` (+ `free_days_body.dart`), the calendar icon on the home screen | +| Rules, Dart port | `phone_app/lib/services/free_day_pool.dart` — same record shape as the Python package, byte for byte | +| Sync | `phone_app/lib/services/free_day_sync.dart` — Firebase only, `freedays-sync/devices//free_days.json` | +| Ring path | `android/.../FreeDays.kt` + the check at the top of `AlarmReceiver.onReceive` | + +## Why there is a native cache + +The alarm fires from Kotlin with no Flutter engine running, so at 08:00 the +Dart pool is unreadable. Dart hands the current free dates to +`FreeDays.store` (channel method `setFreeDays`) after **every** mark, release +and sync; `AlarmReceiver` reads that set before starting `AlarmService`. On a +free day it logs `free day: not ringing; re-armed for tomorrow` and returns — +nothing rings, nothing is shown, and the next morning is normal. + +**Fail closed.** An unreadable or missing cache is "not a free day", matching +`freedays.is_free_day()` on the PC: a corrupt pool restores the normal rules, +it never silences the alarm. Verified on the `wake_alarm_api36` AVD +(2026-09-11, `adb root` + `am broadcast --include-stopped-packages -n +…/.AlarmReceiver`): today in the set → skip line, no service; a different +date → service start; a garbage XML file → service start. + +## What reaches the phone when + +- **Marked on the phone:** immediate. The cache is rewritten before the sync + even runs, so an offline phone still stands down on a day it marked itself. +- **Marked on the PC (`freedays mark …`):** on the phone's next sync, which + happens at app launch and whenever the picker opens. The ring path takes + no background dependency by design (see `DOCS-phone-alarm.md`), so **a day + marked on the PC overnight can miss the morning ring.** Mark on the phone, + or open the app once after marking on the PC. + +## Cross-language check + +The Dart port is a second implementation of the rules, so it is verified +against the Python one rather than against itself: a log written by +`FreeDayPool` (mark, mark today, mark+release future, mark+release after +arrival) read back with `freedays.is_free_day` / `remaining` gives the same +verdicts and the same count (32 of 35), and the PC's live pool read by Dart +gives the same 27 of 35 that `freedays status` prints. Rerun that whenever +either side's policy changes — the shape test in `free_day_pool_test.dart` +only checks field names, not semantics. + +## Do NOT + +- Don't give this namespace a GitHub mirror. The alarm record keeps its + mirror because un-migrated installs depend on it; this pool never had one. +- Don't tombstone a date to un-mark it. crdt tombstones are monotonic; a + deleted date could never be marked again. Flip `state` to `cleared`. +- Don't write `consumed` back to `false`. It is the sticky flag that stops + two devices either side of midnight from refunding a day already used. +- Don't add a warning, a notification or a ring-time prompt. The pool is + consulted silently; the count is shown only when the picker is opened. diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt index 3b2ac7f..2f8b898 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmChannel.kt @@ -61,6 +61,18 @@ object AlarmChannel { AlarmService.start(context) result.success(null) } + // The Dart pool's free dates, cached where AlarmReceiver can + // read them with no engine running. Dart calls this after every + // mark, release and sync; see FreeDays.kt. + "setFreeDays" -> { + val dates = call.argument>("dates") + if (dates == null) { + result.error("bad_args", "dates is required", null) + } else { + FreeDays.store(context, dates) + result.success(null) + } + } "hasNfc" -> result.success(NfcReader.isAvailable(context)) // Raw observations only; home_presence.dart decides what they mean. // Lives here rather than in MainActivity's override (as NfcReader diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt index 4460d2d..6ece7af 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/AlarmReceiver.kt @@ -3,6 +3,7 @@ package com.kuhy.wake_alarm_sync import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import android.util.Log /** * Receives the exact alarm and hands straight off to [AlarmService]. @@ -15,6 +16,18 @@ import android.content.Intent */ class AlarmReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { + // A shared free day means the alarm does not ring -- not later, not + // quieter, not at all. Re-arm for tomorrow (nextOccurrence rolls over + // because the armed instant has passed) so the day after is normal. + if (FreeDays.isToday(context)) { + Log.i(TAG, "free day: not ringing; re-armed for tomorrow") + AlarmScheduler.rearmFromStorage(context) + return + } AlarmService.start(context) } + + private companion object { + const val TAG = "WakeAlarmReceiver" + } } diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/FreeDays.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/FreeDays.kt new file mode 100644 index 0000000..50edc04 --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/FreeDays.kt @@ -0,0 +1,42 @@ +package com.kuhy.wake_alarm_sync + +import android.content.Context +import android.util.Log +import java.time.LocalDate + +/** + * The native copy of the shared free-day pool: the ISO dates on which the + * alarm must not ring. + * + * The alarm fires with no Flutter engine running, so the Dart-side pool + * (`free_day_pool.dart`) is unreadable at 08:00. Dart rewrites this cache + * after every local change and every sync; [AlarmReceiver] reads it before + * making any noise. + * + * Fail closed: anything unreadable means "not a free day", so a corrupt or + * missing cache restores the normal rules rather than silencing the alarm. + * That matches `freedays.is_free_day()` on the PC. + */ +object FreeDays { + + private const val TAG = "WakeAlarmFreeDays" + private const val PREFS = "wake_alarm_freedays" + private const val KEY_DATES = "free_dates" + + /** Replaces the cached set with [isoDates] (`yyyy-MM-dd` each). */ + fun store(context: Context, isoDates: List) { + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit() + .putStringSet(KEY_DATES, isoDates.toSet()) + .apply() + } + + /** Whether today (local calendar day) is in the cached set. */ + fun isToday(context: Context): Boolean = try { + val dates = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + .getStringSet(KEY_DATES, emptySet()) ?: emptySet() + dates.contains(LocalDate.now().toString()) + } catch (e: RuntimeException) { + Log.w(TAG, "free-day cache unreadable; ringing as normal", e) + false + } +} diff --git a/phone_app/lib/screens/free_days_body.dart b/phone_app/lib/screens/free_days_body.dart new file mode 100644 index 0000000..39567e1 --- /dev/null +++ b/phone_app/lib/screens/free_days_body.dart @@ -0,0 +1,111 @@ +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; +import 'package:wake_alarm_sync/ui/theme.dart'; + +/// One upcoming free day, as the list shows it. +typedef UpcomingFreeDay = ({DateTime day, String reason}); + +/// The picker's body: the year's budget, the upcoming days, the status line. +/// +/// Stateless and fed plain values, like `HomeBody`: the screen owns the pool +/// and the sync ordering, this only draws. +class FreeDaysBody extends StatelessWidget { + /// Creates the body from already-resolved state. + const FreeDaysBody({ + required this.year, + required this.remaining, + required this.upcoming, + required this.status, + required this.busy, + required this.onRelease, + super.key, + }); + + /// The calendar year the budget line describes. + final int year; + + /// Days left in [year]. + final int remaining; + + /// Free days from today on, ascending. + final List upcoming; + + /// The status line; may be a raw `Error: …`. + final String status; + + /// Whether a sync is in flight, disabling the release buttons. + final bool busy; + + /// Called when the user gives a day back. + final void Function(DateTime day) onRelease; + + static const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; + + String _label(DateTime day) => + '${_weekdays[day.weekday - 1]} ${FreeDayPool.toIso(day)}'; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final statusColors = theme.extension()!; + return SafeArea( + child: ListView( + // Bottom room for the extended FAB, so the last row stays tappable. + padding: const EdgeInsets.fromLTRB(16, 16, 16, 96), + children: [ + Text( + '$remaining of ${FreeDayPool.annualBudget}', + style: theme.textTheme.displayMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + 'free days left in $year', + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Text( + 'On a free day nothing locks, nothing rings and nothing asks. ' + 'Every app, at once.', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + if (status.isNotEmpty) ...[ + const SizedBox(height: 16), + Text( + status, + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: status.contains('Error') + ? theme.colorScheme.error + : statusColors.success, + ), + ), + ], + const SizedBox(height: 24), + Text('Booked ahead', style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + if (upcoming.isEmpty) + Text( + 'None. Tap "Take a day" to book one.', + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + ), + for (final entry in upcoming) + ListTile( + contentPadding: EdgeInsets.zero, + title: Text(_label(entry.day)), + subtitle: entry.reason.isEmpty ? null : Text(entry.reason), + trailing: TextButton( + onPressed: busy ? null : () => onRelease(entry.day), + child: const Text('Release'), + ), + ), + ], + ), + ); + } +} diff --git a/phone_app/lib/screens/free_days_screen.dart b/phone_app/lib/screens/free_days_screen.dart new file mode 100644 index 0000000..96a8b0e --- /dev/null +++ b/phone_app/lib/screens/free_days_screen.dart @@ -0,0 +1,176 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/free_days_body.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; +import 'package:wake_alarm_sync/services/free_day_sync.dart'; + +/// The one picker for the shared free-day pool. +/// +/// A day marked here stands down every gate app at once — the PC lockers, +/// diet guard, leetcode guard, home guard, and this alarm — and none of them +/// mentions it afterwards. There is no notification, no low-budget warning +/// and no prompt at ring time; you find out how many are left by opening +/// this screen. +/// +/// Syncs on open and after every change. A day marked on the PC reaches the +/// phone the next time this app launches or this screen opens — the ring +/// path takes no background dependency, so an overnight PC mark can miss +/// the morning ring. Marking on the phone is immediate. +class FreeDaysScreen extends StatefulWidget { + /// Creates the picker; the seams are injectable for tests. + const FreeDaysScreen({this.openPool, this.syncer, this.now, super.key}); + + /// Opens the pool; defaults to the on-disk one. + final Future Function()? openPool; + + /// Syncs the pool; defaults to Firebase. + final FreeDaySync? syncer; + + /// The reference date, for tests. + final DateTime Function()? now; + + @override + State createState() => _FreeDaysScreenState(); +} + +class _FreeDaysScreenState extends State { + FreeDayPool? _pool; + bool _busy = true; + String _status = ''; + + late final FreeDaySync _syncer = widget.syncer ?? FreeDaySync(); + + DateTime get _today => + FreeDayPool.dateOnly(widget.now?.call() ?? DateTime.now()); + + @override + void initState() { + super.initState(); + unawaited(_load()); + } + + Future _load() async { + try { + _pool = await (widget.openPool ?? FreeDayPool.open)(); + } on Exception catch (e) { + if (!mounted) return; + setState(() { + _busy = false; + _status = 'Error: pool unavailable ($e)'; + }); + return; + } + await _sync(); + } + + Future _sync() async { + final pool = _pool; + if (pool == null) return; + setState(() { + _busy = true; + _status = 'Syncing…'; + }); + final message = await _syncer.sync(pool); + if (!mounted) return; + setState(() { + _busy = false; + _status = message; + }); + } + + Future _pickDay() async { + final pool = _pool; + if (pool == null) return; + final today = _today; + final picked = await showDatePicker( + context: context, + initialDate: today, + firstDate: today, + lastDate: DateTime(today.year + 1, 12, 31), + helpText: 'Take a free day', + selectableDayPredicate: (day) => !pool.isFree(day), + ); + if (picked == null || !mounted) return; + final reason = await _askReason(); + if (!mounted) return; + await _apply(() => pool.mark(picked, reason: reason ?? '', now: today)); + } + + /// Optional, by design. Enter with an empty field and nothing is stored. + Future _askReason() { + final controller = TextEditingController(); + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Reason (optional)'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(hintText: 'e.g. travelling'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(controller.text), + child: const Text('Mark free'), + ), + ], + ), + ); + } + + Future _release(DateTime day) async { + final pool = _pool; + if (pool == null) return; + await _apply(() => pool.release(day, now: _today)); + } + + /// Runs a pool edit, reports a refusal in the status line, and syncs. + Future _apply(Future Function() edit) async { + try { + await edit(); + } on FreeDayPolicyError catch (e) { + setState(() => _status = e.message); + return; + } + await _sync(); + } + + @override + Widget build(BuildContext context) { + final pool = _pool; + return Scaffold( + appBar: AppBar( + title: const Text('Free days'), + actions: [ + IconButton( + icon: const Icon(Icons.sync), + tooltip: 'Sync now', + onPressed: _busy ? null : () => unawaited(_sync()), + ), + ], + ), + body: pool == null + ? Center(child: Text(_status.isEmpty ? 'Loading…' : _status)) + : FreeDaysBody( + year: _today.year, + remaining: pool.remaining(_today.year), + upcoming: [ + for (final day in pool.freeDays()) + if (!day.isBefore(_today)) + (day: day, reason: pool.reasonFor(day)), + ], + status: _status, + busy: _busy, + onRelease: (day) => unawaited(_release(day)), + ), + floatingActionButton: pool == null + ? null + : FloatingActionButton.extended( + onPressed: _busy ? null : () => unawaited(_pickDay()), + icon: const Icon(Icons.event_available), + label: const Text('Take a day'), + ), + ); + } +} diff --git a/phone_app/lib/screens/home_screen.dart b/phone_app/lib/screens/home_screen.dart index 02af193..f0ccc3b 100644 --- a/phone_app/lib/screens/home_screen.dart +++ b/phone_app/lib/screens/home_screen.dart @@ -3,6 +3,7 @@ import 'dart:developer' as developer; import 'package:flutter/material.dart'; +import 'package:wake_alarm_sync/screens/free_days_screen.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'; @@ -10,6 +11,8 @@ import 'package:wake_alarm_sync/services/alarm_publisher.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/free_day_pool.dart'; +import 'package:wake_alarm_sync/services/free_day_sync.dart'; import 'package:wake_alarm_sync/services/sync_settings.dart'; /// Main screen: displays the current alarm time and syncs it to the PC via @@ -60,6 +63,27 @@ class _HomeScreenState extends State { await _applyPolicy(); await _loadSyncState(); await _syncToPc(); + await _refreshFreeDays(); + } + + /// Pulls the shared free-day pool and hands it to the native ring path. + /// + /// Last, and silent: a day marked on the PC reaches the phone here, and + /// nothing on this screen reports it -- the pool is only ever consulted, + /// never announced. Failures are logged by [FreeDaySync] and swallowed; + /// an unreadable pool means the alarm rings as normal. + Future _refreshFreeDays() async { + try { + final pool = await FreeDayPool.open(); + await FreeDaySync().sync(pool); + } on Exception catch (e, stack) { + developer.log( + 'free-day pool unavailable: $e', + name: 'WakeAlarmSync', + error: e, + stackTrace: stack, + ); + } } /// Opens the sync store and records whether a backend is connected. @@ -173,6 +197,17 @@ class _HomeScreenState extends State { appBar: AppBar( title: const Text('Wake Alarm Sync'), actions: [ + IconButton( + icon: Icon( + Icons.event_available, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + tooltip: 'Free days', + onPressed: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const FreeDaysScreen()), + ), + ), IconButton( icon: Icon( Icons.settings, diff --git a/phone_app/lib/services/alarm_scheduler.dart b/phone_app/lib/services/alarm_scheduler.dart index 4908ec5..50ea6bf 100644 --- a/phone_app/lib/services/alarm_scheduler.dart +++ b/phone_app/lib/services/alarm_scheduler.dart @@ -20,11 +20,10 @@ class AlarmScheduler { /// days) and its baked-in fallback hour. Callers pass a time resolved by /// `AlarmPolicy`, never a user-chosen one: the schedule is fixed at 08:00 /// and only ever ratchets earlier. - Future schedule(int hour, int minute) => - _channel.invokeMethod('schedule', { - 'hour': hour, - 'minute': minute, - }); + Future schedule(int hour, int minute) => _channel.invokeMethod( + 'schedule', + {'hour': hour, 'minute': minute}, + ); // There is deliberately NO cancel(). The alarm cannot be switched off from // the app: the only way past it is the full dismiss ritual at ring time. @@ -35,11 +34,10 @@ class AlarmScheduler { /// /// Called from the app's init seam, so simply launching the app arms the /// alarm — there is no button to forget to press. - Future armSchedule(int hour, int minute) => - _channel.invokeMethod('armSchedule', { - 'hour': hour, - 'minute': minute, - }); + Future armSchedule(int hour, int minute) => _channel.invokeMethod( + 'armSchedule', + {'hour': hour, 'minute': minute}, + ); /// Re-arms from the stored time; false when no alarm was ever set. /// @@ -99,6 +97,15 @@ class AlarmScheduler { Future closeRingScreen() => _channel.invokeMethod('closeRingScreen'); + /// Hands the native ring path the current set of free ISO dates. + /// + /// The alarm fires from Kotlin with no Flutter engine running, so the + /// Dart-side pool is invisible at 08:00. This is the cache `AlarmReceiver` + /// consults before making any noise; it is rewritten after every local + /// change and every sync, so it is only ever as stale as the last launch. + Future setFreeDays(List isoDates) => _channel + .invokeMethod('setFreeDays', {'dates': isoDates}); + /// Starts the ring immediately, without waiting for the alarm instant. /// /// Exists so the foreground-service and full-screen-intent path can be @@ -129,12 +136,14 @@ class AlarmScheduler { double? homeLon, bool withFix = false, }) async { - final result = await _channel - .invokeMapMethod('readPresence', { - 'homeLat': homeLat, - 'homeLon': homeLon, - 'withFix': withFix, - }); + final result = await _channel.invokeMapMethod( + 'readPresence', + { + 'homeLat': homeLat, + 'homeLon': homeLon, + 'withFix': withFix, + }, + ); return result; } } diff --git a/phone_app/lib/services/free_day_pool.dart b/phone_app/lib/services/free_day_pool.dart new file mode 100644 index 0000000..20832b1 --- /dev/null +++ b/phone_app/lib/services/free_day_pool.dart @@ -0,0 +1,231 @@ +import 'dart:io'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:crdt_sync/crdt_sync_io.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:wake_alarm_sync/services/alarm_sync_service.dart'; + +/// The shared free-day pool, as the phone sees it. +/// +/// A Dart port of `~/utils/freedays` (Python), which owns the rules: one +/// global pool for every gate app, 35 days per calendar year resetting on +/// Jan 1, declared for today or later and never backdated, releasing refunds +/// only a day that has not arrived, and `consumed` is sticky. The record +/// shape is byte-identical to the Python package's so both sides merge one +/// log: the record id *is* the ISO date, and un-marking flips `state` rather +/// than tombstoning, because crdt tombstones are monotonic and a deleted date +/// could never be marked again. +/// +/// Nothing here touches the network. `free_day_sync.dart` does that, and the +/// Kotlin ring path reads a cache this pool exports, so an offline phone +/// still stands down on a day it marked itself. +class FreeDayPool { + /// Wraps an already-loaded store writing as [deviceId]. + FreeDayPool(this._store, {required this.deviceId}); + + final LogStore _store; + + /// The device uuid stamped as `actor` on every write. + final String deviceId; + + /// Days granted per calendar year. Mirrors `DEFAULT_ANNUAL_BUDGET`. + static const annualBudget = 35; + + /// Remote layout shared with the Python package: `//`. + static const pathPrefix = 'freedays-sync/devices'; + + /// The per-device file name under [pathPrefix]. + static const filename = 'free_days.json'; + + static const _stateField = 'state'; + static const _consumedField = 'consumed'; + static const _actorField = 'actor'; + static const _reasonField = 'reason'; + static const _free = 'free'; + static const _cleared = 'cleared'; + + /// Opens the on-disk pool, minting the device id the alarm store uses. + /// + /// Same uuid as [AlarmSyncService] on purpose: one install is one actor + /// in every namespace it writes to. + static Future open({ + LogPersistence? persistence, + String? deviceId, + }) async { + final backend = persistence ?? await _defaultPersistence(); + final id = deviceId ?? await AlarmSyncService.loadDeviceId(); + final store = LogStore(persistence: backend, nodeId: id); + await store.load(); + return FreeDayPool(store, deviceId: id); + } + + static Future _defaultPersistence() async { + final dir = await getApplicationDocumentsDirectory(); + return FileLogPersistence(File(p.join(dir.path, 'free_days_log.json'))); + } + + /// Today as a local calendar date, midnight-truncated. + /// + /// Local, never UTC: a free day is a human calendar day, and the Python + /// side decides the same way (`_day.today()`). + static DateTime today() => dateOnly(DateTime.now()); + + /// [when] with its time-of-day dropped, in local time. + static DateTime dateOnly(DateTime when) => + DateTime(when.year, when.month, when.day); + + /// `yyyy-MM-dd`, the record id. + static String toIso(DateTime day) { + final m = day.month.toString().padLeft(2, '0'); + final d = day.day.toString().padLeft(2, '0'); + return '${day.year}-$m-$d'; + } + + /// Parses a record id back to a date, or null when it is not one. + static DateTime? parseIso(String id) { + final match = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(id); + if (match == null) return null; + final parsed = DateTime( + int.parse(match[1]!), + int.parse(match[2]!), + int.parse(match[3]!), + ); + // DateTime normalises 2026-02-30 to March 2 silently; reject that. + return toIso(parsed) == id ? parsed : null; + } + + /// The whole log, for `syncLog`. + Log snapshot() => _store.snapshot(); + + /// Replaces the log with a merged result and persists it. + Future replaceAll(Log merged) => _store.replaceAll(merged); + + static bool _isFree(Record? record) { + if (record == null || record.deleted) return false; + return record.fields[_stateField]?.$1 == _free; + } + + static bool _isConsumed(Record? record) => + record?.fields[_consumedField]?.$1 == true; + + /// Whether the gates stand down on [day]. + /// + /// Answers false for anything it does not understand: an unreadable pool + /// means the normal rules apply, never that everything is switched off. + bool isFree(DateTime day) => _isFree(_store.get(toIso(dateOnly(day)))); + + /// The reason stored for [day], or an empty string. + String reasonFor(DateTime day) { + final value = _store.get(toIso(dateOnly(day)))?.fields[_reasonField]?.$1; + return value is String ? value : ''; + } + + /// Every currently-free date, ascending. + List freeDays() { + final days = [ + for (final record in _store.values) + if (_isFree(record)) ?parseIso(record.id), + ]; + return days..sort(); + } + + /// Every ISO date currently free, for the native ring-path cache. + List freeIsoDates() => freeDays().map(toIso).toList(); + + /// How many of [year]'s days are gone: still free, or released after they + /// had already arrived. Taking Monday off and clearing it on Tuesday does + /// not give Monday back. + int spent(int year) { + var count = 0; + for (final record in _store.values) { + final day = parseIso(record.id); + if (day == null || day.year != year) continue; + if (_isFree(record) || _isConsumed(record)) count++; + } + return count; + } + + /// Days left in [year], never below zero. + int remaining(int year) { + final left = annualBudget - spent(year); + return left < 0 ? 0 : left; + } + + /// Marks [day] free, everywhere, for every app. + /// + /// Throws [FreeDayPolicyError] for a past day, an already-free day, or an + /// exhausted year. [now] is injectable for tests. + Future mark(DateTime day, {String reason = '', DateTime? now}) async { + final target = dateOnly(day); + final reference = dateOnly(now ?? DateTime.now()); + final id = toIso(target); + if (target.isBefore(reference)) { + throw FreeDayPolicyError( + '$id has already passed — free days are declared, not backdated.', + ); + } + final existing = _store.get(id); + if (_isFree(existing)) { + throw FreeDayPolicyError('$id is already a free day.'); + } + if (remaining(target.year) <= 0) { + throw FreeDayPolicyError( + 'No free days left in ${target.year} — all $annualBudget are spent.', + ); + } + // Sticky: a day that has arrived, or was ever spent, stays spent. + final consumed = _isConsumed(existing) || !target.isAfter(reference); + await _write(id, free: true, consumed: consumed, reason: reason); + } + + /// Gives [day] back; refunds it only if it has not arrived yet. + /// + /// Throws [FreeDayPolicyError] when [day] is not currently free. + Future release(DateTime day, {DateTime? now}) async { + final target = dateOnly(day); + final reference = dateOnly(now ?? DateTime.now()); + final id = toIso(target); + final existing = _store.get(id); + if (!_isFree(existing)) { + throw FreeDayPolicyError('$id is not a free day.'); + } + final consumed = _isConsumed(existing) || !target.isAfter(reference); + await _write(id, free: false, consumed: consumed, reason: ''); + } + + /// Every field shares one tick, so a concurrent mark and release of one + /// day resolve together rather than interleaving state from one device + /// with a reason from the other. + Future _write( + String id, { + required bool free, + required bool consumed, + required String reason, + }) async { + final hlc = _store.nextHlc(); + await _store.upsert( + Record( + id: id, + fields: { + _stateField: (free ? _free : _cleared, hlc), + _consumedField: (consumed, hlc), + _actorField: (deviceId, hlc), + _reasonField: (reason, hlc), + }, + ), + ); + } +} + +/// A mark or release the pool's rules refuse. The message is for the user. +class FreeDayPolicyError implements Exception { + /// Creates the refusal with its user-facing [message]. + FreeDayPolicyError(this.message); + + /// Why the pool said no. + final String message; + + @override + String toString() => message; +} diff --git a/phone_app/lib/services/free_day_sync.dart b/phone_app/lib/services/free_day_sync.dart new file mode 100644 index 0000000..4c5eaa0 --- /dev/null +++ b/phone_app/lib/services/free_day_sync.dart @@ -0,0 +1,88 @@ +import 'dart:developer' as developer; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/firebase_backend.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; + +/// Moves the free-day pool between this phone and every other device. +/// +/// Firebase only. The alarm record keeps its GitHub mirror because that +/// fallback is load-bearing for un-migrated installs; this namespace is new +/// and has no such history, so it gets no second transport. +/// +/// Every sync ends by handing the merged pool to the native ring path +/// ([AlarmScheduler.setFreeDays]) — that cache, not the Dart store, is what +/// decides whether the phone rings, so it must never lag a sync. +class FreeDaySync { + /// Creates a syncer; both seams are injectable for tests. + FreeDaySync({ + Future Function()? openClient, + AlarmScheduler? scheduler, + }) : _openClient = openClient ?? openFirebase, + _scheduler = scheduler ?? AlarmScheduler(); + + final Future Function() _openClient; + final AlarmScheduler _scheduler; + + /// Pulls, merges and pushes [pool], then refreshes the native cache. + /// + /// Returns a status line for the screen. Never throws: this also runs + /// unattended at launch, where a dead network must degrade to a message. + /// The native cache is refreshed even when the sync could not run, so a + /// day marked offline still stands the phone down. + Future sync(FreeDayPool pool) async { + final RemoteStore? client; + try { + client = await _openClient(); + } on Object catch (error, stackTrace) { + developer.log( + 'free-day sync: could not open Firebase', + name: 'FreeDaySync', + error: error, + stackTrace: stackTrace, + ); + await publishToNative(pool); + return 'Error: $error'; + } + if (client == null) { + await publishToNative(pool); + return 'Not synced — connect Firebase in Settings.'; + } + try { + final merged = await syncLog( + client: client, + deviceId: pool.deviceId, + pathPrefix: FreeDayPool.pathPrefix, + filename: FreeDayPool.filename, + localLog: pool.snapshot(), + encode: logToJson, + decode: logFromJson, + commitMessage: 'freedays: update pool', + ); + await pool.replaceAll(merged); + return 'Synced ✓'; + } on Exception catch (e) { + return 'Error: $e'; + } finally { + await publishToNative(pool); + } + } + + /// Writes the pool's free dates where `AlarmReceiver` can read them. + /// + /// Swallows a missing platform (widget tests, a probe entry point): the + /// Dart pool is still correct, and the cache is rewritten on the next + /// launch anyway. + Future publishToNative(FreeDayPool pool) async { + try { + await _scheduler.setFreeDays(pool.freeIsoDates()); + } on Object catch (error) { + developer.log( + 'free-day cache not written: $error', + name: 'FreeDaySync', + error: error, + ); + } + } +} diff --git a/phone_app/test/free_days_screen_test.dart b/phone_app/test/free_days_screen_test.dart new file mode 100644 index 0000000..44145d0 --- /dev/null +++ b/phone_app/test/free_days_screen_test.dart @@ -0,0 +1,161 @@ +import 'dart:io'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/screens/free_days_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; +import 'package:wake_alarm_sync/services/free_day_sync.dart'; +import 'package:wake_alarm_sync/ui/theme.dart'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +final _today = DateTime(2026, 9, 11); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late AlarmScheduler scheduler; + late FreeDayPool pool; + late int syncs; + + setUp(() async { + const channel = MethodChannel(AlarmScheduler.channelName); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async => null); + scheduler = AlarmScheduler(channel: channel); + pool = await FreeDayPool.open( + persistence: _MemPersistence(), + deviceId: 'phone', + ); + syncs = 0; + }); + + Widget app() => MaterialApp( + theme: buildAppTheme(), + home: FreeDaysScreen( + openPool: () async => pool, + syncer: FreeDaySync( + openClient: () async { + syncs++; + return null; + }, + scheduler: scheduler, + ), + now: () => _today, + ), + ); + + testWidgets('shows the budget, syncs on open, and lists booked days', ( + tester, + ) async { + await pool.mark(DateTime(2026, 9, 20), reason: 'travelling', now: _today); + // A past free day is not "booked ahead". + await pool.mark(DateTime(2026, 9, 10), now: DateTime(2026, 9, 10)); + await tester.pumpWidget(app()); + await tester.pumpAndSettle(); + + expect(syncs, 1); + expect(find.text('33 of 35'), findsOneWidget); + expect(find.text('free days left in 2026'), findsOneWidget); + expect(find.text('Sun 2026-09-20'), findsOneWidget); + expect(find.text('travelling'), findsOneWidget); + expect(find.textContaining('2026-09-10'), findsNothing); + expect( + find.text('Not synced — connect Firebase in Settings.'), + findsOneWidget, + ); + }); + + testWidgets('release gives a future day back and re-syncs', (tester) async { + await pool.mark(DateTime(2026, 9, 20), now: _today); + await tester.pumpWidget(app()); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Release')); + await tester.pumpAndSettle(); + + expect(pool.isFree(DateTime(2026, 9, 20)), isFalse); + expect(find.text('35 of 35'), findsOneWidget); + expect(find.textContaining('Tap "Take a day"'), findsOneWidget); + expect(syncs, 2); + }); + + testWidgets('take a day walks the date picker and the reason dialog', ( + tester, + ) async { + await tester.pumpWidget(app()); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Take a day')); + await tester.pumpAndSettle(); + expect(find.text('Take a free day'), findsOneWidget); + // Tomorrow, in the calendar grid of the current month. + await tester.tap(find.text('12')); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + + expect(find.text('Reason (optional)'), findsOneWidget); + await tester.enterText(find.byType(TextField), 'dentist'); + await tester.tap(find.text('Mark free')); + await tester.pumpAndSettle(); + + expect(pool.isFree(DateTime(2026, 9, 12)), isTrue); + expect(pool.reasonFor(DateTime(2026, 9, 12)), 'dentist'); + expect(find.text('34 of 35'), findsOneWidget); + expect(find.text('Sat 2026-09-12'), findsOneWidget); + expect(syncs, 2); + }); + + testWidgets('a refused edit shows the reason and does not sync', ( + tester, + ) async { + // Exhaust the year first. + for (var i = 0; i < FreeDayPool.annualBudget; i++) { + await pool.mark(DateTime(2026, 10, 1 + i), now: _today); + } + await tester.pumpWidget(app()); + await tester.pumpAndSettle(); + expect(find.text('0 of 35'), findsOneWidget); + + await tester.tap(find.text('Take a day')); + await tester.pumpAndSettle(); + await tester.tap(find.text('12')); + await tester.tap(find.text('OK')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Mark free')); + await tester.pumpAndSettle(); + + expect(find.textContaining('No free days left in 2026'), findsOneWidget); + expect(syncs, 1); + }); + + testWidgets('a pool that cannot open reports it', (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: buildAppTheme(), + home: FreeDaysScreen( + openPool: () async => throw const FileSystemException('ro'), + syncer: FreeDaySync( + openClient: () async => null, + scheduler: scheduler, + ), + now: () => _today, + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('Error: pool unavailable'), findsOneWidget); + expect(find.text('Take a day'), findsNothing); + }); +} diff --git a/phone_app/test/services/free_day_pool_test.dart b/phone_app/test/services/free_day_pool_test.dart new file mode 100644 index 0000000..a4d3988 --- /dev/null +++ b/phone_app/test/services/free_day_pool_test.dart @@ -0,0 +1,221 @@ +import 'dart:convert'; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +final _today = DateTime(2026, 9, 11); +final _tomorrow = DateTime(2026, 9, 12); +final _yesterday = DateTime(2026, 9, 10); + +Future _open([_MemPersistence? persistence]) => FreeDayPool.open( + persistence: persistence ?? _MemPersistence(), + deviceId: 'phone-test', +); + +void main() { + group('dates', () { + test('toIso pads and parseIso round-trips', () { + expect(FreeDayPool.toIso(DateTime(2026, 1, 5)), '2026-01-05'); + expect(FreeDayPool.parseIso('2026-01-05'), DateTime(2026, 1, 5)); + }); + + test('parseIso rejects junk and impossible dates', () { + expect(FreeDayPool.parseIso('alarm'), isNull); + expect(FreeDayPool.parseIso('2026-02-30'), isNull); + expect(FreeDayPool.parseIso('2026-9-1'), isNull); + }); + + test('dateOnly drops the time of day and today() is local', () { + expect( + FreeDayPool.dateOnly(DateTime(2026, 9, 11, 23, 59)), + DateTime(2026, 9, 11), + ); + expect(FreeDayPool.today().hour, 0); + }); + }); + + group('mark', () { + test('a future day becomes free and is not consumed', () async { + final pool = await _open(); + await pool.mark(_tomorrow, reason: 'travelling', now: _today); + expect(pool.isFree(_tomorrow), isTrue); + expect(pool.reasonFor(_tomorrow), 'travelling'); + expect(pool.freeIsoDates(), ['2026-09-12']); + expect(pool.spent(2026), 1); + expect(pool.remaining(2026), FreeDayPool.annualBudget - 1); + }); + + test('today is allowed and immediately consumed', () async { + final pool = await _open(); + await pool.mark(_today, now: _today); + expect(pool.isFree(_today), isTrue); + await pool.release(_today, now: _today); + expect(pool.isFree(_today), isFalse); + // Those hours were already unguarded: no refund. + expect(pool.spent(2026), 1); + }); + + test('the time of day on the picked date is ignored', () async { + final pool = await _open(); + await pool.mark(DateTime(2026, 9, 12, 15, 30), now: _today); + expect(pool.isFree(_tomorrow), isTrue); + }); + + test('a past day is refused', () async { + final pool = await _open(); + await expectLater( + pool.mark(_yesterday, now: _today), + throwsA( + isA().having( + (e) => e.toString(), + 'message', + contains('already passed'), + ), + ), + ); + expect(pool.freeDays(), isEmpty); + }); + + test('an already-free day is refused', () async { + final pool = await _open(); + await pool.mark(_tomorrow, now: _today); + await expectLater( + pool.mark(_tomorrow, now: _today), + throwsA(isA()), + ); + }); + + test('the budget is per calendar year and refuses the 36th', () async { + final pool = await _open(); + for (var i = 0; i < FreeDayPool.annualBudget; i++) { + await pool.mark(DateTime(2026, 10, 1 + i), now: _today); + } + expect(pool.remaining(2026), 0); + await expectLater( + pool.mark(DateTime(2026, 12, 24), now: _today), + throwsA(isA()), + ); + // Next year is a fresh pool. + await pool.mark(DateTime(2027, 1, 2), now: _today); + expect(pool.remaining(2027), FreeDayPool.annualBudget - 1); + }); + }); + + group('release', () { + test('a future day is refunded', () async { + final pool = await _open(); + await pool.mark(_tomorrow, now: _today); + await pool.release(_tomorrow, now: _today); + expect(pool.isFree(_tomorrow), isFalse); + expect(pool.spent(2026), 0); + // And can be marked again: a flip, not a tombstone. + await pool.mark(_tomorrow, now: _today); + expect(pool.isFree(_tomorrow), isTrue); + }); + + test('a day that is not free is refused', () async { + final pool = await _open(); + await expectLater( + pool.release(_tomorrow, now: _today), + throwsA(isA()), + ); + }); + + test('consumed is sticky across a release and re-mark', () async { + final pool = await _open(); + await pool.mark(_tomorrow, now: _today); + // The day arrives, then is released after the fact. + await pool.release(_tomorrow, now: _tomorrow); + expect(pool.spent(2026), 1); + // Re-marking a later day does not resurrect the refund either. + await pool.mark(DateTime(2026, 9, 20), now: _tomorrow); + expect(pool.spent(2026), 2); + }); + }); + + group('storage', () { + test("records use the Python package's exact shape", () async { + final persistence = _MemPersistence(); + final pool = await _open(persistence); + await pool.mark(_tomorrow, reason: 'r', now: _today); + final json = jsonDecode(persistence.text!) as Map; + final record = json['2026-09-12'] as Map; + final fields = record['fields'] as Map; + expect( + fields.keys, + containsAll(['state', 'consumed', 'actor', 'reason']), + ); + expect((fields['state'] as List).first, 'free'); + expect((fields['consumed'] as List).first, false); + expect((fields['actor'] as List).first, 'phone-test'); + expect(record['deleted'], false); + // Every field shares one clock tick. + final ticks = fields.values.map((v) => (v as List)[1]).toSet(); + expect(ticks, hasLength(1)); + }); + + test('a tombstoned or malformed record reads as not free', () async { + final persistence = _MemPersistence(); + final hlc = Hlc.newTick('other').toStr(); + persistence.text = jsonEncode({ + '2026-09-12': { + 'id': '2026-09-12', + 'fields': { + 'state': ['free', hlc], + }, + 'deleted': true, + 'deleted_hlc': hlc, + }, + '2026-09-13': { + 'id': '2026-09-13', + 'fields': { + 'state': [7, hlc], + }, + 'deleted': false, + 'deleted_hlc': null, + }, + 'not-a-date': { + 'id': 'not-a-date', + 'fields': { + 'state': ['free', hlc], + }, + 'deleted': false, + 'deleted_hlc': null, + }, + }); + final pool = await _open(persistence); + expect(pool.isFree(_tomorrow), isFalse); + expect(pool.isFree(DateTime(2026, 9, 13)), isFalse); + expect(pool.freeDays(), isEmpty); + expect(pool.spent(2026), 0); + expect(pool.reasonFor(_tomorrow), ''); + }); + + test('remaining clamps at zero after a merge over budget', () async { + final pool = await _open(); + final peer = {}; + final hlc = Hlc.newTick('peer'); + for (var i = 0; i < FreeDayPool.annualBudget + 3; i++) { + final id = FreeDayPool.toIso(DateTime(2026, 1, 1 + i)); + peer[id] = Record( + id: id, + fields: {'state': ('free', hlc), 'consumed': (true, hlc)}, + ); + } + await pool.replaceAll(peer); + expect(pool.snapshot(), hasLength(FreeDayPool.annualBudget + 3)); + expect(pool.remaining(2026), 0); + }); + }); +} diff --git a/phone_app/test/services/free_day_sync_test.dart b/phone_app/test/services/free_day_sync_test.dart new file mode 100644 index 0000000..a368bd9 --- /dev/null +++ b/phone_app/test/services/free_day_sync_test.dart @@ -0,0 +1,180 @@ +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/free_day_pool.dart'; +import 'package:wake_alarm_sync/services/free_day_sync.dart'; + +class _MemPersistence implements LogPersistence { + String? text; + + @override + Future read() async => text; + + @override + Future write(String value) async => text = value; +} + +/// An in-memory `RemoteStore`: a flat path -> text map. +class _MemRemote implements RemoteStore { + final Map files = {}; + + @override + Future> listDirectory(String path) async { + final prefix = '$path/'; + return files.keys + .where((k) => k.startsWith(prefix)) + .map((k) => k.substring(prefix.length).split('/').first) + .toSet() + .toList(); + } + + @override + Future getFileText(String path) async => files[path]; + + @override + Future putFileText( + String path, + String text, { + required String message, + }) async => files[path] = text; + + @override + Future deleteFile(String path, {String? message}) async => + files.remove(path); + + @override + Future canAccessRemote() async => true; + + @override + void close() {} +} + +class _Broken implements RemoteStore { + @override + Future> listDirectory(String path) async => + throw RemoteSyncError('offline'); + + @override + Future getFileText(String path) async => + throw RemoteSyncError('offline'); + + @override + Future putFileText( + String path, + String text, { + required String message, + }) async => throw RemoteSyncError('offline'); + + @override + Future deleteFile(String path, {String? message}) async {} + + @override + Future canAccessRemote() async => false; + + @override + void close() {} +} + +final _today = DateTime(2026, 9, 11); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late List calls; + late AlarmScheduler scheduler; + var channelThrows = false; + + setUp(() { + calls = []; + channelThrows = false; + const channel = MethodChannel(AlarmScheduler.channelName); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + if (channelThrows) throw PlatformException(code: 'no_platform'); + return null; + }); + scheduler = AlarmScheduler(channel: channel); + }); + + Future openPool() => + FreeDayPool.open(persistence: _MemPersistence(), deviceId: 'phone'); + + List lastCache() => + ((calls.last.arguments as Map)['dates'] as List).cast(); + + test("pushes the local pool and pulls a peer's day into it", () async { + final remote = _MemRemote(); + // The PC marked a day, under its own device directory. + final pcHlc = Hlc.newTick('pc'); + remote.files['${FreeDayPool.pathPrefix}/pc/${FreeDayPool.filename}'] = + logToJson({ + '2026-09-20': Record( + id: '2026-09-20', + fields: {'state': ('free', pcHlc), 'consumed': (false, pcHlc)}, + ), + }); + final pool = await openPool(); + await pool.mark(DateTime(2026, 9, 12), now: _today); + + final sync = FreeDaySync( + openClient: () async => remote, + scheduler: scheduler, + ); + expect(await sync.sync(pool), 'Synced ✓'); + + expect(pool.isFree(DateTime(2026, 9, 20)), isTrue, reason: 'pulled'); + final pushed = + remote.files['${FreeDayPool.pathPrefix}/phone/${FreeDayPool.filename}']; + expect(pushed, contains('2026-09-12'), reason: 'pushed'); + expect(calls.last.method, 'setFreeDays'); + expect(lastCache(), ['2026-09-12', '2026-09-20']); + }); + + test( + 'a device not connected to Firebase still refreshes the cache', + () async { + final pool = await openPool(); + await pool.mark(DateTime(2026, 9, 12), now: _today); + final sync = FreeDaySync( + openClient: () async => null, + scheduler: scheduler, + ); + expect(await sync.sync(pool), contains('connect Firebase')); + expect(lastCache(), ['2026-09-12']); + }, + ); + + test('an unreachable remote reports an error and keeps the cache', () async { + final pool = await openPool(); + await pool.mark(DateTime(2026, 9, 12), now: _today); + final sync = FreeDaySync( + openClient: () async => _Broken(), + scheduler: scheduler, + ); + expect(await sync.sync(pool), startsWith('Error:')); + expect(pool.isFree(DateTime(2026, 9, 12)), isTrue); + expect(lastCache(), ['2026-09-12']); + }); + + test('a client factory that throws is reported, not propagated', () async { + final pool = await openPool(); + final sync = FreeDaySync( + openClient: () async => throw StateError('keystore locked'), + scheduler: scheduler, + ); + expect(await sync.sync(pool), contains('keystore locked')); + expect(calls.last.method, 'setFreeDays'); + }); + + test('a missing platform channel does not fail the sync', () async { + channelThrows = true; + final pool = await openPool(); + final sync = FreeDaySync( + openClient: () async => _MemRemote(), + scheduler: scheduler, + ); + expect(await sync.sync(pool), 'Synced ✓'); + }); +}