diff --git a/DOCS-bypass.md b/DOCS-bypass.md index 2fb5a7d..a126512 100644 --- a/DOCS-bypass.md +++ b/DOCS-bypass.md @@ -68,7 +68,14 @@ a minute is recorded once (both activities run the launch check). Owner) still lands. - **The phone rings again** (`Bypass.ringAgain`). During a session it is a re-ring: only the full dismiss sequence silences it and `re_rings` goes up - by one when it does (`SessionHandoff.afterDismiss`). + by one when it does (`SessionHandoff.afterDismiss`). It is recorded as + `bypass:` in `re_ring_reasons` (`bypass:fsi_revoked`, + `bypass:suspended`, ...): `Bypass.record` stamps the cause + (`BypassReRing`, dated) before it restarts the ring, and the session takes + it once over `takeBypassReRing`, on the screen's tick or on the dismiss. A + bypass while a deadline re-ring already sounds stamps nothing: one sound, + one re-ring, reason `deadline:`; the `bypass` event, its publish and + the lockdown still happen. - **The PC rings** (`_fallback_policy`, reason `bypass`). The phone pushes the event at once through the headless `publishNowMain` engine. The PC rings from the bypass for up to 30 min (`FALLBACK_RING_CAP` from the @@ -81,6 +88,25 @@ a minute is recorded once (both activities run the launch check). --published ` reads the phone's logs from a JSON list of `[device_id, alarm.json]` pairs instead of Firebase (`_published_file`). +## Testing against a backend: the RTDB emulator + +The AVD never signs in to prod. A probe build with +`--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` syncs to the +Firebase RTDB emulator on the PC instead of prod Firebase *and* the GitHub +mirror (`sync_emulator.dart`; plain HTTP is allowed to `10.0.2.2` in the +debug manifest only). Release builds never set the define. + +1. `systemd-run --user --collect --unit=wa-rtdb-emu /usr/bin/java -jar + ~/.cache/firebase/emulators/firebase-database-emulator-v4.11.2.jar --host + 127.0.0.1 --port 9000` (one default namespace; `auth=owner` is admin). +2. Write a dummy passphrase to `files/passphrase` under the app's + `Android/data//` dir; the probe moves it into the keystore on launch + (`probe_passphrase.dart`). Without one every push is `sync locked`. +3. After the bypass: `HOME= + PYTHONUSERBASE=~/.local /usr/bin/python3 scripts/emu_published.py + http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at + --published out.json`. + ## The 21:00 notifications check Android lets nothing lock "All WakeAlarm notifications", and with them off diff --git a/DOCS-morning-session.md b/DOCS-morning-session.md index 7da13d2..e4e23a3 100644 --- a/DOCS-morning-session.md +++ b/DOCS-morning-session.md @@ -61,7 +61,9 @@ the first leg by itself — there is nothing to walk to. of recreating it. - **Silencing a re-ring is the full dismiss sequence**: tag 1, the walk, tag 2, three questions. The ring screen's `_finishDismiss` sees a live - session for today and resumes it with `reRings + 1`. + session for today and resumes it with `reRings + 1`. `re_ring_reasons` + says why: `deadline:`, or `bypass:` when a bypass restarted + the ring (`DOCS-bypass.md`). - **A silent buzz 3 min before each deadline** (`SessionWarn.kt`, request code 1004), armed and cleared only with the re-ring. - **One re-ring per leg.** After a deadline re-ring is dismissed the leg is diff --git a/phone_app/android/app/src/debug/AndroidManifest.xml b/phone_app/android/app/src/debug/AndroidManifest.xml index 399f698..83d4e12 100644 --- a/phone_app/android/app/src/debug/AndroidManifest.xml +++ b/phone_app/android/app/src/debug/AndroidManifest.xml @@ -4,4 +4,5 @@ to allow setting breakpoints, to provide hot reload, etc. --> + diff --git a/phone_app/android/app/src/debug/res/xml/network_security_config.xml b/phone_app/android/app/src/debug/res/xml/network_security_config.xml new file mode 100644 index 0000000..2bce270 --- /dev/null +++ b/phone_app/android/app/src/debug/res/xml/network_security_config.xml @@ -0,0 +1,9 @@ + + + + + 10.0.2.2 + + 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 3aa04e6..fef8be7 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 @@ -145,6 +145,7 @@ object AlarmChannel { // a deadline that rang while it sat in the background puts the // dismiss sequence in front the moment it is looked at. "isRinging" -> result.success(AlarmService.running) + "takeBypassReRing" -> result.success(BypassReRing.take(context)) "beginStepCount" -> { StepCounter.markRingStart(context) result.success(null) diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/Bypass.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/Bypass.kt index 1101fe5..a6a32f5 100644 --- a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/Bypass.kt +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/Bypass.kt @@ -28,6 +28,21 @@ object BypassRules { /** Today's ring fired, was never dismissed, and nothing is ringing now. */ fun ringKilled(firedToday: Boolean, dismissedToday: Boolean, ringing: Boolean): Boolean = firedToday && !dismissedToday && !ringing + + /** + * Whether this bypass's ring is a new session re-ring to name for it. + * One already sounding (a leg's deadline) stays that re-ring: one sound, + * one re-ring, its reason the one that started it. + */ + fun stampReRing(sessionLive: Boolean, ringing: Boolean): Boolean = sessionLive && !ringing + + fun encodeStamp(cause: String, date: String): String = "$date|$cause" + + /** The cause in [stored] if it was stamped on [today]; a stale one is dropped. */ + fun takeStamp(stored: String?, today: String): String? { + val parts = stored?.split("|", limit = 2) ?: return null + return if (parts.size == 2 && parts[0] == today) parts[1] else null + } } /** @@ -75,6 +90,9 @@ object Bypass { ) if (cause == BypassCause.SUSPENDED) WorkdayStick.sendUnsuspend(context) StickRunner.run(context, "bypass") + if (BypassRules.stampReRing(sessionLive, AlarmService.running)) { + BypassReRing.stamp(context, cause.wire, today.toString()) + } ringAgain(context) HeadlessRingStart.start(context, HeadlessRingStart.PUBLISH_ENTRYPOINT) return true diff --git a/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BypassReRing.kt b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BypassReRing.kt new file mode 100644 index 0000000..42f9f4f --- /dev/null +++ b/phone_app/android/app/src/main/kotlin/com/kuhy/wake_alarm_sync/BypassReRing.kt @@ -0,0 +1,30 @@ +package com.kuhy.wake_alarm_sync + +import android.content.Context +import java.time.LocalDate + +/** + * The cause of a bypass that restarted the ring during a live morning + * session, handed to Dart once (`takeBypassReRing`) so the session records + * that re-ring as `bypass:` rather than the leg's deadline. + * + * Dated, so a session that ends without a dismiss cannot leak it into + * tomorrow's first re-ring. + */ +object BypassReRing { + private const val PREFS = "wake_alarm_bypass_rering" + private const val KEY = "stamp" + + fun stamp(context: Context, cause: String, date: String) { + prefs(context).edit().putString(KEY, BypassRules.encodeStamp(cause, date)).commit() + } + + fun take(context: Context): String? { + val stored = prefs(context).getString(KEY, null) ?: return null + prefs(context).edit().remove(KEY).commit() + return BypassRules.takeStamp(stored, LocalDate.now().toString()) + } + + private fun prefs(context: Context) = + context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) +} diff --git a/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/BypassReRingTest.kt b/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/BypassReRingTest.kt new file mode 100644 index 0000000..e6118f7 --- /dev/null +++ b/phone_app/android/app/src/test/kotlin/com/kuhy/wake_alarm_sync/BypassReRingTest.kt @@ -0,0 +1,37 @@ +package com.kuhy.wake_alarm_sync + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A bypass during a live morning session re-rings it, and that re-ring is + * recorded as `bypass:`, not as the leg's deadline (2026-11-22). + */ +class BypassReRingTest { + @Test + fun `a bypass with the session live and nothing ringing stamps its re-ring`() { + assertTrue(BypassRules.stampReRing(sessionLive = true, ringing = false)) + } + + @Test + fun `a bypass while a deadline re-ring sounds keeps that one`() { + assertFalse(BypassRules.stampReRing(sessionLive = true, ringing = true)) + } + + @Test + fun `a bypass of the first ring is not a session re-ring`() { + assertFalse(BypassRules.stampReRing(sessionLive = false, ringing = false)) + } + + @Test + fun `a stamp is taken only on its own day`() { + val stamp = BypassRules.encodeStamp("fsi_revoked", "2026-11-22") + assertEquals("fsi_revoked", BypassRules.takeStamp(stamp, "2026-11-22")) + assertNull(BypassRules.takeStamp(stamp, "2026-11-23")) + assertNull(BypassRules.takeStamp(null, "2026-11-22")) + assertNull(BypassRules.takeStamp("garbage", "2026-11-22")) + } +} diff --git a/phone_app/lib/main_session_probe.dart b/phone_app/lib/main_session_probe.dart index a7464f7..9054aed 100644 --- a/phone_app/lib/main_session_probe.dart +++ b/phone_app/lib/main_session_probe.dart @@ -2,6 +2,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:wake_alarm_sync/main.dart'; import 'package:wake_alarm_sync/probe/file_driven_scheduler.dart'; +import 'package:wake_alarm_sync/probe/probe_passphrase.dart'; import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; import 'package:wake_alarm_sync/services/room_proof_settings.dart'; import 'package:wake_alarm_sync/services/session_tag_settings.dart'; @@ -24,6 +25,7 @@ import 'package:wake_alarm_sync/services/session_tag_settings.dart'; /// Not part of the shipped app: `flutter build apk` uses `lib/main.dart`. Future main() async { WidgetsFlutterBinding.ensureInitialized(); + await plantProbePassphrase(); await RoomProofSettings.saveNfcTagAt(0, 'ring1'); await RoomProofSettings.saveNfcTagAt(1, 'ring2'); await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath'); diff --git a/phone_app/lib/probe/probe_passphrase.dart b/phone_app/lib/probe/probe_passphrase.dart new file mode 100644 index 0000000..cca392a --- /dev/null +++ b/phone_app/lib/probe/probe_passphrase.dart @@ -0,0 +1,22 @@ +// phone-slot: not-shared-storage (path is per-package: Android/data//files) +import 'dart:io'; + +import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +/// Moves an adb-written `files/passphrase` into the keystore, then deletes it. +/// +/// The emulator syncs to the PC's RTDB emulator (`sync_emulator.dart`), and +/// every push is end-to-end encrypted: with no passphrase in the keystore it +/// throws `SyncLockedException` and nothing is published. The live checks +/// give the AVD a dummy test passphrase this way, never the real one, and +/// the file does not outlive the first launch. Probe-only. +Future plantProbePassphrase() async { + final dir = await getExternalStorageDirectory(); + if (dir == null) return; + final file = File(p.join(dir.path, 'passphrase')); + if (!file.existsSync()) return; + await saveE2ePassphrase((await file.readAsString()).trim()); + await file.delete(); +} diff --git a/phone_app/lib/screens/session_screen.dart b/phone_app/lib/screens/session_screen.dart index d28d8fb..d64c48e 100644 --- a/phone_app/lib/screens/session_screen.dart +++ b/phone_app/lib/screens/session_screen.dart @@ -176,7 +176,7 @@ class _SessionScreenState extends State { // The native deadline already rang (see [AlarmScheduler.isRinging]): // the dismiss sequence belongs in front now, not after the 20 s grace. if (session.isActive && await _scheduler.isRinging()) { - await _ring('deadline:${session.currentLeg!.name}', now); + await _ring(await nativeRingReason(_scheduler, session), now); return; } if (!mounted) return; diff --git a/phone_app/lib/services/alarm_scheduler.dart b/phone_app/lib/services/alarm_scheduler.dart index 42efb06..6f9c438 100644 --- a/phone_app/lib/services/alarm_scheduler.dart +++ b/phone_app/lib/services/alarm_scheduler.dart @@ -207,6 +207,11 @@ class AlarmScheduler { Future isRinging() async => await _channel.invokeMethod('isRinging') ?? false; + /// The cause of a bypass that started today's ring during a live session, + /// or null; taking it clears it, so one bypass names one re-ring. + Future takeBypassReRing() => + _channel.invokeMethod('takeBypassReRing'); + /// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`, /// `distanceMeters`, `reason`. /// diff --git a/phone_app/lib/services/firebase_backend.dart b/phone_app/lib/services/firebase_backend.dart index 17c05a0..9a59e19 100644 --- a/phone_app/lib/services/firebase_backend.dart +++ b/phone_app/lib/services/firebase_backend.dart @@ -17,6 +17,7 @@ import 'package:crdt_sync/crdt_sync.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:http/http.dart' as http; import 'package:wake_alarm_sync/services/google_sign_in_backend.dart'; +import 'package:wake_alarm_sync/services/sync_emulator.dart'; /// The shared `kuhy-syncs` project. /// @@ -48,6 +49,7 @@ SecureCredentialStore credentialStore() => SecureCredentialStore( /// Reads the per-device account, or null when sync has not been set up. Future loadAccount() async { + if (syncEmulatorOn) return emulatorAccount; try { return FirebaseAccount.tryParse( await _secure.read(key: kFirebaseAccountKey), @@ -82,6 +84,7 @@ Future clearAccount() async { /// Signs in with the stored password only when there is no cached refresh /// token, so the usual path costs no authentication round trip. Future openFirebase() async { + if (syncEmulatorOn) return emulatorClient(); final account = await loadAccount(); if (account == null) { // A stored refresh token IS a signed-in device, even with no account @@ -113,6 +116,7 @@ Future openFirebase() async { /// a working device "not connected", which is exactly how a phone that was in /// fact syncing looked broken. Future isFirebaseConfigured() async { + if (syncEmulatorOn) return true; try { final auth = FirebaseTokenProvider( apiKey: kProject.apiKey, @@ -214,6 +218,8 @@ Future _clientFromStoredSession() async { /// (`_fetch_firebase_alarm() or _fetch_github_alarm()`), so a phone that has /// not moved yet still reaches it. Future syncBackend(RemoteStore github) async { + // The emulator alone: a mirror beside it would write prod GitHub. + if (syncEmulatorOn) return emulatorClient(); final firebase = await openFirebase(); return firebase == null ? github diff --git a/phone_app/lib/services/session_handoff.dart b/phone_app/lib/services/session_handoff.dart index 7195177..c90313e 100644 --- a/phone_app/lib/services/session_handoff.dart +++ b/phone_app/lib/services/session_handoff.dart @@ -54,7 +54,9 @@ class SessionHandoff { final current = await store.loadCurrent(); if (current != null && current.date == today) { if (!current.isActive) return false; - current.recordReRing(now); + current + ..adoptBypassReRing(await scheduler.takeBypassReRing()) + ..recordReRing(now); await store.save(current); return true; } diff --git a/phone_app/lib/services/session_notice.dart b/phone_app/lib/services/session_notice.dart index 8ccccfe..366c805 100644 --- a/phone_app/lib/services/session_notice.dart +++ b/phone_app/lib/services/session_notice.dart @@ -34,6 +34,13 @@ Future pointNativeAtLeg( ); } +/// Why the sound the session screen just found is ringing: the bypass +/// `Bypass.kt` stamped for it, else the live leg's deadline. +Future nativeRingReason( + AlarmScheduler scheduler, + MorningSession session, +) async => session.reRingReasonFor(await scheduler.takeBypassReRing()); + /// The notification's one line: glyph + position count, with a running-clock /// marker when the re-ring was spent. String noticeLabel(MorningSession session) { diff --git a/phone_app/lib/services/session_rules.dart b/phone_app/lib/services/session_rules.dart index 2a9ff8b..985ebf4 100644 --- a/phone_app/lib/services/session_rules.dart +++ b/phone_app/lib/services/session_rules.dart @@ -162,6 +162,18 @@ extension SessionRules on MorningSession { updatedAt = now; } + /// Names the re-ring a bypass started natively (`Bypass.kt` stamps + /// [cause] only when nothing was ringing yet), overriding a deadline mark: + /// the screen saw the sound before it saw why. Null leaves the mark. + void adoptBypassReRing(String? cause) { + if (cause != null) pendingReRingReason = reRingReasonFor(cause); + } + + /// `bypass:` for a bypass's re-ring, else the live leg's deadline. + String reRingReasonFor(String? cause) => cause == null + ? 'deadline:${currentLeg?.name ?? 'none'}' + : 'bypass:$cause'; + /// Records that a re-ring was dismissed; the session resumes here. /// /// A leg whose deadline has already passed is marked as rung whatever the @@ -170,7 +182,7 @@ extension SessionRules on MorningSession { void recordReRing(DateTime now) { final leg = currentLeg; reRings++; - reRingReasons.add(pendingReRingReason ?? 'deadline:${leg?.name ?? 'none'}'); + reRingReasons.add(pendingReRingReason ?? reRingReasonFor(null)); pendingReRingReason = null; if (leg != null && !now.isBefore(deadline(leg))) deadlineRung.add(leg); updatedAt = now; diff --git a/phone_app/lib/services/sync_emulator.dart b/phone_app/lib/services/sync_emulator.dart new file mode 100644 index 0000000..b991641 --- /dev/null +++ b/phone_app/lib/services/sync_emulator.dart @@ -0,0 +1,51 @@ +/// A debug-only sync backend: the Firebase RTDB emulator on the PC. +/// +/// The emulator checks (a bypass reaching "the test backend") need a +/// backend, and the AVD must never sign in to prod: a probe's per-date +/// merge would overwrite the phone's real morning. So the probe build +/// passes `--dart-define=WAKE_SYNC_EMULATOR=http://10.0.2.2:9000` (the AVD's +/// name for the PC's loopback), and every sync open then returns this client +/// *instead of* prod Firebase and the GitHub mirror, never beside them. +/// +/// The define is a compile-time constant: release and `deploy.sh` builds +/// never set it, so there the branch is dead code. The emulator answers +/// `auth=owner` as admin, so no Google sign-in is involved. +library; + +import 'package:crdt_sync/crdt_sync.dart'; +import 'package:http/http.dart' as http; + +/// The emulator's origin, or empty (every release build). +const String kSyncEmulatorUrl = String.fromEnvironment('WAKE_SYNC_EMULATOR'); + +/// Whether this build syncs to the emulator only. +bool get syncEmulatorOn => kSyncEmulatorUrl.isNotEmpty; + +/// The account marker the sync gates look for; carries no credential. +const FirebaseAccount emulatorAccount = FirebaseAccount( + email: 'emulator', + password: '', +); + +/// Signs every request `auth=owner`, the emulator's admin token. +class EmulatorTokenProvider extends FirebaseTokenProvider { + /// Creates a provider that never talks to Google. + EmulatorTokenProvider() + : super(apiKey: 'emulator', store: InMemoryCredentialStore()); + + @override + Future idToken() async => 'owner'; + + @override + Future hasSession() async => true; +} + +/// A client for the emulator at [url]. +FirebaseRestClient emulatorClient({ + String url = kSyncEmulatorUrl, + http.Client? httpClient, +}) => FirebaseRestClient( + databaseUrl: url, + auth: EmulatorTokenProvider(), + httpClient: httpClient, +); diff --git a/phone_app/test/services/session_handoff_test.dart b/phone_app/test/services/session_handoff_test.dart index d49ce3b..cf6c661 100644 --- a/phone_app/test/services/session_handoff_test.dart +++ b/phone_app/test/services/session_handoff_test.dart @@ -13,10 +13,12 @@ void main() { final now = DateTime(2026, 9, 17, 8, 4); var hasNfc = true; + String? bypassCause; late List calls; setUp(() { hasNfc = true; + bypassCause = null; calls = []; SharedPreferences.setMockInitialValues({}); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger @@ -24,6 +26,7 @@ void main() { const MethodChannel(AlarmScheduler.channelName), (call) async { calls.add(call.method); + if (call.method == 'takeBypassReRing') return bypassCause; return call.method == 'hasNfc' ? hasNfc : null; }, ); @@ -63,6 +66,23 @@ void main() { }, ); + test('a bypass that rang during a live session names the re-ring', () async { + final store = SessionStore(); + await store.save( + SessionRules.start( + now: now.subtract(const Duration(minutes: 2)), + tags: const SessionTagSettings(tagIds: ['b', 'w', 'd']), + nfcAvailable: true, + ), + ); + bypassCause = 'fsi_revoked'; + expect(await handoff().afterDismiss(away: false), isTrue); + final session = (await store.loadCurrent())!; + expect(session.reRings, 1); + expect(session.reRingReasons, ['bypass:fsi_revoked']); + expect(calls, contains('takeBypassReRing')); + }); + test('a dismiss during a live session is a re-ring', () async { final store = SessionStore(); await store.save( diff --git a/phone_app/test/services/session_rules_test.dart b/phone_app/test/services/session_rules_test.dart index f8b9958..567a9bf 100644 --- a/phone_app/test/services/session_rules_test.dart +++ b/phone_app/test/services/session_rules_test.dart @@ -188,6 +188,23 @@ void main() { }, ); + test('a bypass re-ring is named for its cause and counted once', () { + final s = fresh() + ..markReRing('deadline:bathroomIn', t0) + ..adoptBypassReRing('fsi_revoked') + ..recordReRing(t0.add(const Duration(minutes: 3))); + expect(s.reRings, 1); + expect(s.reRingReasons, ['bypass:fsi_revoked']); + }); + + test('no bypass stamped keeps the deadline reason', () { + final s = fresh() + ..markReRing('deadline:bathroomIn', t0) + ..adoptBypassReRing(null) + ..recordReRing(t0.add(const Duration(minutes: 3))); + expect(s.reRingReasons, ['deadline:bathroomIn']); + }); + test('a miss with no re-rings left fails the session', () { final s = fresh()..reRings = MorningSession.maxReRings; expect(s.nextDeadline(), isNull); diff --git a/phone_app/test/services/sync_emulator_test.dart b/phone_app/test/services/sync_emulator_test.dart new file mode 100644 index 0000000..806acd3 --- /dev/null +++ b/phone_app/test/services/sync_emulator_test.dart @@ -0,0 +1,36 @@ +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'; +import 'package:wake_alarm_sync/services/firebase_backend.dart'; +import 'package:wake_alarm_sync/services/sync_emulator.dart'; + +/// A [RemoteStore] that is only ever compared by identity. +class _Github extends Fake implements RemoteStore {} + +void main() { + test('a build without the define syncs to prod, never the emulator', () async { + expect(kSyncEmulatorUrl, isEmpty); + expect(syncEmulatorOn, isFalse); + expect(kProject.databaseUrl, contains('kuhy-syncs')); + final github = _Github(); + // No Firebase session in tests: prod's rollback path, GitHub alone. + expect(await syncBackend(github), same(github)); + }); + + test('the emulator client signs as owner against the given origin', () async { + final seen = []; + final client = emulatorClient( + url: 'http://10.0.2.2:9000', + httpClient: MockClient((request) async { + seen.add(request.url); + return http.Response('null', 200); + }), + ); + await client.listDirectory('wake-alarm-sync/devices-e2e'); + expect(seen.single.origin, 'http://10.0.2.2:9000'); + expect(seen.single.queryParameters['auth'], 'owner'); + expect(await EmulatorTokenProvider().hasSession(), isTrue); + expect(emulatorAccount.email, 'emulator'); + }); +} diff --git a/phone_app/test/session_screen_bypass_test.dart b/phone_app/test/session_screen_bypass_test.dart new file mode 100644 index 0000000..f0c1f29 --- /dev/null +++ b/phone_app/test/session_screen_bypass_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:wake_alarm_sync/screens/session_screen.dart'; +import 'package:wake_alarm_sync/services/alarm_scheduler.dart'; +import 'package:wake_alarm_sync/services/session_store.dart'; +import 'package:wake_alarm_sync/services/session_tag_settings.dart'; + +/// A bypass during a live session restarts the ring natively; the session +/// screen finds it sounding and must name the re-ring for the bypass, not +/// for the leg's deadline (C7's emulator run recorded `deadline:bathroomIn`). +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final now = DateTime(2026, 9, 17, 8, 4); + String? bypassCause; + late List calls; + + setUp(() async { + calls = []; + bypassCause = null; + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel(AlarmScheduler.channelName), + (call) async { + calls.add(call.method); + if (call.method == 'hasNfc') return true; + if (call.method == 'isRinging') return true; + if (call.method == 'takeBypassReRing') return bypassCause; + return null; + }, + ); + await SessionTagSettings.replaceAll(['bath', 'ward', 'desk'], ''); + }); + + Future ringReasonAfterOneTick(WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + routes: { + '/': (_) => + SessionScreen(clock: () => now, publish: () async => 'pushed'), + '/ring': (_) => const Scaffold(body: Text('RING')), + }, + ), + ); + await tester.pump(); + await tester.pump(); + await tester.pump(kSessionTick); + await tester.pumpAndSettle(); + expect(find.text('RING'), findsOneWidget); + return (await SessionStore().loadCurrent())!.pendingReRingReason; + } + + testWidgets('a ring a bypass started is named for the bypass', ( + tester, + ) async { + bypassCause = 'suspended'; + expect(await ringReasonAfterOneTick(tester), 'bypass:suspended'); + expect(calls, contains('takeBypassReRing')); + }); + + testWidgets('a ring nothing stamped is the deadline', (tester) async { + expect(await ringReasonAfterOneTick(tester), 'deadline:bathroomIn'); + }); +} diff --git a/scripts/emu_published.py b/scripts/emu_published.py new file mode 100644 index 0000000..c3239c4 --- /dev/null +++ b/scripts/emu_published.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Export what the emulator phone published to the Firebase RTDB emulator. + +The emulator live checks (a ``bypass`` reaching "the test backend") use a +probe build that syncs to the PC's RTDB emulator instead of prod +(``phone_app/lib/services/sync_emulator.dart``). This reads it back exactly +the way the PC reads prod -- ``_sync_transport._read_published``: device +discovery plus the E2E unlock -- and writes the ``[[device_id, alarm], ...]`` +list that ``python -m wake_alarm._fallback --dry-run --published`` takes. + +Run it with ``HOME`` set to a scratch directory whose +``.config/crdt-sync/password`` holds the dummy test passphrase the AVD was +given, so the real passphrase is never read, and with +``PYTHONUSERBASE=/home/kuhy/.local`` so ``crdt_sync`` still imports:: + + HOME=$SCRATCH PYTHONUSERBASE=$HOME/.local \\ + /usr/bin/python3 scripts/emu_published.py http://127.0.0.1:9000 out.json + +``crdt_sync`` is imported unguarded on purpose: the transport degrades a +missing module to "nothing published", which here would read as a failed +check instead of a broken setup. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys + +from crdt_sync import FirebaseSyncClient + +from wake_alarm._sync_transport import _read_published + + +class _OwnerToken: + """The emulator's admin token; the RTDB emulator accepts ``auth=owner``.""" + + def id_token(self) -> str: + """Every request's ``auth`` parameter.""" + return "owner" + + +def main(argv: list[str] | None = None) -> int: + """Write the emulator's published logs to the output file; 1 when empty.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("url", help="the RTDB emulator's origin") + parser.add_argument("out", type=Path, help="where to write the JSON list") + args = parser.parse_args(argv) + client = FirebaseSyncClient(args.url, _OwnerToken()) # type: ignore[arg-type] + published = _read_published(client) + pairs = [[device, json.loads(raw)] for device, raw in published] + args.out.write_text(json.dumps(pairs, indent=1), encoding="utf-8") + print(f"{len(pairs)} device(s): {' '.join(device for device, _ in pairs)}") + return 0 if pairs else 1 + + +if __name__ == "__main__": + sys.exit(main())