From e2826e7648ef03c94ed7fa341543f554688a56be Mon Sep 17 00:00:00 2001 From: MikenRafter Date: Tue, 10 Nov 2026 19:59:47 -0700 Subject: [PATCH 1/7] feat(pairing): offer only supported main bands on first run --- lib/l10n/app_de.arb | 8 +- lib/l10n/app_en.arb | 24 +++ lib/l10n/app_es.arb | 8 +- lib/l10n/app_fr.arb | 8 +- lib/l10n/app_hi.arb | 8 +- lib/l10n/app_ru.arb | 8 +- lib/l10n/app_th.arb | 26 ++- lib/l10n/app_zh.arb | 8 +- lib/ui2/pairing/device_picker.dart | 13 +- lib/ui2/pairing/pair_band_view.dart | 184 +++++++++++++++++++ test/russian_review_findings_test.dart | 6 +- test/ui2_pair_band_view_test.dart | 239 +++++++++++++++++++++++++ test/ui2_tokens_test.dart | 2 + 13 files changed, 528 insertions(+), 14 deletions(-) create mode 100644 lib/ui2/pairing/pair_band_view.dart create mode 100644 test/ui2_pair_band_view_test.dart diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 16686705b..81100a0e8 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3531,5 +3531,11 @@ "pairDeviceNamed": "{name} koppeln", "pairUseForWorkouts": "Nur fürs Training nutzen", "pairReplaceUnpairFailed": "Dein Band ließ sich nicht trennen, daher wurde das neue nicht gekoppelt. Versuche es erneut.", - "pairWearableLeadPebble": "Pebble 2 kann deine Tage mit Schlaf, Erholung und Herzfrequenz füllen. Pebble 2 SE zeigt die eigenen Schlaf- und Schrittdaten der Uhr. Sie hat keinen Herzfrequenzsensor, daher kann diese App daraus weder die tägliche Belastung berechnen noch die Erholung schätzen." + "pairWearableLeadPebble": "Pebble 2 kann deine Tage mit Schlaf, Erholung und Herzfrequenz füllen. Pebble 2 SE zeigt die eigenen Schlaf- und Schrittdaten der Uhr. Sie hat keinen Herzfrequenzsensor, daher kann diese App daraus weder die tägliche Belastung berechnen noch die Erholung schätzen.", + "pairMainBandWhoopOnly": "Hauptband: nur WHOOP 4.0 oder WHOOP 5.0/MG. Andere Geräte lassen sich als zusätzliche Geräte hinzufügen.", + "pairBandTitle": "Band koppeln", + "pairBandSubtitle": "Wähle das, das du trägst. Wir suchen es in der Nähe.", + "pairStrapOnlyLink": "Ich habe nur einen Herzfrequenzgurt", + "pairWhoopRowLine": "Schlaf, Erholung, Belastung, Herzfrequenz und mehr", + "pairSetUpTitle": "Einrichten" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 2259bcf59..db2bf2433 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -16629,5 +16629,29 @@ "pairWearableLeadPebble": "Pebble 2 can fill your days with sleep, recovery and heart rate. Pebble 2 SE shows the watch’s own sleep and steps. It has no heart-rate sensor, so this app cannot calculate daily strain or estimate recovery from it.", "@pairWearableLeadPebble": { "description": "Pebble-family pairing lead: SE shows the watch’s own sleep and steps; no HR sensor means no app-calculated daily strain or recovery estimate from the SE alone." + }, + "pairMainBandWhoopOnly": "Main band: WHOOP 4.0 or WHOOP 5.0/MG only. Other devices can be added as additional devices.", + "@pairMainBandWhoopOnly": { + "description": "Plain statement on the pairing screens: only WHOOP can be the main band; other devices are added as additional devices." + }, + "pairBandTitle": "Pair your band", + "@pairBandTitle": { + "description": "Title of the first-run list of bands." + }, + "pairBandSubtitle": "Pick the one you wear. We will look for it nearby.", + "@pairBandSubtitle": { + "description": "Subtitle of the first-run list of bands." + }, + "pairStrapOnlyLink": "I only have a heart-rate strap", + "@pairStrapOnlyLink": { + "description": "Text link under the band list for someone with only a heart-rate strap." + }, + "pairWhoopRowLine": "Sleep, recovery, strain, heart rate and more", + "@pairWhoopRowLine": { + "description": "Line under each WHOOP on the first-run list." + }, + "pairSetUpTitle": "Set up", + "@pairSetUpTitle": { + "description": "Top bar title of the first-run pairing screen." } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index bd0a3f127..fcf8d5027 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2951,5 +2951,11 @@ "pairDeviceNamed": "Emparejar {name}", "pairUseForWorkouts": "Usarla solo para entrenamientos", "pairReplaceUnpairFailed": "No se pudo desemparejar tu pulsera, así que no se emparejó la nueva. Inténtalo de nuevo.", - "pairWearableLeadPebble": "Pebble 2 puede completar tus días con sueño, recuperación y frecuencia cardiaca. Pebble 2 SE muestra el sueño y los pasos registrados por el propio reloj. No tiene sensor de frecuencia cardiaca, por lo que esta app no puede calcular la carga diaria ni estimar la recuperación a partir de sus datos." + "pairWearableLeadPebble": "Pebble 2 puede completar tus días con sueño, recuperación y frecuencia cardiaca. Pebble 2 SE muestra el sueño y los pasos registrados por el propio reloj. No tiene sensor de frecuencia cardiaca, por lo que esta app no puede calcular la carga diaria ni estimar la recuperación a partir de sus datos.", + "pairMainBandWhoopOnly": "Pulsera principal: solo WHOOP 4.0 o WHOOP 5.0/MG. Los demás dispositivos se pueden añadir como dispositivos adicionales.", + "pairBandTitle": "Empareja tu pulsera", + "pairBandSubtitle": "Elige la que llevas puesta. La buscaremos cerca.", + "pairStrapOnlyLink": "Solo tengo una banda de frecuencia cardíaca", + "pairWhoopRowLine": "Sueño, recuperación, esfuerzo, frecuencia cardiaca y más", + "pairSetUpTitle": "Configurar" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 117e8a448..589f5370e 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2922,5 +2922,11 @@ "pairDeviceNamed": "Associer {name}", "pairUseForWorkouts": "L’utiliser seulement pour les entraînements", "pairReplaceUnpairFailed": "Impossible de dissocier votre bracelet, le nouveau n’a donc pas été associé. Réessayez.", - "pairWearableLeadPebble": "Pebble 2 peut compléter vos journées avec le sommeil, la récupération et la fréquence cardiaque. Pebble 2 SE affiche le sommeil et les pas enregistrés par la montre. Elle n’a pas de capteur de fréquence cardiaque, donc cette app ne peut pas calculer la charge quotidienne ni estimer la récupération à partir de ses données." + "pairWearableLeadPebble": "Pebble 2 peut compléter vos journées avec le sommeil, la récupération et la fréquence cardiaque. Pebble 2 SE affiche le sommeil et les pas enregistrés par la montre. Elle n’a pas de capteur de fréquence cardiaque, donc cette app ne peut pas calculer la charge quotidienne ni estimer la récupération à partir de ses données.", + "pairMainBandWhoopOnly": "Bracelet principal : uniquement WHOOP 4.0 ou WHOOP 5.0/MG. Les autres appareils peuvent être ajoutés comme appareils supplémentaires.", + "pairBandTitle": "Associez votre bracelet", + "pairBandSubtitle": "Choisissez celui que vous portez. Nous le chercherons à proximité.", + "pairStrapOnlyLink": "J’ai seulement une ceinture cardiaque", + "pairWhoopRowLine": "Sommeil, récupération, effort, fréquence cardiaque et plus", + "pairSetUpTitle": "Configuration" } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index a1bebc3d1..0e7e9de0f 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -2922,5 +2922,11 @@ "pairDeviceNamed": "{name} पेयर करें", "pairUseForWorkouts": "इसे केवल वर्कआउट के लिए इस्तेमाल करें", "pairReplaceUnpairFailed": "आपका बैंड अनपेयर नहीं हो सका, इसलिए नया बैंड पेयर नहीं किया गया। फिर से कोशिश करें।", - "pairWearableLeadPebble": "Pebble 2 आपके दिनों को नींद, रिकवरी और हृदय गति से भर सकता है। Pebble 2 SE घड़ी की अपनी नींद और कदमों की रीडिंग दिखाता है। उसमें हृदय गति सेंसर नहीं है, इसलिए यह ऐप उसके डेटा से रोज़ का शारीरिक भार नहीं निकाल सकता और न ही रिकवरी का अनुमान लगा सकता है।" + "pairWearableLeadPebble": "Pebble 2 आपके दिनों को नींद, रिकवरी और हृदय गति से भर सकता है। Pebble 2 SE घड़ी की अपनी नींद और कदमों की रीडिंग दिखाता है। उसमें हृदय गति सेंसर नहीं है, इसलिए यह ऐप उसके डेटा से रोज़ का शारीरिक भार नहीं निकाल सकता और न ही रिकवरी का अनुमान लगा सकता है।", + "pairMainBandWhoopOnly": "मुख्य बैंड: केवल WHOOP 4.0 या WHOOP 5.0/MG। दूसरे डिवाइस अतिरिक्त डिवाइस के रूप में जोड़े जा सकते हैं।", + "pairBandTitle": "अपना बैंड पेयर करें", + "pairBandSubtitle": "वही चुनें जो आप पहनते हैं। हम उसे आस-पास खोजेंगे।", + "pairStrapOnlyLink": "मेरे पास सिर्फ़ हार्ट-रेट स्ट्रैप है", + "pairWhoopRowLine": "नींद, रिकवरी, शारीरिक परिश्रम, हृदय गति और बहुत कुछ", + "pairSetUpTitle": "सेट अप" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 1f5bd5f8a..d026ad074 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -8036,5 +8036,11 @@ }, "pairUseForWorkouts": "Использовать только для тренировок", "pairReplaceUnpairFailed": "Не удалось удалить сопряжение с вашим браслетом, поэтому новый не сопряжён. Попробуйте ещё раз.", - "pairWearableLeadPebble": "Pebble 2 может заполнять ваши дни данными о сне, восстановлении и пульсе. Pebble 2 SE показывает сон и шаги по данным самих часов. У него нет датчика пульса, поэтому приложение не может рассчитать дневную нагрузку или оценить восстановление по его данным." + "pairWearableLeadPebble": "Pebble 2 может заполнять ваши дни данными о сне, восстановлении и пульсе. Pebble 2 SE показывает сон и шаги по данным самих часов. У него нет датчика пульса, поэтому приложение не может рассчитать дневную нагрузку или оценить восстановление по его данным.", + "pairMainBandWhoopOnly": "Основной браслет: только WHOOP 4.0 или WHOOP 5.0/MG. Другие устройства можно добавить как дополнительные.", + "pairBandTitle": "Подключите браслет", + "pairBandSubtitle": "Выберите то, что вы носите. Мы поищем его поблизости.", + "pairStrapOnlyLink": "У меня только пульсовой ремень", + "pairWhoopRowLine": "Сон, восстановление, нагрузка, пульс и многое другое", + "pairSetUpTitle": "Настройка" } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 8688c549a..8a4753482 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -16608,5 +16608,29 @@ "@pairReplaceUnpairFailed": { "description": "Shown when unpairing the old band failed during “Unpair (your band) and pair this one”; nothing else ran." }, - "pairWearableLeadPebble": "Pebble 2 เติมข้อมูลการนอน การฟื้นตัว และอัตราการเต้นของหัวใจให้แต่ละวันได้ Pebble 2 SE แสดงข้อมูลการนอนและจำนวนก้าวที่นาฬิกาบันทึกเอง รุ่นนี้ไม่มีเซ็นเซอร์วัดอัตราการเต้นของหัวใจ แอปจึงคำนวณภาระร่างกายรายวันหรือประเมินการฟื้นตัวจากข้อมูลของรุ่นนี้ไม่ได้" + "pairWearableLeadPebble": "Pebble 2 เติมข้อมูลการนอน การฟื้นตัว และอัตราการเต้นของหัวใจให้แต่ละวันได้ Pebble 2 SE แสดงข้อมูลการนอนและจำนวนก้าวที่นาฬิกาบันทึกเอง รุ่นนี้ไม่มีเซ็นเซอร์วัดอัตราการเต้นของหัวใจ แอปจึงคำนวณภาระร่างกายรายวันหรือประเมินการฟื้นตัวจากข้อมูลของรุ่นนี้ไม่ได้", + "pairMainBandWhoopOnly": "สายรัดหลัก: WHOOP 4.0 หรือ WHOOP 5.0/MG เท่านั้น อุปกรณ์อื่นเพิ่มเป็นอุปกรณ์เสริมได้", + "@pairMainBandWhoopOnly": { + "description": "Plain statement on the pairing screens: only WHOOP can be the main band; other devices are added as additional devices." + }, + "pairBandTitle": "จับคู่สายรัดของคุณ", + "@pairBandTitle": { + "description": "Title of the first-run list of bands." + }, + "pairBandSubtitle": "เลือกอันที่คุณสวมอยู่ เราจะค้นหาในบริเวณใกล้เคียง", + "@pairBandSubtitle": { + "description": "Subtitle of the first-run list of bands." + }, + "pairStrapOnlyLink": "ฉันมีแค่สายคาดวัดหัวใจ", + "@pairStrapOnlyLink": { + "description": "Text link under the band list for someone with only a heart-rate strap." + }, + "pairWhoopRowLine": "การนอน การฟื้นตัว ความหนัก อัตราการเต้นของหัวใจ และอื่นๆ", + "@pairWhoopRowLine": { + "description": "Line under each WHOOP on the first-run list." + }, + "pairSetUpTitle": "ตั้งค่า", + "@pairSetUpTitle": { + "description": "Top bar title of the first-run pairing screen." + } } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 507dc86c9..72f46b7b1 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2922,5 +2922,11 @@ "pairDeviceNamed": "配对 {name}", "pairUseForWorkouts": "仅在运动时使用", "pairReplaceUnpairFailed": "无法取消配对你的手环,因此没有配对新手环。请重试。", - "pairWearableLeadPebble": "Pebble 2 可以为你的每一天补上睡眠、恢复和心率。Pebble 2 SE 显示手表自身记录的睡眠和步数。它没有心率传感器,因此本应用无法根据它的数据计算每日身体负荷或估算恢复。" + "pairWearableLeadPebble": "Pebble 2 可以为你的每一天补上睡眠、恢复和心率。Pebble 2 SE 显示手表自身记录的睡眠和步数。它没有心率传感器,因此本应用无法根据它的数据计算每日身体负荷或估算恢复。", + "pairMainBandWhoopOnly": "主手环:仅支持 WHOOP 4.0 或 WHOOP 5.0/MG。其他设备可作为附加设备添加。", + "pairBandTitle": "配对你的手环", + "pairBandSubtitle": "选择你佩戴的那一个,我们会在附近寻找它。", + "pairStrapOnlyLink": "我只有心率带", + "pairWhoopRowLine": "睡眠、恢复、负荷、心率等", + "pairSetUpTitle": "设置" } diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index f96a68b1d..1c2fa2c22 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -54,6 +54,7 @@ import '../../state/app_state.dart'; import '../onboarding/pairing.dart' show PairingScreen; import '../ui2.dart'; import 'add_device_flow.dart'; +import 'pair_band_view.dart'; import 'category_filter_pills.dart'; import 'pair_text.dart' show PairFilter, pairFilterOf; @@ -92,7 +93,7 @@ class DevicePickerScreen extends StatefulWidget { } class _DevicePickerScreenState extends State - implements AddDeviceIo { + implements AddDeviceIo, PairBandHost { final _query = TextEditingController(); String _q = ''; @@ -253,8 +254,10 @@ class _DevicePickerScreenState extends State await _openEntry(entry); } + @override void pickBand(BandEntry entry) => unawaited(_openEntry(entry)); + @override void strapOnlyConfirmed() => unawaited(_openEntry(kBleHrs)); /// The pairing operation itself, for [AddDeviceFlow]. @@ -387,7 +390,13 @@ class _DevicePickerScreenState extends State @override Widget build(BuildContext c) { final l = AppLocalizations.of(c); - final entries = [if (widget.includeBand) kWhoopGen4, ..._notifyEntries]; + if (widget.includeBand) { + return PairBandView( + entries: firstRunBandEntries(), host: this, onSkip: widget.onSkip, + onBack: widget.onBack, problem: _problem, + ); + } + final entries = _notifyEntries; return DevicePickerView( query: _query, title: l?.pairAddDevice ?? 'Add a device', diff --git a/lib/ui2/pairing/pair_band_view.dart b/lib/ui2/pairing/pair_band_view.dart new file mode 100644 index 000000000..28a07df66 --- /dev/null +++ b/lib/ui2/pairing/pair_band_view.dart @@ -0,0 +1,184 @@ +// First-run "Pair your band": the devices that can be the user's main band, +// each marked "Every day", the always-open "Trouble connecting?" card, and +// the ways out (a heart-rate strap only, skip). +import 'package:flutter/material.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; + +import '../../ble/adapters/_registry.dart'; +import '../../l10n/display_text.dart'; +import '../ui2.dart'; +import 'category_filter_pills.dart'; +import 'pair_help.dart'; +import 'pair_sheets.dart'; +import 'pair_text.dart'; +import 'pair_widgets.dart'; +import 'whoop_firmware_warning.dart'; + +/// The devices the first run offers as the main band, in registry order. +List firstRunBandEntries() => [ + for (final e in kBandRegistry) + if (e.canBeMainDevice) e, +]; + +/// What the first-run list asks of the screen around it. +abstract interface class PairBandHost { + /// A device row was tapped. + void pickBand(BandEntry entry); + + /// The user confirmed pairing a heart-rate strap as a sensor (no band). + void strapOnlyConfirmed(); +} + +class PairBandView extends StatefulWidget { + final List entries; + final PairBandHost host; + + /// Non-null only at true first run: walk past pairing. + final VoidCallback? onSkip; + + /// Where the back chevron goes when there is no route underneath to pop + /// (first-run onboarding); null keeps the default `Navigator.maybePop`. + final VoidCallback? onBack; + + /// The last failure, in a sentence. + final String? problem; + final PairLinkOpener openLink; + + const PairBandView({ + super.key, + required this.entries, + required this.host, + this.onSkip, + this.onBack, + this.problem, + this.openLink = const SystemLinkOpener(), + }); + + @override + State createState() => _PairBandViewState(); +} + +class _PairBandViewState extends State { + final _group = ValueNotifier(null); + + @override + void initState() { + super.initState(); + _group.addListener(() => setState(() {})); + } + + @override + void dispose() { + _group.dispose(); + super.dispose(); + } + + Future _strapOnly() async { + if (await showStrapSheet(context, sensor: kBleHrs)) { + widget.host.strapOnlyConfirmed(); + } + } + + @override + Widget build(BuildContext c) { + final p = P.of(c); + final l = pairL10n(c); + final shown = filterByGroup(widget.entries, _group.value); + return Scaffold( + backgroundColor: p.bg, + body: SafeArea( + child: Column(children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: S.x4), + child: NavBar(l.pairSetUpTitle, onBack: widget.onBack), + ), + Expanded( + child: ListView( + padding: const EdgeInsets.fromLTRB(S.x4, S.x2, S.x4, S.x10), + children: [ + const WhoopFirmwareWarning(), + const SizedBox(height: S.x4), + Text(l.pairBandTitle, + key: const ValueKey('pair-band-title'), + style: F.t1.copyWith(color: p.ink)), + const SizedBox(height: S.x2), + Text(l.pairBandSubtitle, style: F.body.copyWith(color: p.ink2)), + const SizedBox(height: S.x2), + Text(l.pairMainBandWhoopOnly, + key: const ValueKey('main-band-whoop-only-note'), + style: F.cap.copyWith(color: p.ink3)), + const SizedBox(height: S.x4), + CategoryFilterPills( + kinds: [for (final e in widget.entries) e.kind], + selection: _group, + ), + if (shown.isNotEmpty) const SizedBox(height: S.x3), + for (var i = 0; i < shown.length; i++) ...[ + if (i > 0) const SizedBox(height: S.x3), + _BandRow( + entry: shown[i], + onTap: () => widget.host.pickBand(shown[i]), + ), + ], + if (widget.problem != null) ...[ + const SizedBox(height: S.x4), + StatusCard(l.pairSensorThatDidNotWork, widget.problem!, + icon: LucideIcons.circleAlert), + ], + const SizedBox(height: S.x4), + TroubleConnectingCard( + entries: widget.entries, openLink: widget.openLink), + TextLinkButton(l.pairStrapOnlyLink, onTap: _strapOnly), + if (widget.onSkip != null) ...[ + BigButton(l.pairingSkipForNow, + color: C.blue, soft: true, onTap: widget.onSkip), + const SizedBox(height: S.x2), + Text(l.pairingSkipNote, + style: F.cap.copyWith(color: p.ink3)), + ], + ], + ), + ), + ]), + ), + ); + } +} + +class _BandRow extends StatelessWidget { + final BandEntry entry; + final VoidCallback onTap; + const _BandRow({required this.entry, required this.onTap}); + + @override + Widget build(BuildContext c) { + final p = P.of(c); + final l = pairL10n(c); + return Surface( + key: ValueKey('band-row-${entry.id}'), + onTap: onTap, + child: Row(children: [ + Container( + width: 48, + height: 48, + alignment: Alignment.center, + decoration: BoxDecoration(color: p.card2, borderRadius: R.rMd), + child: Icon(deviceKindIcon(entry.kind), size: 22, color: p.ink2), + ), + const SizedBox(width: S.x3), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(uiText(c, entry.label), + style: F.body + .copyWith(color: p.ink, fontWeight: FontWeight.w600)), + const SizedBox(height: 2), + Text(l.pairWhoopRowLine, style: F.cap.copyWith(color: p.ink2)), + ]), + ), + Icon(LucideIcons.chevronRight, size: 18, color: p.ink3), + ]), + ); + } +} diff --git a/test/russian_review_findings_test.dart b/test/russian_review_findings_test.dart index 9bfbee005..cc9285c24 100644 --- a/test/russian_review_findings_test.dart +++ b/test/russian_review_findings_test.dart @@ -327,11 +327,7 @@ void main() { ); testWidgets('category search accepts original and Russian blurb', (t) async { - // The firmware warning banner sits above the list; a tall surface keeps - // the filtered row built instead of lazily off-screen. - await t.binding.setSurfaceSize(const Size(800, 3000)); - addTearDown(() => t.binding.setSurfaceSize(null)); - await t.pumpWidget(page(const DevicePickerScreen())); + await t.pumpWidget(page(const DevicePickerScreen(includeBand: false))); await t.pumpAndSettle(); final entry = kBleHrs; for (final query in [ diff --git a/test/ui2_pair_band_view_test.dart b/test/ui2_pair_band_view_test.dart new file mode 100644 index 000000000..4f51d5772 --- /dev/null +++ b/test/ui2_pair_band_view_test.dart @@ -0,0 +1,239 @@ +// First-run "Pair your band": the list, the filter pills, the strap-only +// sheet, the always-open Trouble connecting card and the way out. Rendered with fakes. +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:lucide_icons_flutter/lucide_icons.dart'; +import 'package:openstrap_edge/ble/adapters/_registry.dart'; +import 'package:openstrap_edge/ui2/community_links.dart'; +import 'package:openstrap_edge/ui2/pairing/pair_band_view.dart'; +import 'package:openstrap_edge/ui2/pairing/pair_help.dart' show PairLinkOpener; +import 'package:openstrap_edge/ui2/pairing/pair_text.dart' show PairFilter; + +import 'support/pair_ui_support.dart'; + +class _Links implements PairLinkOpener { + final opened = []; + @override + Future open(String url) async { + opened.add(url); + return true; + } +} + +class _Host implements PairBandHost { + final void Function(BandEntry) onPick; + final VoidCallback onStrap; + _Host(this.onPick, this.onStrap); + @override + void pickBand(BandEntry entry) => onPick(entry); + @override + void strapOnlyConfirmed() => onStrap(); +} + +Finder _row(BandEntry e) => find.byKey(ValueKey('band-row-${e.id}')); + +void main() { + group('which devices the first run offers', () { + test('only the WHOOP bands (DT12)', () { + final ids = [for (final e in firstRunBandEntries()) e.id]; + expect(ids, ['gen4', 'gen5']); + // Other bands pair as additional devices from "Add a device"; sensors, + // scales and the thermometer are never a main device. + for (final id in ['oura', 'colmi', 'miband234', 'ultrahuman', 'pebble', 'coros', 'garmin', + 'ble_hrs', 'polar_pmd', 'thermometer', 'miscale_bc', 'miscale2']) { + expect(ids, isNot(contains(id)), reason: id); + } + }); + }); + + group('PairBandView', () { + Widget view({ + List? entries, + ValueChanged? onPick, + VoidCallback? onStrap, + VoidCallback? onSkip, + VoidCallback? onBack, + String? problem, + _Links? links, + }) => + PairBandView( + entries: entries ?? firstRunBandEntries(), + host: _Host(onPick ?? (_) {}, onStrap ?? () {}), + onSkip: onSkip, + onBack: onBack, + problem: problem, + openLink: links ?? _Links(), + ); + + testWidgets('title, subtitle, and one row per device with what it sends', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + expect(find.text('Set up'), findsOneWidget); + expect(find.byKey(const ValueKey('pair-band-title')), findsOneWidget); + expect(find.text('Pair your band'), findsOneWidget); + expect(find.text('Pick the one you wear. We will look for it nearby.'), findsOneWidget); + for (final e in firstRunBandEntries()) { + expect(_row(e), findsOneWidget, reason: e.id); + expect( + find.descendant( + of: _row(e), + matching: find.text('Sleep, recovery, strain, heart rate and more')), + findsOneWidget, + reason: e.id); + } + }); + + + + testWidgets('says plainly that only WHOOP is the main band', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + expect(find.byKey(const ValueKey('main-band-whoop-only-note')), findsOneWidget); + expect(find.text('Main band: WHOOP 4.0 or WHOOP 5.0/MG only. Other devices can be added as additional devices.'), findsOneWidget); + }); + + testWidgets('never says what a band would NOT send, nor primary/secondary/tier', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + for (final w in ['Doesn’t send', 'primary', 'Primary', 'secondary', 'Secondary', 'Tier', 'Experimental']) { + expect(find.textContaining(w), findsNothing, reason: w); + } + }); + + testWidgets('pills show only the groups in the list; Rings narrows it', (t) async { + // The view works for any list; the first run itself offers WHOOP only. + final all = [kWhoopGen5, kOura, kColmi, kUltrahuman, kMiBand234, kPebble]; + await pumpPair(t, view(entries: all), size: const Size(412, 2400)); + for (final k in ['All', 'WHOOP', 'Rings', 'Watches']) { + expect(find.text(k), findsOneWidget, reason: k); + } + expect(find.text('Chest straps & armbands'), findsNothing); + expect(find.text('Bands'), findsNothing); + expect(find.text('Scales'), findsNothing); + await t.tap(find.text('Rings')); + await t.pumpAndSettle(); + expect(_row(kOura), findsOneWidget); + expect(_row(kColmi), findsOneWidget); + expect(_row(kUltrahuman), findsOneWidget); + expect(_row(kWhoopGen5), findsNothing); + expect(_row(kMiBand234), findsNothing); + // The Mi Band is a watch, with the other watches. + await t.tap(find.text('Watches')); + await t.pumpAndSettle(); + expect(_row(kMiBand234), findsOneWidget); + expect(_row(kPebble), findsOneWidget); + expect(_row(kOura), findsNothing); + await t.tap(find.text('All')); + await t.pumpAndSettle(); + expect(_row(kWhoopGen5), findsOneWidget); + }); + + test('the pills’ groups are PairFilter values (WHOOP, rings, watches, straps)', () { + expect(PairFilter.values.map((f) => f.name), ['whoop', 'rings', 'watches', 'straps']); + }); + + testWidgets('tapping a row picks that device', (t) async { + final picked = []; + await pumpPair(t, view(onPick: (e) => picked.add(e.id)), size: const Size(412, 2400)); + await t.tap(_row(kWhoopGen5)); + expect(picked, ['gen5']); + }); + + testWidgets('the strap-only link opens the strap sheet', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + await t.tap(find.text('I only have a heart-rate strap')); + await t.pumpAndSettle(); + expect(find.text('This is a heart-rate sensor'), findsOneWidget); + expect(find.text('Pair Bluetooth heart rate sensor'), findsOneWidget); + expect(find.text('Go back'), findsOneWidget); + }); + + testWidgets('Go back closes the sheet and pairs nothing', (t) async { + var confirmed = 0; + await pumpPair(t, view(onStrap: () => confirmed++), size: const Size(412, 2400)); + await t.tap(find.text('I only have a heart-rate strap')); + await t.pumpAndSettle(); + await t.tap(find.text('Go back')); + await t.pumpAndSettle(); + expect(find.text('This is a heart-rate sensor'), findsNothing); + expect(confirmed, 0); + }); + + testWidgets('Pair closes the sheet and carries on (strapOnlyConfirmed)', (t) async { + var confirmed = 0; + await pumpPair(t, view(onStrap: () => confirmed++), size: const Size(412, 2400)); + await t.tap(find.text('I only have a heart-rate strap')); + await t.pumpAndSettle(); + await t.tap(find.text('Pair Bluetooth heart rate sensor')); + await t.pumpAndSettle(); + expect(find.text('This is a heart-rate sensor'), findsNothing); + expect(confirmed, 1); + }); + + testWidgets('there is no “I can’t pair my band” button, and no dialog anywhere', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + expect(find.text('I can’t pair my band'), findsNothing); + await t.tap(_row(kWhoopGen5)); + await t.pumpAndSettle(); + expect(find.byType(Dialog), findsNothing); + expect(find.text('Need a hand pairing?'), findsNothing); + }); + + testWidgets('the Trouble connecting card is always there, with a link per WHOOP and Discord', (t) async { + final links = _Links(); + await pumpPair(t, view(links: links), size: const Size(412, 2400)); + expect(find.byKey(const ValueKey('trouble-connecting')), findsOneWidget); + expect(find.text('Trouble connecting?'), findsOneWidget); + for (final e in firstRunBandEntries()) { + expect(find.byKey(ValueKey('trouble-link-${e.id}')), findsOneWidget, reason: e.id); + } + await t.tap(find.byKey(const ValueKey('trouble-link-discord'))); + expect(links.opened, [kDiscordUrl]); + }); + + testWidgets('the card stays, unchanged, after trying a device; its links open each model’s page', (t) async { + final links = _Links(); + await pumpPair(t, view(links: links), size: const Size(412, 2400)); + await t.tap(_row(kWhoopGen5)); + await t.pumpAndSettle(); + expect(find.byKey(const ValueKey('trouble-connecting')), findsOneWidget); + await t.tap(find.byKey(ValueKey('trouble-link-${kWhoopGen5.id}'))); + expect(links.opened, [kWhoopGen5.resetSteps!.officialUrl]); + expect(find.byType(Dialog), findsNothing); + }); + + testWidgets('Skip for now shows only when there is something to skip', (t) async { + await pumpPair(t, view(), size: const Size(412, 2400)); + expect(find.text('Skip for now'), findsNothing); + var skipped = 0; + await pumpPair(t, view(onSkip: () => skipped++), size: const Size(412, 2400)); + await t.tap(find.text('Skip for now')); + expect(skipped, 1); + }); + + testWidgets('the back chevron goes where the first run says', (t) async { + var back = 0; + await pumpPair(t, view(onBack: () => back++), size: const Size(412, 2400)); + await t.tap(find.byIcon(LucideIcons.chevronLeft)); + expect(back, 1); + }); + + testWidgets('a problem is said in a card', (t) async { + await pumpPair(t, view(problem: 'Bluetooth is off.'), size: const Size(412, 2400)); + expect(find.text('Bluetooth is off.'), findsOneWidget); + // The card is under it, not instead of it. + expect(find.byKey(const ValueKey('trouble-connecting')), findsOneWidget); + }); + + testWidgets('German at 2x text on a small phone does not overflow', (t) async { + await pumpPair(t, view(onSkip: () {}), + locale: const Locale('de'), textScale: 2, size: const Size(320, 700)); + expect(t.takeException(), isNull); + // The retained firmware warning adds substantial height at 2x text. + await t.scrollUntilVisible(find.text('Ich habe nur einen Herzfrequenzgurt'), 200, maxScrolls: 100); + await t.ensureVisible(find.text('Ich habe nur einen Herzfrequenzgurt')); + await t.pumpAndSettle(); + await t.tap(find.text('Ich habe nur einen Herzfrequenzgurt')); + await t.pumpAndSettle(); + expect(find.text('Das ist ein Herzfrequenzsensor'), findsOneWidget); + expect(t.takeException(), isNull); + }); + }); +} diff --git a/test/ui2_tokens_test.dart b/test/ui2_tokens_test.dart index c800d3f7a..38bd874ca 100644 --- a/test/ui2_tokens_test.dart +++ b/test/ui2_tokens_test.dart @@ -273,6 +273,8 @@ const _notComponents = { // asserts the copy is not truncated and nothing overflows. 'StartCard', // Pairing pieces are exercised on routes by the pairing widget tests. + 'PairBandView', + // Pairing pieces are exercised on routes by the pairing widget tests. 'PairNote', 'CategoryFilterPills', 'PairChoiceSheet', // Pairing pieces are exercised on routes by the pairing widget tests. 'TroubleConnectingCard', 'ResetStepsView', 'PairingModeSection', 'PairStepRow', 'TextLinkButton', 'ChoiceRow', From a700ad3eae3ae7fd0c92f5f8debb4c4b2621f0de Mon Sep 17 00:00:00 2001 From: abdulsaheel Date: Fri, 13 Nov 2026 14:40:23 +0530 Subject: [PATCH 2/7] first run: the whoop description only shows under whoop rows --- lib/ui2/pairing/pair_band_view.dart | 11 +++++++++-- test/ui2_pair_band_view_test.dart | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/ui2/pairing/pair_band_view.dart b/lib/ui2/pairing/pair_band_view.dart index 28a07df66..9ec0e40b2 100644 --- a/lib/ui2/pairing/pair_band_view.dart +++ b/lib/ui2/pairing/pair_band_view.dart @@ -145,6 +145,10 @@ class _PairBandViewState extends State { } } +/// The line under a row says what a WHOOP sends. It is WHOOP copy, so another +/// main-band entry added later gets no line until it has its own. +bool _isWhoop(BandEntry e) => e.id == kWhoopGen4.id || e.id == kWhoopGen5.id; + class _BandRow extends StatelessWidget { final BandEntry entry; final VoidCallback onTap; @@ -173,8 +177,11 @@ class _BandRow extends StatelessWidget { Text(uiText(c, entry.label), style: F.body .copyWith(color: p.ink, fontWeight: FontWeight.w600)), - const SizedBox(height: 2), - Text(l.pairWhoopRowLine, style: F.cap.copyWith(color: p.ink2)), + if (_isWhoop(entry)) ...[ + const SizedBox(height: 2), + Text(l.pairWhoopRowLine, + style: F.cap.copyWith(color: p.ink2)), + ], ]), ), Icon(LucideIcons.chevronRight, size: 18, color: p.ink3), diff --git a/test/ui2_pair_band_view_test.dart b/test/ui2_pair_band_view_test.dart index 4f51d5772..a1b5797b3 100644 --- a/test/ui2_pair_band_view_test.dart +++ b/test/ui2_pair_band_view_test.dart @@ -84,6 +84,20 @@ void main() { + testWidgets('the WHOOP description is not shown under other devices', (t) async { + await pumpPair(t, view(entries: [kWhoopGen5, kOura, kColmi]), + size: const Size(412, 2400)); + const line = 'Sleep, recovery, strain, heart rate and more'; + expect(find.descendant(of: _row(kWhoopGen5), matching: find.text(line)), + findsOneWidget); + for (final e in [kOura, kColmi]) { + expect(_row(e), findsOneWidget, reason: e.id); + expect(find.descendant(of: _row(e), matching: find.text(line)), + findsNothing, + reason: e.id); + } + }); + testWidgets('says plainly that only WHOOP is the main band', (t) async { await pumpPair(t, view(), size: const Size(412, 2400)); expect(find.byKey(const ValueKey('main-band-whoop-only-note')), findsOneWidget); From a3ba11919710766e74c48b56d126258c54153578 Mon Sep 17 00:00:00 2001 From: MikenRafter Date: Fri, 13 Nov 2026 06:16:06 -0700 Subject: [PATCH 3/7] Distinguish generation comparisons from default assignments --- test/no_gen4_default_test.dart | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/test/no_gen4_default_test.dart b/test/no_gen4_default_test.dart index d73415a5c..6e66f35f2 100644 --- a/test/no_gen4_default_test.dart +++ b/test/no_gen4_default_test.dart @@ -18,6 +18,8 @@ const _bandProfileGen4Defaults = 6; final _pureComment = RegExp(r'^\s*(///|//|\*|/\*)'); +RegExp _assignmentOf(String symbol) => RegExp('(?])=\\s*${RegExp.escape(symbol)}\\b'); + int _countMatches(RegExp pattern) { var total = 0; for (final f in Directory('lib') @@ -33,10 +35,24 @@ int _countMatches(RegExp pattern) { } void main() { + // WHY: a model comparison added by the pairing screen is not a fallback. + // catches: counting the second '=' in == or the '=' in !=/<=/>=. + test('the default counter distinguishes assignment from comparisons', () { + for (final symbol in ['kWhoopGen4', 'BandProfile.gen4']) { + final assignment = _assignmentOf(symbol); + expect(assignment.hasMatch('BandEntry entry = $symbol;'), isTrue); + for (final operator in ['==', '!=', '<=', '>=']) { + expect(assignment.hasMatch('entry $operator $symbol.id'), isFalse, + reason: '$operator is a comparison, not an assignment'); + } + } + }); + + test('kWhoopGen4 default-fallback count only goes down', () { // `?? kWhoopGen4` sites plus the one field default (`= kWhoopGen4`). final count = _countMatches(RegExp(r'\?\?\s*kWhoopGen4')) + - _countMatches(RegExp(r'=\s*kWhoopGen4\b')); + _countMatches(_assignmentOf('kWhoopGen4')); expect(count, _kWhoopGen4Defaults, reason: 'kWhoopGen4-default count drifted from the tracked value. ' 'If a commit just retired a site, lower _kWhoopGen4Defaults in ' @@ -47,7 +63,7 @@ void main() { // `?? BandProfile.gen4` sites plus the one field/parameter default // (`= BandProfile.gen4`). final count = _countMatches(RegExp(r'\?\?\s*BandProfile\.gen4')) + - _countMatches(RegExp(r'=\s*BandProfile\.gen4\b')); + _countMatches(_assignmentOf('BandProfile.gen4')); expect(count, _bandProfileGen4Defaults, reason: 'BandProfile.gen4-default count drifted from the tracked ' 'value. If a commit just retired a site, lower ' From 437c438d00fa9f409a36b6a16dd9071bfb7bf6fb Mon Sep 17 00:00:00 2001 From: MikenRafter Date: Fri, 13 Nov 2026 07:15:21 -0700 Subject: [PATCH 4/7] Exercise the scan race from the sensor picker --- test/pairing_stack_review_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/pairing_stack_review_test.dart b/test/pairing_stack_review_test.dart index 6695a43a7..c71ab4e1f 100644 --- a/test/pairing_stack_review_test.dart +++ b/test/pairing_stack_review_test.dart @@ -257,7 +257,7 @@ void main() { final app = _App(); addTearDown(app.dispose); final probe = Completer(); - await _screen(t, app, DevicePickerScreen(debugScanHeldBackReason: () => probe.future)); + await _screen(t, app, DevicePickerScreen(includeBand: false, debugScanHeldBackReason: () => probe.future)); final view = t.widget(find.byType(DevicePickerView)); view.onScan!(); view.onOpenEntry!(kWhoopGen4); From 83d6a51fd8744114c4e2135f2ec4eb8434e434c4 Mon Sep 17 00:00:00 2001 From: abdulsaheel Date: Sat, 14 Nov 2026 07:58:59 +0530 Subject: [PATCH 5/7] replacement and forget: refuse a candidate that is already a sensor, tag the forgotten band's alarm, write the alarm owner before its epoch, keep a saved pairing when the sensor refresh fails --- lib/state/alarm_schedule.dart | 32 ++++++ lib/state/app_state.dart | 39 +++++-- lib/sync/background_sync.dart | 5 +- lib/ui2/pairing/device_picker.dart | 17 ++- test/alarm_epoch_owner_write_test.dart | 104 ++++++++++++++++++ test/app_state_pairing_confirmation_test.dart | 44 ++++++++ 6 files changed, 224 insertions(+), 17 deletions(-) create mode 100644 test/alarm_epoch_owner_write_test.dart diff --git a/lib/state/alarm_schedule.dart b/lib/state/alarm_schedule.dart index 0a7f2f7d8..fea692517 100644 --- a/lib/state/alarm_schedule.dart +++ b/lib/state/alarm_schedule.dart @@ -22,6 +22,38 @@ int? persistedAlarmEpoch(SharedPreferences prefs, String? remoteId) { return owner == null || owner == remoteId ? prefs.getInt('alarm_epoch') : null; } +/// CLAIM(alarm-band-ownership): tag an untagged (legacy) or this band's own +/// armed epoch with [remoteId] before that band's identity is replaced or +/// forgotten, so a later, different band can never read it as its own arm. +/// True when there is nothing to bind or the write landed. +Future bindAlarmEpochToBand(SharedPreferences prefs, String remoteId) async { + if (prefs.getInt('alarm_epoch') == null) return true; + final owner = prefs.getString(kAlarmRemoteId); + if (owner != null && owner != remoteId) return true; + return prefs.setString(kAlarmRemoteId, remoteId); +} + +/// Persist the armed [epoch] under its owner, in an order that never leaves a +/// window where the epoch reads as another band's arm: a previous owner's +/// epoch is removed first, then the owner is written, then the new epoch. +/// Every write is checked; on a failure this throws and no new epoch is saved. +/// Both the foreground and the headless writer use it. +Future saveArmedAlarmEpoch( + SharedPreferences prefs, int epoch, String? remoteId) async { + if (remoteId != null && prefs.getString(kAlarmRemoteId) != remoteId) { + if (prefs.getInt('alarm_epoch') != null && + !await prefs.remove('alarm_epoch')) { + throw StateError('Could not clear the previous alarm.'); + } + if (!await prefs.setString(kAlarmRemoteId, remoteId)) { + throw StateError('Could not record which band holds the alarm.'); + } + } + if (!await prefs.setInt('alarm_epoch', epoch)) { + throw StateError('Could not save the armed alarm.'); + } +} + /// One weekday's slot in the schedule. Immutable — callers build a new one to /// change a field. class AlarmScheduleEntry { diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index 3b0c1f958..60eb8c466 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -4870,6 +4870,17 @@ class AppState extends ChangeNotifier { if (replacing && existing!.remoteId == remoteId) { throw const SameBandSelectedException(); } + // The primary peripheral must never also hold a secondary connection. A + // candidate that is already a workout sensor here would be saved as the + // primary with its secondary row and link still alive, and the sensor + // link would reconnect the same peripheral. Refuse before anything starts. + if (replacing && + (await LocalDb.deviceRows()).any((r) => + r['remote_id'] == remoteId && + r['id'] != LocalDb.kPrimaryDeviceId)) { + throw Exception( + 'That device is already paired as a sensor. Forget it there first.'); + } final epoch = _pairingEpoch; _pairingInProgress = true; _replacingBand = replacing; @@ -4897,12 +4908,8 @@ class AppState extends ChangeNotifier { // CLAIM(alarm-band-ownership): bind legacy epochs before switching // identity, so a failed remove cannot arm the replacement on paper. final prefs = await SharedPreferences.getInstance(); - if (prefs.getInt('alarm_epoch') != null && - (prefs.getString(kAlarmRemoteId) == null || - prefs.getString(kAlarmRemoteId) == existing!.remoteId)) { - if (!await prefs.setString(kAlarmRemoteId, existing!.remoteId)) { - throw StateError('Could not preserve alarm ownership.'); - } + if (!await bindAlarmEpochToBand(prefs, existing!.remoteId)) { + throw StateError('Could not preserve alarm ownership.'); } } // The ownership write above can outlive a completed forget/reset; @@ -5022,6 +5029,19 @@ class AppState extends ChangeNotifier { Future unpair() async { _pairingEpoch++; await _sync.unpairSession(); + // CLAIM(alarm-band-ownership): an untagged arm belongs to the band being + // forgotten. Without a tag a later, different band reads it as its own and + // is treated as already armed without ever receiving SET_ALARM. + final forgotten = paired?.remoteId ?? (await PairedDevice.load())?.remoteId; + if (forgotten != null) { + final alarmPrefs = await SharedPreferences.getInstance(); + if (!await bindAlarmEpochToBand(alarmPrefs, forgotten)) { + // Forgetting must still work. Drop the epoch rather than leave an + // arm another band could adopt. + _log('[alarm] could not tag the forgotten band\'s alarm; clearing it'); + await alarmPrefs.remove('alarm_epoch'); + } + } await PairedDevice.clear(); pairedIsMaverick = false; // Everything the old band told us about itself. The engine's DeviceState @@ -5460,18 +5480,13 @@ class AppState extends ChangeNotifier { final prefs = await SharedPreferences.getInstance(); // A newer arm (or a clear) during the await owns what is persisted now. if (_disposed || _armGen != gen) return; - if (!await prefs.setInt('alarm_epoch', epoch)) { - throw StateError('Could not save the armed alarm.'); - } + await saveArmedAlarmEpoch(prefs, epoch, paired?.remoteId); if (_disposed || _armGen != gen) return; await prefs.setInt('alarm_set_at_ms', setAtMs); if (_disposed || _armGen != gen) return; // Not confirmed yet — event 56 (below, in _handleAlarmEvent) flips this. await prefs.setBool('alarm_epoch_confirmed', echoed); if (_disposed || _armGen != gen) return; - final remoteId = paired?.remoteId; - if (remoteId != null) await prefs.setString(kAlarmRemoteId, remoteId); - if (_disposed || _armGen != gen) return; if (echoed) { await _finishEchoConfirmed(prefs, gen); return; diff --git a/lib/sync/background_sync.dart b/lib/sync/background_sync.dart index 0874885b6..9b1f175cc 100644 --- a/lib/sync/background_sync.dart +++ b/lib/sync/background_sync.dart @@ -97,12 +97,9 @@ Future headlessArmAndConfirm(Future Function() arm, // The strap's own reply already named this wake time: no wait needed. final confirmed = result.echoed || await awaitAlarmLatch(() => latchedSince(armedAtMs)); - if (!await prefs.setInt('alarm_epoch', result.epoch!)) { - throw StateError('Could not save the armed alarm.'); - } + await saveArmedAlarmEpoch(prefs, result.epoch!, remoteId); await prefs.setInt('alarm_set_at_ms', armedAtMs); await prefs.setBool('alarm_epoch_confirmed', confirmed); - if (remoteId != null) await prefs.setString(kAlarmRemoteId, remoteId); } } diff --git a/lib/ui2/pairing/device_picker.dart b/lib/ui2/pairing/device_picker.dart index b8be55d1b..ed9b3af3b 100644 --- a/lib/ui2/pairing/device_picker.dart +++ b/lib/ui2/pairing/device_picker.dart @@ -68,6 +68,21 @@ import '../profile/devices.dart' import '../profile/pair_sensor.dart' show PairSensorScreen; import '../profile/profile.dart' show SetRow; +/// Refreshes the sensor list once a pairing has been SAVED. The pairing is +/// already durable here, so a failing refresh must not surface as "could not +/// pair" (the caller's catch would say exactly that). The list reloads on its +/// next load. Returns whether the refresh worked. +@visibleForTesting +Future refreshAfterPair(Future Function() refresh) async { + try { + await refresh(); + return true; + } catch (e) { + debugPrint('[pair] sensor list refresh failed after a saved pairing: $e'); + return false; + } +} + class DevicePickerScreen extends StatefulWidget { /// Walk past pairing entirely. Non-null only at true first-run onboarding /// — a re-pair or add-a-sensor push always has a screen underneath to pop @@ -407,7 +422,7 @@ class _DevicePickerScreenState extends State Future _afterPair() async { // Neither sub-flow tells AppState a `device` row changed underneath it. - if (mounted) await context.read().refreshSensors(); + if (mounted) await refreshAfterPair(context.read().refreshSensors); // A framed pair changes `AppState.isPaired`, which nothing here watches // directly — the pushed `PairingScreen` closes itself on success, and the // gate (or `RePair`) reacts to the flag underneath. diff --git a/test/alarm_epoch_owner_write_test.dart b/test/alarm_epoch_owner_write_test.dart new file mode 100644 index 000000000..7da0297b6 --- /dev/null +++ b/test/alarm_epoch_owner_write_test.dart @@ -0,0 +1,104 @@ +// The armed alarm epoch is stored with the band that holds it. The owner must +// be written BEFORE the epoch and every write checked: if the owner write +// fails the epoch must not be saved under the previous owner, where it would +// read back as the previous band's arm and as nothing for the band that took it. +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/state/alarm_schedule.dart'; +import 'package:openstrap_edge/ui2/pairing/device_picker.dart' show refreshAfterPair; +import 'package:shared_preferences/shared_preferences.dart'; +// ignore: depend_on_referenced_packages +import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; + +import 'support/failing_preferences_store.dart'; + +void main() { + late SharedPreferencesStorePlatform original; + + setUp(() { + original = SharedPreferencesStorePlatform.instance; + }); + tearDown(() => SharedPreferencesStorePlatform.instance = original); + + Future prefsWith(Map values) async { + SharedPreferences.setMockInitialValues(values); + return SharedPreferences.getInstance(); + } + + group('saveArmedAlarmEpoch', () { + test('a new band takes the arm: old epoch cleared, owner then epoch written', + () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + await saveArmedAlarmEpoch(prefs, 200, 'B'); + expect(prefs.getString(kAlarmRemoteId), 'B'); + expect(persistedAlarmEpoch(prefs, 'B'), 200); + expect(persistedAlarmEpoch(prefs, 'A'), isNull); + }); + + test('the same band just refreshes its epoch', () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + await saveArmedAlarmEpoch(prefs, 200, 'A'); + expect(persistedAlarmEpoch(prefs, 'A'), 200); + }); + + test('a failed owner write throws and never saves the epoch under the old owner', + () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + SharedPreferencesStorePlatform.instance = FailingPreferencesStore( + SharedPreferencesStorePlatform.instance, + key: kAlarmRemoteId, + throws: false); + await expectLater(saveArmedAlarmEpoch(prefs, 200, 'B'), throwsStateError); + expect(prefs.getInt('alarm_epoch'), isNull, + reason: 'neither the old nor the new epoch is left behind'); + expect(persistedAlarmEpoch(prefs, 'A'), isNull, + reason: 'the previous band is not handed a different band\'s epoch'); + }); + + test('a failed clear of the previous epoch throws before the owner changes', + () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + SharedPreferencesStorePlatform.instance = FailingPreferencesStore( + SharedPreferencesStorePlatform.instance, + key: 'alarm_epoch', + throws: false); + await expectLater(saveArmedAlarmEpoch(prefs, 200, 'B'), throwsStateError); + expect(prefs.getString(kAlarmRemoteId), 'A', + reason: 'the owner is only changed after the old epoch is gone'); + }); + + test('with no paired band the epoch is saved untagged, as before', () async { + final prefs = await prefsWith({}); + await saveArmedAlarmEpoch(prefs, 200, null); + expect(prefs.getInt('alarm_epoch'), 200); + expect(prefs.getString(kAlarmRemoteId), isNull); + }); + }); + + group('bindAlarmEpochToBand', () { + test('tags an untagged epoch with the band being left', () async { + final prefs = await prefsWith({'alarm_epoch': 100}); + expect(await bindAlarmEpochToBand(prefs, 'A'), isTrue); + expect(persistedAlarmEpoch(prefs, 'B'), isNull); + expect(persistedAlarmEpoch(prefs, 'A'), 100); + }); + + test('leaves another band\'s tagged epoch alone', () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'X'}); + expect(await bindAlarmEpochToBand(prefs, 'A'), isTrue); + expect(prefs.getString(kAlarmRemoteId), 'X'); + }); + }); + + group('refreshAfterPair', () { + test('a failing refresh does not turn a saved pairing into a failure', () async { + expect(await refreshAfterPair(() async => throw StateError('db busy')), + isFalse); + }); + + test('a working refresh reports success', () async { + var ran = false; + expect(await refreshAfterPair(() async => ran = true), isTrue); + expect(ran, isTrue); + }); + }); +} diff --git a/test/app_state_pairing_confirmation_test.dart b/test/app_state_pairing_confirmation_test.dart index 80e3d1025..93d1ded80 100644 --- a/test/app_state_pairing_confirmation_test.dart +++ b/test/app_state_pairing_confirmation_test.dart @@ -14,6 +14,7 @@ import 'package:openstrap_edge/ble/ios_ble_restore.dart'; import 'package:openstrap_edge/data/db.dart'; import 'package:openstrap_edge/notify/notification_service.dart'; import 'package:openstrap_edge/state/app_state.dart' show SameBandSelectedException; +import 'package:openstrap_edge/state/alarm_schedule.dart' show kAlarmRemoteId, persistedAlarmEpoch; import 'package:openstrap_edge/state/prefs.dart' show Prefs; import 'package:openstrap_edge/sync/band_ownership.dart'; import 'package:openstrap_edge/sync/paired_device.dart'; @@ -426,6 +427,49 @@ void main() { reason: 'the old band must not be reconnected after the save'); })); + // WHY: the primary peripheral must never also be a secondary sensor. A + // candidate that already has a workout-only row would be saved as primary + // with that row (and its link) still alive. + // catches: replacing onto a band that is already a secondary sensor. + test('replacement refuses a candidate that is already a secondary sensor', + syncCase((rig, timers) async { + await PairedDevice.save(kRemoteId, kSerial, generation: 'gen4'); + await rig.openAndSettle(); + await LocalDb.upsertDevice( + id: 'ble_hrs-$replacementId', + adapterId: 'ble_hrs', + remoteId: replacementId, + label: 'Chest strap'); + rig.engine.events.clear(); + await expectLater( + rig.app.replaceWith(BluetoothDevice.fromId(replacementId)), + throwsA(isA())); + expect((await PairedDevice.load())?.remoteId, kRemoteId, + reason: 'the current band stays paired'); + expect(rig.engine.only('connect'), isEmpty, + reason: 'nothing starts before the refusal'); + expect((await LocalDb.deviceRows()).where((r) => r['remote_id'] == replacementId), + hasLength(1), reason: 'the sensor row is untouched'); + })); + + // WHY: an untagged legacy arm belongs to the band being forgotten. If it + // stays untagged a later, different band reads it as its own. + // catches: forgetting a band and leaving its alarm readable by the next one. + test('forgetting a band tags its untagged alarm so another band cannot adopt it', + syncCase((rig, timers) async { + await PairedDevice.save(kRemoteId, kSerial, generation: 'gen4'); + await rig.openAndSettle(); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(kAlarmRemoteId); + await prefs.setInt('alarm_epoch', 1893456000); + await rig.app.unpair(); + expect(prefs.getString(kAlarmRemoteId), kRemoteId); + expect(persistedAlarmEpoch(prefs, replacementId), isNull, + reason: 'a different band is not treated as armed'); + expect(persistedAlarmEpoch(prefs, kRemoteId), 1893456000, + reason: 'the forgotten band keeps its own arm record'); + })); + // WHY: a lost band's retry must finish before candidate bootstrap starts. // catches: rejecting replacement because the old loop is reconnecting, // or clearing its flag without waiting for its in-flight connect. From bf7bfa4596846e7b494e82a739e866ec8fcadecf Mon Sep 17 00:00:00 2001 From: abdulsaheel Date: Sat, 14 Nov 2026 08:57:44 +0530 Subject: [PATCH 6/7] replacement: refuse a sensor candidate inside the guarded section, drop audit entries for the alarm owner writes that moved --- lib/state/app_state.dart | 22 +++++++++++----------- test/backup/settings_audit_guard_test.dart | 2 -- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index f123f8fd6..5c2eb9ea2 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -4883,23 +4883,23 @@ class AppState extends ChangeNotifier { if (replacing && existing!.remoteId == remoteId) { throw const SameBandSelectedException(); } - // The primary peripheral must never also hold a secondary connection. A - // candidate that is already a workout sensor here would be saved as the - // primary with its secondary row and link still alive, and the sensor - // link would reconnect the same peripheral. Refuse before anything starts. - if (replacing && - (await LocalDb.deviceRows()).any((r) => - r['remote_id'] == remoteId && - r['id'] != LocalDb.kPrimaryDeviceId)) { - throw Exception( - 'That device is already paired as a sensor. Forget it there first.'); - } final epoch = _pairingEpoch; _pairingInProgress = true; _replacingBand = replacing; var committed = false; var started = false; try { + // The primary peripheral must never also hold a secondary connection. A + // candidate that is already a workout sensor here would be saved as the + // primary with its secondary row and link still alive, and the sensor + // link would reconnect the same peripheral. Refuse before anything starts. + if (replacing && + (await LocalDb.deviceRows()).any((r) => + r['remote_id'] == remoteId && + r['id'] != LocalDb.kPrimaryDeviceId)) { + throw Exception( + 'That device is already paired as a sensor. Forget it there first.'); + } final confirmed = await _sync.connectForPairing( PairedDevice(remoteId, serial), replacingRemoteId: replacing ? existing?.remoteId : null, diff --git a/test/backup/settings_audit_guard_test.dart b/test/backup/settings_audit_guard_test.dart index 3c657b085..6e3171a1e 100644 --- a/test/backup/settings_audit_guard_test.dart +++ b/test/backup/settings_audit_guard_test.dart @@ -114,8 +114,6 @@ const _indirectKeys = >{ 'health_import_profile_at', 'health_import_workouts_at'], 'lib/notify/notification_prefs.dart:_kBatteryPct': ['notif_battery_pct'], 'lib/state/app_state.dart:_kHealthSync': ['health_sync'], - 'lib/state/app_state.dart:kAlarmRemoteId': ['alarm_remote_id'], - 'lib/sync/background_sync.dart:kAlarmRemoteId': ['alarm_remote_id'], 'lib/sync/paired_device.dart:_kWornOn': ['paired_worn_on'], 'lib/sync/paired_device.dart:key': [ 'paired_remote_id', 'paired_serial', 'paired_generation'], From 3857ea8b636354dac5579e63953573688d153476 Mon Sep 17 00:00:00 2001 From: abdulsaheel Date: Sat, 14 Nov 2026 14:12:34 +0530 Subject: [PATCH 7/7] alarm arms: drop a pending arm for a band that is no longer paired, recheck superseded arms before the epoch write, checkpoint steps by their own reset generation, tidy pairing copy and sheet motion --- lib/l10n/app_de.arb | 4 +- lib/l10n/app_en.arb | 6 +- lib/l10n/app_es.arb | 4 +- lib/l10n/app_fr.arb | 4 +- lib/l10n/app_hi.arb | 4 +- lib/l10n/app_ru.arb | 4 +- lib/l10n/app_th.arb | 4 +- lib/l10n/app_zh.arb | 4 +- lib/state/alarm_schedule.dart | 14 +++- lib/state/app_state.dart | 37 +++++++++-- lib/ui2/pairing/pair_choice_sheet.dart | 2 + lib/ui2/profile/pair_sensor.dart | 9 ++- test/alarm_epoch_owner_write_test.dart | 42 ++++++++++++ test/app_state_pairing_confirmation_test.dart | 25 +++++++ test/live_step_runs_test.dart | 40 ++++++++++++ test/pairing_copy_test.dart | 65 +++++++++++++++++++ test/support/app_state_sync_harness.dart | 4 ++ 17 files changed, 245 insertions(+), 27 deletions(-) create mode 100644 test/pairing_copy_test.dart diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index b3386f097..aec51eef9 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -3635,11 +3635,11 @@ "pairWearableLead": "Es kann deine Tage mit Schlaf, Erholung und Herzfrequenz füllen.", "pairWearableNote": "Füllt Tage ohne dein WHOOP. Experimentell, also schalte es unter Geräte ein.", "pairStrapLead": "Es liefert Herzfrequenz beim Training. Schlaf, Erholung und tägliche Belastung zeichnet es nicht auf.", - "pairStrapNote": "Für beides muss „Beim Training nutzen“ an sein.", + "pairStrapNote": "Schalte „Beim Training nutzen“ ein, damit die Herzfrequenz beim Training aufgezeichnet wird.", "pairDeviceNamed": "{name} koppeln", "pairUseForWorkouts": "Nur fürs Training nutzen", "pairReplaceUnpairFailed": "Dein neues Band ist gekoppelt, aber das alte Band konnte nicht entfernt werden.", - "pairWearableLeadPebble": "Pebble 2 kann deine Tage mit Schlaf, Erholung und Herzfrequenz füllen. Pebble 2 SE zeigt die eigenen Schlaf- und Schrittdaten der Uhr. Sie hat keinen Herzfrequenzsensor, daher kann diese App daraus weder die tägliche Belastung berechnen noch die Erholung schätzen.", + "pairWearableLeadPebble": "Pebble 2 kann deine Tage mit Schlaf und Herzfrequenz füllen. Pebble 2 SE zeigt die eigenen Schlaf- und Schrittdaten der Uhr. Sie hat keinen Herzfrequenzsensor, daher kann diese App daraus weder die tägliche Belastung berechnen noch die Erholung schätzen.", "pairMainBandWhoopOnly": "Hauptband: nur WHOOP 4.0 oder WHOOP 5.0/MG. Andere Geräte lassen sich als zusätzliche Geräte hinzufügen.", "pairBandTitle": "Band koppeln", "pairBandSubtitle": "Wähle das, das du trägst. Wir suchen es in der Nähe.", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 673ecb655..cd555c9bb 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -16873,9 +16873,9 @@ "@pairStrapLead": { "description": "Sheet lead for a heart-rate strap or sensor." }, - "pairStrapNote": "Both need “Use during workouts” on.", + "pairStrapNote": "Turn on “Use during workouts” to record heart rate while you work out.", "@pairStrapNote": { - "description": "Note under a strap’s table: both workout rows need the switch. Quotes deviceUseWorkoutsTitle." + "description": "Note on a strap’s sheet: workout recording needs the switch. Quotes deviceUseWorkoutsTitle." }, "pairDeviceNamed": "Pair {name}", "@pairDeviceNamed": { @@ -16894,7 +16894,7 @@ "@pairReplaceUnpairFailed": { "description": "Shown when unpairing the old band failed during “Unpair (your band) and pair this one”; nothing else ran." }, - "pairWearableLeadPebble": "Pebble 2 can fill your days with sleep, recovery and heart rate. Pebble 2 SE shows the watch’s own sleep and steps. It has no heart-rate sensor, so this app cannot calculate daily strain or estimate recovery from it.", + "pairWearableLeadPebble": "Pebble 2 can fill your days with sleep and heart rate. Pebble 2 SE shows the watch’s own sleep and steps. It has no heart-rate sensor, so this app cannot calculate daily strain or estimate recovery from it.", "@pairWearableLeadPebble": { "description": "Pebble-family pairing lead: SE shows the watch’s own sleep and steps; no HR sensor means no app-calculated daily strain or recovery estimate from the SE alone." }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 9e1a383b5..416c78f37 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -3085,11 +3085,11 @@ "pairWearableLead": "Puede completar tus días con sueño, recuperación y frecuencia cardiaca.", "pairWearableNote": "Completa los días sin tu WHOOP. Es experimental, así que actívalo en Dispositivos.", "pairStrapLead": "Añade la frecuencia cardiaca mientras entrenas. No registra sueño, recuperación ni esfuerzo diario.", - "pairStrapNote": "Ambos necesitan «Usar durante los entrenamientos» activado.", + "pairStrapNote": "Activa «Usar durante los entrenamientos» para registrar la frecuencia cardiaca durante los entrenamientos.", "pairDeviceNamed": "Emparejar {name}", "pairUseForWorkouts": "Usarla solo para entrenamientos", "pairReplaceUnpairFailed": "Tu pulsera nueva está emparejada, pero no se pudo quitar la anterior.", - "pairWearableLeadPebble": "Pebble 2 puede completar tus días con sueño, recuperación y frecuencia cardiaca. Pebble 2 SE muestra el sueño y los pasos registrados por el propio reloj. No tiene sensor de frecuencia cardiaca, por lo que esta app no puede calcular la carga diaria ni estimar la recuperación a partir de sus datos.", + "pairWearableLeadPebble": "Pebble 2 puede completar tus días con sueño y frecuencia cardiaca. Pebble 2 SE muestra el sueño y los pasos registrados por el propio reloj. No tiene sensor de frecuencia cardiaca, por lo que esta app no puede calcular la carga diaria ni estimar la recuperación a partir de sus datos.", "pairMainBandWhoopOnly": "Pulsera principal: solo WHOOP 4.0 o WHOOP 5.0/MG. Los demás dispositivos se pueden añadir como dispositivos adicionales.", "pairBandTitle": "Empareja tu pulsera", "pairBandSubtitle": "Elige la que llevas puesta. La buscaremos cerca.", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 51fb2b856..1681186b4 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -3405,11 +3405,11 @@ "pairWearableLead": "Il peut compléter vos journées avec le sommeil, la récupération et la fréquence cardiaque.", "pairWearableNote": "Complète les jours sans votre WHOOP. Expérimental : activez-le dans Appareils.", "pairStrapLead": "Il ajoute la fréquence cardiaque pendant l’entraînement. Il n’enregistre ni le sommeil, ni la récupération, ni l’effort quotidien.", - "pairStrapNote": "Les deux nécessitent « Utiliser pendant les entraînements » activé.", + "pairStrapNote": "Activez « Utiliser pendant les entraînements » pour enregistrer la fréquence cardiaque pendant vos entraînements.", "pairDeviceNamed": "Associer {name}", "pairUseForWorkouts": "L’utiliser seulement pour les entraînements", "pairReplaceUnpairFailed": "Votre nouveau bracelet est associé, mais l’ancien n’a pas pu être retiré.", - "pairWearableLeadPebble": "Pebble 2 peut compléter vos journées avec le sommeil, la récupération et la fréquence cardiaque. Pebble 2 SE affiche le sommeil et les pas enregistrés par la montre. Elle n’a pas de capteur de fréquence cardiaque, donc cette app ne peut pas calculer la charge quotidienne ni estimer la récupération à partir de ses données.", + "pairWearableLeadPebble": "Pebble 2 peut compléter vos journées avec le sommeil et la fréquence cardiaque. Pebble 2 SE affiche le sommeil et les pas enregistrés par la montre. Elle n’a pas de capteur de fréquence cardiaque, donc cette app ne peut pas calculer la charge quotidienne ni estimer la récupération à partir de ses données.", "pairMainBandWhoopOnly": "Bracelet principal : uniquement WHOOP 4.0 ou WHOOP 5.0/MG. Les autres appareils peuvent être ajoutés comme appareils supplémentaires.", "pairBandTitle": "Associez votre bracelet", "pairBandSubtitle": "Choisissez celui que vous portez. Nous le chercherons à proximité.", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index f1201dc37..7daad214c 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -3056,11 +3056,11 @@ "pairWearableLead": "यह आपके दिनों को नींद, रिकवरी और हृदय गति से भर सकता है।", "pairWearableNote": "आपके WHOOP के बिना वाले दिनों को भरता है। प्रायोगिक है, इसलिए इसे डिवाइस में चालू करें।", "pairStrapLead": "यह वर्कआउट के दौरान हृदय गति जोड़ता है। यह नींद, रिकवरी या दैनिक शारीरिक परिश्रम रिकॉर्ड नहीं करता।", - "pairStrapNote": "दोनों के लिए “वर्कआउट के दौरान इस्तेमाल करें” चालू होना चाहिए।", + "pairStrapNote": "वर्कआउट के दौरान हृदय गति रिकॉर्ड करने के लिए “वर्कआउट के दौरान इस्तेमाल करें” चालू करें।", "pairDeviceNamed": "{name} पेयर करें", "pairUseForWorkouts": "इसे केवल वर्कआउट के लिए इस्तेमाल करें", "pairReplaceUnpairFailed": "आपका नया बैंड पेयर हो गया है, लेकिन पुराना बैंड हटाया नहीं जा सका।", - "pairWearableLeadPebble": "Pebble 2 आपके दिनों को नींद, रिकवरी और हृदय गति से भर सकता है। Pebble 2 SE घड़ी की अपनी नींद और कदमों की रीडिंग दिखाता है। उसमें हृदय गति सेंसर नहीं है, इसलिए यह ऐप उसके डेटा से रोज़ का शारीरिक भार नहीं निकाल सकता और न ही रिकवरी का अनुमान लगा सकता है।", + "pairWearableLeadPebble": "Pebble 2 आपके दिनों को नींद और हृदय गति से भर सकता है। Pebble 2 SE घड़ी की अपनी नींद और कदमों की रीडिंग दिखाता है। उसमें हृदय गति सेंसर नहीं है, इसलिए यह ऐप उसके डेटा से रोज़ का शारीरिक भार नहीं निकाल सकता और न ही रिकवरी का अनुमान लगा सकता है।", "pairMainBandWhoopOnly": "मुख्य बैंड: केवल WHOOP 4.0 या WHOOP 5.0/MG। दूसरे डिवाइस अतिरिक्त डिवाइस के रूप में जोड़े जा सकते हैं।", "pairBandTitle": "अपना बैंड पेयर करें", "pairBandSubtitle": "वही चुनें जो आप पहनते हैं। हम उसे आस-पास खोजेंगे।", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 86390acd4..0be233c7b 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -8210,7 +8210,7 @@ "pairWearableLead": "Он может заполнять ваши дни данными о сне, восстановлении и пульсе.", "pairWearableNote": "Заполняет дни без вашего WHOOP. Экспериментально, поэтому включите это в разделе «Устройства».", "pairStrapLead": "Он добавляет пульс во время тренировки. Сон, восстановление и дневную нагрузку он не записывает.", - "pairStrapNote": "Для обоих нужно включить «Использовать во время тренировок».", + "pairStrapNote": "Включите «Использовать во время тренировок», чтобы записывать пульс во время тренировок.", "pairDeviceNamed": "Подключить {name}", "@pairDeviceNamed": { "placeholders": { @@ -8221,7 +8221,7 @@ }, "pairUseForWorkouts": "Использовать только для тренировок", "pairReplaceUnpairFailed": "Новый браслет сопряжён, но старый удалить не удалось.", - "pairWearableLeadPebble": "Pebble 2 может заполнять ваши дни данными о сне, восстановлении и пульсе. Pebble 2 SE показывает сон и шаги по данным самих часов. У него нет датчика пульса, поэтому приложение не может рассчитать дневную нагрузку или оценить восстановление по его данным.", + "pairWearableLeadPebble": "Pebble 2 может заполнять ваши дни данными о сне и пульсе. Pebble 2 SE показывает сон и шаги по данным самих часов. У него нет датчика пульса, поэтому приложение не может рассчитать дневную нагрузку или оценить восстановление по его данным.", "pairMainBandWhoopOnly": "Основной браслет: только WHOOP 4.0 или WHOOP 5.0/MG. Другие устройства можно добавить как дополнительные.", "pairBandTitle": "Подключите браслет", "pairBandSubtitle": "Выберите то, что вы носите. Мы поищем его поблизости.", diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index aac0ef27e..3b04f2476 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -16736,7 +16736,7 @@ "@pairStrapLead": { "description": "Sheet lead for a heart-rate strap or sensor." }, - "pairStrapNote": "ทั้งสองอย่างต้องเปิด “ใช้ระหว่างออกกำลังกาย”", + "pairStrapNote": "เปิด “ใช้ระหว่างออกกำลังกาย” เพื่อบันทึกอัตราการเต้นของหัวใจระหว่างออกกำลังกาย", "@pairStrapNote": { "description": "Note under a strap’s table: both workout rows need the switch. Quotes deviceUseWorkoutsTitle." }, @@ -16757,7 +16757,7 @@ "@pairReplaceUnpairFailed": { "description": "Shown when unpairing the old band failed during “Unpair (your band) and pair this one”; nothing else ran." }, - "pairWearableLeadPebble": "Pebble 2 เติมข้อมูลการนอน การฟื้นตัว และอัตราการเต้นของหัวใจให้แต่ละวันได้ Pebble 2 SE แสดงข้อมูลการนอนและจำนวนก้าวที่นาฬิกาบันทึกเอง รุ่นนี้ไม่มีเซ็นเซอร์วัดอัตราการเต้นของหัวใจ แอปจึงคำนวณภาระร่างกายรายวันหรือประเมินการฟื้นตัวจากข้อมูลของรุ่นนี้ไม่ได้", + "pairWearableLeadPebble": "Pebble 2 เติมข้อมูลการนอนและอัตราการเต้นของหัวใจให้แต่ละวันได้ Pebble 2 SE แสดงข้อมูลการนอนและจำนวนก้าวที่นาฬิกาบันทึกเอง รุ่นนี้ไม่มีเซ็นเซอร์วัดอัตราการเต้นของหัวใจ แอปจึงคำนวณภาระร่างกายรายวันหรือประเมินการฟื้นตัวจากข้อมูลของรุ่นนี้ไม่ได้", "pairMainBandWhoopOnly": "สายรัดหลัก: WHOOP 4.0 หรือ WHOOP 5.0/MG เท่านั้น อุปกรณ์อื่นเพิ่มเป็นอุปกรณ์เสริมได้", "@pairMainBandWhoopOnly": { "description": "Plain statement on the pairing screens: only WHOOP can be the main band; other devices are added as additional devices." diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6f5750f19..801f416e1 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -3056,11 +3056,11 @@ "pairWearableLead": "它可以为你的每一天补上睡眠、恢复和心率。", "pairWearableNote": "填补没有 WHOOP 数据的日子。这是实验功能,请在“设备”中开启。", "pairStrapLead": "它在你运动时提供心率,不记录睡眠、恢复或每日负荷。", - "pairStrapNote": "两项都需要开启“在锻炼时使用”。", + "pairStrapNote": "开启“在锻炼时使用”,即可在锻炼时记录心率。", "pairDeviceNamed": "配对 {name}", "pairUseForWorkouts": "仅在运动时使用", "pairReplaceUnpairFailed": "新手环已配对,但无法移除旧手环。", - "pairWearableLeadPebble": "Pebble 2 可以为你的每一天补上睡眠、恢复和心率。Pebble 2 SE 显示手表自身记录的睡眠和步数。它没有心率传感器,因此本应用无法根据它的数据计算每日身体负荷或估算恢复。", + "pairWearableLeadPebble": "Pebble 2 可以为你的每一天补上睡眠和心率。Pebble 2 SE 显示手表自身记录的睡眠和步数。它没有心率传感器,因此本应用无法根据它的数据计算每日身体负荷或估算恢复。", "pairMainBandWhoopOnly": "主手环:仅支持 WHOOP 4.0 或 WHOOP 5.0/MG。其他设备可作为附加设备添加。", "pairBandTitle": "配对你的手环", "pairBandSubtitle": "选择你佩戴的那一个,我们会在附近寻找它。", diff --git a/lib/state/alarm_schedule.dart b/lib/state/alarm_schedule.dart index fea692517..8711497c6 100644 --- a/lib/state/alarm_schedule.dart +++ b/lib/state/alarm_schedule.dart @@ -38,8 +38,16 @@ Future bindAlarmEpochToBand(SharedPreferences prefs, String remoteId) asyn /// epoch is removed first, then the owner is written, then the new epoch. /// Every write is checked; on a failure this throws and no new epoch is saved. /// Both the foreground and the headless writer use it. -Future saveArmedAlarmEpoch( - SharedPreferences prefs, int epoch, String? remoteId) async { +/// +/// [stillCurrent] answers "has a newer arm or a clear superseded this one?". +/// It is asked before anything is written and again, synchronously, right +/// before the epoch write: the removes/writes above await, and a clear or a +/// newer arm that ran in those gaps must not have its result overwritten by +/// this older epoch. Returns false when superseded (nothing more is written). +Future saveArmedAlarmEpoch( + SharedPreferences prefs, int epoch, String? remoteId, + {bool Function()? stillCurrent}) async { + if (stillCurrent != null && !stillCurrent()) return false; if (remoteId != null && prefs.getString(kAlarmRemoteId) != remoteId) { if (prefs.getInt('alarm_epoch') != null && !await prefs.remove('alarm_epoch')) { @@ -49,9 +57,11 @@ Future saveArmedAlarmEpoch( throw StateError('Could not record which band holds the alarm.'); } } + if (stillCurrent != null && !stillCurrent()) return false; if (!await prefs.setInt('alarm_epoch', epoch)) { throw StateError('Could not save the armed alarm.'); } + return true; } /// One weekday's slot in the schedule. Immutable — callers build a new one to diff --git a/lib/state/app_state.dart b/lib/state/app_state.dart index f45763f66..d97c580c7 100644 --- a/lib/state/app_state.dart +++ b/lib/state/app_state.dart @@ -4201,8 +4201,13 @@ class AppState extends ChangeNotifier { static const String _kLiveSessionCheckpoint = 'live_session_checkpoint'; Future _checkpointLiveSession() async { - final resetGeneration = ResetGate.generation; if (_gaitRuns.isEmpty) return; + // The runs were collected under THEIR generation, not the one current now: + // a reset that began or finished since must not have its deleted steps + // written back (and recovered after the next connect). Refused up front + // and again after the reads below. + final resetGeneration = _gaitRunsGeneration ?? ResetGate.generation; + if (ResetGate.changedSince(resetGeneration)) return; try { final prefs = await SharedPreferences.getInstance(); final calibration = await _liveStepCalibrationRuns(); @@ -5329,6 +5334,10 @@ class AppState extends ChangeNotifier { } notifyListeners(); } + // The band that receives this SET. unpair()/replacement can finish while + // the write waits for its reply; the result then belongs to a band that + // is no longer the paired one (see [_onArmed]). + final armedFor = paired?.remoteId; final result = await armNextScheduledOccurrence( engine: engine, schedule: _schedule, @@ -5346,7 +5355,7 @@ class AppState extends ChangeNotifier { final epoch = result.epoch; if (epoch == null) return true; await _onArmed(DateTime.fromMillisecondsSinceEpoch(epoch * 1000), epoch, - echoed: result.echoed); + echoed: result.echoed, armedFor: armedFor); return true; } catch (e) { _log('[alarm] weekly-schedule arm failed: $e'); @@ -5474,6 +5483,7 @@ class AppState extends ChangeNotifier { // rich 20-byte firing form (a hardcoded 0 subsec would still fire, but the // engine owns the exact on-wire layout). Persist the wall instant the // engine reports armed (null = write never reached the band). + final armedFor = paired?.remoteId; final (:armed, :echoed) = await engine.armAlarm(when); if (armed == null) { // Do NOT persist or start the confirmation machine, or we'd strand a @@ -5487,7 +5497,7 @@ class AppState extends ChangeNotifier { throw Exception('Alarm not set'); } await _onArmed(armed, armed.millisecondsSinceEpoch ~/ 1000, - echoed: echoed); + echoed: echoed, armedFor: armedFor); } /// Shared bookkeeping for anything that just armed the band: optimistic @@ -5498,7 +5508,19 @@ class AppState extends ChangeNotifier { /// /// [echoed]: the strap's reply already reported this exact wake time, so the /// arm is confirmed now; event 56 stays as later corroboration. - Future _onArmed(DateTime when, int epoch, {bool echoed = false}) async { + /// + /// [armedFor] is the band that received the SET, captured BEFORE the write. + /// If it is no longer the paired band (a forget or replacement finished while + /// the reply was pending), this arm is dropped: persisting it would save an + /// ownerless epoch that any later band reads as its own and is then never + /// armed. + Future _onArmed(DateTime when, int epoch, + {bool echoed = false, required String? armedFor}) async { + if (armedFor != paired?.remoteId) { + _log('[alarm] the band that took this alarm is no longer paired; ' + 'not recording it.'); + return; + } final gen = ++_armGen; _savedAlarm = epoch; device.alarmEpoch = epoch; // optimistic display @@ -5510,7 +5532,12 @@ class AppState extends ChangeNotifier { final prefs = await SharedPreferences.getInstance(); // A newer arm (or a clear) during the await owns what is persisted now. if (_disposed || _armGen != gen) return; - await saveArmedAlarmEpoch(prefs, epoch, paired?.remoteId); + // Asked again right before the epoch write: the helper awaits, and a clear + // or newer arm in those gaps must not be overwritten by this older epoch. + if (!await saveArmedAlarmEpoch(prefs, epoch, armedFor, + stillCurrent: () => !_disposed && _armGen == gen)) { + return; + } if (_disposed || _armGen != gen) return; await prefs.setInt('alarm_set_at_ms', setAtMs); if (_disposed || _armGen != gen) return; diff --git a/lib/ui2/pairing/pair_choice_sheet.dart b/lib/ui2/pairing/pair_choice_sheet.dart index eeb661a92..b3c869bad 100644 --- a/lib/ui2/pairing/pair_choice_sheet.dart +++ b/lib/ui2/pairing/pair_choice_sheet.dart @@ -109,6 +109,8 @@ Future showPairChoiceSheet(BuildContext c, PairChoiceSheet sheet) { context: c, backgroundColor: p.card, isScrollControlled: true, + // Honours Reduce Motion like every other modal sheet in ui2. + sheetAnimationStyle: sheetMotion(c), // A full-height sheet must not slide under the status bar or a notch. useSafeArea: true, showDragHandle: true, diff --git a/lib/ui2/profile/pair_sensor.dart b/lib/ui2/profile/pair_sensor.dart index df697b343..1f4df6057 100644 --- a/lib/ui2/profile/pair_sensor.dart +++ b/lib/ui2/profile/pair_sensor.dart @@ -405,15 +405,18 @@ class _PairSensorScreenState extends State @override Future pair(BandCandidate cand, BandEntry entry, PairConfirmation? confirmation) async { + // Read before the await: if pairing throws after this screen is gone, the + // catch below must not touch a disposed context. + final l = AppLocalizations.of(context); try { return await pairRegisteredEntry(entry, cand.device, label: cand.label, earlierBand: cand.alsoBand, confirmation: confirmation); } catch (e) { - return PairOutcome.failed(AppLocalizations.of(context) - ?.pairSensorCouldNotPair(e.toString()) ?? - 'Could not pair that device: $e'); + return PairOutcome.failed( + l?.pairSensorCouldNotPair(e.toString()) ?? + 'Could not pair that device: $e'); } } diff --git a/test/alarm_epoch_owner_write_test.dart b/test/alarm_epoch_owner_write_test.dart index 7da0297b6..fda0d2586 100644 --- a/test/alarm_epoch_owner_write_test.dart +++ b/test/alarm_epoch_owner_write_test.dart @@ -66,6 +66,29 @@ void main() { reason: 'the owner is only changed after the old epoch is gone'); }); + test('a clear that lands during the owner change stops the older epoch', () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + var current = true; + SharedPreferencesStorePlatform.instance = _OnWrite( + SharedPreferencesStorePlatform.instance, + 'flutter.$kAlarmRemoteId', + () => current = false); // a clear/newer arm starts during the write + final saved = await saveArmedAlarmEpoch(prefs, 200, 'B', + stillCurrent: () => current); + expect(saved, isFalse); + expect(prefs.getInt('alarm_epoch'), isNull, + reason: 'the superseded epoch must not be written after the clear'); + }); + + test('superseded before anything is written: nothing is touched', () async { + final prefs = await prefsWith({'alarm_epoch': 100, kAlarmRemoteId: 'A'}); + final saved = await saveArmedAlarmEpoch(prefs, 200, 'B', + stillCurrent: () => false); + expect(saved, isFalse); + expect(prefs.getInt('alarm_epoch'), 100); + expect(prefs.getString(kAlarmRemoteId), 'A'); + }); + test('with no paired band the epoch is saved untagged, as before', () async { final prefs = await prefsWith({}); await saveArmedAlarmEpoch(prefs, 200, null); @@ -102,3 +125,22 @@ void main() { }); }); } + +// Runs [onWrite] when the matching key is written, then lets the write through. +class _OnWrite extends SharedPreferencesStorePlatform { + _OnWrite(this.delegate, this.key, this.onWrite); + final SharedPreferencesStorePlatform delegate; + final String key; + final void Function() onWrite; + @override + Future> getAll() => delegate.getAll(); + @override + Future clear() => delegate.clear(); + @override + Future remove(String key) => delegate.remove(key); + @override + Future setValue(String type, String key, Object value) { + if (key == this.key) onWrite(); + return delegate.setValue(type, key, value); + } +} diff --git a/test/app_state_pairing_confirmation_test.dart b/test/app_state_pairing_confirmation_test.dart index 39991db68..63288d951 100644 --- a/test/app_state_pairing_confirmation_test.dart +++ b/test/app_state_pairing_confirmation_test.dart @@ -573,6 +573,31 @@ void main() { reason: 'the replacement must not be saved after the reset'); })); + // WHY: setAlarm waits for the band's reply. If the band is forgotten while + // it waits, the arm must not be saved afterwards: with no paired band the + // epoch would be written ownerless, and any later band reads it as its own. + // catches: persisting an arm for a band that is no longer paired. + test('an alarm arm pending while the band is forgotten is not recorded', + syncCase((rig, timers) async { + await PairedDevice.save(kRemoteId, kSerial, generation: 'gen4'); + await rig.openAndSettle(); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('alarm_epoch'); + await prefs.remove(kAlarmRemoteId); + final gate = Completer(); + rig.engine.armGate = gate; + final arming = rig.app.setAlarm(DateTime.now().add(const Duration(hours: 8))); + await rig.waitFor(() => rig.engine.events.any((e) => e.startsWith('armAlarm'))); + await rig.app.unpair(); + rig.engine.armGate = null; + gate.complete(); + await arming; + expect(prefs.getInt('alarm_epoch'), isNull, + reason: 'an ownerless epoch would be read as armed by the next band'); + expect(persistedAlarmEpoch(prefs, replacementId), isNull); + expect(rig.app.alarmEpoch, isNull); + })); + // WHY: a lost band's retry must finish before candidate bootstrap starts. // catches: rejecting replacement because the old loop is reconnecting, // or clearing its flag without waiting for its in-flight connect. diff --git a/test/live_step_runs_test.dart b/test/live_step_runs_test.dart index 0e6ef67ce..5d488a146 100644 --- a/test/live_step_runs_test.dart +++ b/test/live_step_runs_test.dart @@ -441,6 +441,46 @@ void main() { expect(await db.query('live_coverage'), isNotEmpty); }); + test('control: without a reset the walk is checkpointed', () async { + SharedPreferences.setMockInitialValues({}); + final app = AppState.forTesting(); + addTearDown(app.dispose); + const recTs = 1787100000; + for (var f = 0; f < 700; f++) { + app.debugFeedLiveAccel(_walkFrame(f, 10), + recTs: recTs, atMs: recTs * 1000 + f * 100); + } + await Future.delayed(const Duration(milliseconds: 50)); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.containsKey('live_session_checkpoint'), isTrue); + }); + + test('a reset after the steps were collected is not checkpointed back', + () async { + SharedPreferences.setMockInitialValues({}); + final app = AppState.forTesting(); + addTearDown(app.dispose); + const recTs = 1787000000; + // One full walking minute: runs are buffered and a first checkpoint lands. + for (var f = 0; f < 700; f++) { + app.debugFeedLiveAccel(_walkFrame(f, 10), + recTs: recTs, atMs: recTs * 1000 + f * 100); + } + await Future.delayed(const Duration(milliseconds: 50)); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('live_session_checkpoint'); + ResetGate.enter(); + ResetGate.leave(); + // The next minute completes AFTER the reset; the buffered runs predate it. + for (var f = 700; f < 1400; f++) { + app.debugFeedLiveAccel(_walkFrame(f, 10), + recTs: recTs, atMs: recTs * 1000 + f * 100); + } + await Future.delayed(const Duration(milliseconds: 50)); + expect(prefs.containsKey('live_session_checkpoint'), isFalse, + reason: 'runs from before the reset must not be written back'); + }); + test('a reset after the steps were collected keeps them out of storage', () async { final app = await walked(); diff --git a/test/pairing_copy_test.dart b/test/pairing_copy_test.dart new file mode 100644 index 000000000..5b40ee094 --- /dev/null +++ b/test/pairing_copy_test.dart @@ -0,0 +1,65 @@ +// Two pieces of pairing copy that made claims the app cannot back: +// - the strap note said "Both need ..." on a sheet that shows no table, so +// "both" had nothing to point at; +// - the Pebble 2 lead promised recovery, but the adapter decodes heart rate, +// steps and sleep only, and readiness needs two inputs it does not provide. +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +const _locales = ['en', 'de', 'es', 'fr', 'hi', 'ru', 'th', 'zh']; + +// The word for "recovery" in each locale's own copy. +const _recovery = { + 'en': 'recovery', + 'de': 'Erholung', + 'es': 'recuperación', + 'fr': 'récupération', + 'hi': 'रिकवरी', + 'ru': 'восстановлен', + 'th': 'การฟื้นตัว', + 'zh': '恢复', +}; + +// Words that only make sense with a table in view. +const _both = { + 'en': 'Both', + 'de': 'beides', + 'es': 'Ambos', + 'fr': 'Les deux', + 'hi': 'दोनों', + 'ru': 'обоих', + 'th': 'ทั้งสองอย่าง', + 'zh': '两项', +}; + +Map _arb(String l) => + jsonDecode(File('lib/l10n/app_$l.arb').readAsStringSync()) as Map; + +void main() { + for (final l in _locales) { + group(l, () { + test('the strap note stands alone: no "both", and it names the switch', () { + final note = _arb(l)['pairStrapNote'] as String; + expect(note.contains(_both[l]!), isFalse, + reason: '"$note" refers to a table this sheet does not show'); + // It quotes the localized name of the switch it tells the user to turn on. + final switchName = + RegExp('[“«„](.+?)[”»“]').firstMatch(note)?.group(1) ?? + RegExp('« (.+?) »').firstMatch(note)?.group(1); + expect(switchName, isNotNull, reason: 'the note must name the switch: $note'); + expect(note, contains(switchName!)); + }); + + test('the Pebble 2 lead does not promise recovery', () { + final lead = _arb(l)['pairWearableLeadPebble'] as String; + // Only the part before "Pebble 2 SE" describes what Pebble 2 provides. + // What follows says what an SE (no heart-rate sensor) cannot give. + final first = lead.split('Pebble 2 SE').first; + expect(first.contains(_recovery[l]!), isFalse, + reason: 'Pebble 2 supplies at most one readiness input: "$first"'); + }); + }); + } +} diff --git a/test/support/app_state_sync_harness.dart b/test/support/app_state_sync_harness.dart index 234cc435e..ceaca3dd8 100644 --- a/test/support/app_state_sync_harness.dart +++ b/test/support/app_state_sync_harness.dart @@ -170,6 +170,9 @@ class SyncFakeEngine extends BleEngine { /// Holds every runSync until completed. Completer? syncGate; + /// Holds every armAlarm reply until completed. + Completer? armGate; + /// Runs inside runSync before it answers (to move the durable frontier). Future Function()? onRunSync; @@ -278,6 +281,7 @@ class SyncFakeEngine extends BleEngine { Future<({DateTime? armed, bool echoed})> armAlarm(DateTime when, {int index = 0, List? haptics}) async { events.add('armAlarm:${when.millisecondsSinceEpoch ~/ 1000}'); + if (armGate != null) await armGate!.future; return (armed: when, echoed: true); }