mirror of
https://github.com/kuhyx/wake-alarm.git
synced 2026-11-22 17:42:18 +01:00
Name a bypass's session re-ring for its cause
A bypass during a live morning session restarted the ring natively, and the session recorded that re-ring as deadline:<leg> (C7, 2026-11-22). Bypass.record now stamps the cause (dated) when nothing was ringing; the session takes it on its tick or on the dismiss and records bypass:<cause>. A bypass during a deadline re-ring stamps nothing: one sound, one re-ring. Also a debug-only sync backend: a probe build with WAKE_SYNC_EMULATOR syncs to the PC's RTDB emulator instead of prod and the GitHub mirror, with scripts/emu_published.py reading it back for _fallback --published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1df4f64393
commit
65df7f6682
@ -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:<cause>` 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:<leg>`; 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 <file>` 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/<pkg>/` 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=<scratch with .config/crdt-sync/password>
|
||||
PYTHONUSERBASE=~/.local /usr/bin/python3 scripts/emu_published.py
|
||||
http://127.0.0.1:9000 out.json`, then `_fallback --dry-run --at <instant>
|
||||
--published out.json`.
|
||||
|
||||
## The 21:00 notifications check
|
||||
|
||||
Android lets nothing lock "All WakeAlarm notifications", and with them off
|
||||
|
||||
@ -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:<leg>`, or `bypass:<cause>` 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
|
||||
|
||||
@ -4,4 +4,5 @@
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<application android:networkSecurityConfig="@xml/network_security_config" />
|
||||
</manifest>
|
||||
|
||||
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Debug builds only: plain HTTP to the PC's Firebase RTDB emulator, which
|
||||
the AVD reaches as 10.0.2.2 (lib/services/sync_emulator.dart). Every
|
||||
other host keeps the platform default (HTTPS only). -->
|
||||
<network-security-config>
|
||||
<domain-config cleartextTrafficPermitted="true">
|
||||
<domain includeSubdomains="false">10.0.2.2</domain>
|
||||
</domain-config>
|
||||
</network-security-config>
|
||||
@ -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)
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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:<cause>` 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)
|
||||
}
|
||||
@ -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:<cause>`, 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"))
|
||||
}
|
||||
}
|
||||
@ -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<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await plantProbePassphrase();
|
||||
await RoomProofSettings.saveNfcTagAt(0, 'ring1');
|
||||
await RoomProofSettings.saveNfcTagAt(1, 'ring2');
|
||||
await SessionTagSettings.saveTagAt(SessionTagSlot.bathroom, 'bath');
|
||||
|
||||
22
phone_app/lib/probe/probe_passphrase.dart
Normal file
22
phone_app/lib/probe/probe_passphrase.dart
Normal file
@ -0,0 +1,22 @@
|
||||
// phone-slot: not-shared-storage (path is per-package: Android/data/<package>/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<void> 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();
|
||||
}
|
||||
@ -176,7 +176,7 @@ class _SessionScreenState extends State<SessionScreen> {
|
||||
// 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;
|
||||
|
||||
@ -207,6 +207,11 @@ class AlarmScheduler {
|
||||
Future<bool> isRinging() async =>
|
||||
await _channel.invokeMethod<bool>('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<String?> takeBypassReRing() =>
|
||||
_channel.invokeMethod<String>('takeBypassReRing');
|
||||
|
||||
/// Raw presence observations: `ssid`, `bssid`, `lat`, `lon`, `accuracy`,
|
||||
/// `distanceMeters`, `reason`.
|
||||
///
|
||||
|
||||
@ -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<FirebaseAccount?> loadAccount() async {
|
||||
if (syncEmulatorOn) return emulatorAccount;
|
||||
try {
|
||||
return FirebaseAccount.tryParse(
|
||||
await _secure.read(key: kFirebaseAccountKey),
|
||||
@ -82,6 +84,7 @@ Future<void> 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<FirebaseRestClient?> 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<FirebaseRestClient?> openFirebase() async {
|
||||
/// a working device "not connected", which is exactly how a phone that was in
|
||||
/// fact syncing looked broken.
|
||||
Future<bool> isFirebaseConfigured() async {
|
||||
if (syncEmulatorOn) return true;
|
||||
try {
|
||||
final auth = FirebaseTokenProvider(
|
||||
apiKey: kProject.apiKey,
|
||||
@ -214,6 +218,8 @@ Future<FirebaseRestClient?> _clientFromStoredSession() async {
|
||||
/// (`_fetch_firebase_alarm() or _fetch_github_alarm()`), so a phone that has
|
||||
/// not moved yet still reaches it.
|
||||
Future<RemoteStore> 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
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -34,6 +34,13 @@ Future<void> 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<String> 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) {
|
||||
|
||||
@ -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:<cause>` 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;
|
||||
|
||||
51
phone_app/lib/services/sync_emulator.dart
Normal file
51
phone_app/lib/services/sync_emulator.dart
Normal file
@ -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<String> idToken() async => 'owner';
|
||||
|
||||
@override
|
||||
Future<bool> 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,
|
||||
);
|
||||
@ -13,10 +13,12 @@ void main() {
|
||||
|
||||
final now = DateTime(2026, 9, 17, 8, 4);
|
||||
var hasNfc = true;
|
||||
String? bypassCause;
|
||||
late List<String> calls;
|
||||
|
||||
setUp(() {
|
||||
hasNfc = true;
|
||||
bypassCause = null;
|
||||
calls = <String>[];
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
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: <String>['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, <String>['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(
|
||||
|
||||
@ -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, <String>['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, <String>['deadline:bathroomIn']);
|
||||
});
|
||||
|
||||
test('a miss with no re-rings left fails the session', () {
|
||||
final s = fresh()..reRings = MorningSession.maxReRings;
|
||||
expect(s.nextDeadline(), isNull);
|
||||
|
||||
36
phone_app/test/services/sync_emulator_test.dart
Normal file
36
phone_app/test/services/sync_emulator_test.dart
Normal file
@ -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 = <Uri>[];
|
||||
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');
|
||||
});
|
||||
}
|
||||
67
phone_app/test/session_screen_bypass_test.dart
Normal file
67
phone_app/test/session_screen_bypass_test.dart
Normal file
@ -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<String> calls;
|
||||
|
||||
setUp(() async {
|
||||
calls = <String>[];
|
||||
bypassCause = null;
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
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(<String>['bath', 'ward', 'desk'], '');
|
||||
});
|
||||
|
||||
Future<String?> ringReasonAfterOneTick(WidgetTester tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/': (_) =>
|
||||
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');
|
||||
});
|
||||
}
|
||||
59
scripts/emu_published.py
Normal file
59
scripts/emu_published.py
Normal file
@ -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())
|
||||
Loading…
Reference in New Issue
Block a user