mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-26 20:57:13 +01:00
The PC has been firing the morning routine at 07:00 instead of 08:00, off a
record the phone published on 2026-08-09 and never superseded. The phone was
connected to Firebase the whole time and the home screen still said "Connect a
sync backend in Settings first."
initState fired three futures concurrently and the last one read what the
first two were still writing:
unawaited(_applyPolicy()); // sets _hour/_minute
unawaited(_loadSyncState()); // sets _service
unawaited(_syncToPc()); // reads BOTH
`publish` takes the service as a *parameter*, so it captured `_service` by
value while it was still null. Assigning it moments later could never reach
the call. The startup publish therefore passed null every time and bailed out
before touching the network -- and `_syncToPc` had exactly one call site, that
one, so nothing published, ever. `_applyPolicy` has the same shape: a publish
that did win the race would have sent the baseline instead of an active
override. The bootstrap is now strictly sequential.
Three things conspired to hide it for three weeks:
- `publish` returned "Connect a sync backend in Settings first." for BOTH a
missing backend and a null service, so a broken store looked like a setup
step the user had never done. The advice pointed at something that was not
broken. The two causes now report differently, with a regression test.
- `_loadSyncState` swallowed its exception with `on Exception catch (_)`, so
if the store genuinely failed to open there was no trace anywhere. It logs
now.
- `_pickEarlier` never published at all, so "Wake me earlier tomorrow" -- the
one schedule edit the app offers -- never reached the PC either. It does now.
home_screen.dart went over the 250-line cap, so its body moves to
`screens/home_body.dart` as a stateless widget taking plain values. The screen
keeps the state and the ordering rules, which is where the bugs lived.
Verified on the Pixel 6a: home screen now reads "Synced to PC ✓", and the PC's
`_sync --show --no-cache` returns `08:00 (remote)` stamped seconds earlier,
against `07:00` from 2026-08-09 before. The phone had also minted a new device
id, so both records exist in Firebase and the HLC ranking picks the newer --
which is exactly why that reader ranks by HLC and not by listing order.
104 Dart tests pass; analyzer clean.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PcdngP688mW6rJye3LRkSN
208 lines
7.3 KiB
Dart
208 lines
7.3 KiB
Dart
import 'dart:async';
|
|
import 'dart:developer' as developer;
|
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'package:wake_alarm_sync/screens/home_body.dart';
|
|
import 'package:wake_alarm_sync/screens/settings_screen.dart';
|
|
import 'package:wake_alarm_sync/services/alarm_policy.dart';
|
|
import 'package:wake_alarm_sync/services/alarm_publisher.dart';
|
|
import 'package:wake_alarm_sync/services/alarm_scheduler.dart';
|
|
import 'package:wake_alarm_sync/services/alarm_sync_service.dart';
|
|
import 'package:wake_alarm_sync/services/firebase_backend.dart';
|
|
import 'package:wake_alarm_sync/services/sync_settings.dart';
|
|
|
|
/// Main screen: displays the current alarm time and syncs it to the PC via
|
|
/// the shared crdt_sync transport.
|
|
class HomeScreen extends StatefulWidget {
|
|
/// Creates a [HomeScreen].
|
|
const HomeScreen({super.key});
|
|
|
|
@override
|
|
State<HomeScreen> createState() => _HomeScreenState();
|
|
}
|
|
|
|
class _HomeScreenState extends State<HomeScreen> {
|
|
int _hour = AlarmPolicy.baselineHour;
|
|
int _minute = AlarmPolicy.baselineMinute;
|
|
|
|
/// True while a one-shot earlier start is in force for the next alarm.
|
|
bool _isOverridden = false;
|
|
bool _busy = false;
|
|
String _status = '';
|
|
bool _configured = false;
|
|
AlarmSyncService? _service;
|
|
|
|
/// Platform bridge that arms the app's own alarm (item 1).
|
|
final AlarmPublisher _publisher = AlarmPublisher();
|
|
|
|
/// Platform bridge used to arm the fixed schedule.
|
|
final AlarmScheduler _scheduler = AlarmScheduler();
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// STRICTLY SEQUENTIAL. These three used to run concurrently, and the
|
|
// last one reads what the first two write: `publish` takes the service as
|
|
// a *parameter*, so it captured `_service` while it was still null and
|
|
// every startup publish returned "connect a backend" while a backend was
|
|
// connected. `_applyPolicy` has the same shape -- publishing before it
|
|
// resolves would send the baseline instead of an active override.
|
|
unawaited(_bootstrapSync());
|
|
}
|
|
|
|
/// Resolves the policy and the sync store, then publishes -- in that order.
|
|
///
|
|
/// Publishing to the PC is automatic: it used to require the same tap that
|
|
/// armed the alarm, so a forgotten tap left the PC on its fallback.
|
|
Future<void> _bootstrapSync() async {
|
|
await _applyPolicy();
|
|
await _loadSyncState();
|
|
await _syncToPc();
|
|
}
|
|
|
|
/// Opens the sync store and records whether a backend is connected.
|
|
///
|
|
/// No longer loads a *time*: the schedule is baked in and owned by
|
|
/// [AlarmPolicy], so a stored value could only disagree with it. This exists
|
|
/// to supply the store for publishing and to drive the "connect a backend"
|
|
/// hint.
|
|
Future<void> _loadSyncState() async {
|
|
final SyncSettings settings;
|
|
final AlarmSyncService service;
|
|
try {
|
|
settings = await SyncSettings.load();
|
|
service = await AlarmSyncService.open();
|
|
} on Exception catch (e, stack) {
|
|
// Storage/plugins unavailable (e.g. under a widget test, or a keystore
|
|
// hiccup): keep the on-screen defaults rather than crashing. Logged
|
|
// rather than swallowed -- silence here is what made a broken store
|
|
// look like an unconfigured backend for weeks.
|
|
developer.log(
|
|
'sync store unavailable: $e',
|
|
name: 'WakeAlarmSync',
|
|
error: e,
|
|
stackTrace: stack,
|
|
);
|
|
return;
|
|
}
|
|
// Either backend counts: a device connected only to Firebase is fully
|
|
// configured, and gating on the GitHub token alone would lock it out of
|
|
// syncing entirely once the mirror is retired.
|
|
final firebaseAccount = await loadAccount();
|
|
if (!mounted) return;
|
|
_service = service;
|
|
setState(
|
|
() => _configured = settings.isConfigured || firebaseAccount != null,
|
|
);
|
|
}
|
|
|
|
/// Lets the user move **tomorrow's** alarm earlier, never later.
|
|
///
|
|
/// This is the only schedule edit the app offers. Earlier-only is what makes
|
|
/// it tamper-proof: every change available costs the user sleep, so there is
|
|
/// no lever a half-asleep user can pull to stay in bed. A later time, a
|
|
/// skipped day and an off switch are simply not expressible.
|
|
Future<void> _pickEarlier() async {
|
|
final current = _fmt(_hour, _minute);
|
|
final picked = await showTimePicker(
|
|
context: context,
|
|
initialTime: TimeOfDay(hour: _hour, minute: _minute),
|
|
helpText: 'Earlier than $current only',
|
|
);
|
|
if (picked == null) return;
|
|
final accepted = await AlarmPolicy.setEarlier(picked.hour, picked.minute);
|
|
if (!mounted) return;
|
|
if (!accepted) {
|
|
setState(
|
|
() => _status =
|
|
'That is not earlier than $current. The alarm can only be '
|
|
'moved earlier.',
|
|
);
|
|
return;
|
|
}
|
|
await _applyPolicy();
|
|
if (!mounted) return;
|
|
setState(() => _status = 'Armed for ${_fmt(_hour, _minute)} tomorrow.');
|
|
// The PC has to learn about the new time too. Without this the only
|
|
// publish attempt was the one at startup, so an alarm moved earlier here
|
|
// never reached the PC at all.
|
|
await _syncToPc();
|
|
}
|
|
|
|
/// Re-reads the policy and arms the alarm to match it.
|
|
Future<void> _applyPolicy() async {
|
|
final policy = await AlarmPolicy.load();
|
|
await _scheduler.armSchedule(policy.hour, policy.minute);
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_hour = policy.hour;
|
|
_minute = policy.minute;
|
|
_isOverridden = policy.isOverridden;
|
|
});
|
|
}
|
|
|
|
Future<void> _syncToPc() async {
|
|
setState(() {
|
|
_busy = true;
|
|
_status = 'Syncing to PC…';
|
|
});
|
|
final message = await _publisher.publish(
|
|
service: _service,
|
|
hour: _hour,
|
|
minute: _minute,
|
|
);
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_status = message;
|
|
_busy = false;
|
|
});
|
|
}
|
|
|
|
/// The baseline time, shown when a one-shot override is active.
|
|
String get _baseline =>
|
|
_fmt(AlarmPolicy.baselineHour, AlarmPolicy.baselineMinute);
|
|
String _fmt(int h, int m) =>
|
|
'${h.toString().padLeft(2, '0')}:${m.toString().padLeft(2, '0')}';
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text('Wake Alarm Sync'),
|
|
actions: [
|
|
IconButton(
|
|
icon: Icon(
|
|
Icons.settings,
|
|
// Dimmed relative to the adjacent title text (rule 28).
|
|
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
|
),
|
|
onPressed: () async {
|
|
await Navigator.push<void>(
|
|
context,
|
|
MaterialPageRoute<void>(builder: (_) => const SettingsScreen()),
|
|
);
|
|
await _loadSyncState();
|
|
},
|
|
),
|
|
],
|
|
),
|
|
// SafeArea + scroll. This was a bare Center/Padding/Column, which
|
|
// cannot scroll, so the content simply overflowed with the black-and-
|
|
// yellow stripe pattern painted over the primary control. Two ways that
|
|
// happened: phone landscape leaves only ~360px of body height for ~405px
|
|
// of content, and the status line renders an unbounded raw
|
|
// `'Error: \$e'` with no maxLines, which overflows even in portrait.
|
|
body: HomeBody(
|
|
time: _fmt(_hour, _minute),
|
|
baseline: _baseline,
|
|
isOverridden: _isOverridden,
|
|
busy: _busy,
|
|
status: _status,
|
|
configured: _configured,
|
|
onPickEarlier: () => unawaited(_pickEarlier()),
|
|
),
|
|
);
|
|
}
|
|
}
|