From 70d4034a7e186567342c5639ae2992500ed5d93e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:31:28 +0000 Subject: [PATCH 1/7] Port upstream #129: label hourly SpO2 derived from heart rate as estimated (#103) On a YCBT ring (Ale-Hop2211) the hourly SpO2 in the 05 18 composite record is a fixed function of the heart rate in the same record, while spot SpO2 is a real measurement. EstimatedSpo2 decides it per ring from its own history (hourly = SpO2 history row with a respiratory-rate row at the same timestamp; derived = no heart rate ever paired with two SpO2 values over >= 24 pairs and >= 12 repeats in the last 7 days). Labelled the way derived stress (#67) is: ESTIMATED chip plus a warning-colour footnote on the Vitals card, a line on the Today tile, and the detail chart's disclaimer card. Text goes through tr(); sizes and colours use PulseType and PulseColors tokens. Stored data is unchanged. Ported from foureight84/PulseLoopAndroid#129 (6bf4bd9). Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../com/pulseloop/service/EstimatedSpo2.kt | 147 ++++++++++++++++++ .../java/com/pulseloop/ui/screens/Screens.kt | 17 +- .../com/pulseloop/ui/screens/TodayScreen.kt | 7 + .../com/pulseloop/ui/viewmodels/ViewModels.kt | 21 ++- .../pulseloop/ui/viewmodels/VitalCardState.kt | 4 +- .../pulseloop/service/EstimatedSpo2Test.kt | 143 +++++++++++++++++ 6 files changed, 335 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/EstimatedSpo2.kt create mode 100644 app/src/test/java/com/pulseloop/service/EstimatedSpo2Test.kt diff --git a/app/src/main/java/com/pulseloop/service/EstimatedSpo2.kt b/app/src/main/java/com/pulseloop/service/EstimatedSpo2.kt new file mode 100644 index 00000000..f6ad9911 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/EstimatedSpo2.kt @@ -0,0 +1,147 @@ +package com.pulseloop.service + +import com.pulseloop.data.dao.MeasurementDao +import com.pulseloop.data.entity.MeasurementEntity +import com.pulseloop.ring.MeasurementKind + +/** + * Hourly SpO₂ that a ring computes from heart rate rather than measures (issue #103). + * + * On a YCBT ring (`Ale-Hop2211`, COLMI_SMART_HEALTH) the reporter read all 304 hourly `05 18` + * composite records out of the ring's memory and the same heart rate always came with the same SpO₂, + * without one exception: HR 48 → 88, 57 → 94, 67–92 → 98, 105 → 96, never 99. That is a fixed + * function of heart rate, not a second sensor, and the night "dips" were just a low sleeping heart + * rate. A spot SpO₂ on the same ring is a real measurement (red LED, values up to 99), and the ring + * logs it in the same `05 18` block with heart rate and respiration both 0. + * + * **Detected from the data, not from the family.** A capability list is a static per-family + * constant and says nothing about an individual ring (issue #67); another ring in the family may well + * measure hourly SpO₂ for real, and calling that "estimated" would be a false statement about the + * user's hardware. So the verdict is earned per ring, from what it actually logged. + * + * ## What is stored, and why the rule has this shape + * + * `YCBTHealthRecords.combinedVitals` writes a `05 18` record's SpO₂ (offset 9) and respiratory rate + * (offset 10) as two history rows with the record's own timestamp. It does **not** store the record's + * heart rate (offset 6) — HR history comes from `05 15`, at that log's own timestamps. Hence: + * + * - **Hourly vs spot** is decided by the respiratory row: an SpO₂ history row with a respiratory + * history row at the *identical* timestamp came from a composite record that carried more than + * SpO₂. A spot record logs respiration 0, which the decoder never stores, so a spot reading can + * never qualify — not by threshold, by construction. + * - **"A function of heart rate"** is tested by pairing each hourly row with the nearest HR history + * row within [PAIR_WINDOW_MS], and asking whether any heart rate ever came with two different SpO₂ + * values. A real oximeter, sampled at the same heart rate twice, disagrees with itself sooner or + * later; this ring never did across 304 records, so the test allows no exceptions. + * + * Nothing is labelled until the evidence is there, for the same reason derived stress refuses to + * score below its baseline: an unearned label on a health screen is a claim about the hardware. + */ +object EstimatedSpo2 { + + /** + * How far an HR history row may sit from an hourly SpO₂ row and still be the same measurement. + * The `05 18` records land ~35 s after the hour (the end of the ring's ~35 s HR measurement), and + * the ring runs one measurement at a time, so a neighbour inside two minutes is that measurement. + */ + const val PAIR_WINDOW_MS = 2 * 60_000L + + /** A day of hourly records — fewer, and a constant-looking stretch is a coincidence. */ + const val MIN_PAIRS = 24 + + /** + * Pairs whose heart rate had already been seen. These are the only pairs that *test* the + * mapping; a heart rate seen once is trivially consistent with itself. + */ + const val MIN_REPEATS = 12 + + /** How much history the verdict is drawn from: wider than a chart's 24 h, so one quiet day + * doesn't decide it, and bounded so a previously paired ring ages out of it. */ + const val LOOKBACK_MS = 7 * 86_400_000L + + /** One row reduced to what the rule reads. */ + data class Sample(val timestampMs: Long, val value: Double) + + /** + * The SpO₂ rows that came from an hourly composite record: those with a respiratory-rate row at + * the identical timestamp. Spot records (respiration 0) are excluded by construction. + */ + fun hourly(spo2: List, respiratoryTimestamps: Set): List = + spo2.filter { it.timestampMs in respiratoryTimestamps } + + /** + * Each hourly row paired with the nearest heart-rate sample within [PAIR_WINDOW_MS], as + * (heart rate, SpO₂) whole numbers. Rows with no heart rate close enough are left out. + */ + fun pairs(hourly: List, heartRate: List): List> { + if (hourly.isEmpty() || heartRate.isEmpty()) return emptyList() + val hr = heartRate.sortedBy { it.timestampMs } + val times = hr.map { it.timestampMs } + return hourly.mapNotNull { s -> + val at = times.binarySearch(s.timestampMs).let { if (it >= 0) it else -it - 1 } + val nearest = listOfNotNull(hr.getOrNull(at - 1), hr.getOrNull(at)) + .minByOrNull { kotlin.math.abs(it.timestampMs - s.timestampMs) } + ?.takeIf { kotlin.math.abs(it.timestampMs - s.timestampMs) <= PAIR_WINDOW_MS } + ?: return@mapNotNull null + nearest.value.toInt() to s.value.toInt() + } + } + + /** + * Whether [pairs] (heart rate, SpO₂) show SpO₂ as a fixed function of heart rate. + * + * Requires enough pairs, enough repeated heart rates to actually test the mapping, more than one + * SpO₂ value (a constant reading is a function of anything, and says nothing about where it came + * from), and no heart rate ever paired with two different SpO₂ values. + */ + fun derivesFromHeartRate(pairs: List>): Boolean { + if (pairs.size < MIN_PAIRS) return false + val byHr = pairs.groupBy({ it.first }, { it.second }) + if (pairs.size - byHr.size < MIN_REPEATS) return false + if (pairs.map { it.second }.distinct().size < 2) return false + return byHr.values.all { it.distinct().size == 1 } + } + + /** + * The timestamps of the [spo2] rows to label as estimated: the hourly ones, and only when the + * hourly rows in [evidence] (with [evidenceHeartRate]) show the ring deriving them from heart rate. + */ + fun estimated( + spo2: List, + respiratoryTimestamps: Set, + evidence: List, + evidenceRespiratoryTimestamps: Set, + evidenceHeartRate: List, + ): Set { + val evidencePairs = pairs(hourly(evidence, evidenceRespiratoryTimestamps), evidenceHeartRate) + if (!derivesFromHeartRate(evidencePairs)) return emptySet() + return hourly(spo2, respiratoryTimestamps).mapTo(mutableSetOf()) { it.timestampMs } + } + + /** + * [estimated] over Room: the SpO₂ history rows in [from]..[to] that this ring computed from heart + * rate, judged on the last [LOOKBACK_MS] of its history. Reads only — nothing stored is changed. + */ + suspend fun estimatedTimestamps( + dao: MeasurementDao, + from: Long, + to: Long, + now: Long = System.currentTimeMillis(), + ): Set { + val spo2 = dao.range(MeasurementKind.SPO2.name, from, to).historySamples() + if (spo2.isEmpty()) return emptySet() + val since = now - LOOKBACK_MS + val evidence = dao.range(MeasurementKind.SPO2.name, since, now).historySamples() + val respiratory = dao.timestampsBySource(MeasurementKind.RESPIRATORY_RATE.name, HISTORY_SOURCE, minOf(from, since)) + .toSet() + val heartRate = dao.range(MeasurementKind.HEART_RATE.name, since - PAIR_WINDOW_MS, now + PAIR_WINDOW_MS) + .historySamples() + return estimated(spo2, respiratory, evidence, respiratory, heartRate) + } + + /** The ring's own log only: a live or spot row is the app's reading, never a composite record. */ + private const val HISTORY_SOURCE = "history" + + private fun List.historySamples(): List = + filter { it.sourceRaw == HISTORY_SOURCE }.map { Sample(it.timestamp, it.value) } +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index abeded13..95d99906 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -187,6 +187,12 @@ fun VitalsScreen( referenceBands = c.referenceBands, dashedRules = c.dashedRules, showPoints = true, ) + // Issue #103: the card's ESTIMATED chip says *that*; this says what, and that a + // spot reading is still a measurement. Same wording and treatment as the derived + // stress footnote (issue #67). + if (state.spo2IsEstimated) { + Text(tr(ESTIMATED_SPO2_NOTE), fontSize = 12.sp, color = PulseColors.warning) + } } else { Text(tr("No SpO₂ samples yet — take a reading to start your trend."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } @@ -1180,17 +1186,26 @@ private fun zoneRangeText( } } +/** Issue #103: the SpO₂ card's footnote, shared with the detail disclaimer so they never drift. */ +private const val ESTIMATED_SPO2_NOTE = + "Hourly readings are estimated from heart rate — this ring's hourly SpO₂ isn't a separate " + + "measurement. Spot readings you take are measured." + /** * Warning-card copy for estimated metrics (iOS `disclaimerText`); null hides the card. * * [isDerived] is the issue #67 case: a stress chart computed from HRV because the ring reports no * stress at all. It gets the card for the same reason BP and glucose do — the number on screen is - * an inference, and the user is entitled to know that without leaving the chart. + * an inference, and the user is entitled to know that without leaving the chart. For SpO₂ it is + * issue #103: hourly readings this ring computes from heart rate rather than measures. */ private fun metricDisclaimer(metric: String, isDerived: Boolean): String? = when { metric == "stress" && isDerived -> tr("Estimated from HRV — your ring doesn't measure stress. Scored against your own recent " + "HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.") + metric == "spo2" && isDerived -> + tr(ESTIMATED_SPO2_NOTE + " On this ring the same heart rate always comes with the same hourly " + + "SpO₂, so a night-time dip here follows a low sleeping heart rate rather than measuring oxygen.") metric == "glucose" -> tr("Estimated wellness metric — not for dosing or diabetes decisions. No smart ring or watch is " + "FDA-authorized to measure or estimate glucose on its own.") diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index 1b492b88..c308d75b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -486,6 +486,13 @@ private fun ChartTile(card: VitalCardState, values: List, modifier: Modi ) } } + // Issue #103: hourly SpO₂ computed from heart rate is labelled on every surface it reaches. + if (card.isEstimated) { + Text( + tr("Estimated from heart rate"), fontSize = 12.sp, color = PulseColors.warning, + maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + } Spacer(Modifier.weight(1f)) if (card.isEmpty) { Text(card.statusText, fontSize = 12.sp, color = PulseColors.textMuted) diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 9d52e7d6..38b45454 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -17,6 +17,7 @@ import com.pulseloop.ring.* import com.pulseloop.coach.summaries.CoachSummaryKind import com.pulseloop.service.DailyCalorieEstimator import com.pulseloop.service.DerivedStress +import com.pulseloop.service.EstimatedSpo2 import com.pulseloop.service.HeartRateZones import com.pulseloop.service.SleepCoach import com.pulseloop.service.SleepInsights @@ -668,6 +669,9 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore val usualRanges: Map> = emptyMap(), val hrSamples: List = emptyList(), val spo2Samples: List = emptyList(), + /** The 24 h SpO₂ series holds hourly readings this ring computed from heart rate rather than + * measured (issue #103). Never shown unlabelled. Spot readings never set it. */ + val spo2IsEstimated: Boolean = false, val hrvSamples: List = emptyList(), val stressSamples: List = emptyList(), /** The stress series came from HRV, not from the ring (issue #67). Never shown unlabelled. */ @@ -829,6 +833,12 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore val derivedStressSeries = derived.map { (i, score) -> VitalSample(hrv[i].timestamp, score.toDouble()) } val derivedStress = derivedStressSeries.map { it.value } + // Issue #103: a ring whose hourly SpO₂ is a fixed function of its heart rate presents that + // as a measurement unless we say otherwise. Judged from this ring's own history (not its + // family), and only hourly composite rows qualify — a spot reading is a real measurement. + val spo2Estimated = if (spo2.isEmpty()) emptySet() + else EstimatedSpo2.estimatedTimestamps(db.measurementDao(), twentyFourHoursAgo, now, now) + // Temperature on the Colmi family is the same static-capability trap as stress above: // every Colmi model is catalogued with TEMPERATURE, but some have no sensor. An R06 // (`R06_1.00.06_240921`) never answers the legacy temperature request and doesn't set the @@ -855,6 +865,7 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore usualRanges = usualRanges, hrSamples = hr.map { it.value }, spo2Samples = spo2.map { it.value }, + spo2IsEstimated = spo2.any { it.timestamp in spo2Estimated }, hrvSamples = hrv.map { it.value }, stressSamples = stress.map { it.value }.ifEmpty { derivedStress }, stressIsDerived = stress.isEmpty() && derivedStress.isNotEmpty(), @@ -960,6 +971,7 @@ fun VitalsViewModel.VitalsState.toCardInputs(units: UnitSystem): VitalsCardFacto glucose = glucoseSeries, latestHr = latestHr?.toDouble(), latestSpo2 = latestSpo2?.toDouble(), + spo2Estimated = spo2IsEstimated, restingHr = restingHr, peakHr = peakHr, unitSystem = units, @@ -1251,7 +1263,8 @@ class VitalDetailViewModel( * (issue #60). Demo/seeded rows are included: a user clearing seeded noise out of a * chart is the same gesture as removing a bad measurement. */ val readings: List = emptyList(), - /** This chart is derived rather than measured (issue #67) — carried so the screen says so. + /** This chart is derived rather than measured (issue #67; hourly SpO₂ computed from heart + * rate, issue #103) — carried so the screen says so. * A derived figure shown as a measurement would be worse than the empty chart it replaces, * which is why it travels with the data instead of being re-inferred at the display layer. */ val isDerived: Boolean = false, @@ -1467,6 +1480,10 @@ class VitalDetailViewModel( // has never returned a stress reading at all, never blended with hardware values. val derived = if (kind == MeasurementKind.STRESS && samples.isEmpty() && !dao.hasReal(kindName)) derivedStressIn(windowStart, windowEnd) else emptyList() + // Issue #103: the hourly SpO₂ the card labels as estimated is charted here too, so the + // chart carries the same disclaimer. Only hourly rows count; spot readings never do. + val estimatedSpo2 = if (kind == MeasurementKind.SPO2 && samples.isNotEmpty()) + EstimatedSpo2.estimatedTimestamps(dao, windowStart, windowEnd) else emptySet() val times = if (derived.isNotEmpty()) derived.map { it.timestampMs } else samples.map { it.timestamp } val points = if (derived.isNotEmpty()) derived.map { it.value } else samples.map { convert(it.value) } val labels = buildLabels(times, period) @@ -1527,7 +1544,7 @@ class VitalDetailViewModel( resting = resting, trend = trend, engineZones = engineZones, - isDerived = derived.isNotEmpty(), + isDerived = derived.isNotEmpty() || samples.any { it.timestamp in estimatedSpo2 }, usualRange = usualRange, adjustedNote = when (kind) { MeasurementKind.HEART_RATE -> corrections.describe(setOf( diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt index a7bb0ed0..e167dcc0 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/VitalCardState.kt @@ -178,6 +178,8 @@ object VitalsCardFactory { /** Fallback latest values when the 24h window is empty but a reading exists (iOS TodaySummary). */ val latestHr: Double? = null, val latestSpo2: Double? = null, + /** The SpO₂ series includes hourly readings computed from heart rate (issue #103). */ + val spo2Estimated: Boolean = false, /** Resting/peak HR estimates for the HR subtitle (iOS TodaySummary fields). */ val restingHr: Double? = null, val peakHr: Double? = null, @@ -252,7 +254,7 @@ object VitalsCardFactory { referenceBands = usualBand(MetricKind.SPO2, inputs) ?: listOf(ReferenceBand(95.0, 100.0, VitalColorToken.Cyan)), dashedRules = listOf(92.0), trend = TrendSummary.compute(samples, MetricKind.SPO2, unitLabel = "%"), - sourceQuality = quality, isEstimated = false, confidenceLabel = null, + sourceQuality = quality, isEstimated = inputs.spo2Estimated, confidenceLabel = null, lastUpdatedText = lastUpdated(samples.lastOrNull()?.timestampMs, inputs.nowMs), isEmpty = samples.size < 2, ) diff --git a/app/src/test/java/com/pulseloop/service/EstimatedSpo2Test.kt b/app/src/test/java/com/pulseloop/service/EstimatedSpo2Test.kt new file mode 100644 index 00000000..8cdee541 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/EstimatedSpo2Test.kt @@ -0,0 +1,143 @@ +package com.pulseloop.service + +import com.pulseloop.service.EstimatedSpo2.Sample +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Issue #103: hourly SpO₂ that a YCBT ring computes from heart rate is labelled as estimated. */ +class EstimatedSpo2Test { + + private val hour = 3_600_000L + private val start = 1_757_000_000_000L + + /** The reporter's mapping, read off 304 `05 18` records: HR 48 → 88, 57 → 94, 67–92 → 98, 105 → 96. */ + private fun ringSpo2(hr: Int): Int = when { + hr <= 48 -> 88 + hr <= 57 -> 94 + hr <= 92 -> 98 + else -> 96 + } + + private val heartRates = listOf(48, 57, 67, 75, 82, 92, 105, 70) + + /** [hours] hourly composite records, each logged ~34 s past the hour (the end of the ring's HR run). */ + private fun hourlyTimes(hours: Int) = (0 until hours).map { start + it * hour + 34_000L } + + private data class Ring(val spo2: List, val respiratory: Set, val hr: List) + + private fun ring(hours: Int, spo2For: (index: Int, hr: Int) -> Int = { _, hr -> ringSpo2(hr) }): Ring { + val times = hourlyTimes(hours) + val hrs = times.indices.map { heartRates[it % heartRates.size] } + return Ring( + spo2 = times.mapIndexed { i, t -> Sample(t, spo2For(i, hrs[i]).toDouble()) }, + respiratory = times.toSet(), + // `05 15` logs the same hourly HR run; give it a few seconds' skew to prove pairing is + // by proximity, not by identical timestamps. + hr = times.mapIndexed { i, t -> Sample(t - 5_000L, hrs[i].toDouble()) }, + ) + } + + private fun estimated(r: Ring, spo2: List = r.spo2, hr: List = r.hr): Set = + EstimatedSpo2.estimated(spo2, r.respiratory, spo2, r.respiratory, hr) + + @Test + fun `hourly SpO2 that is a fixed function of heart rate is labelled estimated`() { + val r = ring(hours = 48) + assertEquals(r.spo2.map { it.timestampMs }.toSet(), estimated(r)) + } + + @Test + fun `a spot reading is never labelled, even beside an hourly HR row`() { + val r = ring(hours = 48) + // Spot SpO₂ logged in `05 18` with HR and respiration 0: an SpO₂ row and no respiratory row. + // Put it 90 s after an hourly HR row, inside the pairing window, to show the respiratory + // sibling — not HR proximity — is what decides hourly vs spot. + val spot = Sample(start + 10 * hour + 124_000L, 99.0) + val labelled = estimated(r, spo2 = r.spo2 + spot) + + assertFalse(spot.timestampMs in labelled) + assertEquals(r.spo2.size, labelled.size) + } + + @Test + fun `a real oximeter disagreeing with itself at one heart rate labels nothing`() { + // Same hourly structure, but SpO₂ varies independently of heart rate as a sensor would. + val r = ring(hours = 48) { i, _ -> listOf(97, 98, 99, 96, 98)[i % 5] } + assertTrue(estimated(r).isEmpty()) + } + + @Test + fun `a single exception to the mapping is enough to withhold the label`() { + val r = ring(hours = 48) { i, hr -> if (i == 40) ringSpo2(hr) - 1 else ringSpo2(hr) } + assertTrue(estimated(r).isEmpty()) + } + + @Test + fun `too little history earns no verdict`() { + val r = ring(hours = EstimatedSpo2.MIN_PAIRS - 1) + assertTrue(estimated(r).isEmpty()) + } + + @Test + fun `a constant reading says nothing about where it came from`() { + val r = ring(hours = 48) { _, _ -> 98 } + assertTrue(estimated(r).isEmpty()) + } + + @Test + fun `heart rates that never repeat cannot test the mapping`() { + val times = hourlyTimes(30) + val hrs = times.indices.map { 45 + it * 2 } // 30 distinct heart rates + val spo2 = times.mapIndexed { i, t -> Sample(t, ringSpo2(hrs[i]).toDouble()) } + val hr = times.mapIndexed { i, t -> Sample(t, hrs[i].toDouble()) } + val respiratory = times.toSet() + + assertFalse(EstimatedSpo2.derivesFromHeartRate(EstimatedSpo2.pairs(spo2, hr))) + assertTrue(EstimatedSpo2.estimated(spo2, respiratory, spo2, respiratory, hr).isEmpty()) + } + + @Test + fun `without heart rate history there is nothing to pair and nothing is labelled`() { + val r = ring(hours = 48) + assertTrue(estimated(r, hr = emptyList()).isEmpty()) + } + + @Test + fun `pairing takes the nearest heart rate and ignores one outside the window`() { + val at = start + 34_000L + val hourly = listOf(Sample(at, 94.0)) + val hr = listOf( + Sample(at - 90_000L, 70.0), + Sample(at + 20_000L, 57.0), + Sample(at + EstimatedSpo2.PAIR_WINDOW_MS + 60_000L, 48.0), + ) + assertEquals(listOf(57 to 94), EstimatedSpo2.pairs(hourly, hr)) + assertTrue(EstimatedSpo2.pairs(hourly, listOf(Sample(at + EstimatedSpo2.PAIR_WINDOW_MS + 1, 57.0))).isEmpty()) + } + + @Test + fun `only rows with a respiratory sibling at the identical timestamp are hourly`() { + val a = Sample(start, 98.0) + val b = Sample(start + hour, 99.0) + assertEquals(listOf(a), EstimatedSpo2.hourly(listOf(a, b), setOf(start, start + hour + 1))) + } + + @Test + fun `labels rows outside the evidence window once the ring is judged`() { + val r = ring(hours = 48) + // A month-view chart: an older hourly row the 7-day evidence doesn't include still gets the + // label, because the verdict is about the ring, and a spot row beside it still doesn't. + val oldHourly = Sample(start - 10 * 86_400_000L, 94.0) + val oldSpot = Sample(start - 10 * 86_400_000L + 600_000L, 99.0) + val labelled = EstimatedSpo2.estimated( + spo2 = listOf(oldHourly, oldSpot), + respiratoryTimestamps = setOf(oldHourly.timestampMs), + evidence = r.spo2, + evidenceRespiratoryTimestamps = r.respiratory, + evidenceHeartRate = r.hr, + ) + assertEquals(setOf(oldHourly.timestampMs), labelled) + } +} From 0390a9ae9177ae88cfa39d471d3bc3e27f0cce90 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:31:40 +0000 Subject: [PATCH 2/7] Port upstream #125: CRP reconnect retry after teardown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ported from foureight84/PulseLoopAndroid#125 (a563c58). Adds CRPReconnect (the vendor's 3 s retry after a disconnect), CRPTeardownGate and the process-wide CRPTeardownMonitor, so a CRP reconnect waits for the previous link's physical teardown (or the old handle's close when the link is already down) before reopening GATT, falls back to a fresh-advertisement scan that carries the caller's connect parameters, and stops for a forgotten ring. RECONNECTING is shown as "Reconnecting…" and offers Disconnect in the hero card and Wearable settings. Adapted to this fork: the reconnect-budget branch keeps our IdleLinkPolicy cool-down after ending a spent CRP recovery, the watchdog keeps the idle rest ahead of the new RECONNECTING arm, and the UI strings and the new Disconnect button go through tr() and PulseButton. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../java/com/pulseloop/ring/CRPReconnect.kt | 66 ++++ .../com/pulseloop/ring/CRPTeardownGate.kt | 90 +++++ .../com/pulseloop/ring/CRPTeardownMonitor.kt | 106 ++++++ .../java/com/pulseloop/ring/RingBLEClient.kt | 317 ++++++++++++++++-- .../java/com/pulseloop/ui/PulseLoopApp.kt | 2 +- .../com/pulseloop/ui/components/AppChrome.kt | 3 +- .../pulseloop/ui/components/DeviceHeroCard.kt | 13 +- .../ui/components/DeviceHeroStatus.kt | 16 +- .../ui/screens/SettingsSubScreens.kt | 15 +- .../com/pulseloop/ring/CRPReconnectTest.kt | 140 ++++++++ .../com/pulseloop/ring/CRPTeardownGateTest.kt | 220 ++++++++++++ .../ui/components/DeviceHeroStatusTest.kt | 21 +- 12 files changed, 957 insertions(+), 52 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ring/CRPReconnect.kt create mode 100644 app/src/main/java/com/pulseloop/ring/CRPTeardownGate.kt create mode 100644 app/src/main/java/com/pulseloop/ring/CRPTeardownMonitor.kt create mode 100644 app/src/test/java/com/pulseloop/ring/CRPReconnectTest.kt create mode 100644 app/src/test/java/com/pulseloop/ring/CRPTeardownGateTest.kt diff --git a/app/src/main/java/com/pulseloop/ring/CRPReconnect.kt b/app/src/main/java/com/pulseloop/ring/CRPReconnect.kt new file mode 100644 index 00000000..e438b6dc --- /dev/null +++ b/app/src/main/java/com/pulseloop/ring/CRPReconnect.kt @@ -0,0 +1,66 @@ +package com.pulseloop.ring + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** + * Da Rings retries three seconds after a disconnect (`o3/l.o` in the Android decompile). + * Keep this separate from the 15-second liveness watchdog: a five-second Android connection + * timeout otherwise leaves the user waiting another ten seconds before recovery even starts. + * + * GATT callbacks and lifecycle actions may arrive on different threads. The epoch and monitor + * make cancellation invalidate even a timer that has finished its delay and is waiting to run. + * Callbacks run under that monitor, so cancellation cannot return ahead of a stale retry. + */ +internal class CRPReconnect( + private val scope: CoroutineScope, + private val canRetry: () -> Boolean, + private val onPending: () -> Unit, + private val onRetry: () -> Unit, + private val onAbandoned: () -> Unit, +) { + private val lock = Any() + private var epoch = 0L + private var timer: Job? = null + private var recovering = false + + val isPending: Boolean get() = synchronized(lock) { timer != null } + /** Remains true during a recovery scan, until success, cancellation, or exhausted retries. */ + val isRecovering: Boolean get() = synchronized(lock) { recovering } + + fun schedule(): Boolean = synchronized(lock) { + if (timer != null || !canRetry()) return false + recovering = true + val generation = ++epoch + val job = scope.launch(start = CoroutineStart.LAZY) { + delay(3_000L) + synchronized(lock) { + if (generation != epoch) return@synchronized + timer = null + if (canRetry()) onRetry() else { + recovering = false + onAbandoned() + } + } + } + timer = job + onPending() + job.start() + true + } + + /** A new attempt supersedes the timer but still belongs to the current recovery. */ + fun cancelPending() = synchronized(lock) { + epoch++ + timer?.cancel() + timer = null + } + + fun cancel() = synchronized(lock) { + cancelPending() + recovering = false + } +} diff --git a/app/src/main/java/com/pulseloop/ring/CRPTeardownGate.kt b/app/src/main/java/com/pulseloop/ring/CRPTeardownGate.kt new file mode 100644 index 00000000..68e6cd4f --- /dev/null +++ b/app/src/main/java/com/pulseloop/ring/CRPTeardownGate.kt @@ -0,0 +1,90 @@ +package com.pulseloop.ring + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.withTimeoutOrNull + +/** Physical teardown outlives both the GATT disconnected callback and a worker-owned client. */ +internal class CRPTeardownGate( + private val nowNanos: () -> Long, + private val timeoutMs: Long = 5_000L, +) { + internal class Ticket(val address: String) { + val ready = CompletableDeferred() + var closedAtNanos: Long? = null + var disconnected = false + var scanAfterNanos: Long? = null + } + + private val lock = Any() + private val pending = mutableMapOf() + + fun begin(address: String): Ticket = synchronized(lock) { + // An older close completion must never release a newer teardown for the same ring. + pending.remove(address)?.ready?.complete(false) + Ticket(address).also { pending[address] = it } + } + + fun isPending(address: String): Boolean = synchronized(lock) { address in pending } + + fun gattClosed(ticket: Ticket) = synchronized(lock) { + if (pending[ticket.address] !== ticket) return@synchronized + ticket.closedAtNanos = nowNanos() + finishIfReady(ticket) + } + + fun aclDisconnected(address: String) = synchronized(lock) { + pending[address]?.let { + it.disconnected = true + finishIfReady(it) + } + } + + /** + * The OS already reported no physical link when this teardown began (a watchdog or hung + * CONNECTING reconnect), so no ACL_DISCONNECTED broadcast will follow. Only the GATT close + * remains to wait for. A stale ticket cannot release a newer teardown. + */ + fun linkAlreadyDown(ticket: Ticket) = synchronized(lock) { + if (pending[ticket.address] !== ticket) return@synchronized + ticket.disconnected = true + finishIfReady(ticket) + } + + fun bluetoothOff() = synchronized(lock) { + pending.values.toList().forEach { + it.disconnected = true + finishIfReady(it) + } + } + + /** False means require a fresh scan, never blindly reuse the old link on timeout. */ + suspend fun await(address: String): Boolean { + val ticket = synchronized(lock) { pending[address] } ?: return true + if (synchronized(lock) { ticket.scanAfterNanos != null }) return false + val ready = withTimeoutOrNull(timeoutMs) { ticket.ready.await() } + if (ready != null) return ready + return synchronized(lock) { + if (pending[address] !== ticket) return@synchronized !pending.containsKey(address) + ticket.scanAfterNanos = nowNanos() + false + } + } + + /** Only a post-timeout, freshly observed advertisement can substitute for a missed broadcast. */ + fun freshAdvertisement(address: String, timestampNanos: Long): Boolean = synchronized(lock) { + val ticket = pending[address] ?: return true + val after = ticket.scanAfterNanos ?: return false + val closed = ticket.closedAtNanos ?: return false + if (timestampNanos <= maxOf(after, closed)) return false + pending.remove(address) + ticket.ready.complete(true) + true + } + + private fun finishIfReady(ticket: Ticket) { + if (ticket.closedAtNanos != null && ticket.disconnected) { + pending.remove(ticket.address) + ticket.ready.complete(true) + } + } +} diff --git a/app/src/main/java/com/pulseloop/ring/CRPTeardownMonitor.kt b/app/src/main/java/com/pulseloop/ring/CRPTeardownMonitor.kt new file mode 100644 index 00000000..fe09e1c2 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ring/CRPTeardownMonitor.kt @@ -0,0 +1,106 @@ +package com.pulseloop.ring + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.SystemClock +import android.util.Log +import androidx.core.content.ContextCompat +import androidx.core.content.IntentCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch + +/** + * One monitor per process, using only the application context. A worker can finish while its + * physical link is still disconnecting; a new foreground client must observe the same gate. + * The receiver intentionally lives for the process, including while no client is connecting. + */ +@SuppressLint("MissingPermission") +internal class CRPTeardownMonitor private constructor(context: Context) { + val gate = CRPTeardownGate(SystemClock::elapsedRealtimeNanos) + private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) + private val bluetoothManager: BluetoothManager? = + context.applicationContext.getSystemService(BluetoothManager::class.java) + + init { + val receiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + when (intent.action) { + BluetoothDevice.ACTION_ACL_DISCONNECTED -> { + // Older Android releases may omit EXTRA_TRANSPORT. CRP rings are LE-only. + if (intent.getIntExtra(BluetoothDevice.EXTRA_TRANSPORT, + BluetoothDevice.TRANSPORT_LE) != BluetoothDevice.TRANSPORT_LE) return + // IntentCompat gates the typed overload on API 34: it is buggy on 33. + val device = IntentCompat.getParcelableExtra( + intent, BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java, + ) ?: return + if (gate.isPending(device.address)) { + Log.i("RingBLEClient", "CRP physical disconnect confirmed") + gate.aclDisconnected(device.address) + } + } + BluetoothAdapter.ACTION_STATE_CHANGED -> { + if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) { + gate.bluetoothOff() + } + } + } + } + } + // Bluetooth broadcasts originate in a privileged process outside the system UID. + // These are protected system actions; NOT_EXPORTED can silently miss their delivery. + try { + ContextCompat.registerReceiver( + context.applicationContext, receiver, + IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED).apply { + addAction(BluetoothAdapter.ACTION_STATE_CHANGED) + }, + ContextCompat.RECEIVER_EXPORTED, + ) + } catch (e: Exception) { + Log.w("RingBLEClient", "CRP ACL receiver unavailable; will require fresh advertisement", e) + } + } + + /** Register the wait before disconnecting, and close even if the owning client's scope dies. */ + fun disconnect(gatt: BluetoothGatt, close: () -> Unit) { + // Open the ticket before probing so a broadcast racing the probe is still recorded. + val ticket = gate.begin(gatt.device.address) + if (!linkPhysicallyUp(gatt.device)) { + Log.i("RingBLEClient", "CRP link already down; waiting only for GATT close") + gate.linkAlreadyDown(ticket) + } + try { gatt.disconnect() } catch (_: Exception) {} + scope.launch { + delay(500L) + try { close() } finally { gate.gattClosed(ticket) } + } + } + + /** Unknown (no manager, missing permission) counts as up: wait for the broadcast. */ + private fun linkPhysicallyUp(device: BluetoothDevice): Boolean = try { + bluetoothManager?.getConnectionState(device, BluetoothProfile.GATT) + ?.let { it == BluetoothProfile.STATE_CONNECTED || it == BluetoothProfile.STATE_DISCONNECTING } + ?: true + } catch (_: Exception) { + true + } + + companion object { + @Volatile private var instance: CRPTeardownMonitor? = null + fun current(): CRPTeardownMonitor? = instance + fun get(context: Context): CRPTeardownMonitor = instance ?: synchronized(this) { + instance ?: CRPTeardownMonitor(context.applicationContext).also { instance = it } + } + } +} diff --git a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt index 51a1506c..f04e95e9 100644 --- a/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt +++ b/app/src/main/java/com/pulseloop/ring/RingBLEClient.kt @@ -211,6 +211,45 @@ class RingBLEClient( private var watchdogJob: Job? = null private var ownershipRetryJob: Job? = null @Volatile private var watchdogReconnectPaused = false + @Volatile private var teardownWaitJob: Job? = null + private var teardownWaitAddress: String? = null + @Volatile private var teardownScanAddress: String? = null + /** The queued teardown wait/scan came from an explicit pairing [connectTo], not recovery. */ + @Volatile private var teardownUserInitiated = false + /** The caller's connect parameters, carried through a teardown fallback scan so a pairing + * that honoured the carousel over a generic "SMART_RING" match (#29) is not rescanned as + * JRING. Null when no fallback scan is pending. */ + private data class TeardownConnect( + val deviceType: RingDeviceType?, + val selectedModelID: String?, + val scanDetectedType: RingDeviceType?, + ) + @Volatile private var teardownScanConnect: TeardownConnect? = null + private val teardownWaitEpoch = java.util.concurrent.atomic.AtomicLong() + + private val crpReconnect = CRPReconnect( + scope = scope, + canRetry = { + activeCoordinator?.deviceType == RingDeviceType.CRP && + lastKnownIdentifier != null && !watchdogReconnectPaused && + !prefs.getBoolean(USER_DISCONNECTED_KEY, false) && + !synchronized(forgetLock) { forgetPending || forgetFinalizing } && + bluetoothAdapter.isEnabled && hasPermissions() && + reconnectAttempts < MAX_RECONNECT_ATTEMPTS && + _state.value.connectionState !in setOf( + RingConnectionState.CONNECTED, RingConnectionState.CONNECTING, + ) + }, + onPending = { + recordDiagnostic("CRP reconnect scheduled in 3000ms") + updateState { copy(connectionState = RingConnectionState.RECONNECTING) } + PulseEventBus.publishBlocking( + PulseEvent.DeviceStateChanged(RingConnectionState.RECONNECTING, lastKnownIdentifier) + ) + }, + onRetry = { connectLastKnownInternal() }, + onAbandoned = { finishCrpRecovery() }, + ) // MARK: Idle drops (see IdleLinkPolicy) // @@ -266,6 +305,13 @@ class RingBLEClient( } fun startScanning() { + // A pairing scan supersedes automatic recovery. Recovery's own scans use the private + // entry point so their pending presentation survives until the ring is found. + finishCrpRecovery() + startScanningInternal() + } + + private fun startScanningInternal() { if (!hasPermissions()) { updateState { copy(lastError = "BLE permissions not granted") } return @@ -279,7 +325,9 @@ class RingBLEClient( reconnectScanPending = false updateState { copy( - connectionState = RingConnectionState.SCANNING, + connectionState = if (crpReconnect.isRecovering || teardownScanAddress != null) + RingConnectionState.RECONNECTING + else RingConnectionState.SCANNING, discovered = emptyList(), lastError = null, ) @@ -293,9 +341,11 @@ class RingBLEClient( } fun stopScanning() { + finishCrpRecovery() reconnectScanPending = false scanner?.stopScan(scanCallback) - if (_state.value.connectionState == RingConnectionState.SCANNING) { + if (_state.value.connectionState in setOf( + RingConnectionState.SCANNING, RingConnectionState.RECONNECTING)) { updateState { copy(connectionState = RingConnectionState.IDLE) } } } @@ -341,6 +391,7 @@ class RingBLEClient( else discoveredRing?.wearableModelID ?: selectedModelID, advertisedName = discoveredRing?.name ?: target.name, scanDetectedType = detectedType, + userInitiated = true, ) } @@ -370,6 +421,9 @@ class RingBLEClient( } private fun connectLastKnownInternal() { + // A callback-driven CRP retry owns the next attempt until its timer fires. + if (crpReconnect.isPending) return + if (teardownWaitJob?.isActive == true) return if (!bluetoothAdapter.isEnabled) return // Honor a user-initiated Disconnect: stay off until the user reconnects ([userConnect]) // or pairs a new ring ([connectTo]). Every auto-reconnect path — foreground @@ -378,6 +432,9 @@ class RingBLEClient( if (prefs.getBoolean(USER_DISCONNECTED_KEY, false)) return val lastId = lastKnownIdentifier ?: return if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) { + // A CRP recovery that spent the budget ends here (upstream #125); the cool-down + // below is what may start a fresh round later. + if (crpReconnect.isRecovering || teardownScanAddress != null) finishCrpRecovery() // The cap stops back-to-back churn; it must not strand the ring offline until the // user happens to reopen the app. After a cool-down, unattended retries resume. val now = System.currentTimeMillis() @@ -403,7 +460,7 @@ class RingBLEClient( bluetoothAdapter.getRemoteDevice(lastId) } catch (_: Exception) { null } if (device == null) { - startScanning() + startScanningInternal() return } if (reconnectAttempts % 3 == 1) { @@ -414,14 +471,16 @@ class RingBLEClient( advertisedName = try { device.name } catch (_: Exception) { null }, ) } else { - startScanning() - // Set AFTER startScanning (which clears it to protect pairing scans). + startScanningInternal() + // Set AFTER startScanningInternal (which clears it to protect pairing scans). reconnectScanPending = true } } /** Clear the reconnect throttling — called on user action and app foreground. */ private fun resetReconnectBackoff() { + crpReconnect.cancel() + cancelTeardownConnect() reconnectAttempts = 0 budgetExhaustedAt = 0L sightlessScans = 0 @@ -437,6 +496,8 @@ class RingBLEClient( fun reconnectIfNeeded() { if (!bluetoothAdapter.isEnabled || !hasPermissions()) return val lastId = lastKnownIdentifier ?: return + // Foregrounding must not restart an already scheduled recovery or abandon its scan. + if (crpReconnect.isRecovering || teardownWaitJob?.isActive == true || teardownScanAddress != null) return // Fresh user attention = fresh retry budget (the cap exists to stop unattended // background churn, not to block a user actively waiting on the connection). resetReconnectBackoff() @@ -475,8 +536,15 @@ class RingBLEClient( } private fun connectionWatchdogTick() { - if (!bluetoothAdapter.isEnabled || !hasPermissions()) return + if (!bluetoothAdapter.isEnabled || !hasPermissions()) { + if (crpReconnect.isRecovering || teardownWaitJob != null || teardownScanAddress != null) { + finishCrpRecovery() + } + return + } if (watchdogReconnectPaused) return + if (crpReconnect.isPending) return + if (teardownWaitJob?.isActive == true) return // Time out a hung CONNECTING attempt FIRST — before the last-known-ring guard below — // so it also covers a first-ever pairing (no stored ring yet). The official QRing app // arms this timeout on every connect (mTimeoutRunnable). Without it, a first pair that @@ -494,7 +562,13 @@ class RingBLEClient( } return } - if (lastKnownIdentifier == null) return + if (lastKnownIdentifier == null) { + // Another client forgot the ring: stop this client's recovery scan, but leave an + // explicit pairing that is waiting out a teardown alone. + if (crpReconnect.isRecovering || + (teardownScanAddress != null && !teardownUserInitiated)) finishCrpRecovery() + return + } when (_state.value.connectionState) { RingConnectionState.CONNECTED -> { if (activeCoordinator?.deviceType == RingDeviceType.JRING) { @@ -528,6 +602,11 @@ class RingBLEClient( if (IdleLinkPolicy.isResting(idleRestUntil, System.currentTimeMillis())) return connectLastKnownInternal() } + RingConnectionState.RECONNECTING -> { + // The short timer handles failed attempts; this advances a recovery scan that + // found nothing for a whole watchdog interval, preserving the retry cap. + if (crpReconnect.isRecovering || teardownScanAddress != null) connectLastKnownInternal() + } // CONNECTING is handled above (before the last-known-ring guard). else -> { // SCANNING: a pairing scan proceeds untouched, but a reconnect scan that @@ -545,11 +624,13 @@ class RingBLEClient( } /** - * Abort a stalled connect attempt that has no stored ring to retry (a first pairing that - * hung). Tears the half-open GATT down and surfaces an error so the pairing UI leaves the - * "Connecting…" state instead of spinning forever. + * Abort an unusable connection setup and tear its half-open GATT down. A known CRP ring + * gets the vendor's delayed recovery even if no further disconnect callback arrives; + * first pairing and other families retain their existing failure behavior. */ private fun failConnectAttempt(reason: String) { + crpReconnect.cancel() + cancelTeardownConnect() val gatt = bluetoothGatt bluetoothGatt = null activeDriver?.connectionDidEnd() @@ -557,8 +638,11 @@ class RingBLEClient( subscriptionGate = null resetOpQueue() if (gatt != null) { - try { gatt.disconnect() } catch (_: Exception) {} - closeGattQuietly(gatt) + if (activeCoordinator?.deviceType == RingDeviceType.CRP) disconnectCrpGatt(gatt) + else { + try { gatt.disconnect() } catch (_: Exception) {} + closeGattQuietly(gatt) + } } releaseConnectionOwnership() connectingStartedAt = 0 @@ -566,6 +650,7 @@ class RingBLEClient( PulseEventBus.publishBlocking( PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) ) + scheduleCrpRecovery() } /** @@ -612,6 +697,9 @@ class RingBLEClient( // Lifecycle/worker teardown is intentional. Leave genuine link-loss callbacks eligible // for watchdog recovery, but do not let this client undo an explicit transient teardown. watchdogReconnectPaused = true + crpReconnect.cancel() + cancelTeardownConnect() + reconnectScanPending = false ownershipRetryJob?.cancel(); ownershipRetryJob = null val shouldPublishDisconnect = _state.value.connectionState != RingConnectionState.DISCONNECTED @@ -622,14 +710,16 @@ class RingBLEClient( activeDriver?.connectionDidEnd() writeChar = null; commandChar = null; notifyChars.clear(); batteryChar = null resetOpQueue() - if (gatt != null) { + if (gatt != null && activeCoordinator?.deviceType == RingDeviceType.CRP) { + disconnectCrpGatt(gatt) + } else if (gatt != null) { try { gatt.disconnect() } catch (_: Exception) {} // The official QRing app waits ~500 ms between disconnect() and close() so // the stack finishes the LL teardown before the client handle disappears. scope.launch { delay(GATT_CLOSE_DELAY_MS) closeGattQuietly(gatt) - releaseConnectionOwnership() + if (bluetoothGatt == null) releaseConnectionOwnership() } } else { releaseConnectionOwnership() @@ -683,6 +773,87 @@ class RingBLEClient( try { gatt.close() } catch (_: Exception) {} } + private fun disconnectCrpGatt(gatt: BluetoothGatt) { + recordDiagnostic("CRP physical teardown started") + CRPTeardownMonitor.get(context).disconnect(gatt) { + closeGattQuietly(gatt) + recordDiagnostic("CRP previous GATT closed") + // A close for the old ring must not release a newer connection's ownership. + if (bluetoothGatt == null) releaseConnectionOwnership() + } + } + + private fun cancelTeardownConnect() { + teardownWaitEpoch.incrementAndGet() + teardownWaitJob?.cancel() + teardownWaitJob = null + teardownWaitAddress = null + teardownScanAddress = null + teardownUserInitiated = false + teardownScanConnect = null + } + + /** + * Automatic recovery may only resume toward the ring that is still stored. Another client + * (the foreground one) can Forget while this one waits; its in-memory state is stale here, + * so re-read the shared prefs. An explicit pairing [connectTo] is exempt: its target is not + * stored until the connection succeeds. + */ + private fun teardownTargetStillWanted(address: String, userInitiated: Boolean): Boolean = + userInitiated || address == lastKnownIdentifier + + private fun waitForCrpTeardown( + monitor: CRPTeardownMonitor, + target: BluetoothDevice, + deviceType: RingDeviceType?, + selectedModelID: String?, + advertisedName: String?, + scanDetectedType: RingDeviceType?, + userInitiated: Boolean, + ) { + if (teardownWaitJob?.isActive == true && teardownWaitAddress == target.address) return + cancelTeardownConnect() + crpReconnect.cancelPending() + teardownUserInitiated = userInitiated + val epoch = teardownWaitEpoch.get() + recordDiagnostic("CRP waiting for previous physical disconnect") + // A fresh pairing is still "Connecting…" to the user; only recovery is "Reconnecting…". + val waitState = if (userInitiated) RingConnectionState.CONNECTING + else RingConnectionState.RECONNECTING + updateState { copy(connectionState = waitState) } + PulseEventBus.publishBlocking( + PulseEvent.DeviceStateChanged(waitState, target.address) + ) + teardownWaitAddress = target.address + val job = scope.launch(start = CoroutineStart.LAZY) { + val ready = monitor.gate.await(target.address) + if (epoch != teardownWaitEpoch.get()) return@launch + teardownWaitJob = null + teardownWaitAddress = null + if (watchdogReconnectPaused || prefs.getBoolean(USER_DISCONNECTED_KEY, false) || + !bluetoothAdapter.isEnabled || !hasPermissions() || + synchronized(forgetLock) { forgetPending || forgetFinalizing } || + !teardownTargetStillWanted(target.address, userInitiated)) { + finishCrpRecovery() + return@launch + } + if (ready) { + recordDiagnostic("CRP teardown finished; resuming connection") + beginConnect(target, deviceType, selectedModelID, advertisedName, scanDetectedType, + userInitiated) + } else { + recordDiagnostic("CRP teardown confirmation missing; requiring fresh advertisement") + teardownScanAddress = target.address + teardownUserInitiated = userInitiated + teardownScanConnect = TeardownConnect(deviceType, selectedModelID, scanDetectedType) + startScanningInternal() + reconnectScanPending = true + } + } + teardownWaitJob = job + job.start() + } + /** * Explicit "Forget Ring" action. Mirrors the official app: send the ring-side * UNBOND (0x4B 05) and wait for the ring's UNBOND_ACK before tearing down, so @@ -711,6 +882,8 @@ class RingBLEClient( forgetFinalizing = false forgetRequestGeneration = forgetGeneration } + crpReconnect.cancel() + cancelTeardownConnect() // Clear the known-ring id up front so the watchdog/auto-reconnect can't grab // the ring back during or after the unbind window. prefs.edit() @@ -854,9 +1027,28 @@ class RingBLEClient( * the attempt didn't come from a fresh scan match. [DriverReroute.shouldRerouteToJring] * needs it to tell a generic-"SMART_RING" guess apart from a confident family match. */ scanDetectedType: RingDeviceType? = null, + /** An explicit pairing [connectTo]; recovery must otherwise target the stored ring. */ + userInitiated: Boolean = false, ) { if (watchdogReconnectPaused) return if (synchronized(forgetLock) { forgetPending || forgetFinalizing }) return + // A hard reconnect can also replace a still-live CRP handle. Start its physical + // teardown before checking the shared gate, rather than reopening against that link. + if (activeCoordinator?.deviceType == RingDeviceType.CRP) { + bluetoothGatt?.let { old -> + bluetoothGatt = null + activeDriver?.connectionDidEnd() + resetOpQueue() + disconnectCrpGatt(old) + } + } + val teardownMonitor = CRPTeardownMonitor.current() + if (teardownMonitor?.gate?.isPending(target.address) == true) { + waitForCrpTeardown(teardownMonitor, target, deviceType, selectedModelID, + advertisedName, scanDetectedType, userInitiated) + return + } + cancelTeardownConnect() if (!claimConnectionOwnership()) { Log.i("RingBLEClient", "Connection skipped: another PulseLoop BLE client owns GATT") updateState { copy(connectionState = RingConnectionState.DISCONNECTED) } @@ -865,11 +1057,13 @@ class RingBLEClient( ownershipRetryJob = scope.launch { delay(PROCESS_OWNER_RETRY_MS) ownershipRetryJob = null - beginConnect(target, deviceType, selectedModelID, advertisedName, scanDetectedType) + beginConnect(target, deviceType, selectedModelID, advertisedName, scanDetectedType, + userInitiated) } } return } + crpReconnect.cancelPending() ownershipRetryJob = null syncCompletedOnLink = false // a new link has synced nothing yet scanner?.stopScan(scanCallback) @@ -1390,18 +1584,46 @@ class RingBLEClient( val matchedModel = com.pulseloop.wearables.WearableModel.modelForAdvertisedName(name) discoveredPeripherals[device.address] = device + val teardownScan = device.address == teardownScanAddress + if (teardownScan && !teardownTargetStillWanted(device.address, teardownUserInitiated)) { + // Forgotten (possibly by another client) while this recovery scan was running. + finishCrpRecovery() + return + } + if (teardownScan && CRPTeardownMonitor.current()?.gate + ?.freshAdvertisement(device.address, result.timestampNanos) == false) return + // Reconnect scan: the known ring is advertising again — grab it now. - if (reconnectScanPending && device.address == lastKnownIdentifier) { + if (reconnectScanPending && (teardownScan || device.address == lastKnownIdentifier)) { + val userInitiated = teardownScan && teardownUserInitiated + val carried = if (teardownScan) teardownScanConnect else null + teardownScanAddress = null + teardownUserInitiated = false + teardownScanConnect = null reconnectScanPending = false sightlessScans = 0 scanner?.stopScan(this) connectingName = name + if (carried != null) { + // Resume exactly the attempt that hit the gate; a pairing must not pick up + // the previously stored ring's family or model. + beginConnect( + device, + carried.deviceType ?: matchedType, + selectedModelID = carried.selectedModelID, + advertisedName = name, + scanDetectedType = carried.scanDetectedType ?: matchedType, + userInitiated = userInitiated, + ) + return + } beginConnect( device, - matchedType ?: lastKnownDeviceType, - selectedModelID = lastKnownWearableModelID, + matchedType ?: lastKnownDeviceType ?: activeCoordinator?.deviceType, + selectedModelID = lastKnownWearableModelID ?: _state.value.activeWearableModelID, advertisedName = name, scanDetectedType = matchedType, + userInitiated = userInitiated, ) return } @@ -1491,6 +1713,13 @@ class RingBLEClient( failConnectAttempt("Service discovery failed (GATT $status)") return } + // A manual disconnect/reconnect can reuse an Android link whose ATT channel is + // already gone. The October 17 capture returns GATT_SUCCESS with an empty cache in + // both reproductions. This is failed discovery, not proof that the ring lacks fdd3. + if (gatt.services.isEmpty() && activeCoordinator?.deviceType == RingDeviceType.CRP) { + failConnectAttempt("Ring service discovery returned no services") + return + } // Log all discovered service UUIDs for diagnostics val serviceUuids = gatt.services.map { it.uuid.toString() } @@ -1954,14 +2183,8 @@ class RingBLEClient( // Ignore late callbacks from a GATT we already superseded during a reconnect // (we close the old handle in beginConnect). Acting on them would clobber the // CONNECTING state of the fresh attempt with a spurious DISCONNECTED. - if (bluetoothGatt != null && gatt !== bluetoothGatt) { - closeGattQuietly(gatt) - return - } - // Duplicate callback for a GATT we already tore down (bluetoothGatt is null - // after teardown): don't re-publish DISCONNECTED or re-close. - if (bluetoothGatt == null && - _state.value.connectionState == RingConnectionState.DISCONNECTED) { + if (gatt !== bluetoothGatt) { + if (bluetoothGatt != null) closeGattQuietly(gatt) return } resetOpQueue() @@ -1971,8 +2194,8 @@ class RingBLEClient( // Release the dead client immediately (the link is already down, so no // disconnect/delay needed): refresh the GATT cache and close, matching the // official QRing app's teardown. Holding the old handle for autoConnect is - // what left zombie clients in the stack — the watchdog now owns reconnection - // and always starts from a fresh connectGatt. + // what left zombie clients in the stack — both CRP's short retry and the watchdog + // start from a fresh connectGatt. bluetoothGatt = null writeChar = null; commandChar = null; notifyChars.clear(); batteryChar = null subscriptionGate = null @@ -2011,20 +2234,50 @@ class RingBLEClient( idleSince = if (idleDrop) now else null, ) } + scheduleCrpRecovery() + } + + private fun scheduleCrpRecovery() { + if (!crpReconnect.schedule() && crpReconnect.isRecovering && !crpReconnect.isPending) { + finishCrpRecovery() + } + } + + private fun finishCrpRecovery() { + // A pairing that was waiting out a teardown shows CONNECTING with no GATT yet. + val pairingWait = teardownUserInitiated && bluetoothGatt == null + crpReconnect.cancel() + cancelTeardownConnect() + if (reconnectScanPending) scanner?.stopScan(scanCallback) + reconnectScanPending = false + val shown = _state.value.connectionState + if (shown == RingConnectionState.RECONNECTING || + (pairingWait && shown == RingConnectionState.CONNECTING)) { + updateState { copy(connectionState = RingConnectionState.DISCONNECTED) } + PulseEventBus.publishBlocking( + PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) + ) + } } /** Tear down this client. Returns true only if it owned PulseLoop's process-wide GATT slot. */ fun destroy(): Boolean { + watchdogReconnectPaused = true + crpReconnect.cancel() + cancelTeardownConnect() watchdogJob?.cancel() ownershipRetryJob?.cancel(); ownershipRetryJob = null stopKeepalive() scanner?.stopScan(scanCallback) activeDriver?.connectionDidEnd() - // The scope is about to die, so the graceful delayed close in disconnect() - // would never run — tear the GATT down synchronously instead. + // The client scope is about to die. CRP close lives in the shared process monitor so + // a foreground client can wait for it; other families still close synchronously here. bluetoothGatt?.let { gatt -> - try { gatt.disconnect() } catch (_: Exception) {} - closeGattQuietly(gatt) + if (activeCoordinator?.deviceType == RingDeviceType.CRP) disconnectCrpGatt(gatt) + else { + try { gatt.disconnect() } catch (_: Exception) {} + closeGattQuietly(gatt) + } } bluetoothGatt = null val releasedConnection = releaseConnectionOwnership() diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index f5143954..3a5d11c6 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -227,7 +227,7 @@ fun PulseLoopApp() { // process restart — the live GATT is gone, so the views would otherwise show a // false "Connected". Reset until a real connection re-confirms it. db.deviceDao().current()?.let { dev -> - if (dev.stateRaw == "CONNECTED" || dev.stateRaw == "CONNECTING") { + if (dev.stateRaw in setOf("CONNECTED", "CONNECTING", "RECONNECTING")) { db.deviceDao().upsert(dev.copy(stateRaw = "DISCONNECTED", updatedAt = System.currentTimeMillis())) } } diff --git a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt index d9134296..23be8625 100644 --- a/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt +++ b/app/src/main/java/com/pulseloop/ui/components/AppChrome.kt @@ -172,7 +172,8 @@ fun ConnectionStatusPill( val label = sourceLabel ?: when (state) { RingConnectionState.CONNECTED -> if (batteryPercent != null && batteryPercent > 0) trf("Connected · {0}%", batteryPercent) else tr("Connected") - RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> tr("Connecting…") + RingConnectionState.CONNECTING -> tr("Connecting…") + RingConnectionState.RECONNECTING -> tr("Reconnecting…") RingConnectionState.FAILED -> tr("Sync failed") else -> if (idleNow) { if (batteryPercent != null && batteryPercent > 0) trf("Idle · {0}%", batteryPercent) else tr("Idle") diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt index 9e01c22f..f676c0ff 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroCard.kt @@ -160,8 +160,9 @@ fun DeviceHeroCard( } // The connected card is purely informational and opens Wearable settings, where - // Disconnect lives. Setup/reconnect remain available here only when not connected. - if (status.action != DeviceHeroStatus.Action.DISCONNECT) { + // Disconnect lives. Setup/reconnect remain available here only when not connected, and + // automatic recovery offers Disconnect so the user can stop it (issue #124). + if (!connected) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { Text( status.actionTitle, @@ -176,12 +177,8 @@ fun DeviceHeroCard( when (status.action) { DeviceHeroStatus.Action.CONNECT -> onConnect() DeviceHeroStatus.Action.SET_UP -> onSetUp() - // Unreachable today: the row above only renders when action != - // DISCONNECT, and DeviceHeroStatus produces DISCONNECT only for - // the connected state — so this is a tripwire, not a fix (the PR - // description once claimed a dead button here; there never was - // one). Exhaustiveness needs the branch, and if the render - // condition is ever relaxed it must call through, not do nothing. + // Reached while RECONNECTING: stops automatic recovery through + // the same sticky userDisconnect path as the Settings button. DeviceHeroStatus.Action.DISCONNECT -> onDisconnect() // Already inert: actionEnabled is false while a connect is in flight. DeviceHeroStatus.Action.PENDING -> {} diff --git a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt index cbcefa9e..9421ef08 100644 --- a/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt +++ b/app/src/main/java/com/pulseloop/ui/components/DeviceHeroStatus.kt @@ -26,7 +26,7 @@ data class DeviceHeroStatus( DISCONNECT, CONNECT, SET_UP, - /** A connect attempt is in flight (connecting / reconnecting / scanning). */ + /** A connect attempt is in flight (connecting / scanning). */ PENDING, } @@ -38,8 +38,9 @@ data class DeviceHeroStatus( Action.PENDING -> tr("Connecting…") } - /** The action button is inert while a connection attempt is in flight, so a tap can't - * cancel or restart an in-progress (re)connect. */ + /** The action button is inert while a single connection attempt is in flight, so a tap + * can't cancel or restart it. Automatic recovery (RECONNECTING) can run for minutes, so it + * offers Disconnect instead (issue #124). */ val actionEnabled: Boolean get() = action != Action.PENDING companion object { @@ -66,9 +67,12 @@ data class DeviceHeroStatus( RingConnectionState.CONNECTED -> { statusLine = tr("Connected"); statusTint = PulseColors.success } - RingConnectionState.CONNECTING, RingConnectionState.RECONNECTING -> { + RingConnectionState.CONNECTING -> { statusLine = tr("Connecting…"); statusTint = PulseColors.warning } + RingConnectionState.RECONNECTING -> { + statusLine = tr("Reconnecting…"); statusTint = PulseColors.warning + } RingConnectionState.SCANNING -> { statusLine = tr("Searching…"); statusTint = PulseColors.warning } @@ -90,9 +94,9 @@ data class DeviceHeroStatus( val syncText = lastSyncAt?.let { trf("Synced {0}", relativeShort(it, now)) } val action = when (state) { - RingConnectionState.CONNECTED -> Action.DISCONNECT + RingConnectionState.CONNECTED, + RingConnectionState.RECONNECTING -> Action.DISCONNECT RingConnectionState.CONNECTING, - RingConnectionState.RECONNECTING, RingConnectionState.SCANNING -> Action.PENDING RingConnectionState.IDLE, RingConnectionState.DISCONNECTED, diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 0f8b58f8..97f555b4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -2145,9 +2145,18 @@ fun WearableSettingsScreen( Spacer(Modifier.width(4.dp)) Text(tr("Disconnect")) } - } else if (bleClient?.hasLastKnownRing == true && - bleState.connectionState != RingConnectionState.RECONNECTING - ) { + } else if (bleState.connectionState == RingConnectionState.RECONNECTING) { + // Automatic recovery can scan for minutes; let the user stop it (issue #124). + Spacer(Modifier.height(12.dp)) + PulseButton(PulseButtonStyle.Outlined, + onClick = { bleClient?.userDisconnect() }, + modifier = Modifier.fillMaxWidth(), + ) { + Icon(Icons.Filled.Close, null, Modifier.size(16.dp)) + Spacer(Modifier.width(4.dp)) + Text(tr("Disconnect")) + } + } else if (bleClient?.hasLastKnownRing == true) { Spacer(Modifier.height(12.dp)) PulseButton(PulseButtonStyle.Outlined, onClick = { bleClient.userConnect() }, diff --git a/app/src/test/java/com/pulseloop/ring/CRPReconnectTest.kt b/app/src/test/java/com/pulseloop/ring/CRPReconnectTest.kt new file mode 100644 index 00000000..aa27aac4 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/CRPReconnectTest.kt @@ -0,0 +1,140 @@ +package com.pulseloop.ring + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.* +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class CRPReconnectTest { + @Test + fun `five second connection failure retries three seconds later instead of next watchdog tick`() = runTest { + val events = mutableListOf>() + val recovery = CRPReconnect( + scope = this, + canRetry = { true }, + onPending = { events += testScheduler.currentTime to "reconnecting" }, + onRetry = { events += testScheduler.currentTime to "scan" }, + onAbandoned = { fail("retry is eligible") }, + ) + // Replay the failed first attempt in the October 17 capture. + advanceTimeBy(5_000) + assertTrue(recovery.schedule()) + runCurrent() + assertTrue(recovery.isPending) + advanceTimeBy(2_999) + runCurrent() + assertEquals(listOf(5_000L to "reconnecting"), events) + advanceTimeBy(1) + runCurrent() + assertEquals(listOf(5_000L to "reconnecting", 8_000L to "scan"), events) + assertFalse(recovery.isPending) + assertTrue("scan remains part of recovery", recovery.isRecovering) + recovery.cancel() + } + + @Test + fun `duplicate scheduling and watchdog checks cannot dispatch a second attempt`() = runTest { + var attempts = 0 + val recovery = CRPReconnect(this, { true }, {}, { attempts++ }, {}) + assertTrue(recovery.schedule()) + runCurrent() + advanceTimeBy(1_000) + assertFalse(recovery.schedule()) + assertTrue("watchdog must yield to pending retry", recovery.isPending) + advanceTimeBy(2_000) + runCurrent() + assertEquals(1, attempts) + advanceTimeBy(15_000) + runCurrent() + assertEquals("timer is one-shot", 1, attempts) + recovery.cancel() + } + + @Test + fun `cancellation invalidates a timer already ready on the dispatcher`() = runTest { + var attempts = 0 + val recovery = CRPReconnect(this, { true }, {}, { attempts++ }, {}) + recovery.schedule() + runCurrent() + advanceTimeBy(3_000) // Deadline reached, continuation has not run yet. + recovery.cancel() + runCurrent() + assertEquals(0, attempts) + assertFalse(recovery.isPending) + assertFalse(recovery.isRecovering) + } + + @Test + fun `a superseding attempt invalidates the old timer without ending recovery`() = runTest { + var attempts = 0 + val recovery = CRPReconnect(this, { true }, {}, { attempts++ }, {}) + recovery.schedule() + runCurrent() + advanceTimeBy(3_000) + recovery.cancelPending() + runCurrent() + assertEquals(0, attempts) + assertTrue(recovery.isRecovering) + // If the superseding attempt fails, its new deadline must win over the old one. + assertTrue(recovery.schedule()) + runCurrent() + advanceTimeBy(2_999) + runCurrent() + assertEquals(0, attempts) + advanceTimeBy(1) + runCurrent() + assertEquals(1, attempts) + recovery.cancel() + } + + @Test + fun `ineligible recovery never schedules or changes presentation`() = runTest { + val recovery = CRPReconnect(this, { false }, { fail("must stay disconnected") }, + { fail("must not connect") }, { fail("nothing was scheduled") }) + assertFalse(recovery.schedule()) + advanceTimeBy(15_000) + runCurrent() + assertFalse(recovery.isPending) + assertFalse(recovery.isRecovering) + } + + @Test + fun `eligibility revoked before dispatch abandons recovery without a connection attempt`() = runTest { + var eligible = true + var abandoned = 0 + val recovery = CRPReconnect(this, { eligible }, {}, + { fail("eligibility was revoked") }, { abandoned++ }) + recovery.schedule() + runCurrent() + eligible = false + advanceTimeBy(3_000) + runCurrent() + assertEquals(1, abandoned) + assertFalse(recovery.isPending) + assertFalse(recovery.isRecovering) + } + + @Test + fun `repeated cancellation permits only a fresh recovery`() = runTest { + var attempts = 0 + val recovery = CRPReconnect(this, { true }, {}, { attempts++ }, {}) + repeat(4) { + recovery.schedule() + runCurrent() + advanceTimeBy(1_000) + recovery.cancel() + advanceTimeBy(3_000) + runCurrent() + } + assertEquals(0, attempts) + recovery.schedule() + runCurrent() + advanceTimeBy(3_000) + runCurrent() + assertEquals(1, attempts) + recovery.cancel() + } +} diff --git a/app/src/test/java/com/pulseloop/ring/CRPTeardownGateTest.kt b/app/src/test/java/com/pulseloop/ring/CRPTeardownGateTest.kt new file mode 100644 index 00000000..086b9138 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ring/CRPTeardownGateTest.kt @@ -0,0 +1,220 @@ +package com.pulseloop.ring + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Assert.* +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class CRPTeardownGateTest { + private val ring = "ring" + + @Test + fun `quick reconnect waits for the physical teardown captured at 1472 ms`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + advanceTimeBy(500) + gate.gattClosed(old) + advanceTimeBy(822) // User taps reconnect 1.322 s after Disconnect. + val connect = async { gate.await(ring) } + runCurrent() + assertFalse("GATT close is not proof of physical disconnect", connect.isCompleted) + advanceTimeBy(150) + gate.aclDisconnected(ring) + runCurrent() + assertTrue(connect.await()) + assertEquals(1_472L, testScheduler.currentTime) + assertFalse(gate.isPending(ring)) + } + + @Test + fun `an early physical disconnect still waits for the old GATT close`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + val connect = async { gate.await(ring) } + runCurrent() + gate.aclDisconnected(ring) + runCurrent() + assertFalse(connect.isCompleted) + advanceTimeBy(500) + gate.gattClosed(old) + runCurrent() + assertTrue(connect.await()) + } + + @Test + fun `a link already down waits only for the GATT close, not a broadcast`() = runTest { + // Watchdog / hung-CONNECTING reconnect: the OS reports no GATT link, so no + // ACL_DISCONNECTED will arrive. Must not fall through to the 5 s timeout and scan. + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.linkAlreadyDown(old) + val connect = async { gate.await(ring) } + runCurrent() + assertFalse("the old handle must still close first", connect.isCompleted) + advanceTimeBy(500) + gate.gattClosed(old) + runCurrent() + assertTrue(connect.await()) + assertEquals(500L, testScheduler.currentTime) + assertFalse(gate.isPending(ring)) + } + + @Test + fun `a stale link-down probe cannot release a newer teardown`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val stale = gate.begin(ring) + val current = gate.begin(ring) + gate.linkAlreadyDown(stale) + gate.gattClosed(current) + assertTrue(gate.isPending(ring)) + } + + @Test + fun `reconnecting after completed teardown adds no delay`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + gate.aclDisconnected(ring) + assertTrue(gate.await(ring)) + assertEquals(0L, testScheduler.currentTime) + } + + @Test + fun `a different device disconnect cannot release this ring`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + val connect = async { gate.await(ring) } + runCurrent() + gate.aclDisconnected("headphones") + runCurrent() + assertFalse(connect.isCompleted) + gate.aclDisconnected(ring) + runCurrent() + assertTrue(connect.await()) + } + + @Test + fun `a stale GATT close cannot release a newer teardown`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val stale = gate.begin(ring) + val current = gate.begin(ring) + val connect = async { gate.await(ring) } + runCurrent() + gate.gattClosed(stale) + gate.aclDisconnected(ring) + runCurrent() + assertFalse(connect.isCompleted) + gate.gattClosed(current) + runCurrent() + assertTrue(connect.await()) + } + + @Test + fun `cancelling one client's wait preserves teardown for the next client`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + val worker = async { gate.await(ring) } + runCurrent() + worker.cancel() + val foreground = async { gate.await(ring) } + runCurrent() + assertTrue(gate.isPending(ring)) + assertFalse(foreground.isCompleted) + gate.aclDisconnected(ring) + runCurrent() + assertTrue(foreground.await()) + assertTrue(worker.isCancelled) + } + + @Test + fun `a missing broadcast requires scanning at timeout rather than blind reconnect`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + val connect = async { gate.await(ring) } + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertFalse(connect.await()) + assertTrue("other clients must not bypass the missing confirmation", gate.isPending(ring)) + assertFalse(gate.await(ring)) + assertEquals(5_000L, testScheduler.currentTime) + } + + @Test + fun `cached advertisement cannot substitute for missing disconnect confirmation`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + assertFalse("advertising alone cannot skip the normal physical wait", + gate.freshAdvertisement(ring, 100)) + val connect = async { gate.await(ring) } + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertFalse(connect.await()) + assertFalse(gate.freshAdvertisement(ring, 4_999_000_000)) + assertFalse(gate.freshAdvertisement(ring, 5_000_000_000)) + assertTrue(gate.freshAdvertisement(ring, 5_001_000_000)) + assertTrue(gate.await(ring)) + } + + @Test + fun `fresh advertisement must also be newer than the actual GATT close`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + val connect = async { gate.await(ring) } + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertFalse(connect.await()) + assertFalse(gate.freshAdvertisement(ring, 5_001_000_000)) + advanceTimeBy(100) + gate.gattClosed(old) + assertFalse(gate.freshAdvertisement(ring, 5_001_000_000)) + assertTrue(gate.freshAdvertisement(ring, 5_101_000_000)) + } + + @Test + fun `a late disconnect broadcast releases the scan fallback normally`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + gate.gattClosed(old) + val connect = async { gate.await(ring) } + runCurrent() + advanceTimeBy(5_000) + runCurrent() + assertFalse(connect.await()) + gate.aclDisconnected(ring) + assertFalse(gate.isPending(ring)) + assertTrue(gate.await(ring)) + } + + @Test + fun `bluetooth off clears physical waits after their handles close`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + val old = gate.begin(ring) + val connect = async { gate.await(ring) } + runCurrent() + gate.bluetoothOff() + runCurrent() + assertFalse(connect.isCompleted) + gate.gattClosed(old) + runCurrent() + assertTrue(connect.await()) // The caller still checks Bluetooth and user intent before connecting. + } + + @Test + fun `an unrelated ring is not delayed by pending CRP teardown`() = runTest { + val gate = CRPTeardownGate({ testScheduler.currentTime * 1_000_000 }) + gate.begin(ring) + assertTrue(gate.await("another-ring")) + assertTrue(gate.isPending(ring)) + } +} diff --git a/app/src/test/java/com/pulseloop/ui/components/DeviceHeroStatusTest.kt b/app/src/test/java/com/pulseloop/ui/components/DeviceHeroStatusTest.kt index 987c8710..bcc6a2e5 100644 --- a/app/src/test/java/com/pulseloop/ui/components/DeviceHeroStatusTest.kt +++ b/app/src/test/java/com/pulseloop/ui/components/DeviceHeroStatusTest.kt @@ -104,7 +104,6 @@ class DeviceHeroStatusTest { fun `pending states disable the action`() { for (state in listOf( RingConnectionState.CONNECTING, - RingConnectionState.RECONNECTING, RingConnectionState.SCANNING, )) { val s = DeviceHeroStatus.make( @@ -116,4 +115,24 @@ class DeviceHeroStatusTest { assertEquals(false, s.actionEnabled) } } + + @Test + fun `automatic recovery tells the user it is still reconnecting`() { + val status = DeviceHeroStatus.make( + state = RingConnectionState.RECONNECTING, connectedName = null, + knownName = "Colmi R11", batteryPercent = null, lastSyncAt = null, now = now, + ) + assertEquals("Reconnecting…", status.statusLine) + } + + @Test + fun `automatic recovery can be stopped with disconnect`() { + val status = DeviceHeroStatus.make( + state = RingConnectionState.RECONNECTING, connectedName = null, + knownName = "Colmi R11", batteryPercent = null, lastSyncAt = null, now = now, + ) + assertEquals(DeviceHeroStatus.Action.DISCONNECT, status.action) + assertEquals("Disconnect", status.actionTitle) + assertEquals(true, status.actionEnabled) + } } From aa6152fbda3c03f387e44221bc0bb61f43841786 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:32:05 +0000 Subject: [PATCH 3/7] Port upstream #127: retry a refused Gemini grounding turn without web search Ported from foureight84/PulseLoopAndroid#127 (7728117). Free-tier Gemini keys can be refused google_search grounding with HTTP 429 while every other call on the key works. GeminiClient now re-sends a refused grounding turn once without google_search, as the schema turn, with a note asking the model to say web search was skipped, and remembers the key for the process. Settings shows a hint under Web Search for the Gemini provider. GeminiClient.kt and GeminiClientTest.kt are taken verbatim; the Settings hint is adapted to this fork's tr() strings. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../pulseloop/coach/gemini/GeminiClient.kt | 89 ++++++++++-- .../ui/screens/SettingsSubScreens.kt | 5 + .../com/pulseloop/coach/GeminiClientTest.kt | 130 ++++++++++++++++++ 3 files changed, 216 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/pulseloop/coach/gemini/GeminiClient.kt b/app/src/main/java/com/pulseloop/coach/gemini/GeminiClient.kt index 255ad767..8d9328ce 100644 --- a/app/src/main/java/com/pulseloop/coach/gemini/GeminiClient.kt +++ b/app/src/main/java/com/pulseloop/coach/gemini/GeminiClient.kt @@ -31,6 +31,8 @@ class GeminiClient( private val apiKey: String, model: String = GeminiModel.DEFAULT.slug, private val baseURL: String = "https://generativelanguage.googleapis.com/v1beta/models", + // Network seam: a test can answer or fail requests without an HTTP stack. + private val transport: suspend (String, ByteArray) -> String = { u, b -> ResponsesHttp.post(u, b) }, ) : ResponsesClient { // The model the orchestrator selected, taken from each request body's `model` // field (see `send`); the constructor value is only a fallback if that's absent. @@ -54,6 +56,10 @@ class GeminiClient( // Sources cited by a google_search turn, queued to prepend to the next user // message so the schema turn can fill the response `sources` array. private var pendingSourcesNote: String? = null + // Inputs of the last built body, so a refused grounding turn can be rebuilt + // as the plain schema turn it would otherwise have been (issue #123). + private var lastTextFormat: JsonObject? = null + private var lastThinkingLevel: String? = null override suspend fun send(requestBody: ByteArray): OpenAIResponse { if (apiKey.isBlank()) throw ResponsesError.MissingAPIKey @@ -65,9 +71,23 @@ class GeminiClient( } val geminiBody = buildRequestBody(req) - val bodyBytes = json.encodeToString(JsonObject.serializer(), geminiBody).toByteArray() - - val body = postWithOverloadRetry("$baseURL/$model:generateContent?key=$apiKey", bodyBytes) + val body = try { + post(geminiBody) + } catch (e: ResponsesError.Http) { + if (e.status != 429 || !isGroundingBody(geminiBody)) throw e + // A free-tier key can be refused `google_search` grounding outright (429 + // RESOURCE_EXHAUSTED) while every other call on the same key succeeds (issue + // #123). Re-send this turn once without it — as the schema turn it would + // otherwise have been — so the answer still arrives. The rebuilt body carries + // no google_search, so this cannot loop; a 429 on it is a real quota refusal + // and surfaces as before. + val ungrounded = post(ungroundedRetryBody()) + // Only now is it proven that grounding, not the key, was refused: stop asking + // for it on this key for the rest of the process so later questions don't pay + // the extra round trip. An app restart (e.g. after upgrading the plan) re-tries. + groundingRefusedKeys.add(apiKey) + ungrounded + } val root = try { json.parseToJsonElement(body).jsonObject @@ -95,7 +115,7 @@ class GeminiClient( url: String, bodyBytes: ByteArray, backoffMs: Long = OVERLOAD_BACKOFF_MS, - post: suspend (String, ByteArray) -> String = { u, b -> ResponsesHttp.post(u, b) }, + post: suspend (String, ByteArray) -> String = transport, ): String { for (attempt in 0..MAX_OVERLOAD_RETRIES) { try { @@ -108,9 +128,51 @@ class GeminiClient( throw IllegalStateException("overload retry loop never returned") } + private suspend fun post(geminiBody: JsonObject): String { + val bodyBytes = json.encodeToString(JsonObject.serializer(), geminiBody).toByteArray() + return postWithOverloadRetry("$baseURL/$model:generateContent?key=$apiKey", bodyBytes) + } + + private fun isGroundingBody(body: JsonObject): Boolean = + (body["tools"] as? JsonArray)?.any { (it as? JsonObject)?.containsKey("google_search") == true } == true + + /** The refused grounding turn rebuilt without `google_search` (issue #123): same + * conversation, the response schema applied, and a note so the answer says web + * search was skipped. `webSearchGrounded` is already set, so it never re-grounds. */ + private fun ungroundedRetryBody(): JsonObject { + noteWebSearchSkipped() + return buildGeminiBody(emptyList(), lastTextFormat, lastThinkingLevel) + } + + /** Tells the model, on the current user turn, that web search didn't run — so it + * leaves `sources` empty and says so in `data_quality_note`, which the chat shows + * under the answer. Prompt-level on purpose: no UI plumbing (issue #123). */ + private fun noteWebSearchSkipped() { + val note = JsonObject(mapOf("text" to JsonPrimitive(WEB_SEARCH_SKIPPED_NOTE))) + val last = contents.lastOrNull() + if (last != null && (last["role"] as? JsonPrimitive)?.contentOrNull == "user") { + val parts = (last["parts"] as? JsonArray).orEmpty() + note + contents[contents.lastIndex] = JsonObject(last + ("parts" to JsonArray(parts))) + } else { + contents.add(JsonObject(mapOf( + "role" to JsonPrimitive("user"), + "parts" to JsonArray(listOf(note)), + ))) + } + } + private companion object { const val MAX_OVERLOAD_RETRIES = 2 const val OVERLOAD_BACKOFF_MS = 2_000L + + const val WEB_SEARCH_SKIPPED_NOTE = "Web search was not available for this answer " + + "(Google refused Search grounding for this API key; free-tier keys often can't use it). " + + "Answer from the health data alone, leave `sources` empty, and say briefly in " + + "`data_quality_note` that web search was skipped." + + // Keys whose grounding turn was refused with a 429 while the same turn succeeded + // without it (issue #123). Process-wide because each agent turn gets a fresh client. + val groundingRefusedKeys: MutableSet = java.util.concurrent.ConcurrentHashMap.newKeySet() } // ── Request assembly (internal for unit tests) ─────────────────────── @@ -137,6 +199,8 @@ class GeminiClient( appendContinuation(previousResponseId, input) } + lastTextFormat = textFormat + lastThinkingLevel = thinkingLevel return buildGeminiBody(convertTools(tools), textFormat, thinkingLevel) } @@ -362,12 +426,21 @@ class GeminiClient( // and skip the schema. The grounded prose + cited sources land in history; // the orchestrator's subsequent tool-less repair turn then enforces the // coach_response schema (and can fill the `sources` array from them). - val groundingTurn = tools.isEmpty() && webSearchRequested && !webSearchGrounded + // + // A key already known to be refused grounding (issue #123) skips it here and gets + // the plain schema turn with a "web search skipped" note instead. + var groundingTurn = tools.isEmpty() && webSearchRequested && !webSearchGrounded if (groundingTurn) { - body["tools"] = JsonArray(listOf(JsonObject(mapOf( - "google_search" to JsonObject(emptyMap()), - )))) webSearchGrounded = true + if (apiKey in groundingRefusedKeys) { + groundingTurn = false + noteWebSearchSkipped() + body["contents"] = JsonArray(contents) + } else { + body["tools"] = JsonArray(listOf(JsonObject(mapOf( + "google_search" to JsonObject(emptyMap()), + )))) + } } // Gemini rejects function declarations combined with a JSON response diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 97f555b4..3e032154 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -832,6 +832,11 @@ fun CoachSettingsScreen(onBack: () -> Unit) { Column(Modifier.weight(1f)) { Text(tr("Web Search")) Text(tr("Uses additional tokens"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + // Free-tier Gemini keys can be refused Google Search grounding (HTTP 429) + // while every other call works; the coach then answers without it (issue #123). + if (providerMode == CoachProviderMode.USER_GEMINI_KEY) { + Text(tr("Google Search grounding may need a paid Gemini plan — free-tier keys can be refused, and the coach then answers without web results."), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } } Switch(checked = webSearch, onCheckedChange = null) } diff --git a/app/src/test/java/com/pulseloop/coach/GeminiClientTest.kt b/app/src/test/java/com/pulseloop/coach/GeminiClientTest.kt index 388a2e89..446e53e5 100644 --- a/app/src/test/java/com/pulseloop/coach/GeminiClientTest.kt +++ b/app/src/test/java/com/pulseloop/coach/GeminiClientTest.kt @@ -408,4 +408,134 @@ class GeminiClientTest { } assertEquals(1, attempts) } + + // ── Refused grounding turn (issue #123) ──────────────────────────── + + private val schemaFormat = JsonObject(mapOf( + "type" to JsonPrimitive("json_schema"), + "schema" to JsonObject(mapOf("type" to JsonPrimitive("object"))), + )) + + private fun bytes(req: JsonObject) = req.toString().toByteArray() + + private fun isGrounding(body: JsonObject) = + body["tools"]?.jsonArray?.any { it.jsonObject.containsKey("google_search") } == true + + /** Tool turn (web search requested) answered with prose; returns its response id. */ + private suspend fun toolTurn(client: GeminiClient): String = client.send(bytes(request( + listOf(msg("user", "hi")), + tools = listOf(webSearchTool, functionTool("t", JsonObject(mapOf("type" to JsonPrimitive("object"))))), + textFormat = schemaFormat, + ))).id + + private suspend fun repairTurn(client: GeminiClient, previousId: String) = client.send(bytes(request( + listOf(msg("user", "format it")), textFormat = schemaFormat, previousResponseId = previousId, + ))) + + private fun lastUserText(body: JsonObject) = body["contents"]!!.jsonArray.last().jsonObject["parts"]!! + .jsonArray.joinToString(" ") { it.jsonObject["text"]?.jsonPrimitive?.content ?: "" } + + @Test + fun `a 429 on the grounding turn is retried once without google_search`() = kotlinx.coroutines.runBlocking { + // Free-tier keys get 429 RESOURCE_EXHAUSTED for google_search alone while plain, function + // and schema calls succeed — every coach question failed with Web Search on. + val sent = mutableListOf() + val client = GeminiClient("key-123-retry", transport = { _, b -> + val body = Json.parseToJsonElement(String(b)).jsonObject + sent.add(body) + if (isGrounding(body)) throw ResponsesError.Http(429, "You exceeded your current quota") + textResponse(if (sent.size == 1) "prose" else """{"title":"ok"}""").toString() + }) + + val answer = repairTurn(client, toolTurn(client)) + + assertEquals("""{"title":"ok"}""", answer.outputText) + assertEquals(3, sent.size) + assertTrue(isGrounding(sent[1])) + val retry = sent[2] + assertFalse(isGrounding(retry)) + assertNull(retry["tools"]) + // The retry is the schema turn it would otherwise have been, and says search was skipped. + assertNotNull(retry["generationConfig"]!!.jsonObject["responseSchema"]) + assertTrue(lastUserText(retry).contains("Web search was not available")) + } + + @Test + fun `a refused key skips grounding on later turns without the extra round trip`() = kotlinx.coroutines.runBlocking { + val key = "key-123-remembered" + var refusals = 0 + val transport: suspend (String, ByteArray) -> String = { _, b -> + val body = Json.parseToJsonElement(String(b)).jsonObject + if (isGrounding(body)) { refusals++; throw ResponsesError.Http(429, "quota") } + textResponse("prose").toString() + } + val first = GeminiClient(key, transport = transport) + repairTurn(first, toolTurn(first)) + assertEquals(1, refusals) + + // Next agent turn: a fresh client (as the orchestrator builds one per turn). + val sent = mutableListOf() + val second = GeminiClient(key, transport = { u, b -> + sent.add(Json.parseToJsonElement(String(b)).jsonObject) + transport(u, b) + }) + repairTurn(second, toolTurn(second)) + assertEquals(1, refusals) + assertEquals(2, sent.size) + assertFalse(isGrounding(sent[1])) + assertNotNull(sent[1]["generationConfig"]!!.jsonObject["responseSchema"]) + assertTrue(lastUserText(sent[1]).contains("Web search was not available")) + + // A different key is unaffected. + val other = GeminiClient("key-123-other", transport = { _, b -> + sent.add(Json.parseToJsonElement(String(b)).jsonObject) + textResponse("prose").toString() + }) + repairTurn(other, toolTurn(other)) + assertTrue(isGrounding(sent.last())) + } + + @Test + fun `a 429 on a non-grounding turn still surfaces`() = kotlinx.coroutines.runBlocking { + var attempts = 0 + val client = GeminiClient("key-123-plain", transport = { _, _ -> + attempts++ + throw ResponsesError.Http(429, "You exceeded your current quota") + }) + try { + toolTurn(client) + fail("a quota refusal on a normal turn must surface") + } catch (e: ResponsesError.Http) { + assertEquals(429, e.status) + } + assertEquals(1, attempts) + } + + @Test + fun `a 429 on the ungrounded retry surfaces and is not remembered`() = kotlinx.coroutines.runBlocking { + // The key itself is out of quota: the retry fails too, and grounding is not blamed. + val key = "key-123-exhausted" + var calls = 0 + val client = GeminiClient(key, transport = { _, _ -> + if (calls++ == 0) textResponse("prose").toString() + else throw ResponsesError.Http(429, "You exceeded your current quota") + }) + val id = toolTurn(client) + try { + repairTurn(client, id) + fail("a 429 on the retry must surface, not loop") + } catch (e: ResponsesError.Http) { + assertEquals(429, e.status) + } + assertEquals(3, calls) // tool turn, grounding turn, one retry + + // Not marked as grounding-refused: a later turn on the same key still grounds. + val sent = mutableListOf() + val next = GeminiClient(key, transport = { _, b -> + sent.add(Json.parseToJsonElement(String(b)).jsonObject) + textResponse("prose").toString() + }) + repairTurn(next, toolTurn(next)) + assertTrue(isGrounding(sent.last())) + } } From cf6bd740911189cca824c176d2f8e67f7e042f3a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:32:50 +0000 Subject: [PATCH 4/7] Port upstream #133: coach past conversations list with delete (#131) Ported from foureight84/PulseLoopAndroid#133 (e00a245). The Coach header gains a history button (between usage and new chat) that opens a sheet of past conversations: first question, when, message count, newest first. Tap to reopen; swipe (or the accessibility action) to delete, or delete all; both ask first. A delete clears messages, the tool-call trace and attached photos; deleting the open thread starts a new one. Empty threads are not listed. A reply now lands only on the thread it was asked in, and a reply whose conversation was deleted mid-turn is dropped. Adapted to our design system: PulseButton for every button, tr()/trf() for all text, 12/14/16sp sizes, 8dp radius, Chevron() on rows, 48dp targets, the open thread marked by text and a neutral edge rather than mint. The header's three actions share one Row so the title keeps room. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../main/java/com/pulseloop/data/dao/Daos.kt | 57 +++++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 17 ++ .../pulseloop/ui/screens/CoachHistorySheet.kt | 242 ++++++++++++++++++ .../com/pulseloop/ui/screens/CoachScreen.kt | 35 ++- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 96 ++++++- .../ui/screens/CoachHistoryTextTest.kt | 54 ++++ 6 files changed, 479 insertions(+), 22 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/ui/screens/CoachHistorySheet.kt create mode 100644 app/src/test/java/com/pulseloop/ui/screens/CoachHistoryTextTest.kt diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index 5393d9a1..1352832c 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -437,8 +437,44 @@ interface CoachConversationDao { @Upsert suspend fun upsert(conversation: CoachConversationEntity) + + @Query("SELECT * FROM coach_conversations WHERE id = :id LIMIT 1") + suspend fun byId(id: String): CoachConversationEntity? + + /** + * The coach's past conversations for the history sheet (issue #131), newest first. Only ones + * with at least one message: "+" persists its thread up front, so an unused one is an empty + * row that would otherwise list as a blank entry. + */ + @Query( + """SELECT c.id, c.createdAt, c.updatedAt, + (SELECT m.body FROM coach_messages m WHERE m.conversationId = c.id AND m.role = 'user' + ORDER BY m.createdAt ASC LIMIT 1) AS firstQuestion, + (SELECT COUNT(*) FROM coach_messages m WHERE m.conversationId = c.id) AS messageCount + FROM coach_conversations c + WHERE EXISTS (SELECT 1 FROM coach_messages m WHERE m.conversationId = c.id) + ORDER BY c.updatedAt DESC""" + ) + fun historyFlow(): Flow> + + /** Delete its messages and tool calls first — see [CoachMessageDao], [CoachToolCallDao]. */ + @Query("DELETE FROM coach_conversations WHERE id = :id") + suspend fun deleteById(id: String) + + @Query("DELETE FROM coach_conversations") + suspend fun deleteAll() } +/** One row of the coach history sheet (issue #131). */ +data class CoachConversationSummary( + val id: String, + val createdAt: Long, + val updatedAt: Long, + /** The first thing the user asked; null only if the thread holds no user message. */ + val firstQuestion: String?, + val messageCount: Int, +) + @Dao interface CoachMessageDao { @Query("SELECT * FROM coach_messages WHERE conversationId = :convId ORDER BY createdAt ASC") @@ -449,6 +485,20 @@ interface CoachMessageDao { @Insert suspend fun insert(message: CoachMessageEntity) + + /** Attachment refs of a conversation's messages, so deleting it can delete the image files. */ + @Query("SELECT attachmentsJson FROM coach_messages WHERE conversationId = :convId AND attachmentsJson IS NOT NULL") + suspend fun attachmentsJsonFor(convId: String): List + + @Query("SELECT attachmentsJson FROM coach_messages WHERE attachmentsJson IS NOT NULL") + suspend fun allAttachmentsJson(): List + + /** Explicit rather than trusting the cascade, which only fires with SQLite's foreign keys on. */ + @Query("DELETE FROM coach_messages WHERE conversationId = :convId") + suspend fun deleteForConversation(convId: String) + + @Query("DELETE FROM coach_messages") + suspend fun deleteAll() } @Dao @@ -479,6 +529,13 @@ interface CoachToolCallDao { @Insert suspend fun insert(call: CoachToolCallEntity) + + /** `coach_tool_calls` has no foreign key to its conversation, so a delete has to clear it. */ + @Query("DELETE FROM coach_tool_calls WHERE conversationId = :convId") + suspend fun deleteForConversation(convId: String) + + @Query("DELETE FROM coach_tool_calls") + suspend fun deleteAll() } @Dao diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index f5143954..4c125a94 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -157,6 +157,9 @@ fun PulseLoopApp() { com.pulseloop.coach.attachments.CoachAttachmentStore.payloads(context, refs) }, environmentSnapshot = { weatherContextService.snapshot() }, + deleteAttachments = { refs -> + refs.forEach { com.pulseloop.coach.attachments.CoachAttachmentStore.delete(context, it) } + }, ) } @@ -487,6 +490,7 @@ fun PulseLoopApp() { // frosted glass bar the other tabs use so the chat scrolls under it // (owner choice, issue #22). var showCoachUsage by remember { mutableStateOf(false) } + var showCoachHistory by remember { mutableStateOf(false) } CoachHeader( // Which brain answers, when it is the one on this phone. subtitle = if (providerStore.providerMode == com.pulseloop.coach.config.CoachProviderMode.ON_DEVICE) @@ -494,7 +498,20 @@ fun PulseLoopApp() { onBack = { navController.popBackStack() }, onNewChat = { coachVM.newConversation() }, onOpenUsage = { showCoachUsage = true }, + onOpenHistory = { showCoachHistory = true }, ) + if (showCoachHistory) { + val history by coachVM.history.collectAsState(initial = emptyList()) + val coachState by coachVM.state.collectAsState() + com.pulseloop.ui.screens.CoachHistorySheet( + conversations = history, + currentId = coachState.conversationId, + onOpen = { id -> coachVM.openConversation(id); showCoachHistory = false }, + onDelete = { id -> coachVM.deleteConversation(id) }, + onDeleteAll = { coachVM.deleteAllConversations(); showCoachHistory = false }, + onDismiss = { showCoachHistory = false }, + ) + } if (showCoachUsage) { var usageData by remember { mutableStateOf>?>(null) diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachHistorySheet.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachHistorySheet.kt new file mode 100644 index 00000000..f539a652 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachHistorySheet.kt @@ -0,0 +1,242 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SwipeToDismissBox +import androidx.compose.material3.SwipeToDismissBoxValue +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.material3.rememberSwipeToDismissBoxState +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.dao.CoachConversationSummary +import com.pulseloop.ui.components.Chevron +import com.pulseloop.ui.components.PulseButton +import com.pulseloop.ui.components.PulseButtonStyle +import com.pulseloop.ui.i18n.tr +import com.pulseloop.ui.i18n.trf +import com.pulseloop.ui.theme.PulseColors +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import java.util.Locale + +/** + * The coach's past conversations (issue #131): tap one to reopen it, swipe it away to delete it, + * or delete them all. Every delete asks first — it takes the messages, the tool-call trace and any + * attached photos with it, and there is no undo. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun CoachHistorySheet( + conversations: List, + currentId: String?, + onOpen: (String) -> Unit, + onDelete: (String) -> Unit, + onDeleteAll: () -> Unit, + onDismiss: () -> Unit, +) { + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false) + var pendingDelete by remember { mutableStateOf(null) } + var confirmDeleteAll by remember { mutableStateOf(false) } + + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = PulseColors.background) { + Column( + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp) + .padding(bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Text(tr("Past conversations"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) + if (conversations.isEmpty()) { + Text( + tr("No conversations yet. Ask the coach something and it will show up here."), + fontSize = 14.sp, color = PulseColors.textMuted, + ) + } else { + Text(tr("Swipe a conversation to delete it."), fontSize = 12.sp, color = PulseColors.textMuted) + LazyColumn( + Modifier.weight(1f, fill = false), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + items(conversations, key = { it.id }) { convo -> + HistoryRow( + convo = convo, + isCurrent = convo.id == currentId, + onOpen = { onOpen(convo.id) }, + onSwipedAway = { pendingDelete = convo }, + ) + } + } + PulseButton( + PulseButtonStyle.Text, + onClick = { confirmDeleteAll = true }, + modifier = Modifier.align(Alignment.CenterHorizontally), + ) { Text(tr("Delete all conversations"), color = PulseColors.danger) } + } + } + } + + pendingDelete?.let { convo -> + AlertDialog( + onDismissRequest = { pendingDelete = null }, + title = { Text(tr("Delete this conversation?")) }, + text = { + Text(trf("“{0}” and its replies will be deleted. This can't be undone.", CoachHistoryText.title(convo.firstQuestion))) + }, + confirmButton = { + PulseButton(PulseButtonStyle.Text, onClick = { onDelete(convo.id); pendingDelete = null }) { + Text(tr("Delete"), color = PulseColors.danger) + } + }, + dismissButton = { + PulseButton(PulseButtonStyle.Text, onClick = { pendingDelete = null }) { Text(tr("Cancel")) } + }, + ) + } + if (confirmDeleteAll) { + AlertDialog( + onDismissRequest = { confirmDeleteAll = false }, + title = { Text(tr("Delete all conversations?")) }, + text = { + Text(trf("All {0} conversations and their replies will be deleted. This can't be undone.", conversations.size)) + }, + confirmButton = { + PulseButton(PulseButtonStyle.Text, onClick = { confirmDeleteAll = false; onDeleteAll() }) { + Text(tr("Delete all"), color = PulseColors.danger) + } + }, + dismissButton = { + PulseButton(PulseButtonStyle.Text, onClick = { confirmDeleteAll = false }) { Text(tr("Cancel")) } + }, + ) + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun HistoryRow( + convo: CoachConversationSummary, + isCurrent: Boolean, + onOpen: () -> Unit, + onSwipedAway: () -> Unit, +) { + // The swipe only asks; the row snaps back and the dialog decides. Returning false keeps the + // state from settling on "dismissed", which would leave a cancelled row swiped off screen. + val dismissState = rememberSwipeToDismissBoxState( + confirmValueChange = { value -> + if (value != SwipeToDismissBoxValue.Settled) onSwipedAway() + false + }, + ) + val shape = RoundedCornerShape(8.dp) + val deleteLabel = tr("Delete") + SwipeToDismissBox( + state = dismissState, + backgroundContent = { + Box( + Modifier + .fillMaxSize() + .clip(shape) + .background(PulseColors.danger.copy(alpha = 0.25f)) + .padding(horizontal = 16.dp), + contentAlignment = Alignment.CenterEnd, + ) { + Icon(Icons.Filled.Delete, deleteLabel, tint = PulseColors.danger) + } + }, + ) { + Row( + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(shape) + .background(PulseColors.card) + // The open conversation is told apart by its "open now" line and a stronger edge; + // not the brand colour, which marks what to tap. + .border(1.dp, if (isCurrent) PulseColors.textMuted else PulseColors.borderSubtle, shape) + .clickable(role = Role.Button, onClick = onOpen) + // A swipe can't be found or performed by every user; the same delete is offered + // as an accessibility action. + .semantics { + customActions = listOf(CustomAccessibilityAction(deleteLabel) { onSwipedAway(); true }) + } + .padding(start = 16.dp, end = 8.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Column(Modifier.weight(1f)) { + Text( + CoachHistoryText.title(convo.firstQuestion), + fontSize = 14.sp, color = PulseColors.textPrimary, + maxLines = 2, overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(2.dp)) + Text( + CoachHistoryText.subtitle(convo, isCurrent), + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } + Chevron() + } + } +} + +/** The history row's text, kept out of the composable so it can be unit-tested. */ +internal object CoachHistoryText { + + fun title(firstQuestion: String?): String = + firstQuestion?.replace(Regex("\\s+"), " ")?.trim()?.takeIf { it.isNotEmpty() } + ?: tr("Untitled conversation") + + fun subtitle( + convo: CoachConversationSummary, + isCurrent: Boolean, + zone: ZoneId = ZoneId.systemDefault(), + today: LocalDate = LocalDate.now(zone), + ): String { + val parts = mutableListOf(whenText(convo.updatedAt, zone, today)) + parts += if (convo.messageCount == 1) tr("1 message") else trf("{0} messages", convo.messageCount) + if (isCurrent) parts += tr("open now") + return parts.joinToString(" · ") + } + + fun whenText(epochMs: Long, zone: ZoneId, today: LocalDate): String { + val at = Instant.ofEpochMilli(epochMs).atZone(zone) + val day = at.toLocalDate() + return when { + day == today -> trf("Today {0}", at.format(time())) + day == today.minusDays(1) -> trf("Yesterday {0}", at.format(time())) + day.year == today.year -> at.format(DateTimeFormatter.ofPattern("MMM d", Locale.getDefault())) + else -> at.format(DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.getDefault())) + } + } + + // Built per call, not held in vals: the default Locale follows the app language (L10n), so a + // formatter created once would keep the first language's month names. + private fun time(): DateTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt index 5dc5d58b..5eae75ee 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/CoachScreen.kt @@ -30,6 +30,7 @@ import androidx.compose.material.icons.filled.AddPhotoAlternate import androidx.compose.material.icons.outlined.Flag import androidx.compose.material.icons.filled.ArrowUpward import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Info import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -51,6 +52,7 @@ import androidx.compose.ui.semantics.liveRegion import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -202,6 +204,8 @@ fun CoachScreen( fun CoachHeader( onNewChat: () -> Unit, onOpenUsage: (() -> Unit)? = null, + /** Opens the past-conversations sheet (issue #131). */ + onOpenHistory: (() -> Unit)? = null, onBack: (() -> Unit)? = null, /** Replaces "Using your latest ring sync", e.g. "On this phone · Gemma 3 1B". */ subtitle: String? = null, @@ -235,16 +239,31 @@ fun CoachHeader( ) } Column(Modifier.weight(1f)) { - Text(tr("PulseLoop Coach"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary) - Text(subtitle ?: tr("Using your latest ring sync"), fontSize = 12.sp, color = PulseColors.textMuted) + Text( + tr("PulseLoop Coach"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, + maxLines = 1, overflow = TextOverflow.Ellipsis, + ) + Text( + subtitle ?: tr("Using your latest ring sync"), fontSize = 12.sp, color = PulseColors.textMuted, + maxLines = 1, overflow = TextOverflow.Ellipsis, + ) } - if (onOpenUsage != null) { - RoundIconTarget(visualSize = 36.dp, onClick = onOpenUsage) { - Icon(Icons.Filled.Info, tr("Usage & cost"), tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp)) + // The actions sit side by side with no extra gap: each 48dp target already pads its 36dp + // circle, so three of them (usage, past conversations, new chat) still leave the title room. + Row(verticalAlignment = Alignment.CenterVertically) { + if (onOpenUsage != null) { + RoundIconTarget(visualSize = 36.dp, onClick = onOpenUsage) { + Icon(Icons.Filled.Info, tr("Usage & cost"), tint = PulseColors.textSecondary, modifier = Modifier.size(16.dp)) + } + } + if (onOpenHistory != null) { + RoundIconTarget(visualSize = 36.dp, onClick = onOpenHistory) { + Icon(Icons.Filled.History, tr("Past conversations"), tint = PulseColors.textSecondary, modifier = Modifier.size(20.dp)) + } + } + RoundIconTarget(visualSize = 36.dp, onClick = onNewChat) { + Icon(Icons.Filled.Add, tr("New chat"), tint = PulseColors.textSecondary, modifier = Modifier.size(20.dp)) } - } - RoundIconTarget(visualSize = 36.dp, onClick = onNewChat) { - Icon(Icons.Filled.Add, tr("New chat"), tint = PulseColors.textSecondary, modifier = Modifier.size(20.dp)) } } } diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 9d52e7d6..47d69813 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -6,6 +6,7 @@ import com.pulseloop.ui.i18n.tr import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import androidx.room.withTransaction import com.pulseloop.data.ActivityBucketDeletion import com.pulseloop.data.DemoDataPolicy import com.pulseloop.data.PulseLoopDatabase @@ -978,11 +979,15 @@ class CoachViewModel( private val attachmentPayloads: (List) -> List = { emptyList() }, /** Opt-in city + weather (iOS #65d), injected so the VM stays context-free like [attachmentPayloads]. */ private val environmentSnapshot: suspend () -> com.pulseloop.coach.context.EnvironmentContext? = { null }, + /** Deletes the image files behind attachment refs, when their conversation is deleted (issue #131). */ + private val deleteAttachments: (List) -> Unit = {}, ) : ViewModel() { data class CoachState( val messages: List = emptyList(), val isThinking: Boolean = false, val error: String? = null, + /** The thread on screen, so the history sheet can mark it (issue #131). */ + val conversationId: String? = null, ) data class ChatMessage( @@ -1049,15 +1054,69 @@ class CoachViewModel( private suspend fun loadOrCreateConversation() { val existing = db.coachConversationDao().recent(limit = 1).firstOrNull() if (existing != null) { - currentConversation = existing - val messages = db.coachMessageDao().forConversation(existing.id) - if (messages.isNotEmpty()) { - _state.update { it.copy(messages = messages.map { m -> m.toChatMessage() }) } - } + show(existing) return } currentConversation = CoachConversationEntity() db.coachConversationDao().upsert(currentConversation) + _state.update { it.copy(conversationId = currentConversation.id) } + } + + /** Make [conversation] the active thread and show its persisted messages (or the greeting). */ + private suspend fun show(conversation: CoachConversationEntity) { + currentConversation = conversation + val messages = db.coachMessageDao().forConversation(conversation.id) + _state.value = CoachState( + messages = if (messages.isEmpty()) listOf(greeting) else messages.map { m -> m.toChatMessage() }, + conversationId = conversation.id, + ) + } + + /** Past conversations for the history sheet (issue #131), newest first, empty ones left out. */ + val history: Flow> = + db.coachConversationDao().historyFlow() + + /** + * Reopen a past conversation (issue #131). A turn still in flight on the old thread keeps + * going and is stored under it; it just no longer lands on screen (see [sendMessage]). + */ + fun openConversation(id: String) { + if (id == currentConversation.id) return + conversationReady = viewModelScope.launch { + val conversation = db.coachConversationDao().byId(id) ?: return@launch + show(conversation) + } + } + + /** Delete one conversation with its messages, tool-call trace and attached images (issue #131). + * Deleting the one on screen starts a new thread in its place. */ + fun deleteConversation(id: String) { + val wasCurrent = id == currentConversation.id + if (wasCurrent) newConversation() + viewModelScope.launch { + val attachments = db.coachMessageDao().attachmentsJsonFor(id) + db.withTransaction { + db.coachToolCallDao().deleteForConversation(id) + db.coachMessageDao().deleteForConversation(id) + db.coachConversationDao().deleteById(id) + } + deleteAttachments(attachments.flatMap { com.pulseloop.coach.attachments.CoachAttachmentRef.decode(it) }) + } + } + + /** Delete every conversation (issue #131) and start a new one. */ + fun deleteAllConversations() { + viewModelScope.launch { + conversationReady.join() + val attachments = db.coachMessageDao().allAttachmentsJson() + db.withTransaction { + db.coachToolCallDao().deleteAll() + db.coachMessageDao().deleteAll() + db.coachConversationDao().deleteAll() + } + deleteAttachments(attachments.flatMap { com.pulseloop.coach.attachments.CoachAttachmentRef.decode(it) }) + newConversation() + } } /** The active thread's id, for the usage sheet — a one-shot fetch when the sheet opens rather @@ -1087,8 +1146,8 @@ class CoachViewModel( /** Reset to a fresh thread (iOS CoachView "+" button). Starts a NEW persisted conversation — * the old one's rows are left in Room untouched, not deleted. */ fun newConversation() { - _state.value = CoachState(messages = listOf(greeting)) currentConversation = CoachConversationEntity() + _state.value = CoachState(messages = listOf(greeting), conversationId = currentConversation.id) conversationReady = viewModelScope.launch { db.coachConversationDao().upsert(currentConversation) } } @@ -1149,13 +1208,20 @@ class CoachViewModel( // `error`, or CoachScreen renders a duplicate "Error: " footer for the same // failure. `error` stays null here and is reserved for the catch-block path below, // which shows a plain (non-error-bubble) apology and needs the footer. - _state.update { it.copy( - messages = it.messages + reply, - isThinking = false, - ) } + // Only onto the thread it was asked in: after "+" or opening another conversation + // mid-turn, the reply is stored under its own thread but not shown on this one. + if (currentConversation.id == conversationId) { + _state.update { it.copy( + messages = it.messages + reply, + isThinking = false, + ) } + } // A failed turn still burned tokens, so it's persisted too (role "error", not // "assistant") — the context-replay filter above keys off isError, not the // persisted role, so this doesn't leak into future prompts. + // Deleted while the provider was answering (issue #131): storing the reply and + // touching the row below would bring the conversation back with half its turn. + if (db.coachConversationDao().byId(conversationId) == null) return@launch val persistedRole = if (reply.isError) "error" else "assistant" val usage = result.usage // Cost prefers the provider-reported figure (OpenRouter); else the catalog @@ -1194,10 +1260,12 @@ class CoachViewModel( } catch (e: Exception) { // A state, not a log: the exception text goes to logcat, not into the chat. android.util.Log.w("CoachViewModel", "Coach turn failed", e) - _state.update { it.copy( - messages = it.messages + ChatMessage("assistant", tr("Couldn't reach the coach. Try again."), isError = true), - isThinking = false, error = null, - ) } + if (currentConversation.id == conversationId) { + _state.update { it.copy( + messages = it.messages + ChatMessage("assistant", tr("Couldn't reach the coach. Try again."), isError = true), + isThinking = false, error = null, + ) } + } } } } diff --git a/app/src/test/java/com/pulseloop/ui/screens/CoachHistoryTextTest.kt b/app/src/test/java/com/pulseloop/ui/screens/CoachHistoryTextTest.kt new file mode 100644 index 00000000..ba47a129 --- /dev/null +++ b/app/src/test/java/com/pulseloop/ui/screens/CoachHistoryTextTest.kt @@ -0,0 +1,54 @@ +package com.pulseloop.ui.screens + +import com.pulseloop.data.dao.CoachConversationSummary +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZoneId + +/** Issue #131: how a past coach conversation reads in the history sheet. */ +class CoachHistoryTextTest { + + private val zone = ZoneId.of("Europe/Paris") + private val today = LocalDate.of(2026, 10, 21) + + private fun ms(y: Int, mo: Int, d: Int, h: Int = 9, mi: Int = 15): Long = + LocalDateTime.of(y, mo, d, h, mi).atZone(zone).toInstant().toEpochMilli() + + private fun convo(updatedAt: Long, count: Int = 4) = + CoachConversationSummary("id", updatedAt, updatedAt, "How did I sleep?", count) + + @Test + fun `title is the first question on one line`() { + assertEquals("How did I sleep last night?", CoachHistoryText.title(" How did I sleep\n\nlast night? ")) + } + + @Test + fun `missing or blank question gets a placeholder`() { + assertEquals("Untitled conversation", CoachHistoryText.title(null)) + assertEquals("Untitled conversation", CoachHistoryText.title(" \n ")) + } + + @Test + fun `today and yesterday are named with the time`() { + assertTrue(CoachHistoryText.whenText(ms(2026, 10, 21), zone, today).startsWith("Today ")) + assertTrue(CoachHistoryText.whenText(ms(2026, 10, 20), zone, today).startsWith("Yesterday ")) + } + + @Test + fun `older dates show the year only when it differs`() { + assertFalse(CoachHistoryText.whenText(ms(2026, 10, 12), zone, today).contains("2026")) + assertTrue(CoachHistoryText.whenText(ms(2025, 12, 30), zone, today).contains("2025")) + } + + @Test + fun `subtitle counts messages and marks the open conversation`() { + val at = ms(2026, 10, 12) + val date = CoachHistoryText.whenText(at, zone, today) + assertEquals("$date · 1 message", CoachHistoryText.subtitle(convo(at, 1), false, zone, today)) + assertEquals("$date · 4 messages · open now", CoachHistoryText.subtitle(convo(at), true, zone, today)) + } +} From 411fecded585ec4945784f10084efeba40576199 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:35:16 +0000 Subject: [PATCH 5/7] Port upstream #134: longer SpO2 intervals and app-started spot SpO2 (#103, #106) - ScheduledSpo2Worker/Slots/Prefs: opt-in spot SpO2 started by the app on its own 60/120/180-min cadence, halfway between the ring's own readings, holding the link until 04 0e; offered for YCBT and COLMI_SMART_HEALTH rings with manual SpO2. Revived from app start and RingSyncWorker; RingSyncWorker yields while a scheduled run measures, and the worker waits out a sync. Includes the follow-up that skips successor scheduling when a run is stopped, so a retried run does not double the chain. - EventPersistenceSubscriber is one per process and started from PulseLoopApplication, so a background-only process persists what it syncs. - YCBT heart-rate monitor accepts 120 min; the other samplers keep 60. - "Hide estimated SpO2" filters hourly estimates out of Vitals/Today and the detail chart; detail rows label estimated readings. Estimated SpO2 and YCBT respiratory rate are no longer exported to Health Connect. - Day-view charts scale the line-break gap with the median sample interval. - Sleep: the records card shows for single-record nights too. Adapted to this fork: text through tr()/trf(), 12sp floor and token colours for the estimated chip, 48dp delete target kept. The scheduled_spo2 prefs file rides in ArchivedSettings (hide_estimated decides whether data shows). Ported from foureight84/PulseLoopAndroid#134 (f9fba78) and its follow-up (3f39c09). Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../main/java/com/pulseloop/AppServices.kt | 13 +- .../com/pulseloop/PulseLoopApplication.kt | 4 + .../com/pulseloop/data/ArchivedSettings.kt | 4 + .../health/exporters/VitalsExporter.kt | 27 +- .../java/com/pulseloop/ring/YCBTEncoder.kt | 10 +- .../service/EventPersistenceSubscriber.kt | 23 ++ .../com/pulseloop/service/RingSyncWorker.kt | 14 + .../pulseloop/service/ScheduledSpo2Slots.kt | 71 +++++ .../pulseloop/service/ScheduledSpo2Worker.kt | 245 ++++++++++++++++++ .../pulseloop/settings/ScheduledSpo2Prefs.kt | 77 ++++++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 4 +- .../com/pulseloop/ui/components/Charts.kt | 3 +- .../pulseloop/ui/components/ZoneLineChart.kt | 9 +- .../ui/components/ZoneLineSplitter.kt | 37 ++- .../java/com/pulseloop/ui/screens/Screens.kt | 17 +- .../ui/screens/SettingsSubScreens.kt | 117 ++++++++- .../com/pulseloop/ui/screens/SleepScreen.kt | 11 +- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 50 +++- .../pulseloop/widgets/WidgetTileRenderer.kt | 4 +- .../health/VitalsExporterFilteringTest.kt | 50 ++++ .../com/pulseloop/ring/YCBTEncoderTest.kt | 15 ++ .../service/ScheduledSpo2SlotsTest.kt | 146 +++++++++++ .../service/ScheduledSpo2WorkerTest.kt | 80 ++++++ .../settings/ScheduledSpo2PrefsTest.kt | 114 ++++++++ .../ui/components/ZoneLineSplitterTest.kt | 41 +++ 25 files changed, 1135 insertions(+), 51 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/ScheduledSpo2Slots.kt create mode 100644 app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt create mode 100644 app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt create mode 100644 app/src/test/java/com/pulseloop/health/VitalsExporterFilteringTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/ScheduledSpo2SlotsTest.kt create mode 100644 app/src/test/java/com/pulseloop/service/ScheduledSpo2WorkerTest.kt create mode 100644 app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt diff --git a/app/src/main/java/com/pulseloop/AppServices.kt b/app/src/main/java/com/pulseloop/AppServices.kt index 6c740795..8c59e441 100644 --- a/app/src/main/java/com/pulseloop/AppServices.kt +++ b/app/src/main/java/com/pulseloop/AppServices.kt @@ -13,7 +13,6 @@ import com.pulseloop.service.GpsRouteRecorder import com.pulseloop.service.LiveWorkoutManager import com.pulseloop.service.RingSyncCoordinator import com.pulseloop.settings.ApiKeyStore -import com.pulseloop.widgets.WidgetSnapshotPublisher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -39,12 +38,8 @@ class AppServices private constructor(context: Context) { val gpsRecorder = GpsRouteRecorder(context, db) val liveWorkout = LiveWorkoutManager(coordinator, db, gpsRecorder, context) - // Every persisted ring-sync batch republishes the widget snapshot (debounced 2 s), - // mirroring the iOS PulseDataChange → WidgetSnapshotPublisher pipeline. - val persistence = EventPersistenceSubscriber( - context, db, - onDataPersisted = { WidgetSnapshotPublisher.publishDebounced(context) }, - ) + /** Process-wide, not per-[AppServices]: background workers need it without the UI's services. */ + val persistence = EventPersistenceSubscriber.shared(context) val batteryAlerts = BatteryAlertMonitor(context) val providerStore = CoachProviderSettingsStore(context) val summaryCoordinator = CoachSummaryCoordinator(db, apiKeyStore, providerStore) @@ -85,6 +80,10 @@ class AppServices private constructor(context: Context) { instance ?: synchronized(this) { instance ?: AppServices(context.applicationContext).also { instance = it } } + + /** The services if the UI already built them, without building them: a background worker + * must not create the app's ring client, whose watchdog would start reconnecting. */ + fun peek(): AppServices? = instance } } diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 8fd3574b..74864c83 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -8,6 +8,7 @@ import com.pulseloop.data.DataRepairs import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.diagnostics.CrashLogger import com.pulseloop.diagnostics.DiagnosticsSubscriber +import com.pulseloop.service.EventPersistenceSubscriber import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.widgets.WidgetRefreshWorker import com.pulseloop.widgets.WidgetSnapshotPublisher @@ -40,6 +41,9 @@ class PulseLoopApplication : Application() { // What the ring saw the user doing, said after each sync (docs/activity-recognition-plan.md). com.pulseloop.notifications.ActivityDetectionNotifier.createChannel(this) com.pulseloop.notifications.ActivityDetectionNotifier.start(this, appScope) + // Same reason, for the ring data itself: a process launched only for RingSyncWorker never + // runs the UI's startup, and without a collector its events are dropped. + EventPersistenceSubscriber.shared(this).start() // One-time cleanup of activity totals corrupted by the old bucket handling; runs off the // main thread and is prefs-gated so it executes once. Safe to race the first sync — the // ring can't connect before this completes a couple of DELETE statements. diff --git a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt index 5307d7aa..4010d0f3 100644 --- a/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt +++ b/app/src/main/java/com/pulseloop/data/ArchivedSettings.kt @@ -44,6 +44,10 @@ object ArchivedSettings { "rest_mode" to emptySet(), // Whether the coach may use the lab results. "lab_reports" to emptySet(), + // Issue #103: whether estimated hourly SpO₂ is shown at all, and the app-started spot SpO₂ + // the user chose (on/off, every 1–3 h). The worker re-checks the ring before each run, so + // a restore onto a phone with another ring (or none) measures nothing. + "scheduled_spo2" to emptySet(), // Never "mcp_server": the network server's switch and paired-tool tokens are device state // and security material, so a restore starts off with nothing paired (docs/mcp-threat-model.md). ) diff --git a/app/src/main/java/com/pulseloop/health/exporters/VitalsExporter.kt b/app/src/main/java/com/pulseloop/health/exporters/VitalsExporter.kt index 0c5a887d..50b065cc 100644 --- a/app/src/main/java/com/pulseloop/health/exporters/VitalsExporter.kt +++ b/app/src/main/java/com/pulseloop/health/exporters/VitalsExporter.kt @@ -44,6 +44,16 @@ import java.time.ZoneId */ class VitalsExporter(private val db: PulseLoopDatabase) { + companion object { + /** Issue #103: only export genuine spot/measured SpO2; exclude hourly estimates derived from HR. */ + fun shouldExportSpo2(value: Double, timestamp: Long, estimatedTimestamps: Set): Boolean = + HealthConnectTypeMappings.isPlausibleSpO2(value) && timestamp !in estimatedTimestamps + + /** Issue #103: do not export respiratory rate for rings that derive it from heart rate. */ + fun shouldExportRespRate(value: Double, isYcbt: Boolean): Boolean = + !isYcbt && HealthConnectTypeMappings.isPlausibleRespRate(value) + } + /** * kindKey (the id token, e.g. "hr") -> the `measurements.kindRaw` column value to query. * Every write path persists kindRaw = MeasurementKind..name (EventPersistenceSubscriber, @@ -227,11 +237,24 @@ class VitalsExporter(private val db: PulseLoopDatabase) { val highWaters = mutableListOf() var droppedHigh: Long? = selected.filter { it.sourceRaw in EXCLUDED_SOURCES } .maxOfOrNull { it.createdAt } + + val estimatedSpo2 = if (kindKey == "spo2" && rows.isNotEmpty()) { + val minTs = rows.minOf { it.timestamp } + val maxTs = rows.maxOf { it.timestamp } + com.pulseloop.service.EstimatedSpo2.estimatedTimestamps(db.measurementDao(), minTs, maxTs) + } else emptySet() + + val currentRealDevice = if (kindKey == "resp_rate") db.deviceDao().currentReal() else null + val isYcbt = currentRealDevice?.deviceType in setOf( + com.pulseloop.ring.RingDeviceType.YCBT, + com.pulseloop.ring.RingDeviceType.COLMI_SMART_HEALTH, + ) + for (row in rows) { val instant = Instant.ofEpochMilli(row.timestamp) val offset = HealthConnectTypeMappings.zoneOffsetAt(instant, zone) val record: Record? = when (kindKey) { - "spo2" -> if (HealthConnectTypeMappings.isPlausibleSpO2(row.value)) { + "spo2" -> if (shouldExportSpo2(row.value, row.timestamp, estimatedSpo2)) { OxygenSaturationRecord(instant, offset, Percentage(row.value), metadata(row, "spo2", device)) } else null "hrv" -> if (HealthConnectTypeMappings.isPlausibleHrvRmssd(row.value)) { @@ -254,7 +277,7 @@ class VitalsExporter(private val db: PulseLoopDatabase) { metadata = metadata(row, "glucose", device), ) } else null - "resp_rate" -> if (HealthConnectTypeMappings.isPlausibleRespRate(row.value)) { + "resp_rate" -> if (shouldExportRespRate(row.value, isYcbt)) { RespiratoryRateRecord( time = instant, zoneOffset = offset, diff --git a/app/src/main/java/com/pulseloop/ring/YCBTEncoder.kt b/app/src/main/java/com/pulseloop/ring/YCBTEncoder.kt index 2f8aa5bf..3d75a628 100644 --- a/app/src/main/java/com/pulseloop/ring/YCBTEncoder.kt +++ b/app/src/main/java/com/pulseloop/ring/YCBTEncoder.kt @@ -25,6 +25,7 @@ class YCBTSettingsEncoder { companion object { const val MINIMUM_INTERVAL_MINUTES = 30 const val DEFAULT_INTERVAL_MINUTES = 60 + private const val MONITOR_INTERVAL_CEILING_MINUTES = 60 fun clampInterval(minutes: Int): Int { if (minutes <= 0) return DEFAULT_INTERVAL_MINUTES @@ -78,9 +79,14 @@ class YCBTSettingsEncoder { /** The five background samplers, each {enable, intervalMinutes}. */ fun monitorCommands(settings: MeasurementSettings): List { - val interval = clampInterval(settings.hrIntervalMinutes).toByte() + val hrInterval = clampInterval(settings.hrIntervalMinutes) + // 120 min is only evidenced on the heart-rate key itself (issue #103: the ring ACKed + // `01 0c 01 78` and read at 10:00 and 12:00). Every other sampler keeps the 60-min ceiling + // the UI always had, so their on-air bytes are unchanged — in particular the blood-oxygen + // key, whose grid the scheduled spot SpO₂ has to stay between. + val interval = minOf(hrInterval, MONITOR_INTERVAL_CEILING_MINUTES).toByte() return listOf( - heartMonitor(enabled = settings.hrEnabled, intervalMinutes = interval), + heartMonitor(enabled = settings.hrEnabled, intervalMinutes = hrInterval.toByte()), bloodPressureMonitor(enabled = settings.hrEnabled, intervalMinutes = interval), temperatureMonitor(enabled = settings.temperatureEnabled, intervalMinutes = interval), // Blood oxygen carries its own interval where the user set one (issue #66); 0 means diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 7ad3e3d4..b8e3466e 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -8,6 +8,7 @@ import com.pulseloop.data.entity.* import com.pulseloop.health.HealthConnectExportWorker import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.ring.* +import com.pulseloop.widgets.WidgetSnapshotPublisher import kotlinx.coroutines.* import kotlinx.coroutines.sync.withLock @@ -889,6 +890,28 @@ class EventPersistenceSubscriber( /** How far back [spotReadings] is primed from the table on first use. */ const val SPOT_LOOKBACK_MS = 7L * 24 * 60 * 60_000 private const val MAX_SLEEP_TIMELINE_MINUTES = 24 * 60 + + @Volatile private var shared: EventPersistenceSubscriber? = null + + /** + * The process's one subscriber, started from `PulseLoopApplication.onCreate`. + * + * It used to be built and started only by the UI's startup (`AppServices` / + * `PulseLoopApp`). A process Android launched just to run `RingSyncWorker` never got + * there, and the bus keeps no backlog (`replay = 0`), so everything that background sync + * pulled from the ring was published to no one and dropped. + */ + fun shared(context: Context): EventPersistenceSubscriber = + shared ?: synchronized(this) { + shared ?: context.applicationContext.let { app -> + // Every persisted ring-sync batch republishes the widget snapshot (debounced + // 2 s), mirroring the iOS PulseDataChange → WidgetSnapshotPublisher pipeline. + EventPersistenceSubscriber( + app, PulseLoopDatabase.getInstance(app), + onDataPersisted = { WidgetSnapshotPublisher.publishDebounced(app) }, + ) + }.also { shared = it } + } } } diff --git a/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt b/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt index 134b4f01..4e74a053 100644 --- a/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt +++ b/app/src/main/java/com/pulseloop/service/RingSyncWorker.kt @@ -32,6 +32,10 @@ class RingSyncWorker( private const val SYNC_TIMEOUT_SECONDS = 45L private const val TAG = "RingSyncWorker" + @Volatile + var isSyncing: Boolean = false + internal set + /** Schedule periodic background ring sync. Call from MainActivity. */ fun schedule(context: Context) { val request = PeriodicWorkRequestBuilder( @@ -63,11 +67,19 @@ class RingSyncWorker( } override suspend fun doWork(): Result { + // The scheduled spot SpO₂ chain (issue #103) dies if one of its runs is cancelled; this + // periodic job is what reliably comes back, so it revives it. + ScheduledSpo2Worker.ensureScheduled(applicationContext) + // The foreground app owns the live GATT. An overdue periodic job can start at the same // moment as MainActivity after process launch; opening a second client interleaves both // command queues and lets this worker's cleanup disconnect the UI-owned session. if (isAppForeground()) return Result.success() + // If scheduled spot SpO2 is in flight, yield this periodic sync window — the SpO2 worker + // runs startup sync anyway so history is still pulled without fighting over GATT (issue #103). + if (ScheduledSpo2Worker.isMeasuring) return Result.success() + val keyStore = ApiKeyStore(applicationContext) val db = PulseLoopDatabase.getInstance(applicationContext) @@ -85,6 +97,7 @@ class RingSyncWorker( val measurementSettings = loadPersistedMeasurementSettings(db) val profileValues = loadPersistedUserProfile(db, keyStore) + isSyncing = true return try { withTimeout(SYNC_TIMEOUT_SECONDS * 1000L) { // Connect to last-known ring @@ -130,6 +143,7 @@ class RingSyncWorker( } catch (e: Exception) { Result.retry() } finally { + isSyncing = false // This client is worker-owned. Cancel its watchdog as well as closing GATT so it // cannot reconnect after doWork() has returned. val releasedConnection = bleClient.destroy() diff --git a/app/src/main/java/com/pulseloop/service/ScheduledSpo2Slots.kt b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Slots.kt new file mode 100644 index 00000000..e7a3e3e6 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Slots.kt @@ -0,0 +1,71 @@ +package com.pulseloop.service + +import java.time.LocalTime +import java.time.ZonedDateTime + +/** + * When the app starts its own spot SpO₂ (issue #103). + * + * The ring runs its own all-day reading on a grid from local midnight at the configured interval + * (hourly on the reporter's ring: 06:00:42, 07:00:39, 08:00:26) and serves one measurement at a + * time: a second start dropped the first. So the app aims at the **midpoint** between two of the + * ring's readings — 60 min → :30, 30 min → :15 and :45 — the slot furthest from both. + * + * WorkManager runs late, and overnight Doze can hold a run for a long time. [isClear] is the guard + * for that: a run that would start within a few minutes of a ring reading, or still be measuring + * when the next one starts, is skipped instead. + * + * Local wall-clock seconds rather than epoch arithmetic, so a DST day keeps its slots on the half + * hour instead of shifting them by the hour the clock jumped. + */ +internal object ScheduledSpo2Slots { + + /** The ring ends a spot SpO₂ with `04 0e` at 50–63 s (issue #59 captures); the coordinator's + * ceiling for it is 75 s. */ + const val MEASUREMENT_SECONDS = 75 + + /** How far a run must start from the ring's own reading: five minutes, or a quarter of a + * shorter interval so a 15-minute grid still has room. */ + fun marginSeconds(intervalMinutes: Int): Int = minOf(5 * 60, intervalMinutes * 60 / 4) + + /** + * The first slot strictly after [now]. [intervalMinutes] is the app's own cadence; + * [ringIntervalMinutes] is the interval the ring reads SpO₂ on — slots start half of it past + * local midnight and repeat every [intervalMinutes]. At the ring's own cadence that is the + * midpoint between two of its readings; on a longer app interval (120/180 min) the grid keeps + * the same half-interval offset, which holds it clear of the ring's readings whenever the + * intervals divide evenly — and [isClear] skips any slot that lands close regardless. + */ + fun nextSlot( + now: ZonedDateTime, + intervalMinutes: Int, + ringIntervalMinutes: Int = intervalMinutes, + ): ZonedDateTime { + val interval = intervalMinutes * 60 + val half = when { + ringIntervalMinutes == 120 && intervalMinutes == 120 -> 60 * 60 + ringIntervalMinutes >= 60 -> 30 * 60 + else -> ringIntervalMinutes * 60 / 2 + } + val secs = now.toLocalTime().toSecondOfDay() + val k = if (secs < half) 0 else (secs - half) / interval + 1 + val slot = half + k * interval + val day = if (slot >= SECONDS_PER_DAY) now.toLocalDate().plusDays(1) else now.toLocalDate() + val slotOfDay = if (slot >= SECONDS_PER_DAY) half else slot + return day.atTime(LocalTime.ofSecondOfDay(slotOfDay.toLong())).atZone(now.zone) + } + + /** Whether a measurement starting at [now] stays clear of the ring's readings either side. */ + fun isClear(now: ZonedDateTime, intervalMinutes: Int): Boolean { + val interval = intervalMinutes * 60 + val margin = marginSeconds(intervalMinutes) + val secs = now.toLocalTime().toSecondOfDay() + val sincePrevious = secs % interval + // The grid restarts at midnight, so an interval that doesn't divide the day has a short + // last step before it. + val untilNext = minOf(interval - sincePrevious, SECONDS_PER_DAY - secs) + return sincePrevious >= margin && untilNext >= margin + MEASUREMENT_SECONDS + } + + private const val SECONDS_PER_DAY = 24 * 60 * 60 +} diff --git a/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt new file mode 100644 index 00000000..73674cc4 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/ScheduledSpo2Worker.kt @@ -0,0 +1,245 @@ +package com.pulseloop.service + +import android.content.Context +import android.util.Log +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.ProcessLifecycleOwner +import androidx.work.* +import com.pulseloop.AppServices +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.ring.PulseEvent +import com.pulseloop.ring.PulseEventBus +import com.pulseloop.ring.RingBLEClient +import com.pulseloop.ring.RingConnectionState +import com.pulseloop.settings.ApiKeyStore +import com.pulseloop.settings.ScheduledSpo2Prefs +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import java.time.Duration +import java.time.ZonedDateTime +import java.util.concurrent.TimeUnit + +/** + * Starts a real spot SpO₂ on the app's own schedule (issue #103), when the user opted in + * ([ScheduledSpo2Prefs] — a cadence of its own, 60/120/180 min, independent of the ring's SpO₂ + * interval). + * + * One-time work that enqueues the next slot as it finishes, rather than periodic work: a periodic + * request can't be pinned to the half hour, and its 15-minute floor and flex would put runs on top + * of the ring's own reading. It is best effort — Doze defers it, and [ScheduledSpo2Slots.isClear] + * skips a run that lands too close to the ring's reading. A cancelled chain is revived by + * [ensureScheduled] from app start and from every [RingSyncWorker] run. + * + * The ring stops the measurement the moment the link drops (the reporter's test: start, disconnect + * 3 s later, LED off, nothing stored), so the run holds the connection until the ring's `04 0e`. + * It uses the app's own connection when there is one, and otherwise opens a private one the way + * [RingSyncWorker] does, with its own [RingSyncCoordinator] so the reading is settled and stored + * exactly as the Vitals button's is. + */ +class ScheduledSpo2Worker( + context: Context, + params: WorkerParameters, +) : CoroutineWorker(context, params) { + + companion object { + private const val WORK_NAME = "scheduled_spot_spo2" + private const val TAG = "ScheduledSpo2Worker" + private const val CONNECT_TIMEOUT_MS = 45_000L + /** Startup history has to drain before the sensor is taken — the ring serves one thing at a time. */ + private const val SYNC_DRAIN_TIMEOUT_MS = 45_000L + + @Volatile + var isMeasuring: Boolean = false + internal set + + /** After a settings change: replace whatever is queued with the next slot, or cancel. */ + suspend fun reschedule(context: Context) { + enqueueNext(context, ExistingWorkPolicy.REPLACE) + } + + /** Revive the chain if it died (cancelled, or never started); a queued run is left alone. */ + suspend fun ensureScheduled(context: Context) { + enqueueNext(context, ExistingWorkPolicy.KEEP) + } + + internal fun shouldEnqueueNext(isStopped: Boolean): Boolean = !isStopped + + private suspend fun enqueueNext(context: Context, policy: ExistingWorkPolicy) { + val wm = WorkManager.getInstance(context) + if (!ScheduledSpo2Prefs(context).enabled) { + wm.cancelUniqueWork(WORK_NAME) + return + } + // A run re-checks the intervals when it starts, so a change after this only moves one run. + val appInterval = ScheduledSpo2Prefs(context).intervalMinutes + val ringInterval = withContext(Dispatchers.IO) { + intervalMinutes(PulseLoopDatabase.getInstance(context)) + } ?: run { wm.cancelUniqueWork(WORK_NAME); return } + val now = ZonedDateTime.now() + val delayMs = Duration.between(now, ScheduledSpo2Slots.nextSlot(now, appInterval, ringInterval)).toMillis() + val request = OneTimeWorkRequestBuilder() + .setInitialDelay(delayMs, TimeUnit.MILLISECONDS) + .setConstraints(Constraints.Builder().setRequiresBatteryNotLow(true).build()) + .build() + wm.enqueueUniqueWork(WORK_NAME, policy, request) + } + + /** + * The interval the ring measures on, to keep the app's spot SpO₂ clear of. + * On YCBT rings (including Colmi SmartHealth), background measurements follow the + * heart-rate schedule (the ring derives SpO₂ during HR measurements and ignores 0x26). + * Even if the user turns off the ring's SpO₂ toggle, the ring still measures on the HR + * interval. Supports HR intervals up to 120 min (issue #103). + */ + internal fun computeRingIntervalMinutes( + isYcbt: Boolean, + hrIntervalMinutes: Int, + spo2IntervalMinutes: Int, + spo2Enabled: Boolean, + ): Int? { + val minutes = if (isYcbt) { + hrIntervalMinutes.takeIf { it > 0 } ?: 60 + } else { + if (!spo2Enabled) return null + spo2IntervalMinutes.takeIf { it > 0 } ?: hrIntervalMinutes + } + return minutes.coerceIn(5, 120) + } + + private suspend fun intervalMinutes(db: PulseLoopDatabase): Int? { + val settings = loadPersistedMeasurementSettings(db) ?: return null + val device = db.deviceDao().currentReal() + val isYcbt = device?.deviceType in setOf( + com.pulseloop.ring.RingDeviceType.YCBT, + com.pulseloop.ring.RingDeviceType.COLMI_SMART_HEALTH, + ) + return computeRingIntervalMinutes( + isYcbt = isYcbt, + hrIntervalMinutes = settings.hrIntervalMinutes, + spo2IntervalMinutes = settings.spo2IntervalMinutes, + spo2Enabled = settings.spo2Enabled, + ) + } + } + + override suspend fun doWork(): Result { + if (!ScheduledSpo2Prefs(applicationContext).enabled) return Result.success() + val db = PulseLoopDatabase.getInstance(applicationContext) + try { + val ringInterval = intervalMinutes(db) ?: return Result.success() + if (!ScheduledSpo2Prefs.isSupported(db.deviceDao().currentReal())) return Result.success() + if (!ScheduledSpo2Slots.isClear(ZonedDateTime.now(), ringInterval)) { + Log.i(TAG, "Skipped: too close to the ring's own reading") + return Result.success() + } + measure(db) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Scheduled SpO2 failed", e) + } finally { + // Append: the next run waits for this one, and REPLACE from inside a running worker + // would cancel it. Always succeed, since a failed run fails its appended successor. + // Do not enqueue a successor if stopped/cancelled: WorkManager will retry a stopped + // worker (which will enqueue its own successor upon completion), and scheduling here + // would cause duplicate chained runs and schedule drift (issue #103). + if (shouldEnqueueNext(isStopped)) { + withContext(NonCancellable) { + enqueueNext(applicationContext, ExistingWorkPolicy.APPEND_OR_REPLACE) + } + } + } + return Result.success() + } + + private suspend fun measure(db: PulseLoopDatabase) { + isMeasuring = true + try { + measureInternal(db) + } finally { + isMeasuring = false + } + } + + private suspend fun measureInternal(db: PulseLoopDatabase) { + // The app's own link, if it has one: a second client can't connect while it holds GATT. + AppServices.peek()?.coordinator?.let { coordinator -> + val ran = withContext(Dispatchers.Main) { + if (!coordinator.isConnected) return@withContext false + // A workout polls SpO₂ itself, and a measurement in flight holds the sensor. + if (!coordinator.workoutHRActive) coordinator.measureSpO2Only() + true + } + if (ran) return + } + // The app is opening and owns the connection it is about to make. + if (isAppForeground()) return + + val client = RingBLEClient(applicationContext, transientOwner = true) + if (!client.hasPermissions()) { client.destroy(); return } + val coordinator = RingSyncCoordinator(client, db, ApiKeyStore(applicationContext)) + try { + withContext(Dispatchers.Main) { coordinator.start() } + // The same startup the app runs on connect: claims the ring and pushes settings, and + // pulls history while it is at it. + client.onConnected = { withContext(Dispatchers.Main) { coordinator.runStartupSequence() } } + client.connectLastKnown() + + // If background sync is currently running, pause our connect timeout countdown so we + // don't burn the connection budget while sync holds GATT (issue #103). + var remainingTimeoutMs = CONNECT_TIMEOUT_MS + var syncWaitMs = 60_000L + while (!coordinator.isConnected && remainingTimeoutMs > 0) { + if (isAppForeground()) return + if (RingSyncWorker.isSyncing && syncWaitMs > 0) { + delay(1000) + syncWaitMs -= 1000 + continue + } + if (client.state.value.connectionState == RingConnectionState.DISCONNECTED) { + client.connectLastKnown() + } + delay(1000) + remainingTimeoutMs -= 1000 + } + if (!coordinator.isConnected) return + + // runStartupSequence opens the progress just after connect; wait for it to open, then + // to drain (the same wait factoryResetRing uses before it takes the ring). + withTimeoutOrNull(3_000L) { coordinator.syncProgress.first { it != null } } + withTimeoutOrNull(SYNC_DRAIN_TIMEOUT_MS) { + coordinator.syncProgress.first { it == null || it >= 100 } + } + delay(800) + // Hand the ring over to the app if it opened meanwhile; once measuring, finish — the + // reading is lost if the link drops, and the app only waits for one minute. + if (isAppForeground() || !coordinator.isConnected) return + val value = withContext(Dispatchers.Main) { coordinator.measureSpO2Only() } + Log.i(TAG, "Scheduled SpO2: ${value ?: "no reading"}") + // The stop frame is only enqueued; let it reach the ring before the link closes. + client.awaitOpsFlushed() + } finally { + withContext(NonCancellable) { + // Cancel watchdog and tear down GATT before stopping coordinator, so that a + // CancellationException or failure in stop() cannot leave the BLE watchdog + // reconnecting indefinitely (issue #103). + val releasedConnection = client.destroy() + withContext(Dispatchers.Main) { coordinator.stop() } + if (releasedConnection && !isAppForeground()) { + PulseEventBus.publishBlocking( + PulseEvent.DeviceStateChanged(RingConnectionState.DISCONNECTED, null) + ) + } + } + } + } + + private suspend fun isAppForeground(): Boolean = withContext(Dispatchers.Main.immediate) { + ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) + } +} diff --git a/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt b/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt new file mode 100644 index 00000000..a37a6482 --- /dev/null +++ b/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt @@ -0,0 +1,77 @@ +package com.pulseloop.settings + +import android.content.Context +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.RingDeviceType +import com.pulseloop.ring.WearableCapability + +/** + * The opt-in behind issue #103: have the app start a real spot SpO₂ on the SpO₂ interval. + * + * On a YCBT ring the hourly SpO₂ is computed from heart rate (one HR always maps to the same + * value), so the history line is an estimate. The ring's manual measurement is real — red LED, + * logged on its own — so the app runs that instead, between the ring's own readings + * ([com.pulseloop.service.ScheduledSpo2Slots]). + * + * Off by default: each run holds the connection and the optical sensor for about a minute. + * In SharedPreferences rather than `device_measurement_configs` to stay clear of a schema bump. + * The file rides in the backup archive (`ArchivedSettings`): `hide_estimated` decides whether data + * shows, and the rest is the user's own choice — a restore must not drop either. + */ +class ScheduledSpo2Prefs internal constructor(private val prefs: android.content.SharedPreferences) { + + constructor(context: Context) : this(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)) + + var enabled: Boolean + get() = prefs.getBoolean(KEY_ENABLED, false) + set(value) { prefs.edit().putBoolean(KEY_ENABLED, value).apply() } + + /** + * How often the app starts its own spot SpO₂, in minutes — independent of the interval the + * ring reads SpO₂ on (issue #103: each app run holds the red LED and the link for ~50 s, so + * at 2–3 h the battery and the night-time flashes are both spared). The ring's own SpO₂ + * monitor keeps its own setting; the slots stay between its readings either way. + */ + var intervalMinutes: Int + get() = prefs.getInt(KEY_INTERVAL_MINUTES, DEFAULT_INTERVAL_MINUTES) + set(value) { prefs.edit().putInt(KEY_INTERVAL_MINUTES, sanitizeIntervalMinutes(value)).apply() } + + /** + * Whether to hide estimated hourly SpO₂ (computed by the ring from heart rate) and only + * display real spot measurements. Defaults to true. + */ + var hideEstimated: Boolean + get() = prefs.getBoolean(KEY_HIDE_ESTIMATED, true) + set(value) { prefs.edit().putBoolean(KEY_HIDE_ESTIMATED, value).apply() } + + companion object { + private const val PREFS_NAME = "scheduled_spo2" + private const val KEY_ENABLED = "enabled" + private const val KEY_INTERVAL_MINUTES = "interval_minutes" + private const val KEY_HIDE_ESTIMATED = "hide_estimated" + + /** Options are 60/120/180; 60 is what the app ran at before a choice existed. */ + const val DEFAULT_INTERVAL_MINUTES = 60 + const val MIN_INTERVAL_MINUTES = 60 + const val MAX_INTERVAL_MINUTES = 180 + + fun sanitizeIntervalMinutes(minutes: Int): Int { + val snapped = ((minutes + 30) / 60) * 60 + return snapped.coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES) + } + + /** + * Rings this is offered for: a manual SpO₂ that ends with the ring's own `04 0e` verdict, + * so the run has a known end and the connection can be released right after it. The YCBT + * protocol families signal that today (issue #59) — `COLMI_SMART_HEALTH` included, which + * rides the same [com.pulseloop.ring.YCBTDriver] but is its own `RingDeviceType`, so the + * original `== YCBT` check hid both #103 controls from those rings (issue #103, + * Albabit's `colmi-smarthealth` unit, 2026-10-23). + */ + fun isSupported(device: DeviceEntity?): Boolean = + device != null && device.deviceType in setOf( + RingDeviceType.YCBT, + RingDeviceType.COLMI_SMART_HEALTH, + ) && WearableCapability.MANUAL_SPO2 in device.capabilities + } +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index f5143954..748480f5 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -143,7 +143,7 @@ fun PulseLoopApp() { // ── ViewModels ─────────────────────────────────────────────────── val todayVM = remember { TodayViewModel(db, apiKeyStore) } - val vitalsVM = remember { VitalsViewModel(db, apiKeyStore) } + val vitalsVM = remember { VitalsViewModel(db, apiKeyStore, com.pulseloop.settings.ScheduledSpo2Prefs(context)) } val sleepVM = remember { val appContext = context.applicationContext SleepViewModel(db, gapBridge = { com.pulseloop.service.SleepGapBridge.fromSettings(appContext) }) @@ -246,6 +246,8 @@ fun PulseLoopApp() { // The breastfeeding allowance grows at six months and ends at twelve. runCatching { com.pulseloop.ui.screens.syncCalorieGoal(context.applicationContext) } runCatching { com.pulseloop.health.ProfileAging.refresh(db) } + // Opt-in app-started spot SpO₂ (issue #103); revives the chain if it was cancelled. + com.pulseloop.service.ScheduledSpo2Worker.ensureScheduled(context.applicationContext) // NOTE: demo data is never auto-seeded. A clean install starts empty so the UI // reflects only real ring data. Demo data is seeded exclusively via the diff --git a/app/src/main/java/com/pulseloop/ui/components/Charts.kt b/app/src/main/java/com/pulseloop/ui/components/Charts.kt index 12b26cc2..049e174e 100644 --- a/app/src/main/java/com/pulseloop/ui/components/Charts.kt +++ b/app/src/main/java/com/pulseloop/ui/components/Charts.kt @@ -387,7 +387,8 @@ fun TrendChart( // The primary line is drawn zone-split and gap-broken (iOS #35): each sample pair // splits at zone boundaries so a piece never spans two zones, and runs separated // by more than the range-tuned max gap break instead of bridging. - val maxGapMs = if (useTime) ZoneLineSplitter.maxGapMs(fullRangeMs) else Long.MAX_VALUE + val sampleInterval = ZoneLineSplitter.sampleIntervalMs(timestamps) + val maxGapMs = if (useTime) ZoneLineSplitter.maxGapMs(fullRangeMs, sampleInterval) else Long.MAX_VALUE val primaryOffsets = points.mapIndexed { i, v -> Offset(xForIndex(i), yForValue(v)) } val secondaryOffsets = secondary.mapIndexed { i, v -> Offset(xForSecondary(i), yForValue(v)) } clipRect(plotLeft, plotTop, plotRight, plotBottom) { diff --git a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt index 249fac86..9e286bcd 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineChart.kt @@ -85,7 +85,14 @@ fun ZoneLineChart( .filter { it > yDomain.start && it < yDomain.endInclusive } .distinct().sorted() // Computed once per data set rather than on every draw pass. - val runs = remember(samples, maxGapMs) { ZoneLineSplitter.segmentsByGap(samples.map { it.timestampMs }, maxGapMs) } + // The break threshold scales with the series' own cadence (issue #103), so 120/180-min readings + // stay connected in a day view while real gaps still break the line. + val runs = remember(samples, maxGapMs) { + val timestamps = samples.map { it.timestampMs } + val sampleInterval = ZoneLineSplitter.sampleIntervalMs(timestamps) + val effectiveMaxGapMs = ZoneLineSplitter.maxGapMs(span, sampleInterval).coerceAtLeast(maxGapMs) + ZoneLineSplitter.segmentsByGap(timestamps, effectiveMaxGapMs) + } val summary = remember(samples, label) { val values = samples.map { it.value } val fmt = if (values.all { it % 1.0 == 0.0 }) "%.0f" else "%.1f" diff --git a/app/src/main/java/com/pulseloop/ui/components/ZoneLineSplitter.kt b/app/src/main/java/com/pulseloop/ui/components/ZoneLineSplitter.kt index 1abb8ea5..432b3a8b 100644 --- a/app/src/main/java/com/pulseloop/ui/components/ZoneLineSplitter.kt +++ b/app/src/main/java/com/pulseloop/ui/components/ZoneLineSplitter.kt @@ -66,15 +66,42 @@ object ZoneLineSplitter { return runs } + /** + * Compute the representative sample interval in milliseconds across a series of timestamps. + * Uses the median delta between adjacent samples so that occasional spot readings or + * midnight double-records (e.g. 22s apart) don't collapse the interval down to seconds + * and break the chart line (issue #103). + */ + fun sampleIntervalMs(timestamps: List): Long? { + if (timestamps.size < 2) return null + val deltas = (1 until timestamps.size) + .map { timestamps[it] - timestamps[it - 1] } + .filter { it > 0 } + .sorted() + if (deltas.isEmpty()) return null + return deltas[deltas.size / 2] + } + /** * The maximum allowed gap before the line breaks, tuned to the plotted span so denser * windows break sooner. Mirrors ChartSampleBuilder.maxGap: 24h→90 min, 7d→36 h, * 30d→4 days, longer→45 days. + * + * In day view ([spanMs] <= 26h), [sampleIntervalMs] scales the break threshold to + * `max(90m, interval * 1.5)` so user-configured 120 min or 180 min intervals keep their + * points connected while still breaking across real gaps (issue #103). */ - fun maxGapMs(spanMs: Long): Long = when { - spanMs <= 26 * 3600_000L -> 90 * 60_000L - spanMs <= 8 * 86_400_000L -> 36 * 3600_000L - spanMs <= 32 * 86_400_000L -> 4 * 86_400_000L - else -> 45 * 86_400_000L + fun maxGapMs(spanMs: Long, sampleIntervalMs: Long? = null): Long { + val baseGap = when { + spanMs <= 26 * 3600_000L -> 90 * 60_000L + spanMs <= 8 * 86_400_000L -> 36 * 3600_000L + spanMs <= 32 * 86_400_000L -> 4 * 86_400_000L + else -> 45 * 86_400_000L + } + return if (sampleIntervalMs != null && sampleIntervalMs > 0 && spanMs <= 26 * 3600_000L) { + maxOf(baseGap, (sampleIntervalMs * 1.5).toLong()) + } else { + baseGap + } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt index 95d99906..0a358529 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/Screens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/Screens.kt @@ -679,7 +679,8 @@ fun VitalDetailScreen( // Glucose display unit for the detail chart's zones/axis/stats (iOS #43 §3); the VM already // converts the plotted readings, this converts the reference layer the screen owns. val gUnit = apiKeyStore?.preferredGlucoseUnit ?: com.pulseloop.service.GlucoseUnit.MGDL - val vm = remember { VitalDetailViewModel(db, metric, apiKeyStore, units) } + val scheduledSpo2Prefs = remember { com.pulseloop.settings.ScheduledSpo2Prefs(context) } + val vm = remember { VitalDetailViewModel(db, metric, apiKeyStore, units, scheduledSpo2Prefs) } val state by vm.state.collectAsState() val title = metricDisplayName(metric) @@ -1059,6 +1060,20 @@ private fun ReadingsCard( color = PulseColors.textMuted, ) } + // Issue #103: an hourly SpO₂ this ring computed from heart rate says so on its + // own row, in the same amber chip the Vitals card uses for ESTIMATED. + if (reading.isEstimated) { + Spacer(Modifier.width(4.dp)) + Text( + tr("Estimated"), + fontSize = 12.sp, + color = PulseColors.warning, + modifier = Modifier + .clip(RoundedCornerShape(50)) + .dither(PulseColors.warning, 0.14f) + .padding(horizontal = 8.dp, vertical = 2.dp), + ) + } IconButton(onClick = { pendingDelete = reading }) { Icon( Icons.Filled.DeleteOutline, diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 0f8b58f8..1d25534d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -63,6 +63,8 @@ import com.pulseloop.coach.config.MiniMaxModel import com.pulseloop.coach.config.OpenRouterModel import com.pulseloop.data.DemoDataSeeder import com.pulseloop.data.PulseLoopDatabase +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import com.pulseloop.data.entity.UserGoalEntity import com.pulseloop.health.HealthConnectAvailability import com.pulseloop.health.HealthConnectPermissions @@ -83,11 +85,13 @@ import com.pulseloop.service.GlucoseUnit import com.pulseloop.service.MetricZone import com.pulseloop.service.RingSyncCoordinator import com.pulseloop.service.RingSyncWorker +import com.pulseloop.service.ScheduledSpo2Worker import com.pulseloop.service.VitalColorToken import com.pulseloop.service.VitalSample import com.pulseloop.service.ZoneSeverity import com.pulseloop.settings.ApiKeyStore import com.pulseloop.settings.QuietHoursPrefs +import com.pulseloop.settings.ScheduledSpo2Prefs import com.pulseloop.settings.UnitSystem import com.pulseloop.settings.ZenModeListener import com.pulseloop.ui.components.DeviceHeroStatus @@ -1688,8 +1692,17 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U .collectAsState(initial = null).value val device: com.pulseloop.data.entity.DeviceEntity? = deviceLoad?.orElse(null) val capabilities = device?.capabilities.orEmpty() - val minimumInterval = if (device?.deviceType == RingDeviceType.YCBT) 30 else 5 - val intervalSteps = ((60 - minimumInterval) / 5 - 1).coerceAtLeast(0) + // Both YCBT-protocol families get the raised bounds: `COLMI_SMART_HEALTH` rides the same + // [com.pulseloop.ring.YCBTDriver], so its ring can carry the same settings (issue #103, + // Albabit's `colmi-smarthealth` unit was capped at 5–60 until 2026-10-23). + val isYcbtProtocol = device?.deviceType in setOf(RingDeviceType.YCBT, RingDeviceType.COLMI_SMART_HEALTH) + val minimumInterval = if (isYcbtProtocol) 30 else 5 + // 120 min is the only interval beyond the vendor app's own menu (which stops at 60) that is + // tested on hardware: the ring ACKed `01 0c 01 78` and read at 10:00 and 12:00 (issue #103, + // 2026-10-22). Nothing longer until someone tries it, and YCBT-protocol rings only — it is + // not the vendor app's behaviour, it is one ring's. + val maximumHrInterval = if (isYcbtProtocol) 120 else 60 + val intervalSteps = ((maximumHrInterval - minimumInterval) / 5 - 1).coerceAtLeast(0) // Only offered where the ring's protocol actually carries a separate blood-oxygen interval — // elsewhere the slider moved, the value saved, and "Saved & sent to ring ✓" appeared over a // setting nothing on the wire could express (issue #66). @@ -1698,8 +1711,12 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U // so it needs its own step count: reusing the HR one put ticks 5.45 min apart, none of which // the 5-minute snap could land on. val spo2IntervalSteps = ((60 - (minimumInterval - 5)) / 5 - 1).coerceAtLeast(0) + // Same exclusion as [RingDeviceType.YCBT]: the YCBT wire format has no stress-monitor + // setting ([com.pulseloop.ring.YCBTEncoder.monitorCommands] carries HR/BP/temp/SpO₂/HRV + // only), so a toggle here would be a no-op the ring never sees — the capability bit alone + // is not enough to offer it. val supportsStressSetting = WearableCapability.STRESS in capabilities && - device?.deviceType != RingDeviceType.YCBT + !isYcbtProtocol var cfgHrEnabled by remember { mutableStateOf(true) } var cfgHrInterval by remember { mutableStateOf(5) } @@ -1709,6 +1726,11 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U var cfgStress by remember { mutableStateOf(true) } var cfgHrv by remember { mutableStateOf(true) } var cfgTemp by remember { mutableStateOf(true) } + val scheduledSpo2Prefs = remember { ScheduledSpo2Prefs(context) } + val supportsScheduledSpo2 = ScheduledSpo2Prefs.isSupported(device) + var cfgAppSpo2 by remember { mutableStateOf(false) } + var cfgAppSpo2Interval by remember { mutableStateOf(ScheduledSpo2Prefs.DEFAULT_INTERVAL_MINUTES) } + var cfgHideEstimatedSpo2 by remember { mutableStateOf(true) } var cfgLoaded by remember { mutableStateOf(false) } var cfgSavedMsg by remember { mutableStateOf(null) } @@ -1717,7 +1739,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U cfgLoaded = false val config = db.deviceMeasurementConfigDao().byDevice(id) cfgHrEnabled = config?.hrEnabled ?: true - cfgHrInterval = (config?.hrIntervalMinutes ?: minimumInterval).coerceIn(minimumInterval, 60) + cfgHrInterval = (config?.hrIntervalMinutes ?: minimumInterval).coerceIn(minimumInterval, maximumHrInterval) cfgSpo2 = (config?.spo2Enabled ?: true) && WearableCapability.SPO2 in capabilities cfgSpo2Interval = (config?.spo2IntervalMinutes ?: 0).let { if (it <= 0) 0 else it.coerceIn(minimumInterval, 60) @@ -1725,6 +1747,9 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U cfgStress = (config?.stressEnabled ?: true) && supportsStressSetting cfgHrv = (config?.hrvEnabled ?: true) && WearableCapability.HRV in capabilities cfgTemp = (config?.temperatureEnabled ?: true) && WearableCapability.TEMPERATURE in capabilities + cfgAppSpo2 = scheduledSpo2Prefs.enabled + cfgAppSpo2Interval = scheduledSpo2Prefs.intervalMinutes + cfgHideEstimatedSpo2 = scheduledSpo2Prefs.hideEstimated cfgLoaded = true } @@ -1768,8 +1793,8 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U Slider( enabled = cfgLoaded, value = cfgHrInterval.toFloat(), - onValueChange = { cfgHrInterval = ((it / 5).toInt() * 5).coerceIn(minimumInterval, 60); cfgSavedMsg = null }, - valueRange = minimumInterval.toFloat()..60f, + onValueChange = { cfgHrInterval = ((it / 5).toInt() * 5).coerceIn(minimumInterval, maximumHrInterval); cfgSavedMsg = null }, + valueRange = minimumInterval.toFloat()..maximumHrInterval.toFloat(), steps = intervalSteps, ) } @@ -1782,7 +1807,9 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U // running both monitors hourly that is most of the battery (issue #66). if (cfgSpo2 && supportsSpo2Interval) { Text( - if (cfgSpo2Interval <= 0) tr("Same as heart rate") else trf("Every {0} min", cfgSpo2Interval), + // The blood-oxygen command keeps the 60-min ceiling whatever the + // heart-rate slider shows (no evidence past 60 on that key). + if (cfgSpo2Interval <= 0) tr("Same as heart rate, at most every 60 min") else trf("Every {0} min", cfgSpo2Interval), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -1800,6 +1827,48 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U steps = spo2IntervalSteps, ) } + // Issue #103: this ring's own SpO₂ is computed from heart rate, so the app + // can run the ring's real spot measurement on the schedule instead. + if (supportsScheduledSpo2) { + VitalToggle(tr("Measure SpO₂ from the app"), cfgAppSpo2) { + cfgAppSpo2 = it + cfgSavedMsg = null + } + if (cfgAppSpo2) { + Text( + tr("This ring's all-day SpO₂ is estimated from heart rate. When on, PulseLoop starts a real spot measurement on the schedule below, between the ring's own readings, about a minute each, which uses more battery. Android may delay or skip runs while the phone is asleep."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + // Independent of the ring's SpO₂ interval: the app starts these runs + // itself, so the ring's limits don't apply (issue #103). Each run is + // ~50 s of red LED, which is what 2–3 h spacing is for. + Text( + if (cfgAppSpo2Interval == 60) tr("Every hour") else trf("Every {0} hours", cfgAppSpo2Interval / 60), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Slider( + enabled = cfgLoaded, + value = cfgAppSpo2Interval.toFloat(), + onValueChange = { + cfgAppSpo2Interval = ScheduledSpo2Prefs.sanitizeIntervalMinutes(kotlin.math.round(it / 60f).toInt() * 60) + cfgSavedMsg = null + }, + valueRange = 60f..180f, + steps = 1, + ) + VitalToggle(tr("Hide estimated SpO₂"), cfgHideEstimatedSpo2) { + cfgHideEstimatedSpo2 = it + cfgSavedMsg = null + } + Text( + tr("Display only real spot measurements on charts and vitals cards, hiding the hourly estimates."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } } if (supportsStressSetting) { VitalToggle(tr("Stress"), cfgStress) { cfgStress = it } @@ -1819,7 +1888,7 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U db.deviceMeasurementConfigDao().upsert( com.pulseloop.data.entity.DeviceMeasurementConfigEntity( deviceId = device.id, - hrIntervalMinutes = cfgHrInterval.coerceIn(minimumInterval, 60), + hrIntervalMinutes = cfgHrInterval.coerceIn(minimumInterval, maximumHrInterval), hrEnabled = cfgHrEnabled, spo2Enabled = cfgSpo2 && WearableCapability.SPO2 in capabilities, spo2IntervalMinutes = if (!supportsSpo2Interval || cfgSpo2Interval <= 0) 0 @@ -1831,6 +1900,10 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U ) ) coordinator?.applyMeasurementSettings() + scheduledSpo2Prefs.enabled = cfgAppSpo2 && supportsScheduledSpo2 + scheduledSpo2Prefs.intervalMinutes = cfgAppSpo2Interval + scheduledSpo2Prefs.hideEstimated = cfgHideEstimatedSpo2 + ScheduledSpo2Worker.reschedule(context.applicationContext) cfgSavedMsg = if (coordinator?.isConnected == true) tr("Saved & sent to ring ✓") else tr("Saved — will sync on next connect") } @@ -3383,6 +3456,19 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { } } + // Issue #103: a YCBT-protocol ring derives respiratory rate from heart rate, so that row is + // shown as not exported (VitalsExporter.shouldExportRespRate holds it back regardless). + var currentRealDevice by remember { mutableStateOf(null) } + LaunchedEffect(Unit) { + currentRealDevice = withContext(Dispatchers.IO) { + PulseLoopDatabase.getInstance(context).deviceDao().currentReal() + } + } + val isYcbtDevice = currentRealDevice?.deviceType in setOf( + com.pulseloop.ring.RingDeviceType.YCBT, + com.pulseloop.ring.RingDeviceType.COLMI_SMART_HEALTH, + ) + SettingsSubScreen(title = tr("Health Connect"), onBack = onBack) { SubScreenCard { Column(Modifier.padding(16.dp)) { @@ -3512,11 +3598,12 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { ) } if (typesOpen) for ((row, label) in rows) { + val isRespRateOnYcbt = row == HealthConnectPermissions.DataTypeRow.RESPIRATORY_RATE && isYcbtDevice val rowPerms = HealthConnectPermissions.permissionsForRow(row) - val rowGranted = rowPerms.isEmpty() || rowPerms.any { it in granted } + val rowGranted = !isRespRateOnYcbt && (rowPerms.isEmpty() || rowPerms.any { it in granted }) Row( Modifier.fillMaxWidth().padding(vertical = 4.dp) - .switchRow(checked = prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = { on -> + .switchRow(checked = if (isRespRateOnYcbt) false else prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = { on -> store.update { p -> p.withToggleFor(row, on) } // Re-enabling a VITALS kind must backfill the readings recorded while it // was off: the VITALS group watermark is driven by the *enabled* kinds @@ -3534,7 +3621,13 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { ) { Column(Modifier.weight(1f)) { Text(tr(label), style = MaterialTheme.typography.bodyMedium) - if (!rowGranted) { + if (isRespRateOnYcbt) { + Text( + tr("Derived from heart rate by current ring — export disabled"), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else if (!rowGranted) { Text( tr("Awaiting permission"), style = MaterialTheme.typography.bodySmall, @@ -3552,7 +3645,7 @@ fun HealthConnectSettingsScreen(onBack: () -> Unit) { ) } } - Switch(checked = prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = null) + Switch(checked = if (isRespRateOnYcbt) false else prefs.toggleFor(row), enabled = rowGranted, onCheckedChange = null) } if (row == HealthConnectPermissions.DataTypeRow.HEART_RATE_VARIABILITY) { // Plan §7 open item: the rings' HRV metric is vendor-undocumented, and diff --git a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt index 9c77aed6..a1c52cc6 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -182,13 +182,12 @@ private fun androidx.compose.foundation.lazy.LazyListScope.sessionPageItems( SleepHypnogram(blocks = remember(blocks) { com.pulseloop.service.hypnogramBlocks(blocks) }, spanMin = session.spanMinutes, startTs = session.startAt) } } - // The individual ring records behind the merged night (issue #68). Only when there is more - // than one — on an unsplit night the session *is* the record and a second card saying so is - // noise. The guard is on the `item` rather than inside it: an item that emits nothing still - // takes its share of the list's 16 dp spacing, which put a 32 dp hole in every single-record - // night. + // The individual ring records behind the merged night (issue #68). Rendered whenever + // runs is not empty so that single-record nights can also be edited or extended over missed + // sleep (issues #106, #103). The guard is on the `item` rather than inside it: an item that + // emits nothing still takes its share of the list's 16 dp spacing. val runs = com.pulseloop.service.sleepRecordRuns(blocks) - if (runs.size > 1) item { SleepRecordsCard(session, runs, viewModel) } + if (runs.isNotEmpty()) item { SleepRecordsCard(session, runs, viewModel) } item { val byStage = remember(blocks) { blocks.groupBy { it.stageRaw }.mapValues { (_, b) -> b.sumOf { it.durationMinutes } } } SleepStageSummaryCards( diff --git a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt index 38b45454..d7b5acdc 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -663,7 +663,11 @@ class ActivityViewModel(db: PulseLoopDatabase) : ViewModel() { * Uses reactive polling so data appears as soon as the ring syncs. */ @OptIn(kotlinx.coroutines.FlowPreview::class) -class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore: ApiKeyStore? = null) : ViewModel() { +class VitalsViewModel( + private val db: PulseLoopDatabase, + private val apiKeyStore: ApiKeyStore? = null, + private val scheduledSpo2Prefs: com.pulseloop.settings.ScheduledSpo2Prefs? = null, +) : ViewModel() { data class VitalsState( /** The user's own 30-day usual range per metric (service/UsualRange), for chart bands. */ val usualRanges: Map> = emptyMap(), @@ -756,7 +760,7 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore } private suspend fun refresh(db: PulseLoopDatabase) { - _state.value = buildState(db, apiKeyStore).copy(loaded = true) + _state.value = buildState(db, apiKeyStore, scheduledSpo2Prefs).copy(loaded = true) } companion object { @@ -767,7 +771,11 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore * ([com.pulseloop.widgets.WidgetSnapshotPublisher]) — a widget tile is built from exactly the * same series fetches, offsets, and capability gating as its Vitals/Today card. */ - suspend fun buildState(db: PulseLoopDatabase, apiKeyStore: ApiKeyStore? = null): VitalsState { + suspend fun buildState( + db: PulseLoopDatabase, + apiKeyStore: ApiKeyStore? = null, + scheduledSpo2Prefs: com.pulseloop.settings.ScheduledSpo2Prefs? = null, + ): VitalsState { val now = System.currentTimeMillis() val twentyFourHoursAgo = now - 24 * 3600_000L val device = db.deviceDao().current() @@ -839,6 +847,15 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore val spo2Estimated = if (spo2.isEmpty()) emptySet() else EstimatedSpo2.estimatedTimestamps(db.measurementDao(), twentyFourHoursAgo, now, now) + // Issue #103: the user can hide those estimates (Settings → Measurement frequency), so + // the cards, charts and widgets show only real spot measurements. + val hideEstimated = scheduledSpo2Prefs?.hideEstimated ?: false + val displayedSpo2 = if (hideEstimated && spo2Estimated.isNotEmpty()) { + spo2.filterNot { it.timestamp in spo2Estimated } + } else { + spo2 + } + // Temperature on the Colmi family is the same static-capability trap as stress above: // every Colmi model is catalogued with TEMPERATURE, but some have no sensor. An R06 // (`R06_1.00.06_240921`) never answers the legacy temperature request and doesn't set the @@ -864,8 +881,8 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore return VitalsState( usualRanges = usualRanges, hrSamples = hr.map { it.value }, - spo2Samples = spo2.map { it.value }, - spo2IsEstimated = spo2.any { it.timestamp in spo2Estimated }, + spo2Samples = displayedSpo2.map { it.value }, + spo2IsEstimated = !hideEstimated && displayedSpo2.any { it.timestamp in spo2Estimated }, hrvSamples = hrv.map { it.value }, stressSamples = stress.map { it.value }.ifEmpty { derivedStress }, stressIsDerived = stress.isEmpty() && derivedStress.isNotEmpty(), @@ -873,7 +890,7 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore tempSamples = temp.map { it.value }, latestHr = hr.lastOrNull()?.value?.toInt(), restingHr = HeartRateZones.restingHeartRate(hr.map { it.value }), - latestSpo2 = spo2.lastOrNull()?.value?.toInt(), + latestSpo2 = displayedSpo2.lastOrNull()?.value?.toInt(), latestHrv = hrv.lastOrNull()?.value, latestStress = stress.lastOrNull()?.value ?: derivedStress.lastOrNull(), latestFatigue = fatigue.lastOrNull()?.value, @@ -891,7 +908,7 @@ class VitalsViewModel(private val db: PulseLoopDatabase, private val apiKeyStore bpDiaSamples = bpDia.map { it.value }, glucoseSamples = gluc.map { it.value + glucoseOffset }, hrSeries = hr.map { VitalSample(it.timestamp, it.value) }, - spo2Series = spo2.map { VitalSample(it.timestamp, it.value) }, + spo2Series = displayedSpo2.map { VitalSample(it.timestamp, it.value) }, hrvSeries = hrv.map { VitalSample(it.timestamp, it.value) }, stressSeries = stress.map { VitalSample(it.timestamp, it.value) }.ifEmpty { derivedStressSeries }, fatigueSeries = fatigue.map { VitalSample(it.timestamp, it.value) }, @@ -1232,6 +1249,7 @@ class VitalDetailViewModel( private val metric: String, private val apiKeyStore: ApiKeyStore? = null, private val unitSystem: UnitSystem = UnitSystem.METRIC, + private val scheduledSpo2Prefs: com.pulseloop.settings.ScheduledSpo2Prefs? = null, ) : ViewModel() { enum class Trend { UP, DOWN, FLAT } @@ -1289,6 +1307,8 @@ class VitalDetailViewModel( /** True when the ring supplied this from its own log, so a re-sync could restore it — * which is why deleting it also writes a tombstone. Shown as provenance in the list. */ val fromHistory: Boolean = false, + /** True when this hourly SpO₂ reading was computed from heart rate rather than measured. */ + val isEstimated: Boolean = false, ) private val _state = MutableStateFlow(DetailState()) @@ -1484,15 +1504,20 @@ class VitalDetailViewModel( // chart carries the same disclaimer. Only hourly rows count; spot readings never do. val estimatedSpo2 = if (kind == MeasurementKind.SPO2 && samples.isNotEmpty()) EstimatedSpo2.estimatedTimestamps(dao, windowStart, windowEnd) else emptySet() - val times = if (derived.isNotEmpty()) derived.map { it.timestampMs } else samples.map { it.timestamp } - val points = if (derived.isNotEmpty()) derived.map { it.value } else samples.map { convert(it.value) } + val hideEstimated = kind == MeasurementKind.SPO2 && scheduledSpo2Prefs?.hideEstimated == true + val effectiveSamples = if (hideEstimated && estimatedSpo2.isNotEmpty()) + samples.filterNot { it.timestamp in estimatedSpo2 } else samples + val times = if (derived.isNotEmpty()) derived.map { it.timestampMs } else effectiveSamples.map { it.timestamp } + val points = if (derived.isNotEmpty()) derived.map { it.value } else effectiveSamples.map { convert(it.value) } val labels = buildLabels(times, period) val prevSamples = dao.range(kindName, prevStart, prevEnd) + val prevEffective = if (hideEstimated && estimatedSpo2.isNotEmpty()) + prevSamples.filterNot { it.timestamp in estimatedSpo2 } else prevSamples val prevDerived = if (derived.isNotEmpty()) derivedStressIn(prevStart, prevEnd) else emptyList() val prevAvg = when { prevDerived.isNotEmpty() -> prevDerived.map { it.value }.average() - prevSamples.isNotEmpty() -> convert(prevSamples.map { it.value }.average()) + prevEffective.isNotEmpty() -> convert(prevEffective.map { it.value }.average()) else -> null } val thisAvg = if (points.isNotEmpty()) points.average() else null @@ -1529,8 +1554,9 @@ class VitalDetailViewModel( timestamp = it.timestamp, value = convert(it.value), fromHistory = it.id.startsWith(MeasurementDeletionDao.HISTORY_ID_PREFIX), + isEstimated = it.timestamp in estimatedSpo2, ) - }.asReversed() + }.let { if (hideEstimated) it.filterNot { r -> r.isEstimated } else it }.asReversed() _state.update { it.copy( anchor = anchor, @@ -1544,7 +1570,7 @@ class VitalDetailViewModel( resting = resting, trend = trend, engineZones = engineZones, - isDerived = derived.isNotEmpty() || samples.any { it.timestamp in estimatedSpo2 }, + isDerived = derived.isNotEmpty() || (!hideEstimated && samples.any { it.timestamp in estimatedSpo2 }), usualRange = usualRange, adjustedNote = when (kind) { MeasurementKind.HEART_RATE -> corrections.describe(setOf( diff --git a/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt b/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt index 69408662..4568ba0e 100644 --- a/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt +++ b/app/src/main/java/com/pulseloop/widgets/WidgetTileRenderer.kt @@ -452,7 +452,9 @@ class WidgetTileRenderer(private val density: Float) { } // Zone-colored line, broken across data gaps (90 min — the card-chart gap on 24h ranges). val timestampsMs = samples.map { it.t * 1000L } - val runs = ZoneLineSplitter.segmentsByGap(timestampsMs, 90 * 60_000L) + val sampleInterval = ZoneLineSplitter.sampleIntervalMs(timestampsMs) + val maxGapMs = ZoneLineSplitter.maxGapMs(24 * 3600_000L, sampleInterval) + val runs = ZoneLineSplitter.segmentsByGap(timestampsMs, maxGapMs) runs.forEach { run -> if (run.first == run.last) { val s = samples[run.first] diff --git a/app/src/test/java/com/pulseloop/health/VitalsExporterFilteringTest.kt b/app/src/test/java/com/pulseloop/health/VitalsExporterFilteringTest.kt new file mode 100644 index 00000000..9b55ee99 --- /dev/null +++ b/app/src/test/java/com/pulseloop/health/VitalsExporterFilteringTest.kt @@ -0,0 +1,50 @@ +package com.pulseloop.health + +import com.pulseloop.health.exporters.VitalsExporter +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Issue #103: tests that estimated SpO2 and derived respiratory rate are excluded from Health Connect export. + */ +class VitalsExporterFilteringTest { + + @Test + fun `genuine spot SpO2 reading is exported`() { + val timestamp = 1729000000000L + val estimatedSet = setOf(1729003600000L, 1729007200000L) + assertTrue(VitalsExporter.shouldExportSpo2(98.0, timestamp, estimatedSet)) + } + + @Test + fun `hourly SpO2 estimated from heart rate is excluded`() { + val timestamp = 1729003600000L + val estimatedSet = setOf(timestamp, 1729007200000L) + assertFalse(VitalsExporter.shouldExportSpo2(98.0, timestamp, estimatedSet)) + } + + @Test + fun `implausible SpO2 is excluded even if not estimated`() { + val timestamp = 1729000000000L + assertFalse(VitalsExporter.shouldExportSpo2(105.0, timestamp, emptySet())) + assertFalse(VitalsExporter.shouldExportSpo2(0.0, timestamp, emptySet())) + } + + @Test + fun `respiratory rate on YCBT ring is excluded from export`() { + // YCBT rings derive respiratory rate as ~0.2 * HR without a real sensor + assertFalse(VitalsExporter.shouldExportRespRate(16.0, isYcbt = true)) + } + + @Test + fun `respiratory rate on non-YCBT ring with native sensor is exported`() { + assertTrue(VitalsExporter.shouldExportRespRate(16.0, isYcbt = false)) + } + + @Test + fun `implausible respiratory rate is excluded on any ring`() { + assertFalse(VitalsExporter.shouldExportRespRate(0.0, isYcbt = false)) + assertFalse(VitalsExporter.shouldExportRespRate(100.0, isYcbt = false)) + } +} diff --git a/app/src/test/java/com/pulseloop/ring/YCBTEncoderTest.kt b/app/src/test/java/com/pulseloop/ring/YCBTEncoderTest.kt index a20ea671..c48a557f 100644 --- a/app/src/test/java/com/pulseloop/ring/YCBTEncoderTest.kt +++ b/app/src/test/java/com/pulseloop/ring/YCBTEncoderTest.kt @@ -63,6 +63,21 @@ class YCBTEncoderTest { assertArrayEquals(byteArrayOf(0x01, 0x45, 0x00, 60, 0, 0, 0), commands[3]) } + @Test + fun `heart rate carries 120 minutes while the other monitors keep the 60 minute ceiling`() { + // 120 is evidenced on the heart-rate key only (issue #103); the other samplers' bytes are + // unchanged from what the UI's 60-min cap always produced. + val settings = MeasurementSettings( + hrEnabled = true, hrIntervalMinutes = 120, + spo2Enabled = true, stressEnabled = true, hrvEnabled = true, temperatureEnabled = true, + ) + val commands = encoder.monitorCommands(settings, allMonitorCapabilities) + assertArrayEquals(byteArrayOf(0x01, 0x0c, 0x01, 120), commands[0]) + assertArrayEquals(byteArrayOf(0x01, 0x20, 0x01, 60), commands[1]) + assertArrayEquals(byteArrayOf(0x01, 0x26, 0x01, 60), commands[2]) + assertArrayEquals(byteArrayOf(0x01, 0x45, 0x01, 60, 0, 0, 0), commands[3]) + } + @Test fun `userInfo carries real profile`() { val profile = UserProfileValues(metric = true, gender = 0x01u, age = 31u, heightCm = 183u, weightKg = 78u) diff --git a/app/src/test/java/com/pulseloop/service/ScheduledSpo2SlotsTest.kt b/app/src/test/java/com/pulseloop/service/ScheduledSpo2SlotsTest.kt new file mode 100644 index 00000000..9dcfb7a5 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ScheduledSpo2SlotsTest.kt @@ -0,0 +1,146 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZonedDateTime + +/** Issue #103: the app's own spot SpO₂ lands between the ring's readings, never on top of them. */ +class ScheduledSpo2SlotsTest { + + private val zone = ZoneId.of("Europe/Paris") + + private fun at(h: Int, m: Int, s: Int = 0, day: Int = 21, month: Int = 10): ZonedDateTime = + LocalDateTime.of(2026, month, day, h, m, s).atZone(zone) + + @Test + fun `hourly lands at half past`() { + // Just after the ring's own 10:00:42 reading — the reporter's timing. + assertEquals(at(10, 30), ScheduledSpo2Slots.nextSlot(at(10, 0, 42), 60)) + assertEquals(at(10, 30), ScheduledSpo2Slots.nextSlot(at(9, 30, 1), 60)) + } + + @Test + fun `next slot is strictly after now`() { + assertEquals(at(11, 30), ScheduledSpo2Slots.nextSlot(at(10, 30), 60)) + } + + @Test + fun `half hour interval lands at quarter past and quarter to`() { + assertEquals(at(10, 15), ScheduledSpo2Slots.nextSlot(at(10, 5), 30)) + assertEquals(at(10, 45), ScheduledSpo2Slots.nextSlot(at(10, 20), 30)) + } + + @Test + fun `last slot of the day rolls over to the first of the next`() { + assertEquals(at(0, 30, day = 22), ScheduledSpo2Slots.nextSlot(at(23, 45), 60)) + } + + @Test + fun `interval that does not divide the day restarts its grid at midnight`() { + // 35 min: grid …23:20, 23:55, then 00:00; slots 23:37:30, then 00:17:30 the next day. + assertEquals(at(23, 37, 30), ScheduledSpo2Slots.nextSlot(at(23, 20), 35)) + assertEquals(at(0, 17, 30, day = 22), ScheduledSpo2Slots.nextSlot(at(23, 40), 35)) + // 23:57 sits two minutes after the 23:55 reading. + assertFalse(ScheduledSpo2Slots.isClear(at(23, 57), 35)) + } + + @Test + fun `slots stay on the half hour across a DST change`() { + // Europe/Paris falls back on 2026-10-25 (03:00 → 02:00): the slot after 01:40 is still 02:30. + val slot = ScheduledSpo2Slots.nextSlot(at(1, 40, day = 25), 60) + assertEquals(2, slot.hour) + assertEquals(30, slot.minute) + } + + @Test + fun `a late run near the top of the hour is not clear`() { + assertTrue(ScheduledSpo2Slots.isClear(at(10, 30), 60)) + assertFalse(ScheduledSpo2Slots.isClear(at(10, 2), 60)) + // Starting at 10:57 would still be measuring at 10:58:15 — too close to 11:00. + assertFalse(ScheduledSpo2Slots.isClear(at(10, 57), 60)) + assertTrue(ScheduledSpo2Slots.isClear(at(10, 53), 60)) + } + + @Test + fun `short intervals use a smaller margin`() { + // 15 min: margin 3:45, so a run at 10:07:30 (the slot) is clear and 10:02 is not. + assertTrue(ScheduledSpo2Slots.isClear(at(10, 7, 30), 15)) + assertFalse(ScheduledSpo2Slots.isClear(at(10, 2), 15)) + } + + @Test + fun `every slot is itself clear`() { + for (interval in listOf(15, 20, 30, 35, 45, 60)) { + var t = at(0, 0) + repeat(200) { + t = ScheduledSpo2Slots.nextSlot(t, interval) + assertTrue("interval $interval slot $t", ScheduledSpo2Slots.isClear(t, interval)) + } + } + } + + @Test + fun `two hour app interval keeps the half past slot on an hourly ring grid`() { + // The app's own grid starts at :30 (half the ring's interval) and repeats every 2 h. + assertEquals(at(10, 30), ScheduledSpo2Slots.nextSlot(at(10, 0, 42), 120, 60)) + assertEquals(at(12, 30), ScheduledSpo2Slots.nextSlot(at(10, 30), 120, 60)) + assertEquals(at(0, 30, day = 22), ScheduledSpo2Slots.nextSlot(at(22, 31), 120, 60)) + } + + @Test + fun `three hour app interval slots every third hour`() { + assertEquals(at(12, 30), ScheduledSpo2Slots.nextSlot(at(10, 0, 42), 180, 60)) + // 00:30 + 8 × 3 h wraps exactly onto 00:30, so the offset survives the rollover. + assertEquals(at(0, 30, day = 22), ScheduledSpo2Slots.nextSlot(at(23, 45), 180, 60)) + } + + @Test + fun `every 2 and 3 hour slot stays clear of an hourly ring grid`() { + for (appInterval in listOf(120, 180)) { + var t = at(0, 0) + repeat(40) { + t = ScheduledSpo2Slots.nextSlot(t, appInterval, 60) + assertTrue("app $appInterval slot $t", ScheduledSpo2Slots.isClear(t, 60)) + } + } + } + + @Test + fun `half hour ring grid puts the two hour slots at quarter past`() { + assertEquals(at(10, 15), ScheduledSpo2Slots.nextSlot(at(10, 5), 120, 30)) + assertTrue(ScheduledSpo2Slots.isClear(at(10, 15), 30)) + } + + @Test + fun `two hour ring grid with two hour app interval lands at odd hours`() { + assertEquals(at(11, 0), ScheduledSpo2Slots.nextSlot(at(10, 5), 120, 120)) + assertEquals(at(13, 0), ScheduledSpo2Slots.nextSlot(at(11, 0), 120, 120)) + assertTrue(ScheduledSpo2Slots.isClear(at(11, 0), 120)) + // Late run at 22:25 (delayed from 22:00) is clear of 00:00 ring reading + assertTrue(ScheduledSpo2Slots.isClear(at(22, 25), 120)) + // 23:58 is 2 min before midnight reading => not clear + assertFalse(ScheduledSpo2Slots.isClear(at(23, 58), 120)) + } + + @Test + fun `two hour ring grid with hourly app interval lands at half past`() { + assertEquals(at(10, 30), ScheduledSpo2Slots.nextSlot(at(10, 5), 60, 120)) + assertEquals(at(11, 30), ScheduledSpo2Slots.nextSlot(at(10, 30), 60, 120)) + assertTrue(ScheduledSpo2Slots.isClear(at(10, 30), 120)) + assertTrue(ScheduledSpo2Slots.isClear(at(11, 30), 120)) + } + + @Test + fun `two hour ring grid with three hour app interval lands at half past and stays clear`() { + assertEquals(at(12, 30), ScheduledSpo2Slots.nextSlot(at(10, 5), 180, 120)) + var t = at(0, 0) + repeat(40) { + t = ScheduledSpo2Slots.nextSlot(t, 180, 120) + assertTrue("180m app slot $t on 120m ring grid", ScheduledSpo2Slots.isClear(t, 120)) + } + } +} diff --git a/app/src/test/java/com/pulseloop/service/ScheduledSpo2WorkerTest.kt b/app/src/test/java/com/pulseloop/service/ScheduledSpo2WorkerTest.kt new file mode 100644 index 00000000..fc0ff5f1 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/ScheduledSpo2WorkerTest.kt @@ -0,0 +1,80 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * Issue #103: tests for ScheduledSpo2Worker interval computation and scheduling guards. + */ +class ScheduledSpo2WorkerTest { + + @Test + fun `ycbt uses hr interval even when spo2 is disabled`() { + val interval = ScheduledSpo2Worker.computeRingIntervalMinutes( + isYcbt = true, + hrIntervalMinutes = 120, + spo2IntervalMinutes = 0, + spo2Enabled = false, + ) + // Turning off the ring's fake SpO2 toggle must not cancel the app's spot SpO2 schedule + assertEquals(120, interval) + } + + @Test + fun `ycbt ignores spo2 interval and uses hr interval`() { + val interval = ScheduledSpo2Worker.computeRingIntervalMinutes( + isYcbt = true, + hrIntervalMinutes = 120, + spo2IntervalMinutes = 30, + spo2Enabled = true, + ) + // Ring ignores 01 26 and measures on HR cadence, so interval must be 120 to avoid false skips + assertEquals(120, interval) + } + + @Test + fun `ycbt defaults to 60 min when hr interval is unset`() { + val interval = ScheduledSpo2Worker.computeRingIntervalMinutes( + isYcbt = true, + hrIntervalMinutes = 0, + spo2IntervalMinutes = 30, + spo2Enabled = true, + ) + assertEquals(60, interval) + } + + @Test + fun `non ycbt returns null when spo2 is disabled`() { + val interval = ScheduledSpo2Worker.computeRingIntervalMinutes( + isYcbt = false, + hrIntervalMinutes = 60, + spo2IntervalMinutes = 30, + spo2Enabled = false, + ) + assertNull(interval) + } + + @Test + fun `non ycbt uses spo2 interval when enabled`() { + val interval = ScheduledSpo2Worker.computeRingIntervalMinutes( + isYcbt = false, + hrIntervalMinutes = 60, + spo2IntervalMinutes = 30, + spo2Enabled = true, + ) + assertEquals(30, interval) + } + + @Test + fun `syncing and measuring lock flags default to false and are observable`() { + assertEquals(false, RingSyncWorker.isSyncing) + assertEquals(false, ScheduledSpo2Worker.isMeasuring) + } + + @Test + fun `shouldEnqueueNext is false when worker is stopped`() { + assertEquals(false, ScheduledSpo2Worker.shouldEnqueueNext(isStopped = true)) + assertEquals(true, ScheduledSpo2Worker.shouldEnqueueNext(isStopped = false)) + } +} diff --git a/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt b/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt new file mode 100644 index 00000000..46301ed2 --- /dev/null +++ b/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt @@ -0,0 +1,114 @@ +package com.pulseloop.settings + +import android.content.SharedPreferences +import com.pulseloop.data.entity.DeviceEntity +import com.pulseloop.ring.RingDeviceType +import com.pulseloop.ring.WearableCapability +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The interval picker behind issue #103's request to space the app's own spot SpO₂ past an hour. + */ +class ScheduledSpo2PrefsTest { + + private class FakeSharedPreferences : SharedPreferences { + val map = HashMap() + override fun getAll(): MutableMap = map + override fun getString(key: String?, defValue: String?): String? = map[key] as? String ?: defValue + override fun getStringSet(key: String?, defValues: MutableSet?): MutableSet? = + map[key] as? MutableSet ?: defValues + override fun getInt(key: String?, defValue: Int): Int = map[key] as? Int ?: defValue + override fun getLong(key: String?, defValue: Long): Long = map[key] as? Long ?: defValue + override fun getFloat(key: String?, defValue: Float): Float = map[key] as? Float ?: defValue + override fun getBoolean(key: String?, defValue: Boolean): Boolean = map[key] as? Boolean ?: defValue + override fun contains(key: String?): Boolean = map.containsKey(key) + override fun edit(): SharedPreferences.Editor = FakeEditor(this) + override fun registerOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener?) {} + override fun unregisterOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener?) {} + + private class FakeEditor(private val prefs: FakeSharedPreferences) : SharedPreferences.Editor { + override fun putString(key: String?, value: String?): SharedPreferences.Editor { if (value != null) prefs.map[key!!] = value; return this } + override fun putStringSet(key: String?, values: MutableSet?): SharedPreferences.Editor = this + override fun putInt(key: String?, value: Int): SharedPreferences.Editor { prefs.map[key!!] = value; return this } + override fun putLong(key: String?, value: Long): SharedPreferences.Editor { prefs.map[key!!] = value; return this } + override fun putFloat(key: String?, value: Float): SharedPreferences.Editor = this + override fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor { prefs.map[key!!] = value; return this } + override fun remove(key: String?): SharedPreferences.Editor { prefs.map.remove(key); return this } + override fun clear(): SharedPreferences.Editor { prefs.map.clear(); return this } + override fun commit(): Boolean = true + override fun apply() {} + } + } + + @Test + fun `hideEstimated defaults to true and round trips`() { + val fakePrefs = FakeSharedPreferences() + val prefs = ScheduledSpo2Prefs(fakePrefs) + assertTrue(prefs.hideEstimated) + prefs.hideEstimated = false + assertFalse(prefs.hideEstimated) + prefs.hideEstimated = true + assertTrue(prefs.hideEstimated) + } + + @Test + fun `enabled defaults to false and interval defaults to 60`() { + val fakePrefs = FakeSharedPreferences() + val prefs = ScheduledSpo2Prefs(fakePrefs) + assertFalse(prefs.enabled) + assertEquals(60, prefs.intervalMinutes) + prefs.intervalMinutes = 120 + assertEquals(120, prefs.intervalMinutes) + } + + @Test + fun `the offered options pass through unchanged`() { + for (minutes in listOf(60, 120, 180)) { + assertEquals(minutes, ScheduledSpo2Prefs.sanitizeIntervalMinutes(minutes)) + } + } + + @Test + fun `anything else snaps to the nearest option and stays inside the range`() { + assertEquals(60, ScheduledSpo2Prefs.sanitizeIntervalMinutes(0)) + assertEquals(60, ScheduledSpo2Prefs.sanitizeIntervalMinutes(59)) + assertEquals(60, ScheduledSpo2Prefs.sanitizeIntervalMinutes(89)) + assertEquals(120, ScheduledSpo2Prefs.sanitizeIntervalMinutes(90)) + assertEquals(180, ScheduledSpo2Prefs.sanitizeIntervalMinutes(150)) + assertEquals(180, ScheduledSpo2Prefs.sanitizeIntervalMinutes(151)) + assertEquals(180, ScheduledSpo2Prefs.sanitizeIntervalMinutes(300)) + assertEquals(60, ScheduledSpo2Prefs.sanitizeIntervalMinutes(-30)) + } + + /** Albabit's ring (issue #103, 2026-10-23): `colmi-smarthealth`, SmartHealth/YCBT protocol, + * `manualSpo2` in its capabilities — both #103 controls must reach it, not just `YCBT`. */ + @Test + fun `COLMI_SMART_HEALTH with MANUAL_SPO2 is supported`() { + val device = DeviceEntity( + deviceTypeRaw = RingDeviceType.COLMI_SMART_HEALTH.name, + capabilitiesRaw = WearableCapability.MANUAL_SPO2.key, + ) + assertTrue(ScheduledSpo2Prefs.isSupported(device)) + } + + @Test + fun `YCBT with MANUAL_SPO2 is still supported`() { + val device = DeviceEntity( + deviceTypeRaw = RingDeviceType.YCBT.name, + capabilitiesRaw = WearableCapability.MANUAL_SPO2.key, + ) + assertTrue(ScheduledSpo2Prefs.isSupported(device)) + } + + @Test + fun `the MANUAL_SPO2 capability is still required`() { + val device = DeviceEntity( + deviceTypeRaw = RingDeviceType.COLMI_SMART_HEALTH.name, + capabilitiesRaw = WearableCapability.SPO2.key, + ) + assertFalse(ScheduledSpo2Prefs.isSupported(device)) + } +} diff --git a/app/src/test/java/com/pulseloop/ui/components/ZoneLineSplitterTest.kt b/app/src/test/java/com/pulseloop/ui/components/ZoneLineSplitterTest.kt index 4549047b..4265d275 100644 --- a/app/src/test/java/com/pulseloop/ui/components/ZoneLineSplitterTest.kt +++ b/app/src/test/java/com/pulseloop/ui/components/ZoneLineSplitterTest.kt @@ -55,4 +55,45 @@ class ZoneLineSplitterTest { assertEquals(4 * 86_400_000L, ZoneLineSplitter.maxGapMs(30 * 86_400_000L)) assertEquals(45 * 86_400_000L, ZoneLineSplitter.maxGapMs(365 * 86_400_000L)) } + + @Test + fun `max gap in day view expands for wider measurement intervals`() { + val daySpan = 24 * 3600_000L + // Default / 60m interval stays 90m + assertEquals(90 * 60_000L, ZoneLineSplitter.maxGapMs(daySpan, 60 * 60_000L)) + // 120m interval expands to 180m (120 * 1.5) so consecutive points stay connected + assertEquals(180 * 60_000L, ZoneLineSplitter.maxGapMs(daySpan, 120 * 60_000L)) + // 180m interval expands to 270m (180 * 1.5) + assertEquals(270 * 60_000L, ZoneLineSplitter.maxGapMs(daySpan, 180 * 60_000L)) + // Multi-day spans ignore sampleIntervalMs + assertEquals(36 * 3600_000L, ZoneLineSplitter.maxGapMs(7 * 86_400_000L, 120 * 60_000L)) + } + + @Test + fun `sampleIntervalMs uses median delta so occasional spot or midnight records do not collapse interval`() { + // Empty or single timestamp has no interval + assertEquals(null, ZoneLineSplitter.sampleIntervalMs(emptyList())) + assertEquals(null, ZoneLineSplitter.sampleIntervalMs(listOf(1000L))) + + // Pair of timestamps + assertEquals(120 * 60_000L, ZoneLineSplitter.sampleIntervalMs(listOf(0L, 120 * 60_000L))) + + // 120m periodic series with one 22-second midnight anomaly (issue #103) + val h120 = 120 * 60_000L + val timestamps = listOf( + 0L, + 22_000L, // 22s midnight record + h120, // 120m + 2 * h120, + 3 * h120, + 4 * h120, + 5 * h120, + ) + assertEquals(h120, ZoneLineSplitter.sampleIntervalMs(timestamps)) + + // maxGapMs calculated from this sampleInterval keeps the 120m points connected + val sampleInterval = ZoneLineSplitter.sampleIntervalMs(timestamps) + val maxGap = ZoneLineSplitter.maxGapMs(24 * 3600_000L, sampleInterval) + assertEquals(180 * 60_000L, maxGap) + } } From aa2280fb5088f1a28e9dacb460bbb5a9a31c3516 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:36:51 +0000 Subject: [PATCH 6/7] Port upstream #130: extend a sleep record over time the ring missed (#106) Ported from foureight84/PulseLoopAndroid#130 (408178a). Record editing (#82) could only shorten. A record can now also be pulled earlier or later to cover time the ring missed. The added minutes are stored as a new SleepStage.ADDED: counted as asleep, kept out of the stage breakdown and the score. The hypnogram draws them as a hatched "Added by you" band, and Health Connect gets them as STAGE_TYPE_SLEEPING. - editedRecordBlocks (SleepRecordExtension.kt) maps a record through an edit; SleepRecordDeletion.edit and the import's edit gate both call it, so a re-sync writes back the edit's blocks with the same startAt values. - Limits: the neighbouring record, 2 h past the ring's own bounds, the 7 PM waking-day turnover, and one measured minute kept. The dialog names the limit a pick ran past. At import, a stored extension gives way to any other stored record. - Scores use measuredAsleepMinutes in reconcileWakingDay, restateSession and SleepScore.calculate. - Added blocks carry the record's recordStartAt, so a covered gap stops counting as awake between records (#81). Service, data, Health Connect and test changes are upstream's verbatim. The Sleep screen changes are adapted: every string through tr()/trf(), 12sp legend and readout, the band in the muted ink token instead of a literal colour, the existing PulseButton dialog kept, and the hypnogram's spoken summary names the added minutes. The archive needs no change: stage blocks carry stageRaw as a string, so ADDED round-trips as is. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- AGENTS.md | 25 ++ .../com/pulseloop/data/SleepRecordDeletion.kt | 85 +++-- .../health/HealthConnectTypeMappings.kt | 3 + .../com/pulseloop/ring/RingDecodedEvent.kt | 10 +- .../service/EventPersistenceSubscriber.kt | 160 +++++----- .../com/pulseloop/service/SleepInsights.kt | 37 ++- .../pulseloop/service/SleepRecordExtension.kt | 228 ++++++++++++++ .../com/pulseloop/ui/screens/SleepScreen.kt | 139 +++++++-- .../pulseloop/data/SleepRecordDeletionTest.kt | 15 - .../service/SleepRecordExtensionTest.kt | 295 ++++++++++++++++++ 10 files changed, 849 insertions(+), 148 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/SleepRecordExtension.kt create mode 100644 app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt diff --git a/AGENTS.md b/AGENTS.md index fd1fcd22..6c7bc994 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -989,6 +989,31 @@ things to preserve: The sync's reconcile and `SleepRecordDeletion`'s restate must segment with the same bridge, or a record delete would split a night the next sync merges back. +## An extended record's added minutes are asleep but unstaged (issue #106) + +Editing (#82) can extend a record over time the ring missed, not only shorten it. The added minutes +are stored as `SleepStage.ADDED` blocks — **not** `UNKNOWN`, which is a stage byte the ring did +record and we can't read. + +- **In time asleep, out of everything that judges stages.** `asleepMinutes` already admits them (it + excludes only AWAKE). Every score or stage share uses `measuredAsleepMinutes` / drops `addedMinutes`: + `sleepStageScore` in `reconcileWakingDay` and `SleepRecordDeletion.restateSession`, and + `SleepScore.calculate`. Health Connect gets `STAGE_TYPE_SLEEPING`. The hypnogram draws them as a + hatched band, not a lane. +- **They carry the ring record's `recordStartAt`**, so `sleepRecordRuns` keeps them in that record + and the covered gap stops counting as a between-record waking (#81) with no special case. +- **One function maps a record through an edit**: `editedRecordBlocks` (`SleepRecordExtension.kt`). + `SleepRecordDeletion.edit` and the import's edit gate both call it, so a re-sync writes back the + edit's blocks with the same `startAt`s. It ignores existing ADDED blocks and re-derives them from + the bounds, and snaps the bounds inwards onto the record's own minute grid. Don't hand-build + ADDED blocks anywhere else. +- **Limits** (`recordEditLimits`): back to the previous record's end, forward to the next record's + start, otherwise 2 h past the ring's own bounds, never across the 7 PM waking-day turnover, and a + record must keep one measured minute. At import, a stored extension is also clamped clear of any + other stored record, so the ring's measurement always beats an extension. +- **Known divergence**: the edit path only sees stored blocks. Re-extending over minutes an earlier + edit trimmed off makes them ADDED until the next sync, which restores the ring's real stages there. + ## Long-lived services belong to the process, not the composition (issue #113) **`RingBLEClient`, `RingSyncCoordinator`, `EventPersistenceSubscriber` and the other app-lifetime diff --git a/app/src/main/java/com/pulseloop/data/SleepRecordDeletion.kt b/app/src/main/java/com/pulseloop/data/SleepRecordDeletion.kt index 9c18f311..4a718cae 100644 --- a/app/src/main/java/com/pulseloop/data/SleepRecordDeletion.kt +++ b/app/src/main/java/com/pulseloop/data/SleepRecordDeletion.kt @@ -82,13 +82,18 @@ object SleepRecordDeletion { } /** - * Adjust the declared boundaries of the ring record whose blocks carry [recordStartAt] to - * [newStartAt]..[newEndAt] (issue #82). + * Move the bounds of the ring record whose blocks carry [recordStartAt] to + * [newStartAt]..[newEndAt] (issue #82) — shorter, longer, or one side each (issue #106). * - * Stages inside the new range stay; stages now outside it are removed and drop from session - * totals. The edit is recorded in [MeasurementDeletionDao] so it survives a re-sync. + * Stages outside the new range are removed and drop from session totals. Time inside it that + * the ring didn't measure becomes [SleepStage.ADDED] minutes: asleep, unstaged, unscored. The + * blocks come from [com.pulseloop.service.editedRecordBlocks], the function the import uses to + * re-apply the stored edit, so the next sync of the night writes back exactly these blocks. * - * Returns true when the record was successfully updated. + * The bounds are held to [com.pulseloop.service.recordEditLimits] (the dialog's limits: the + * neighbouring record, two hours outward, the night's turnover) and clear of records in the + * day's other sessions, which the dialog doesn't see. Returns false when nothing changed or the + * new range keeps none of the ring's own minutes. */ suspend fun edit( db: PulseLoopDatabase, @@ -115,39 +120,51 @@ object SleepRecordDeletion { val targetRecordStart = targets.first().recordStartAt.let { if (it > 0L) it else targets.first().startAt } val day = session.date - // Trim each target block to [newStartAt, newEndAt) - val survivingTargets = mutableListOf() - for (b in targets) { - val bStart = b.startAt - val bEnd = b.startAt + b.durationMinutes * 60_000L - val keepStart = maxOf(bStart, newStartAt) - val keepEnd = minOf(bEnd, newEndAt) - - if (keepStart < keepEnd) { - val duration = ((keepEnd - keepStart) / 60_000L).toInt() - if (duration > 0) { - survivingTargets.add( - b.copy( - startAt = keepStart, - durationMinutes = duration, - ) - ) - } - } - } - - // If trimming leaves no stages in this record, delete the record completely - if (survivingTargets.isEmpty()) { - return@withTransaction delete(db, sessionId, recordStartAt) - } + val (start, end) = clampEdit(db, session, blocks, targets, newStartAt, newEndAt) + val edited = com.pulseloop.service.editedRecordBlocks(targets, targetRecordStart, start, end) + ?: return@withTransaction false - db.measurementDeletionDao().recordSleepEdit(day, targetRecordStart, newStartAt, newEndAt) + db.measurementDeletionDao().recordSleepEdit(day, targetRecordStart, start, end) val nonTargets = blocks - targets.toSet() - restateSession(db, session, nonTargets + survivingTargets, bridge) + restateSession(db, session, nonTargets + edited, bridge) true } + /** + * [newStartAt]..[newEndAt] held to the limits the dialog applies, and clear of every block in + * the day's other sessions (issue #106). The dialog already clamps; this is the authority, so a + * stale dialog or another caller can't extend a record over a neighbour. + */ + private suspend fun clampEdit( + db: PulseLoopDatabase, + session: SleepSessionEntity, + blocks: List, + targets: List, + newStartAt: Long, + newEndAt: Long, + ): Pair { + val runs = com.pulseloop.service.sleepRecordRuns(blocks) + val first = targets.minOf { it.startAt } + val index = runs.indexOfFirst { run -> run.blocks.any { it.startAt == first } } + val run = runs.getOrNull(index) ?: com.pulseloop.service.sleepRecordRuns(targets).first() + val limits = com.pulseloop.service.recordEditLimits( + run = run, + previous = runs.getOrNull(index - 1).takeIf { index > 0 }, + next = runs.getOrNull(index + 1).takeIf { index >= 0 }, + wakingDay = session.date, + ) + val start = newStartAt.coerceAtLeast(limits.earliestStart) + val end = newEndAt.coerceAtMost(limits.latestEnd) + val otherSessions = db.sleepSessionDao().ringAllByDay(session.date).filter { it.id != session.id } + val others = if (otherSessions.isEmpty()) emptyList() + else db.sleepStageBlockDao().forSessions(otherSessions.map { it.id }) + val (nightStart, nightEnd) = com.pulseloop.service.nightWindow(session.date) + return com.pulseloop.service.clampEditToNeighbours( + start, end, limits.measuredStart, limits.measuredEnd, others, nightStart, nightEnd, + ) + } + /** The next stamped record boundary after [after], or end-of-night — bounds the legacy fallback. */ private fun nextStampedStart(blocks: List, after: Long): Long = blocks.map { it.recordStartAt }.filter { it > after }.minOrNull() ?: Long.MAX_VALUE @@ -188,6 +205,8 @@ object SleepRecordDeletion { val totalMin = com.pulseloop.service.asleepMinutes(row.blocks) val deepMin = row.blocks.filter { it.stageRaw == SleepStage.DEEP.name } .sumOf { it.durationMinutes } + // Scored on the ring's own minutes, as `reconcileWakingDay` does (issue #106). + val measuredMin = com.pulseloop.service.measuredAsleepMinutes(row.blocks) // Parent session BEFORE its blocks (FK sleep_stage_blocks -> sleep_sessions.id). db.sleepSessionDao().upsert( session.copy( @@ -195,7 +214,7 @@ object SleepRecordDeletion { startAt = row.startAt, endAt = row.endAt, totalMinutes = totalMin, - score = com.pulseloop.service.sleepStageScore(deepMin, totalMin), + score = com.pulseloop.service.sleepStageScore(deepMin, measuredMin), updatedAt = now, ), ) diff --git a/app/src/main/java/com/pulseloop/health/HealthConnectTypeMappings.kt b/app/src/main/java/com/pulseloop/health/HealthConnectTypeMappings.kt index 1e947b49..d5b51616 100644 --- a/app/src/main/java/com/pulseloop/health/HealthConnectTypeMappings.kt +++ b/app/src/main/java/com/pulseloop/health/HealthConnectTypeMappings.kt @@ -521,6 +521,9 @@ object HealthConnectTypeMappings { SleepStage.REM.name -> SleepSessionRecord.STAGE_TYPE_REM SleepStage.AWAKE.name -> SleepSessionRecord.STAGE_TYPE_AWAKE SleepStage.UNKNOWN.name -> SleepSessionRecord.STAGE_TYPE_UNKNOWN + // Minutes the wearer added over time the ring missed (issue #106): asleep, but no stage was + // measured, so the generic asleep type rather than any specific stage. + SleepStage.ADDED.name -> SleepSessionRecord.STAGE_TYPE_SLEEPING else -> SleepSessionRecord.STAGE_TYPE_UNKNOWN } diff --git a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt index d6e25c90..dd813a1b 100644 --- a/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt +++ b/app/src/main/java/com/pulseloop/ring/RingDecodedEvent.kt @@ -44,7 +44,15 @@ enum class SpotVital( * Ported from [SleepStage] in PulseModels.swift. */ enum class SleepStage { - LIGHT, DEEP, AWAKE, UNKNOWN, REM; + LIGHT, DEEP, AWAKE, UNKNOWN, REM, + + /** + * Minutes the wearer added to a ring record by editing it over time the ring missed (issue + * #106). Asleep, but unstaged: counted in time asleep, left out of the stage breakdown and the + * score. No decoder ever produces it — only `editedRecordBlocks` (SleepRecordExtension.kt) does. + * Deliberately not [UNKNOWN], which is a stage byte the ring *did* record and we can't read. + */ + ADDED; companion object { /** diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 7ad3e3d4..e2a9f0c1 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -623,21 +623,15 @@ class EventPersistenceSubscriber( return } - // Sleep record edit gate (issue #82): adjust boundaries if user edited this record + // Sleep record edit gate (issue #82, #106): the user's bounds for this record, re-applied + // inside the transaction below — trimming *and* re-creating any minutes they added over + // time the ring missed, through the same function the edit itself used. val edit = db.measurementDeletionDao().getSleepEdit(dayStart, ts) ?: db.measurementDeletionDao().getSleepEdit(origDayStart, ts) - if (edit != null) { - val recEnd = effectiveTs + effectiveStages.size * 60_000L - val trimmedStart = maxOf(effectiveTs, edit.newStartAt) - val trimmedEnd = minOf(recEnd, edit.newEndAt) - if (trimmedStart >= trimmedEnd) return - val startIndex = ((trimmedStart - effectiveTs) / 60_000L).toInt() - val endIndex = ((trimmedEnd - effectiveTs) / 60_000L).toInt() - effectiveTs = trimmedStart - effectiveStages = effectiveStages.subList(startIndex, endIndex) - } - db.withTransaction { upsertSleepSessionAtomic(effectiveTs, effectiveStages, completeSession, originalRecordStart = ts) } + db.withTransaction { + upsertSleepSessionAtomic(effectiveTs, effectiveStages, completeSession, originalRecordStart = ts, edit = edit) + } } private suspend fun upsertSleepSessionAtomic( @@ -645,28 +639,47 @@ class EventPersistenceSubscriber( stages: List, completeSession: Boolean, originalRecordStart: Long = ts, + edit: com.pulseloop.data.dao.SleepRecordEditBounds? = null, ) { // Group packets by the waking-day boundary (sleep from 7 PM rolls to the next morning) so // a night that starts before midnight lands under the morning of waking instead of being // split into two sessions at midnight. Matches the iOS reference // (PulseEventBus.persistSleepTimeline + Calendar.wakingDay(forSleepStart:)). val dayStart = com.pulseloop.util.TimeUtil.wakingDayLocal(ts) - val packetEnd = ts + stages.size * 60_000L + val ringEnd = ts + stages.size * 60_000L // Include legacy rows keyed to the wrong day if they overlap this packet. Reconciliation // re-points their surviving blocks to the correct waking day. - val overlapping = db.sleepSessionDao().ringOverlapping(ts, packetEnd) + val overlapping = db.sleepSessionDao().ringOverlapping(ts, ringEnd) val existing = (db.sleepSessionDao().ringAllByDay(dayStart) + overlapping).distinctBy { it.id } val existingBlocks = if (existing.isEmpty()) emptyList() else db.sleepStageBlockDao().forSessions(existing.map { it.id }) + var recordBlocks = buildStageBlocks("", ts, stages, recordStartAt = originalRecordStart) + if (edit != null) { + // Re-apply the user's edit (issue #82, #106) with `editedRecordBlocks`, the function + // `SleepRecordDeletion.edit` used, so this sync reproduces the edit's blocks — the same + // `startAt`s, so tombstones and the restate stay idempotent. Added minutes give way to + // any other record already stored: the ring's measurement beats an extension. + val (nightStart, nightEnd) = nightWindow(dayStart) + val (start, end) = clampEditToNeighbours( + edit.newStartAt, edit.newEndAt, ts, ringEnd, + others = existingBlocks.filter { it.recordStartAt != originalRecordStart }, + nightStart = nightStart, nightEnd = nightEnd, + ) + recordBlocks = editedRecordBlocks(recordBlocks, originalRecordStart, start, end) ?: return + } + // The interval this packet is authoritative for: the record as edited, added minutes and all. + val packetStart = recordBlocks.minOf { it.startAt } + val packetEnd = recordBlocks.maxOf { it.startAt + it.durationMinutes * 60_000L } + // YCBT complete records are authoritative for the ring session they describe, including // shortened revisions. Packet-based families replace only the packet interval. In both // cases the unaffected blocks remain available for SleepSegmentation to preserve // separate naps — and, for a complete record, the *other* ring sessions of the same night // (issue #63): see [completeSessionSurvivors] for why "the session it describes" is a // contiguous run of blocks and not every block of every row the packet touches. - val replacements = buildStageBlocks("", ts, stages, recordStartAt = originalRecordStart) + val replacements = recordBlocks // Tombstone check (issue #78): a deleted ring record's blocks come back with the same // `startAt` values on every re-send of that night, so the re-derive must drop them // here or `SleepRecordDeletion`'s work lasts exactly one sync. @@ -677,12 +690,12 @@ class EventPersistenceSubscriber( } val dayBlocks = replaceOverlappingSleepBlocks( existing = if (completeSession) { - completeSessionSurvivors(existingBlocks, ts, packetEnd) + completeSessionSurvivors(existingBlocks, packetStart, packetEnd) } else { existingBlocks }, replacements = replacements, - replacementStart = ts, + replacementStart = packetStart, replacementEnd = packetEnd, ) @@ -762,7 +775,8 @@ class EventPersistenceSubscriber( val deepMin = seg.blocks .filter { it.stageRaw == SleepStage.DEEP.name } .sumOf { it.durationMinutes } - val score = computeSleepScore(deepMin, totalMin) + // Scored on the minutes the ring measured: added ones are asleep but unstaged (#106). + val score = computeSleepScore(deepMin, measuredAsleepMinutes(seg.blocks)) // Parent session BEFORE its blocks (FK sleep_stage_blocks -> sleep_sessions.id). db.sleepSessionDao().upsert( @@ -794,61 +808,6 @@ class EventPersistenceSubscriber( available.forEach { db.sleepSessionDao().deleteById(it.id) } } - /** - * Build SleepStageBlockEntity entries with run-length encoding. - * Consecutive minutes of the same stage are merged into one block. - * - * Every block carries [startTs] as its `recordStartAt` — the declared start of the ring record - * these stages arrived in (issue #68). This is the only point at which that is known: the night - * is merged into one session immediately afterwards, and the record boundary is not recoverable - * from the stored timeline, because this ring reopens a record a single minute after closing - * one and that is the same width as the minute-grid rounding seam between two blocks of the - * same record. - */ - private fun buildStageBlocks( - sessionId: String, - startTs: Long, - stages: List, - recordStartAt: Long = startTs, - ): List { - if (stages.isEmpty()) return emptyList() - val blocks = mutableListOf() - var currentStage = stages[0] - var blockStart = startTs - var blockMinute = 0 - var duration = 1 - - for (i in 1 until stages.size) { - val stage = stages[i] - if (stage == currentStage) { - duration++ - } else { - blocks.add(SleepStageBlockEntity( - sessionId = sessionId, - startAt = blockStart, - startMinute = blockMinute, - durationMinutes = duration, - stageRaw = currentStage.name, - recordStartAt = recordStartAt, - )) - currentStage = stage - blockStart = startTs + i * 60_000L - blockMinute = i - duration = 1 - } - } - // Final block - blocks.add(SleepStageBlockEntity( - sessionId = sessionId, - startAt = blockStart, - startMinute = blockMinute, - durationMinutes = duration, - stageRaw = currentStage.name, - recordStartAt = recordStartAt, - )) - return blocks - } - /** * Sleep quality score (0-100) based on deep sleep ratio. * Medical research: optimal deep sleep = 15-25% of total. @@ -913,6 +872,61 @@ internal fun spotReadingsMatching( window: Long = EventPersistenceSubscriber.SPOT_MATCH_MS, ): List = ours.filter { kotlin.math.abs(it - historyAt) <= window } +/** + * Build SleepStageBlockEntity entries with run-length encoding. + * Consecutive minutes of the same stage are merged into one block. + * + * Every block carries [startTs] as its `recordStartAt` — the declared start of the ring record + * these stages arrived in (issue #68). This is the only point at which that is known: the night + * is merged into one session immediately afterwards, and the record boundary is not recoverable + * from the stored timeline, because this ring reopens a record a single minute after closing + * one and that is the same width as the minute-grid rounding seam between two blocks of the + * same record. + */ +internal fun buildStageBlocks( + sessionId: String, + startTs: Long, + stages: List, + recordStartAt: Long = startTs, +): List { + if (stages.isEmpty()) return emptyList() + val blocks = mutableListOf() + var currentStage = stages[0] + var blockStart = startTs + var blockMinute = 0 + var duration = 1 + + for (i in 1 until stages.size) { + val stage = stages[i] + if (stage == currentStage) { + duration++ + } else { + blocks.add(SleepStageBlockEntity( + sessionId = sessionId, + startAt = blockStart, + startMinute = blockMinute, + durationMinutes = duration, + stageRaw = currentStage.name, + recordStartAt = recordStartAt, + )) + currentStage = stage + blockStart = startTs + i * 60_000L + blockMinute = i + duration = 1 + } + } + // Final block + blocks.add(SleepStageBlockEntity( + sessionId = sessionId, + startAt = blockStart, + startMinute = blockMinute, + durationMinutes = duration, + stageRaw = currentStage.name, + recordStartAt = recordStartAt, + )) + return blocks +} + internal fun historyMeasurementId(kind: MeasurementKind, timestamp: Long): String = "history:${kind.key}:$timestamp" diff --git a/app/src/main/java/com/pulseloop/service/SleepInsights.kt b/app/src/main/java/com/pulseloop/service/SleepInsights.kt index 9ef735fd..8750fc06 100644 --- a/app/src/main/java/com/pulseloop/service/SleepInsights.kt +++ b/app/src/main/java/com/pulseloop/service/SleepInsights.kt @@ -56,7 +56,13 @@ object SleepScore { // label awake at all" heuristic are judged against it, since both are about time in bed — // and judged against asleep time the coverage test below would be true for every ring, // handing a ring that never labels awake the full awake sub-score for nothing. - val total = if (session.totalMinutes > 0) session.totalMinutes.toDouble() else 0.0 + // + // Minutes the wearer added over time the ring missed (issue #106) are asleep but carry no + // stage, so the score judges the night the ring measured: they leave `total` (they would + // dilute every stage share) and the coverage test, and stay in `span`, which held them as a + // between-record gap before the edit and still does. + val added = addedMinutes(blocks) + val total = if (session.totalMinutes > 0) (session.totalMinutes - added).coerceAtLeast(0).toDouble() else 0.0 val span = session.spanMinutes.toDouble().takeIf { it > 0 } ?: total // stageRaw is persisted as the SleepStage enum name (uppercase) — match it exactly. // deepPct keeps its historical meaning (deep + REM, the restorative share the stage @@ -66,7 +72,8 @@ object SleepScore { val deep = minutesFor(SleepStage.DEEP, SleepStage.REM) val light = minutesFor(SleepStage.LIGHT) val awake = minutesFor(SleepStage.AWAKE) - val coveredStageMin = blocks.sumOf { it.durationMinutes.toDouble() } + val coveredStageMin = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name } + .sumOf { it.durationMinutes.toDouble() } val hasAwakeSignal = blocks.any { it.stageRaw == SleepStage.AWAKE.name } || awake > 0 || (span > 0 && coveredStageMin >= span * 0.95) @@ -202,6 +209,22 @@ fun asleepMinutes(blocks: List): Int = .sumOf { it.durationMinutes } .coerceAtLeast(0) +/** + * Minutes the wearer added to a record over time the ring missed (issue #106) — asleep, unstaged. + * They are inside [asleepMinutes] (the AWAKE-exclusion rule already admits them) and outside + * everything that judges stages: subtract them wherever a stage share or score is computed. + */ +fun addedMinutes(blocks: List): Int = + blocks.filter { it.stageRaw == SleepStage.ADDED.name }.sumOf { it.durationMinutes } + +/** + * The asleep minutes the ring itself measured: [asleepMinutes] less [addedMinutes]. The + * denominator for [sleepStageScore], so a night the wearer extended scores exactly as the ring's + * own record would have (issue #106). + */ +fun measuredAsleepMinutes(blocks: List): Int = + (asleepMinutes(blocks) - addedMinutes(blocks)).coerceAtLeast(0) + /** * Awake minutes for a session, including the short gaps between its ring records (issue #81). * @@ -283,7 +306,8 @@ fun hypnogramBlocks(blocks: List): List 0L }?.recordStartAt ?: startAt val asleepMinutes: Int get() = asleepMinutes(blocks) + /** Minutes the wearer added over time the ring missed (issue #106); part of [asleepMinutes]. */ + val addedMinutes: Int get() = addedMinutes(blocks) + private val measured get() = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name } + /** Where the ring's own recording starts and ends inside this run, without the added minutes — + * the bounds an extension is measured from (issue #106). The run's own when nothing is measured. */ + val measuredStartAt: Long get() = measured.minOfOrNull { it.startAt } ?: startAt + val measuredEndAt: Long get() = measured.maxOfOrNull { it.startAt + it.durationMinutes * 60_000L } ?: endAt val spanMinutes: Int get() = ((endAt - startAt) / 60_000L).toInt().coerceAtLeast(0) } diff --git a/app/src/main/java/com/pulseloop/service/SleepRecordExtension.kt b/app/src/main/java/com/pulseloop/service/SleepRecordExtension.kt new file mode 100644 index 00000000..3ada1ae9 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/SleepRecordExtension.kt @@ -0,0 +1,228 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.ring.SleepStage +import com.pulseloop.util.TimeUtil +import java.time.Instant +import java.time.ZoneId + +/** + * Editing a ring sleep record's bounds, including **extending** it over time the ring missed + * (issue #106). Pure: the edit path (`SleepRecordDeletion.edit`) and the import path + * (`EventPersistenceSubscriber`, which re-applies a stored edit on every re-sync of the night) both + * map a record through [editedRecordBlocks], so a re-sync produces exactly the blocks the edit did. + * + * The reporter's ring recorded 12:51–5:44 and 6:56–8:07, but they were asleep again from about + * 5:46; the app counted the hole as 1 h 12 awake (#81). Editing (#82) could only shorten. Minutes an + * extension adds are stored as [SleepStage.ADDED] blocks — **asleep but unstaged**: in time asleep, + * out of the stage breakdown and the score, drawn as their own band on the hypnogram. They carry + * the ring record's `recordStartAt`, so they belong to that record for `sleepRecordRuns`, and the + * gap they cover stops counting as a between-record waking with no further change. + */ + +/** How far a record may be extended beyond the ring's own bounds where no neighbour limits it. */ +const val MAX_OUTWARD_EXTENSION_MINUTES = 120 + +private const val MINUTE_MS = 60_000L + +/** + * The first point on the record's minute grid at or after [t]. A ring record's stages sit on a + * grid anchored at its declared start (`buildStageBlocks`), and its blocks' `startAt` values are + * the identity tombstones key on, so an edit snaps to that grid rather than to wall-clock minutes. + */ +internal fun gridCeil(t: Long, origin: Long): Long = + origin + Math.floorDiv(t - origin + MINUTE_MS - 1, MINUTE_MS) * MINUTE_MS + +/** The last point on the record's minute grid at or before [t]. See [gridCeil]. */ +internal fun gridFloor(t: Long, origin: Long): Long = + origin + Math.floorDiv(t - origin, MINUTE_MS) * MINUTE_MS + +/** + * One record's blocks after an edit to [editStart]..[editEnd] — the single function both paths + * use (issue #106). + * + * [blocks] are the record's blocks: the import passes the ring's freshly built ones, the edit path + * the stored ones. Any [SleepStage.ADDED] block among them is ignored — a previous extension is + * re-derived from the new bounds, never kept — so editing back inside the ring's bounds removes the + * added minutes, and re-applying the same edit to its own output is a no-op. + * + * The bounds snap inwards onto the grid anchored at [gridOrigin] (the record's declared start): + * the start up, the end down, so the result never reaches past a limit the caller clamped to. + * Measured blocks are trimmed to the bounds exactly as a shortening always did; time outside the + * ring's own measured span becomes one ADDED block on each side that needs one. + * + * Null when the bounds keep none of the ring's own minutes — a record made only of added time has + * nothing to anchor it to, so the edit is refused rather than inventing a night. + */ +fun editedRecordBlocks( + blocks: List, + gridOrigin: Long, + editStart: Long, + editEnd: Long, +): List? { + val measured = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name }.sortedBy { it.startAt } + if (measured.isEmpty()) return null + val start = gridCeil(editStart, gridOrigin) + val end = gridFloor(editEnd, gridOrigin) + if (start >= end) return null + + val kept = measured.mapNotNull { b -> + val keepStart = maxOf(b.startAt, start) + val keepEnd = minOf(b.startAt + b.durationMinutes * MINUTE_MS, end) + val minutes = ((keepEnd - keepStart) / MINUTE_MS).toInt() + if (minutes > 0) b.copy(startAt = keepStart, durationMinutes = minutes) else null + } + if (kept.isEmpty()) return null + + val template = measured.first() + val measuredStart = template.startAt + val measuredEnd = measured.maxOf { it.startAt + it.durationMinutes * MINUTE_MS } + fun added(from: Long, until: Long): SleepStageBlockEntity? { + val minutes = ((until - from) / MINUTE_MS).toInt() + if (minutes <= 0) return null + return SleepStageBlockEntity( + sessionId = template.sessionId, + startAt = from, + startMinute = 0, // re-keyed against the session start by whoever writes the row + durationMinutes = minutes, + stageRaw = SleepStage.ADDED.name, + recordStartAt = template.recordStartAt, + ) + } + return listOfNotNull(if (start < measuredStart) added(start, measuredStart) else null) + + kept + + listOfNotNull(if (end > measuredEnd) added(measuredEnd, end) else null) +} + +/** Why an edit bound stops where it does — what the dialog names when a pick goes past it. */ +enum class RecordEditLimit { + /** The previous record of the same night ends here. */ + PREVIOUS_RECORD, + /** The next record of the same night starts here. */ + NEXT_RECORD, + /** [MAX_OUTWARD_EXTENSION_MINUTES] past the ring's own bounds, before the night's first record + * or after its last. */ + OUTWARD_CAP, + /** The waking day's 7 PM turnover: further would move the record into another night. */ + NIGHT_BOUNDARY, + /** The record must keep at least one minute the ring measured. */ + RING_MINUTES, +} + +/** + * How far one record's bounds may move (issue #106). The start may go back to the previous + * record's end (no cap: that is the gap the ring missed, however long the Bedtime bridge let it + * be) or, for the night's first record, [MAX_OUTWARD_EXTENSION_MINUTES] before the ring's own + * start; the end likewise forward. Never across the waking day's 7 PM turnover. Shortening is + * limited only by keeping one measured minute. + */ +data class RecordEditLimits( + val gridOrigin: Long, + val earliestStart: Long, + val earliestStartLimit: RecordEditLimit, + val latestEnd: Long, + val latestEndLimit: RecordEditLimit, + /** The ring's own measured span inside the record, which a shortening must keep a minute of. */ + val measuredStart: Long, + val measuredEnd: Long, +) + +fun recordEditLimits( + run: SleepRecordRun, + previous: SleepRecordRun?, + next: SleepRecordRun?, + wakingDay: Long, + zone: ZoneId = ZoneId.systemDefault(), +): RecordEditLimits { + val origin = run.recordStartAt + val measuredStart = run.measuredStartAt + val measuredEnd = run.measuredEndAt + val cap = MAX_OUTWARD_EXTENSION_MINUTES * MINUTE_MS + val (nightStart, nightEnd) = nightWindow(wakingDay, zone) + + val startCandidates = listOf( + if (previous != null) gridCeil(previous.endAt, origin) to RecordEditLimit.PREVIOUS_RECORD + else gridCeil(measuredStart - cap, origin) to RecordEditLimit.OUTWARD_CAP, + gridCeil(nightStart, origin) to RecordEditLimit.NIGHT_BOUNDARY, + ) + val endCandidates = listOf( + if (next != null) gridFloor(next.startAt, origin) to RecordEditLimit.NEXT_RECORD + else gridFloor(measuredEnd + cap, origin) to RecordEditLimit.OUTWARD_CAP, + gridFloor(nightEnd, origin) to RecordEditLimit.NIGHT_BOUNDARY, + ) + // A limit never cuts into the record as it already stands (overlapping legacy rows). + val (earliest, earliestWhy) = startCandidates.maxBy { it.first } + val (latest, latestWhy) = endCandidates.minBy { it.first } + return RecordEditLimits( + gridOrigin = origin, + earliestStart = minOf(earliest, run.startAt), + earliestStartLimit = earliestWhy, + latestEnd = maxOf(latest, run.endAt), + latestEndLimit = latestWhy, + measuredStart = measuredStart, + measuredEnd = measuredEnd, + ) +} + +/** A picked bound after the limits: [at] is what to use, [limit] is set when the pick went past one. */ +data class ClampedEditPick(val at: Long, val limit: RecordEditLimit?) + +/** + * A start picked in the dialog (a whole minute) placed on the record's grid and held inside + * [limits]. The grid point inside the picked minute is the one the button then shows, so picking + * the minute already displayed is never a change and never a message (issue #106, #116). + */ +fun clampStartPick(picked: Long, limits: RecordEditLimits): ClampedEditPick { + val at = gridCeil(picked - picked % MINUTE_MS, limits.gridOrigin) + val lastStart = gridFloor(limits.measuredEnd - MINUTE_MS, limits.gridOrigin) + return when { + at < limits.earliestStart -> ClampedEditPick(limits.earliestStart, limits.earliestStartLimit) + at > lastStart -> ClampedEditPick(lastStart, RecordEditLimit.RING_MINUTES) + else -> ClampedEditPick(at, null) + } +} + +/** The end-side twin of [clampStartPick]. */ +fun clampEndPick(picked: Long, limits: RecordEditLimits): ClampedEditPick { + val at = gridCeil(picked - picked % MINUTE_MS, limits.gridOrigin) + val firstEnd = gridCeil(limits.measuredStart + MINUTE_MS, limits.gridOrigin) + return when { + at > limits.latestEnd -> ClampedEditPick(limits.latestEnd, limits.latestEndLimit) + at < firstEnd -> ClampedEditPick(firstEnd, RecordEditLimit.RING_MINUTES) + else -> ClampedEditPick(at, null) + } +} + +/** + * The span of waking day [wakingDay] (local midnight): from 7 PM the evening before to 7 PM on the + * day — `TimeUtil.wakingDayLocal`'s turnover, so a record extended inside it keeps its date. + */ +internal fun nightWindow(wakingDay: Long, zone: ZoneId = ZoneId.systemDefault()): Pair { + val day = Instant.ofEpochMilli(wakingDay).atZone(zone).toLocalDate() + val hour = TimeUtil.SLEEP_EVENING_BOUNDARY_HOUR + val start = day.minusDays(1).atTime(hour, 0).atZone(zone).toInstant().toEpochMilli() + val end = day.atTime(hour, 0).atZone(zone).toInstant().toEpochMilli() + return start to end +} + +/** + * Hold edit bounds clear of every block that isn't this record's — the import's guard, and the edit + * path's against records in *other* sessions of the day, which the dialog doesn't see. The ring's + * measurement always beats an extension: whichever arrives first, the added minutes give way + * (`replaceOverlappingSleepBlocks` trims them when a neighbour arrives later). + */ +internal fun clampEditToNeighbours( + editStart: Long, + editEnd: Long, + measuredStart: Long, + measuredEnd: Long, + others: List, + nightStart: Long, + nightEnd: Long, +): Pair { + val before = others.map { it.startAt + it.durationMinutes * MINUTE_MS }.filter { it <= measuredStart } + val after = others.map { it.startAt }.filter { it >= measuredEnd } + val lo = maxOf(before.maxOrNull() ?: Long.MIN_VALUE, nightStart) + val hi = minOf(after.minOrNull() ?: Long.MAX_VALUE, nightEnd) + return maxOf(editStart, minOf(lo, measuredStart)) to minOf(editEnd, maxOf(hi, measuredEnd)) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt index 9c77aed6..f372bbf3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -63,6 +63,8 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.ring.SleepStage +import androidx.compose.ui.graphics.drawscope.clipRect import com.pulseloop.service.SleepBar import com.pulseloop.service.SleepFormat import com.pulseloop.service.SleepInsights @@ -500,6 +502,10 @@ private fun SleepHypnogram( val sorted = remember(blocks) { blocks.filter { it.durationMinutes > 0 && it.stageRaw != "UNKNOWN" }.sortedBy { it.startMinute } } + // Minutes the wearer added over time the ring missed (issue #106) have no lane — no stage was + // measured — so they are drawn as a hatched band across the asleep lanes instead of a step, and + // the step line simply doesn't connect into or out of them. + fun isAdded(stage: String) = stage == SleepStage.ADDED.name // The x axis is wall-clock time, so it is scaled by the session's SPAN, never by its duration. // Since issue #63 those are different numbers — `totalMinutes` is time asleep and excludes the // awake stretches and the gap between a split night's two records, so scaling by it would @@ -552,12 +558,14 @@ private fun SleepHypnogram( val parts = lanes.reversed().mapNotNull { stage -> perStage[stage]?.let { "${stageName(stage)} ${SleepFormat.duration(it)}" } } + val added = sorted.filter { isAdded(it.stageRaw) }.sumOf { it.durationMinutes } + val allParts = if (added > 0) parts + "${tr("Added by you")} ${SleepFormat.duration(added)}" else parts trf("Sleep stages from {0} to {1}", clockTime(startTs), clockTime(startTs + safeTotal * 60_000L)) + - if (parts.isEmpty()) ": " + tr("no stage data") else ": " + parts.joinToString(", ") + if (allParts.isEmpty()) ": " + tr("no stage data") else ": " + allParts.joinToString(", ") } fun readoutText(block: SleepStageBlockEntity): String { - val stage = stageName(block.stageRaw) + val stage = if (isAdded(block.stageRaw)) tr("Added by you") else stageName(block.stageRaw) val startTime = clockTime(startTs + block.startMinute * 60_000L) val endTime = clockTime(startTs + (block.startMinute + block.durationMinutes) * 60_000L) return "$stage · $startTime – $endTime" @@ -627,10 +635,38 @@ private fun SleepHypnogram( Canvas(Modifier.fillMaxSize()) { if (sorted.isEmpty()) return@Canvas + // Added-by-you bands first, under everything else (issue #106): muted fill and + // diagonal hatching from the REM lane to the DEEP lane. + sorted.filter { isAdded(it.stageRaw) }.forEach { block -> + val startX = xForMinute(block.startMinute, size.width) + val endX = xForMinute(block.startMinute + block.durationMinutes, size.width) + .coerceAtLeast(startX + 1f) + val top = size.height * (laneFrac["REM"] ?: 0.38f) + val bottom = size.height * (laneFrac["DEEP"] ?: 0.85f) + drawRect( + color = ADDED_BAND_COLOR.copy(alpha = 0.14f), + topLeft = Offset(startX, top), + size = androidx.compose.ui.geometry.Size(endX - startX, bottom - top), + ) + clipRect(left = startX, top = top, right = endX, bottom = bottom) { + val step = 7.dp.toPx() + var x = startX - (bottom - top) + while (x < endX) { + drawLine( + color = ADDED_BAND_COLOR.copy(alpha = 0.45f), + start = Offset(x, bottom), end = Offset(x + (bottom - top), top), + strokeWidth = 1.dp.toPx(), + ) + x += step + } + } + } + // Dashed vertical connectors between consecutive blocks. for (i in 1 until sorted.size) { val prev = sorted[i - 1] val cur = sorted[i] + if (isAdded(prev.stageRaw) || isAdded(cur.stageRaw)) continue val cx = xForMinute(cur.startMinute, size.width) drawLine( color = PulseColors.sleep.copy(alpha = 0.46f), @@ -642,7 +678,7 @@ private fun SleepHypnogram( ) } // Horizontal segment per block: soft halo underlay + solid line. - sorted.forEach { block -> + sorted.filterNot { isAdded(it.stageRaw) }.forEach { block -> val y = laneY(block.stageRaw, size.height) val startX = xForMinute(block.startMinute, size.width) val endX = xForMinute(block.startMinute + block.durationMinutes, size.width) @@ -741,9 +777,26 @@ private fun SleepHypnogram( ) { ticks.forEach { Text(it, fontSize = 12.sp, color = PulseColors.textMuted) } } + if (sorted.any { isAdded(it.stageRaw) }) { + Row( + Modifier.padding(start = plotInsets.x), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Box(Modifier.size(width = 12.dp, height = 8.dp).background(ADDED_BAND_COLOR.copy(alpha = 0.45f))) + Text( + tr("Added by you · asleep, no stage measured"), + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } + } } } +/** The hatched band for minutes the wearer added over time the ring missed (issue #106): the + * neutral muted ink, so it never reads as one of the four measured stage colours (or as mint). */ +private val ADDED_BAND_COLOR: Color get() = PulseColors.textMuted + /** Three side-by-side stage duration cards (SleepStageSummaryCardsView in Swift). */ @Composable private fun SleepStageSummaryCards(prefix: String = "", deep: String, light: String, awake: String) { @@ -1076,6 +1129,14 @@ private fun SleepRecordsCard( fontSize = 12.sp, color = PulseColors.textMuted, ) + // Minutes the wearer added over time the ring missed (issue #106). + if (run.addedMinutes > 0) { + Text( + trf("Includes {0} added by you, not staged or scored", SleepFormat.duration(run.addedMinutes)), + fontSize = 12.sp, + color = PulseColors.textMuted, + ) + } } // Edit start/end boundaries (issue #82). IconButton(onClick = { editingRun = run }) { @@ -1122,8 +1183,17 @@ private fun SleepRecordsCard( } editingRun?.let { run -> + val index = runs.indexOf(run) SleepRecordEditDialog( run = run, + limits = remember(run, runs, session.date) { + com.pulseloop.service.recordEditLimits( + run = run, + previous = runs.getOrNull(index - 1), + next = runs.getOrNull(index + 1), + wakingDay = session.date, + ) + }, onDismiss = { editingRun = null }, onSave = { newStart, newEnd -> editingRun = null @@ -1166,6 +1236,7 @@ private fun SleepRecordsCard( @Composable private fun SleepRecordEditDialog( run: com.pulseloop.service.SleepRecordRun, + limits: com.pulseloop.service.RecordEditLimits, onDismiss: () -> Unit, onSave: (newStartAt: Long, newEndAt: Long) -> Unit, ) { @@ -1173,9 +1244,8 @@ private fun SleepRecordEditDialog( var currentStart by remember { mutableStateOf(run.startAt) } var currentEnd by remember { mutableStateOf(run.endAt) } var pickingTime by remember { mutableStateOf(null) } // "start" or "end" - // Set when the last picked time fell outside the record and was pulled back to its edge, which - // otherwise looks like the edit didn't register (issue #106). - var pickedOutside by remember { mutableStateOf(false) } + // The limit the last pick ran past, named rather than silently snapped back to (issue #106). + var limitMessage by remember { mutableStateOf(null) } AlertDialog( onDismissRequest = onDismiss, @@ -1183,7 +1253,7 @@ private fun SleepRecordEditDialog( text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Text( - tr("Adjust start or end time to trim this record. Stages outside the new range will be removed."), + tr("Trim this record, or extend it over time the ring missed. Added time counts as asleep but has no stage, so it stays out of the stage breakdown and score."), style = androidx.compose.material3.MaterialTheme.typography.bodySmall, color = PulseColors.textMuted, ) @@ -1204,12 +1274,8 @@ private fun SleepRecordEditDialog( Text(trf("End: {0}", clockTime(currentEnd))) } } - if (pickedOutside) { - Text( - trf("This record runs {0} – {1}. You can only shorten it.", clockTime(run.startAt), clockTime(run.endAt)), - color = PulseColors.danger, - fontSize = 12.sp, - ) + limitMessage?.let { + Text(it, color = PulseColors.danger, fontSize = 12.sp) } if (currentStart >= currentEnd) { Text( @@ -1251,13 +1317,21 @@ private fun SleepRecordEditDialog( text = { if (landscape) TimeInput(state = timeState) else TimePicker(state = timeState) }, confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { - val picked = resolveAdjustedTime(targetTs, run.startAt, run.endAt, timeState.hour, timeState.minute, zone) - val resolved = picked.coerceIn(run.startAt, run.endAt) - pickedOutside = isOutsideRecord(picked, run.startAt, run.endAt) + // Resolve the date against the whole span the record may cover, so 11:30 PM + // picked for a record starting 12:51 AM lands the evening before. + val picked = resolveAdjustedTime( + targetTs, limits.earliestStart, limits.latestEnd, timeState.hour, timeState.minute, zone, + ) + val clamped = if (which == "start") { + com.pulseloop.service.clampStartPick(picked, limits) + } else { + com.pulseloop.service.clampEndPick(picked, limits) + } + limitMessage = clamped.limit?.let { editLimitMessage(it, which == "start", clamped.at, limits) } if (which == "start") { - currentStart = resolved + currentStart = clamped.at } else { - currentEnd = resolved + currentEnd = clamped.at } pickingTime = null }) { Text(tr("Done")) } @@ -1270,12 +1344,31 @@ private fun SleepRecordEditDialog( } /** - * Whether a time picked in the edit dialog falls outside the record, by more than the seconds the - * picker can't show: the record's own start and end carry seconds, so picking the minute shown on - * the button must not count as outside (issue #106). + * The dialog's line for a pick that ran past [limit], naming the limit (issue #106). [at] is where + * the pick was held — the previous record's end, the earliest start the cap allows, and so on. */ -internal fun isOutsideRecord(picked: Long, recordStart: Long, recordEnd: Long): Boolean = - picked < recordStart - recordStart % 60_000L || picked >= recordEnd - recordEnd % 60_000L + 60_000L +internal fun editLimitMessage( + limit: com.pulseloop.service.RecordEditLimit, + isStart: Boolean, + at: Long, + limits: com.pulseloop.service.RecordEditLimits, +): String { + val time = clockTime(at) + return when (limit) { + com.pulseloop.service.RecordEditLimit.PREVIOUS_RECORD -> trf("The previous record ends at {0}.", time) + com.pulseloop.service.RecordEditLimit.NEXT_RECORD -> trf("The next record starts at {0}.", time) + com.pulseloop.service.RecordEditLimit.OUTWARD_CAP -> { + val hours = com.pulseloop.service.MAX_OUTWARD_EXTENSION_MINUTES / 60 + if (isStart) trf("A record can be extended by up to {0} hours, so it can start at {1} at the earliest.", hours, time) + else trf("A record can be extended by up to {0} hours, so it can end at {1} at the latest.", hours, time) + } + com.pulseloop.service.RecordEditLimit.NIGHT_BOUNDARY -> + if (isStart) trf("Starting before {0} would move it into another night.", time) + else trf("Ending after {0} would move it into another night.", time) + com.pulseloop.service.RecordEditLimit.RING_MINUTES -> + trf("Keep at least a minute of what the ring recorded ({0} – {1}).", clockTime(limits.measuredStart), clockTime(limits.measuredEnd)) + } +} /** * Resolves the epoch millis for an adjusted time within/near a sleep record [recordStart]..[recordEnd]. diff --git a/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt b/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt index f1517008..22e085cc 100644 --- a/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt +++ b/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt @@ -296,19 +296,4 @@ class SleepRecordDeletionTest { assertEquals(2, targets.size) assertEquals(listOf(b1.startAt, b2.startAt), targets.map { it.startAt }) } - - // ── Issue #106: a picked time outside the record says so ───────────── - - @Test - fun `a picked time outside the record is reported, the record's own minutes are not`() { - val start = 1_791_766_260_000L + 13_000L // a record starting at :13 s - val end = start + 293 * 60_000L - val outside = { picked: Long -> com.pulseloop.ui.screens.isOutsideRecord(picked, start, end) } - // The minutes shown on the buttons, picked back, are inside despite the record's seconds. - assertFalse(outside(start - 13_000L)) - assertFalse(outside(end - end % 60_000L)) - // A minute earlier than the start, or later than the end, is outside. - assertTrue(outside(start - 13_000L - 60_000L)) - assertTrue(outside(end - end % 60_000L + 60_000L)) - } } diff --git a/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt new file mode 100644 index 00000000..dc737cb2 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt @@ -0,0 +1,295 @@ +package com.pulseloop.service + +import androidx.health.connect.client.records.SleepSessionRecord +import com.pulseloop.data.entity.SleepSessionEntity +import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.health.HealthConnectTypeMappings +import com.pulseloop.ring.SleepStage +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.ZoneId +import java.time.ZonedDateTime + +/** + * Extending a sleep record over time the ring missed (issue #106). + * + * The reporter's night: the ring recorded 12:51–5:44 and 6:56–8:07, they were asleep again from + * about 5:46, and the app counted the hole as 1 h 12 awake. The added minutes are asleep but + * unstaged — in time asleep, out of the breakdown and the score — and the edit path and the import + * path both go through [editedRecordBlocks], so a re-sync writes back exactly what the edit did. + */ +class SleepRecordExtensionTest { + + private val zone = ZoneId.of("UTC") + private val wakingDay = ZonedDateTime.of(2026, 10, 8, 0, 0, 0, 0, zone).toInstant().toEpochMilli() + private fun at(h: Int, m: Int, s: Int = 0) = wakingDay + ((h * 60L + m) * 60 + s) * 1000 + + // Records start on :23 s, as a real ring's do — so the grid is not the wall-clock minute. + private val aStart = at(0, 51, 23) + private val bStart = at(6, 56, 23) + + /** Record A, 293 minutes: light/deep/light/rem as the ring sends them, one stage per minute. */ + private val aStages = List(100) { SleepStage.LIGHT } + List(80) { SleepStage.DEEP } + + List(70) { SleepStage.LIGHT } + List(43) { SleepStage.REM } + /** Record B, 71 minutes. */ + private val bStages = List(30) { SleepStage.LIGHT } + List(20) { SleepStage.DEEP } + List(21) { SleepStage.LIGHT } + + private fun ring(start: Long, stages: List) = + buildStageBlocks("s", start, stages, recordStartAt = start) + + private val a get() = ring(aStart, aStages) + private val b get() = ring(bStart, bStages) + + private fun end(blocks: List) = blocks.maxOf { it.startAt + it.durationMinutes * 60_000L } + + /** What identity and the restate care about — ids are re-minted on every write. */ + private fun shape(blocks: List) = + blocks.sortedBy { it.startAt }.map { listOf(it.startAt, it.durationMinutes.toLong(), it.stageRaw, it.recordStartAt) } + + private fun session(blocks: List) = SleepSessionEntity( + id = "s", date = wakingDay, + startAt = blocks.minOf { it.startAt }, endAt = end(blocks), + totalMinutes = asleepMinutes(blocks), score = null, + ) + + // ── The shared function ───────────────────────────────────────────── + + @Test + fun `extending the start adds one unstaged block before the ring's own`() { + val edited = editedRecordBlocks(b, bStart, at(5, 46, 23), end(b))!! + + val added = edited.first() + assertEquals(SleepStage.ADDED.name, added.stageRaw) + assertEquals(at(5, 46, 23), added.startAt) + assertEquals(70, added.durationMinutes) + assertEquals("added minutes belong to the ring record", bStart, added.recordStartAt) + assertEquals("the ring's blocks are untouched", shape(b), shape(edited.drop(1))) + } + + @Test + fun `extending the end adds one unstaged block after the ring's own`() { + val edited = editedRecordBlocks(b, bStart, bStart, at(8, 30, 23))!! + + assertEquals(shape(b), shape(edited.dropLast(1))) + val added = edited.last() + assertEquals(SleepStage.ADDED.name, added.stageRaw) + assertEquals(end(b), added.startAt) + assertEquals(23, added.durationMinutes) + } + + @Test + fun `one edit can shorten one side and extend the other`() { + val edited = editedRecordBlocks(b, bStart, bStart + 10 * 60_000L, at(8, 17, 23))!! + + assertEquals(bStart + 10 * 60_000L, edited.first().startAt) + assertEquals(SleepStage.LIGHT.name, edited.first().stageRaw) + assertEquals(20, edited.first().durationMinutes) + assertEquals(SleepStage.ADDED.name, edited.last().stageRaw) + assertEquals(10, edited.last().durationMinutes) + assertEquals(61, measuredAsleepMinutes(edited)) + assertEquals(71, asleepMinutes(edited)) + } + + @Test + fun `shortening alone works exactly as before, adding nothing`() { + val edited = editedRecordBlocks(a, aStart, aStart + 30 * 60_000L, end(a) - 13 * 60_000L)!! + + assertEquals(0, addedMinutes(edited)) + assertEquals(293 - 30 - 13, asleepMinutes(edited)) + } + + @Test + fun `a whole-minute pick snaps inwards onto the record's grid`() { + // An edit stored before #106 holds the picker's whole minutes, not the record's :23 s. + val edited = editedRecordBlocks(b, bStart, at(5, 46), at(8, 30))!! + + assertEquals("start rounds up into the picked minute", at(5, 46, 23), edited.first().startAt) + assertEquals("end rounds down, never past the bound", at(8, 29, 23), end(edited)) + } + + @Test + fun `an edit keeping none of the ring's minutes is refused`() { + assertNull(editedRecordBlocks(b, bStart, at(5, 0, 23), bStart)) + assertNull(editedRecordBlocks(b, bStart, end(b), at(8, 30, 23))) + } + + @Test + fun `editing back inside the ring's bounds removes the added minutes`() { + val extended = editedRecordBlocks(b, bStart, at(5, 46, 23), end(b))!! + val undone = editedRecordBlocks(extended, bStart, bStart, end(b))!! + + assertEquals(shape(b), shape(undone)) + } + + // ── Re-sync: the import reproduces the edit ─────────────────────────── + + @Test + fun `re-importing the night re-creates the edit's blocks exactly`() { + val editStart = at(5, 46, 23) + val editEnd = end(b) - 5 * 60_000L + // What `SleepRecordDeletion.edit` stores: the stored record through the shared function. + val afterEdit = editedRecordBlocks(b, bStart, editStart, editEnd)!! + // What the next sync builds: the ring's raw stages, then the stored edit re-applied. + val reimported = editedRecordBlocks(ring(bStart, bStages), bStart, editStart, editEnd)!! + + assertEquals(shape(afterEdit), shape(reimported)) + // Re-applying to its own output is a no-op, so a second edit pass changes nothing either. + assertEquals(shape(afterEdit), shape(editedRecordBlocks(afterEdit, bStart, editStart, editEnd)!!)) + + // And the day's merge is idempotent: replacing the edited record's interval with the + // re-import leaves the stored night exactly as it was, record A included. + val stored = a + afterEdit + val merged = replaceOverlappingSleepBlocks( + existing = stored, + replacements = reimported, + replacementStart = reimported.minOf { it.startAt }, + replacementEnd = end(reimported), + ) + assertEquals(shape(stored), shape(merged)) + } + + @Test + fun `a stored edit gives way to a neighbour record at import`() { + // The stored edit reaches back to 5:30, but record A ends 5:44: the ring's minutes win. + val (nightStart, nightEnd) = nightWindow(wakingDay, zone) + val (start, endAt) = clampEditToNeighbours( + at(5, 30, 23), end(b), bStart, end(b), others = a, nightStart = nightStart, nightEnd = nightEnd, + ) + assertEquals(end(a), start) + assertEquals(end(b), endAt) + } + + // ── Limits and the dialog's picks ──────────────────────────────────── + + private fun limitsForB() = recordEditLimits( + run = sleepRecordRuns(a + b)[1], + previous = sleepRecordRuns(a + b)[0], + next = null, + wakingDay = wakingDay, + zone = zone, + ) + + @Test + fun `extending into the gap stops at the previous record's end`() { + val limits = limitsForB() + assertEquals(end(a), limits.earliestStart) + assertEquals(RecordEditLimit.PREVIOUS_RECORD, limits.earliestStartLimit) + + val pick = clampStartPick(at(5, 30), limits) + assertEquals(end(a), pick.at) + assertEquals(RecordEditLimit.PREVIOUS_RECORD, pick.limit) + + // The reporter's pick: 5:46, inside the gap, no message. + val ok = clampStartPick(at(5, 46), limits) + assertEquals(at(5, 46, 23), ok.at) + assertNull(ok.limit) + } + + @Test + fun `extending outward is capped at two hours past the ring's bounds`() { + val limits = limitsForB() + assertEquals(RecordEditLimit.OUTWARD_CAP, limits.latestEndLimit) + assertEquals(end(b) + 120 * 60_000L, limits.latestEnd) + + val pick = clampEndPick(at(11, 0), limits) + assertEquals(end(b) + 120 * 60_000L, pick.at) + assertEquals(RecordEditLimit.OUTWARD_CAP, pick.limit) + + val first = recordEditLimits(sleepRecordRuns(a + b)[0], null, sleepRecordRuns(a + b)[1], wakingDay, zone) + assertEquals(aStart - 120 * 60_000L, first.earliestStart) + assertEquals(RecordEditLimit.OUTWARD_CAP, first.earliestStartLimit) + assertEquals(bStart, first.latestEnd) + assertEquals(RecordEditLimit.NEXT_RECORD, first.latestEndLimit) + } + + @Test + fun `the cap counts from the ring's bounds, not a previous extension`() { + val extended = editedRecordBlocks(b, bStart, bStart, end(b) + 60 * 60_000L)!! + val limits = recordEditLimits(sleepRecordRuns(extended).single(), null, null, wakingDay, zone) + assertEquals(end(b) + 120 * 60_000L, limits.latestEnd) + } + + @Test + fun `an extension never crosses the night's 7 PM turnover`() { + // A record starting 8:10 PM the evening before: two hours back would be 6:10 PM. + val start = at(-4, 10, 23) // 20:10:23 on Oct 7 + val record = ring(start, List(60) { SleepStage.LIGHT }) + val limits = recordEditLimits(sleepRecordRuns(record).single(), null, null, wakingDay, zone) + assertEquals(RecordEditLimit.NIGHT_BOUNDARY, limits.earliestStartLimit) + assertEquals(at(-5, 0, 23), limits.earliestStart) // 19:00:23, the first grid point inside + } + + @Test + fun `picking the minute the button shows is not a change and not a message`() { + val limits = limitsForB() + val start = clampStartPick(at(6, 56), limits) + assertEquals(bStart, start.at) + assertNull(start.limit) + val endPick = clampEndPick(at(8, 7), limits) + assertEquals(end(b), endPick.at) + assertNull(endPick.limit) + } + + @Test + fun `shortening must keep a minute the ring measured`() { + val limits = limitsForB() + val pick = clampStartPick(at(9, 0), limits) + assertEquals(RecordEditLimit.RING_MINUTES, pick.limit) + assertEquals(end(b) - 60_000L, pick.at) + } + + // ── Asleep, but unstaged and unscored ──────────────────────────────── + + @Test + fun `added minutes count as asleep but not in the score or the stage shares`() { + val extended = a + editedRecordBlocks(b, bStart, end(a), end(b))!! + val ringOnly = a + b + + assertEquals(asleepMinutes(ringOnly) + 72, asleepMinutes(extended)) + assertEquals(asleepMinutes(ringOnly), measuredAsleepMinutes(extended)) + assertEquals(72, addedMinutes(extended)) + + val withAdded = SleepScore.calculate(session(extended), extended) + val without = SleepScore.calculate(session(ringOnly), ringOnly) + assertEquals(without.deepPct, withAdded.deepPct) + assertEquals(without.lightPct, withAdded.lightPct) + assertEquals(without.score, withAdded.score) + assertEquals( + sleepStageScore(100, measuredAsleepMinutes(ringOnly)), + sleepStageScore(100, measuredAsleepMinutes(extended)), + ) + } + + @Test + fun `covering the gap removes it from awake and from the hypnogram`() { + val ringOnly = a + b + assertEquals(72, awakeMinutes(ringOnly)) + + val extended = a + editedRecordBlocks(b, bStart, end(a), end(b))!! + assertEquals("still two records", 2, sleepRecordRuns(extended).size) + assertEquals(0, awakeMinutes(extended)) + assertEquals(extended.size, hypnogramBlocks(extended).size) + + // A partial cover leaves the rest of the gap as a waking. + val partial = a + editedRecordBlocks(b, bStart, at(5, 46, 23), end(b))!! + assertEquals(2, awakeMinutes(partial)) + } + + @Test + fun `closing an hour-plus gap makes the two records one night`() { + assertEquals(2, SleepSegmentation.segment(a + b).size) + val extended = a + editedRecordBlocks(b, bStart, end(a), end(b))!! + assertEquals(1, SleepSegmentation.segment(extended).size) + } + + @Test + fun `added minutes export to Health Connect as generic asleep`() { + assertEquals( + SleepSessionRecord.STAGE_TYPE_SLEEPING, + HealthConnectTypeMappings.sleepStageType(SleepStage.ADDED.name), + ) + assertTrue(SleepSessionRecord.STAGE_TYPE_SLEEPING != SleepSessionRecord.STAGE_TYPE_UNKNOWN) + } +} From e6a2bb4f9c88d66621e5c44c4020e68acad1461b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 18:39:06 +0000 Subject: [PATCH 7/7] =?UTF-8?q?Six=20upstream=20ports:=20pt-BR,=20estimate?= =?UTF-8?q?d=20SpO=E2=82=82=20shown=20by=20default,=20ledger=20and=20audit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ports merged from three worktree branches (one commit per upstream PR, each citing its upstream merge). This commit adds the pt-BR entries, removes three orphaned keys, makes Hide estimated SpO2 default off and visible on every supported ring (our derived-metric rule; upstream hid them by default), records the 2026-11-10 triage in docs/ios-sync.md and adds the audit. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- app/src/main/assets/i18n/pt-BR.json | 42 +++++++++- .../pulseloop/settings/ScheduledSpo2Prefs.kt | 5 +- .../ui/screens/SettingsSubScreens.kt | 22 +++--- .../settings/ScheduledSpo2PrefsTest.kt | 6 +- audits/2026-11-10-v2.16.0-upstream-ports.md | 79 +++++++++++++++++++ docs/ios-sync.md | 21 ++++- 6 files changed, 156 insertions(+), 19 deletions(-) create mode 100644 audits/2026-11-10-v2.16.0-upstream-ports.md diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index e074c70d..502d65e6 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -38,6 +38,7 @@ "1 lab marker to review": "1 marcador de exame para revisar", "1 ladle (100 g)": "1 concha (100 g)", "1 medium": "1 médio", + "1 message": "1 mensagem", "1 or 2": "1 ou 2", "1 plate": "1 prato", "1 plate, 1 tsp olive oil": "1 prato, 1 colher de chá de azeite", @@ -85,6 +86,8 @@ "A normal blood-oxygen level is 95–100%.{0}": "Um nível normal de oxigênio no sangue é 95–100%.{0}", "A nudge about 30 minutes before your suggested bedtime.": "Um lembrete cerca de 30 minutos antes do horário sugerido para dormir.", "A painful, red or swollen leg or arm": "Uma perna ou braço dolorido, vermelho ou inchado", + "A record can be extended by up to {0} hours, so it can end at {1} at the latest.": "Um registro pode ser estendido em até {0} horas, então pode terminar no máximo às {1}.", + "A record can be extended by up to {0} hours, so it can start at {1} at the earliest.": "Um registro pode ser estendido em até {0} horas, então pode começar no mínimo às {1}.", "A record for you and your doctor. PulseLoop doesn't check interactions or doses; ask your pharmacist.": "Um registro para você e seu médico. O PulseLoop não verifica interações nem doses; consulte seu farmacêutico.", "A ring is paired. Forget it in Settings → Ring & sync first: the two would count the same steps and nights.": "Há um anel pareado. Esqueça-o primeiro em Configurações → Anel e sincronização: os dois contariam os mesmos passos e noites.", "A screening questionnaire, not a diagnosis.": "Um questionário de rastreamento, não um diagnóstico.", @@ -154,9 +157,10 @@ "Add workout": "Adicionar treino", "Add your age in Settings → User Profile for cardio capacity.": "Adicione sua idade em Configurações → Perfil do usuário para a capacidade cardiorrespiratória.", "Add your ring": "Adicione seu anel", + "Added by you": "Adicionado por você", + "Added by you · asleep, no stage measured": "Adicionado por você · dormindo, sem fase medida", "Adequate": "Adequado", "Adjust end time": "Ajustar horário de término", - "Adjust start or end time to trim this record. Stages outside the new range will be removed.": "Ajuste o horário de início ou de término para recortar este registro. As fases fora do novo intervalo serão removidas.", "Adjust start time": "Ajustar horário de início", "Adjusted by your accuracy check: {0}. Settings → Accuracy check to change.": "Ajustado pela sua verificação de precisão: {0}. Configurações → Verificação de precisão para alterar.", "Adjusting your ring": "Ajustando seu anel", @@ -183,6 +187,7 @@ "All health areas steady": "Todas as áreas estáveis", "All models from {0} ({1})": "Todos os modelos de {0} ({1})", "All three hold. LAM is about 98% effective only while all three do.": "As três condições valem. A LAM tem cerca de 98% de eficácia somente enquanto as três valerem.", + "All {0} conversations and their replies will be deleted. This can't be undone.": "As {0} conversas e as respostas serão excluídas. Não é possível desfazer.", "All-day heart rate": "Frequência cardíaca o dia todo", "Allow": "Permitir", "Allow Bluetooth access": "Permitir acesso ao Bluetooth", @@ -520,6 +525,9 @@ "Default ports — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. The /v1 path is added for you.": "Portas padrão — Ollama 11434 · LM Studio 1234 · llama.cpp 8080 · vLLM 8000 · SGLang 30000. O caminho /v1 é adicionado para você.", "Delete": "Excluir", "Delete \"{0}\" ({1} kcal) from {2}?": "Apagar \"{0}\" ({1} kcal) de {2}?", + "Delete all": "Excluir todas", + "Delete all conversations": "Excluir todas as conversas", + "Delete all conversations?": "Excluir todas as conversas?", "Delete drink?": "Excluir bebida?", "Delete every record PulseLoop wrote to Health Connect and reset the export to start fresh. Your ring data in PulseLoop is untouched.": "Exclua todos os registros que o PulseLoop gravou no Health Connect e redefina a exportação para começar do zero. Os dados do anel no PulseLoop não são afetados.", "Delete meal?": "Excluir refeição?", @@ -528,6 +536,7 @@ "Delete report": "Excluir laudo", "Delete this activity record": "Excluir este registro de atividade", "Delete this activity record?": "Excluir este registro de atividade?", + "Delete this conversation?": "Excluir esta conversa?", "Delete this period?": "Apagar este período?", "Delete this reading": "Excluir esta leitura", "Delete this reading?": "Excluir esta leitura?", @@ -543,6 +552,7 @@ "Deleting needs write permission, and PulseLoop has none right now — re-grant above, or delete the data in the Health Connect app.": "A exclusão precisa de permissão de gravação, e o PulseLoop não tem nenhuma agora — conceda de novo acima ou exclua os dados no app Health Connect.", "Demo Data": "Dados de demonstração", "Demo data": "Dados de demonstração", + "Derived from heart rate by current ring — export disabled": "Derivado da frequência cardíaca pelo anel atual — exportação desativada", "Describe": "Descrever", "Describe your meal": "Descreva sua refeição", "Destructive actions: reset app data, or unpair the ring and reset. To only forget the ring, use Ring & sync.": "Ações destrutivas: redefinir os dados do app, ou desparear o anel e redefinir. Para apenas esquecer o anel, use Anel e sincronização.", @@ -568,6 +578,7 @@ "Disconnected": "Desconectado", "Disconnected from Strava": "Desconectado do Strava", "Dismiss": "Dispensar", + "Display only real spot measurements on charts and vitals cards, hiding the hourly estimates.": "Mostra apenas medições pontuais reais nos gráficos e cartões de sinais vitais, ocultando as estimativas horárias.", "Disque Saúde (find a human milk bank)": "Disque Saúde (encontre um banco de leite humano)", "Distance": "Distância", "Distance, calories, and heart-rate stats are recalculated for the new window.": "Distância, calorias e estatísticas de frequência cardíaca são recalculadas para o novo período.", @@ -625,6 +636,7 @@ "End: {0}": "Fim: {0}", "Ended early.": "Encerrado antes do previsto.", "Ended early: a different ring was paired.": "Encerrado antes do previsto: outro anel foi pareado.", + "Ending after {0} would move it into another night.": "Terminar depois das {0} o levaria para outra noite.", "Ends": "Termina", "Energy and sleep can dip; resting heart rate is often at its lowest.": "Energia e sono podem cair; a frequência cardíaca em repouso costuma estar no ponto mais baixo.", "Enter a valid mg/dL reading": "Insira uma leitura válida em mg/dL", @@ -639,6 +651,7 @@ "Estimated cost": "Custo estimado", "Estimated from HRV — your ring doesn't measure stress": "Estimado a partir da HRV — seu anel não mede estresse", "Estimated from HRV — your ring doesn't measure stress. Scored against your own recent HRV readings, so it says how this reading compares with your normal, not how you compare with anyone else.": "Estimado a partir do HRV — seu anel não mede estresse. A pontuação compara com suas próprias leituras recentes de HRV, então mostra como esta leitura se compara com o seu normal, não com outras pessoas.", + "Estimated from heart rate": "Estimado pela frequência cardíaca", "Estimated from resting heart rate and age": "Estimado a partir da frequência cardíaca em repouso e da idade", "Estimated from the current discharge at %.1f %%/h.": "Estimado a partir da descarga atual de %.1f %%/h.", "Estimated wellness metric": "Métrica de bem-estar estimada", @@ -652,6 +665,8 @@ "Evening check-in": "Check-in da noite", "Evening type": "Vespertino", "Every exam": "Todos os exames", + "Every hour": "A cada hora", + "Every {0} hours": "A cada {0} horas", "Every {0} min": "A cada {0} min", "Everything compared agrees within its band.": "Tudo o que foi comparado está dentro da faixa.", "Excellent": "Excelente", @@ -761,6 +776,7 @@ "Good night": "Boa noite", "Good sign": "Bom sinal", "Good sleep, with some restlessness": "Sono bom, com alguma inquietação", + "Google Search grounding may need a paid Gemini plan — free-tier keys can be refused, and the coach then answers without web results.": "A pesquisa do Google pode exigir um plano pago do Gemini — chaves gratuitas podem ser recusadas, e aí o coach responde sem resultados da web.", "Great balance of movement and recovery. Keep it up.": "Ótimo equilíbrio entre movimento e recuperação. Continue assim.", "Grounds suggestions in your city's current weather": "Baseia as sugestões no clima atual da sua cidade", "Gym": "Academia", @@ -811,6 +827,7 @@ "Hide": "Ocultar", "Hide activity records": "Ocultar registros de atividade", "Hide connection details": "Ocultar detalhes da conexão", + "Hide estimated SpO₂": "Ocultar SpO₂ estimado", "Hide key": "Ocultar chave", "Hide packets": "Ocultar pacotes", "Hide readings": "Ocultar leituras", @@ -822,6 +839,8 @@ "Higher risk": "Risco maior", "Hiking": "Trilha", "Hormones": "Hormônios", + "Hourly readings are estimated from heart rate — this ring's hourly SpO₂ isn't a separate measurement. Spot readings you take are measured.": "As leituras horárias são estimadas a partir da frequência cardíaca — o SpO₂ horário deste anel não é uma medição separada. As leituras pontuais que você faz são medidas.", + "Hourly readings are estimated from heart rate — this ring's hourly SpO₂ isn't a separate measurement. Spot readings you take are measured. On this ring the same heart rate always comes with the same hourly SpO₂, so a night-time dip here follows a low sleeping heart rate rather than measuring oxygen.": "As leituras horárias são estimadas a partir da frequência cardíaca — o SpO₂ horário deste anel não é uma medição separada. As leituras pontuais que você faz são medidas. Neste anel, a mesma frequência cardíaca sempre vem com o mesmo SpO₂ horário, então uma queda durante a noite aqui acompanha uma frequência cardíaca baixa durante o sono, e não uma medição de oxigênio.", "How am I doing on my goal? What should I focus on this week?": "Como estou indo na minha meta? No que devo focar esta semana?", "How am I doing today?": "Como estou hoje?", "How can I sleep better?": "Como posso dormir melhor?", @@ -872,6 +891,7 @@ "In sync": "Em sincronia", "In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.", "Inactivity": "Inatividade", + "Includes {0} added by you, not staged or scored": "Inclui {0} adicionados por você, sem fase nem pontuação", "Increase duration by 5 minutes": "Aumentar a duração em 5 minutos", "Increase {0}": "Aumentar {0}", "Increasing risk": "Risco crescente", @@ -886,6 +906,7 @@ "Its markers and its PDF are removed from this phone.": "Os marcadores e o PDF dele são removidos deste celular.", "Journal": "Diário", "Keep": "Manter", + "Keep at least a minute of what the ring recorded ({0} – {1}).": "Mantenha pelo menos um minuto do que o anel registrou ({0} – {1}).", "Keep editing": "Continuar editando", "Keep going": "Continue", "Keep it always on?": "Deixar sempre ligado?", @@ -1032,6 +1053,7 @@ "Meal photo": "Foto da refeição", "Meal reminder": "Lembrete de refeição", "Measure": "Medir", + "Measure SpO₂ from the app": "Medir SpO₂ pelo app", "Measured by your ring": "Medido pelo seu anel", "Measurement": "Medição", "Measurement Frequency": "Frequência de medição", @@ -1129,6 +1151,7 @@ "No body measurements found in Health Connect yet.": "Nenhuma medida corporal encontrada no Health Connect ainda.", "No calibration set": "Nenhuma calibração definida", "No clear difference": "Sem diferença clara", + "No conversations yet. Ask the coach something and it will show up here.": "Nenhuma conversa ainda. Pergunte algo ao coach e ela aparecerá aqui.", "No data": "Sem dados", "No data yet today": "Ainda sem dados hoje", "No daytime stress readings today yet.": "Ainda não há leituras de estresse diurno hoje.", @@ -1290,6 +1313,7 @@ "Paired {0} · last used {1}": "Pareada em {0} · último uso em {1}", "Paired {0} · not used yet": "Pareada em {0} · ainda não usada", "Past checks": "Verificações anteriores", + "Past conversations": "Conversas anteriores", "Patinho moído": "Patinho moído", "Pause": "Pausar", "Paused by the accuracy check": "Pausado pela verificação de precisão", @@ -1387,6 +1411,7 @@ "Recommended": "Recomendado", "Recompute": "Recalcular", "Reconnect last ring": "Reconectar último anel", + "Reconnecting…": "Reconectando…", "Record activity": "Registrar atividade", "Recorded by {0}": "Registrado por {0}", "Recording a workout needs the Physical activity permission. You can allow it in Android Settings › Apps › PulseLoop › Permissions.": "Gravar um treino precisa da permissão de Atividade física. Você pode permitir em Configurações do Android › Apps › PulseLoop › Permissões.", @@ -1482,7 +1507,7 @@ "SPLITS": "PARCIAIS", "SYS": "SIS", "Salada verde com tomate": "Salada verde com tomate", - "Same as heart rate": "Igual à frequência cardíaca", + "Same as heart rate, at most every 60 min": "Igual à frequência cardíaca, no máximo a cada 60 min", "Save": "Salvar", "Save Key": "Salvar chave", "Save calibration": "Salvar calibração", @@ -1646,6 +1671,7 @@ "Started": "Iniciado", "Started or ended today": "Começou ou terminou hoje", "Started or ended today, or a past one": "Começou ou terminou hoje, ou uma anterior", + "Starting before {0} would move it into another night.": "Começar antes das {0} o levaria para outra noite.", "Starting the download…": "Iniciando o download…", "Starting…": "Iniciando…", "Starts": "Início", @@ -1684,6 +1710,7 @@ "Supplement": "Suplemento", "Support": "Suporte", "Support in Brazil": "Suporte no Brasil", + "Swipe a conversation to delete it.": "Deslize uma conversa para excluí-la.", "Swipe to find your model, then tap to connect.\nYou can also explore first and pair later.": "Deslize para encontrar seu modelo e toque para conectar.\nVocê também pode explorar primeiro e parear depois.", "Symptom Radar": "Radar de sintomas", "Symptom Radar: {0}": "Radar de Sintomas: {0}", @@ -1748,6 +1775,8 @@ "The download isn't signed like this app, so it wasn't installed.": "O download não tem a assinatura deste app, então não foi instalado.", "The import failed. Try again in a moment.": "A importação falhou. Tente novamente em instantes.", "The model isn't available to download right now. Try again later.": "O modelo não está disponível para download agora. Tente mais tarde.", + "The next record starts at {0}.": "O próximo registro começa às {0}.", + "The previous record ends at {0}.": "O registro anterior termina às {0}.", "The report covers the days so far. You'll then choose what happens to the paused Health Connect export.": "O relatório abrange os dias até agora. Depois você escolherá o que acontece com a exportação pausada para o Health Connect.", "The report printed no range for this marker.": "O laudo não trouxe faixa de referência para este marcador.", "The ring disconnected during measurement.": "O anel se desconectou durante a medição.", @@ -1774,9 +1803,9 @@ "This is information, not contraception advice. Talk to your clinician about the method that suits you.": "Isto é informação, não orientação contraceptiva. Converse com seu profissional de saúde sobre o método mais adequado para você.", "This permanently deletes everything currently in the app and replaces it with the contents of this file. This can't be undone.": "Isso exclui permanentemente tudo o que está no app e substitui pelo conteúdo deste arquivo. Não é possível desfazer.", "This permanently erases all your data — metrics, sleep, activity, coach history, settings, and saved API keys — and can't be undone.": "Isso apaga permanentemente todos os seus dados — métricas, sono, atividade, histórico do coach, configurações e chaves de API salvas — e não pode ser desfeito.", - "This record runs {0} – {1}. You can only shorten it.": "Este registro vai de {0} a {1}. Você só pode encurtá-lo.", "This removes the session and its recorded route. This can't be undone.": "Isso remove a sessão e o trajeto gravado. Não dá para desfazer.", "This report's PDF isn't on this phone.": "O PDF deste laudo não está neste celular.", + "This ring's all-day SpO₂ is estimated from heart rate. When on, PulseLoop starts a real spot measurement on the schedule below, between the ring's own readings, about a minute each, which uses more battery. Android may delay or skip runs while the phone is asleep.": "O SpO₂ contínuo deste anel é estimado a partir da frequência cardíaca. Quando ativado, o PulseLoop inicia uma medição pontual real no intervalo abaixo, entre as leituras do próprio anel, cerca de um minuto cada, o que gasta mais bateria. O Android pode atrasar ou pular medições enquanto o celular está em repouso.", "This score suggests depression is likely. Please talk to your doctor, nurse or midwife this week.": "Esta pontuação sugere que a depressão é provável. Por favor, converse com seu médico, enfermeira ou obstetriz ainda esta semana.", "This score suggests possible depression. Talk to your doctor, nurse or midwife soon.": "Esta pontuação sugere possível depressão. Converse em breve com seu médico, enfermeira ou obstetriz.", "This unbinds the ring and removes it from the app. Your synced data is kept, but you'll need to pair the ring again to keep syncing.": "Isso desvincula o anel e o remove do app. Seus dados sincronizados são mantidos, mas você precisará parear o anel novamente para continuar sincronizando.", @@ -1804,6 +1833,7 @@ "Tired — consider lighter activity and good sleep.": "Cansado — prefira atividades mais leves e uma boa noite de sono.", "To log when Bedtime or Do Not Disturb turns on and off while PulseLoop is in the background, Android requires Notification access. PulseLoop only listens for Mode changes and does not read your notifications.\n\nIf the switch is greyed out, open PulseLoop's App info, tap ⋮ → Allow restricted settings, then come back here.": "Para registrar quando o modo Hora de dormir ou Não perturbe liga e desliga com o PulseLoop em segundo plano, o Android exige acesso às notificações. O PulseLoop só escuta as mudanças de modo e não lê suas notificações.\n\nSe a chave estiver cinza, abra as Informações do app do PulseLoop, toque em ⋮ → Permitir configurações restritas e volte aqui.", "Today": "Hoje", + "Today {0}": "Hoje {0}", "Today's steps against your step goal. It fills up as the day goes on.": "Os passos de hoje em relação à sua meta. A barra enche ao longo do dia.", "Today: {0}": "Hoje: {0}", "Tonight: {0} drink{1}": "Hoje à noite: {0} bebida{1}", @@ -1824,6 +1854,7 @@ "Trends": "Tendências", "Trends & lab reports": "Tendências e exames", "Trigger real-time ring readings": "Acionar leituras do anel em tempo real", + "Trim this record, or extend it over time the ring missed. Added time counts as asleep but has no stage, so it stays out of the stage breakdown and score.": "Recorte este registro ou estenda-o sobre o tempo que o anel não registrou. O tempo adicionado conta como sono, mas não tem fase, então fica fora da divisão por fases e da pontuação.", "Trouble breathing, chest pain or a racing heart": "Falta de ar, dor no peito ou coração acelerado", "Try again": "Tentar novamente", "Turn off": "Desativar", @@ -1853,6 +1884,7 @@ "Unpair ring?": "Desparear anel?", "Unpair your ring? The ring will forget this phone; your data stays.": "Desparear seu anel? O anel vai esquecer este celular; seus dados permanecem.", "Until {0}": "Até {0}", + "Untitled conversation": "Conversa sem título", "Unusual last night: ": "Incomum na última noite: ", "Unusual signals alert": "Alerta de sinais incomuns", "Unusual-signal alerts, your weekly report and wind-down reminders": "Alertas de sinais incomuns, seu relatório semanal e lembretes para relaxar", @@ -1976,6 +2008,7 @@ "Yearly Sleep": "Sono anual", "Yes, a nap": "Sim, um cochilo", "Yesterday": "Ontem", + "Yesterday {0}": "Ontem {0}", "Yesterday's steps compared with your usual. Both a very inactive day and an unusually heavy one lower this.": "Os passos de ontem comparados com o seu habitual. Tanto um dia muito parado quanto um dia excepcionalmente puxado reduzem este valor.", "Yoga": "Ioga", "You are now a developer!": "Agora você é um desenvolvedor!", @@ -2096,6 +2129,7 @@ "nothing logged yet": "nada registrado ainda", "of {0}": "de {0}", "of {0} this week": "de {0} esta semana", + "open now": "aberta agora", "reports · {0} markers tracked": "laudos · {0} marcadores acompanhados", "resting HR {0}{1}": "HR em repouso {0}{1}", "resting heart rate {0} bpm {1}": "frequência cardíaca em repouso {0} bpm {1}", @@ -2160,6 +2194,7 @@ "{0} markers": "{0} marcadores", "{0} markers found": "{0} marcadores encontrados", "{0} markers outside the lab's range in your latest report. Talk them over with your doctor.": "{0} marcadores fora da faixa do laboratório no seu último laudo. Converse sobre eles com seu médico.", + "{0} messages": "{0} mensagens", "{0} min": "{0} min", "{0} min a night less than your usual over the last 7 nights.": "{0} min por noite a menos que o seu habitual nas últimas 7 noites.", "{0} min a night more than your usual over the last 7 nights.": "{0} min por noite a mais que o seu habitual nas últimas 7 noites.", @@ -2227,6 +2262,7 @@ "{0}m ago": "há {0}m", "{0}{1} {2} in 90 days": "{0}{1} {2} em 90 dias", "±{0}m · {1} pts": "±{0}m · {1} pts", + "“{0}” and its replies will be deleted. This can't be undone.": "“{0}” e as respostas serão excluídas. Não é possível desfazer.", "−%.1f °C from your usual": "−%.1f °C em relação ao seu habitual", "≈ {0} kcal · {1} g protein · leaves {2} kcal": "≈ {0} kcal · {1} g de proteína · sobram {2} kcal" } diff --git a/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt b/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt index a37a6482..e38b2466 100644 --- a/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt +++ b/app/src/main/java/com/pulseloop/settings/ScheduledSpo2Prefs.kt @@ -38,10 +38,11 @@ class ScheduledSpo2Prefs internal constructor(private val prefs: android.content /** * Whether to hide estimated hourly SpO₂ (computed by the ring from heart rate) and only - * display real spot measurements. Defaults to true. + * display real spot measurements. Defaults to false: estimated readings are shown, labelled + * "Estimated" (AGENTS.md "A derived metric must say it is derived"). Upstream defaulted to true. */ var hideEstimated: Boolean - get() = prefs.getBoolean(KEY_HIDE_ESTIMATED, true) + get() = prefs.getBoolean(KEY_HIDE_ESTIMATED, false) set(value) { prefs.edit().putBoolean(KEY_HIDE_ESTIMATED, value).apply() } companion object { diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt index 68a55e24..ffe194e1 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1863,16 +1863,20 @@ fun MeasurementSettingsScreen(coordinator: RingSyncCoordinator?, onBack: () -> U valueRange = 60f..180f, steps = 1, ) - VitalToggle(tr("Hide estimated SpO₂"), cfgHideEstimatedSpo2) { - cfgHideEstimatedSpo2 = it - cfgSavedMsg = null - } - Text( - tr("Display only real spot measurements on charts and vitals cards, hiding the hourly estimates."), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) } + // Shown on every supported ring, on or off: estimated readings are + // shown labelled by default (AGENTS.md "A derived metric must say it is + // derived"); hiding them is the user's choice (divergence from upstream, + // which defaulted to hidden and only offered this with app SpO₂ on). + VitalToggle(tr("Hide estimated SpO₂"), cfgHideEstimatedSpo2) { + cfgHideEstimatedSpo2 = it + cfgSavedMsg = null + } + Text( + tr("Display only real spot measurements on charts and vitals cards, hiding the hourly estimates."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) } } if (supportsStressSetting) { diff --git a/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt b/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt index 46301ed2..bb4d8c57 100644 --- a/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt +++ b/app/src/test/java/com/pulseloop/settings/ScheduledSpo2PrefsTest.kt @@ -44,14 +44,14 @@ class ScheduledSpo2PrefsTest { } @Test - fun `hideEstimated defaults to true and round trips`() { + fun `hideEstimated defaults to false and round trips`() { val fakePrefs = FakeSharedPreferences() val prefs = ScheduledSpo2Prefs(fakePrefs) - assertTrue(prefs.hideEstimated) - prefs.hideEstimated = false assertFalse(prefs.hideEstimated) prefs.hideEstimated = true assertTrue(prefs.hideEstimated) + prefs.hideEstimated = false + assertFalse(prefs.hideEstimated) } @Test diff --git a/audits/2026-11-10-v2.16.0-upstream-ports.md b/audits/2026-11-10-v2.16.0-upstream-ports.md new file mode 100644 index 00000000..7d7d4332 --- /dev/null +++ b/audits/2026-11-10-v2.16.0-upstream-ports.md @@ -0,0 +1,79 @@ +# Audit: six upstream ports (v2.16.0) + +Date: 2026-11-10 · Ports of foureight84/PulseLoopAndroid #125, #127, #129, #130, #133 and #134 +(with `3f39c09`) · Auditor: Claude, by reading the code. There is no device in this session, so +there are no screenshots. Each port was rebuilt in this fork's design, not merged as-is. + +## Scope (every changed surface) + +1. **Ring status (#125).** A new "Reconnecting…" label in the header pill and on the device hero + card. While reconnecting, the Wearable settings screen shows a Disconnect button (Outlined + PulseButton). +2. **Coach (#127).** A one-line hint under Web Search for Gemini. +3. **Estimated SpO₂ (#129).** + - Vitals card: an ESTIMATED chip and a 12sp `warning` footnote, matching the derived-stress + treatment. + - Today tile: a one-line "Estimated from heart rate". + - Vital detail: a disclaimer card and an "Estimated" chip on each estimated row. +4. **Scheduled SpO₂ (#134).** + - Measurement settings: the heart-rate slider goes to 120 min on YCBT; "Measure SpO₂ from the + app" with its explanation and 1–3 h slider. + - "Hide estimated SpO₂" now shows on every supported ring and is **off by default**. This is a + divergence from upstream, which hid estimates by default; our rule is that a derived metric + is shown and labelled. + - The Health Connect respiratory-rate row is disabled on YCBT, with its reason shown. + - Charts join readings 2–3 h apart. +5. **Sleep (#130).** + - The edit dialog now trims or extends, and names the limit a pick ran into. + - Added minutes appear as a hatched "Added by you" band in `textMuted`, with a legend row, a + line on the Records card, and a mention in the spoken summary. + - The Records card also shows on single-record nights. +6. **Coach history (#133).** + - A History button in the coach header, a 48dp target between Usage and New chat. + - A new sheet: rows with Chevron, swipe to delete plus an accessibility Delete action, "Delete + all", and two confirm dialogs. + +## ux-user-flows (§13) + +| # | Question | Result | +|---|---|---| +| 1 | Jobs | Reconnect a dropped ring; ask the coach without paid search; know which SpO₂ is real; measure SpO₂ for real; add sleep the ring missed; get back to an old conversation. Pass | +| 2 | Entries | No new doors except the coach History button, which sits where coach actions already live. Pass | +| 3 | Happy paths | One tap or one switch each. Common taps did not rise. Pass | +| 4–6 | Branches, states, errors | Reconnecting/Disconnect; grounding refused, then answered without search; estimated vs measured; extend limits named; empty history; delete confirm. Pass | +| 7 | Control | Every destructive step asks first: delete one conversation, delete all. An extension can be undone by editing again. Pass | +| 9 | Memory | Scheduled SpO₂ settings ride in the backup (`ArchivedSettings`); conversations and sleep edits are in Room, which the backup already carries. Pass | +| 13 | Accessibility | Swipe delete has an accessibility action; the hatched band is spoken; targets are 48dp. Pass | +| 14 | Ethics | Estimated SpO₂ is shown and labelled, never hidden by default; added sleep is never staged or scored; scheduled SpO₂ states its battery cost. Pass | +| 15 | Evidence | Upstream's tests carried over (12 files) and pass in CI | + +## impeccable + +Accessibility 4 · Performance 4 · Theming 4 · Platform 4 · Adaptivity 4. **20/20.** + +Findings: +- **P3, carried.** Home-screen widgets still show estimated SpO₂ when the user hides it, because + the widget publisher doesn't read that preference. Same as upstream. +- **P3, carried.** The Health Connect "{0} of {1} on" count still includes the respiratory-rate + switch on YCBT, where it is forced off. + +## graphic-design-fundamentals (§13) + +| Item | Result | +|---|---| +| Colour | Pass: no mint on anything you can't tap; the estimated footnotes use `warning`, the added-sleep band `textMuted`, the open conversation a muted border | +| Typography and spacing | Pass: 12sp floor (upstream used 10–11sp); 8dp radius | +| Consistency | Pass: chips, disclaimer card and sheet reuse existing patterns | +| Production | Pass: every `tr()` key has a pt-BR entry; icons imported; no off-scale `fontSize`; no direct Material button (all script-checked) | + +## less-is-more + +- The four-line Bedtime/estimate explanations stay. Each answers "is this number real?", which is + question 1 (consent and honesty). +- Upstream's separate "Fallback schedule" style labels are not added. +- The history sheet has one text button ("Delete all") and no header actions. + +## Verdict + +Merge. There are no P0–P2 findings; the two P3s above are carried. Hardware checks still owed: +CRP reconnect timing (ring owner zaggash) and scheduled SpO₂ on a YCBT ring. diff --git a/docs/ios-sync.md b/docs/ios-sync.md index 4347e051..b8d9d3ec 100644 --- a/docs/ios-sync.md +++ b/docs/ios-sync.md @@ -29,13 +29,30 @@ the work list, and assembling one from all three is how items get missed. |---|---| | **Canonical iOS repo** | `github.com/saksham2001/PulseLoopiOS` (always `main`) | | **Fork baseline (iOS)** | `600c7a8` — Merge PR #6, 2026-06-20 | -| **Last triaged iOS commit** | `8833ee0` — Merge PR #140 (coach model catalog, Oct 2026) | -| **Last triage date** | 2026-10-14 — see [2026-10-14 triage](#2026-10-14-triage-since-124877f--8833ee0-1-first-parent) | +| **Last triaged iOS commit** | `8d8d8b6` — Merge PR #122 (HealthKit export completion, 2026-10-29) | +| **Last triage date** | 2026-11-10 — see [2026-11-10 triage](#2026-11-10-triage-since-8833ee0--8d8d8b6-2-first-parent) | | **Last port date** | 2026-10-14 — PR #140 coach model catalog + per-model reasoning levels, plus live per-provider model lists (`52c25e9`). 2026-08-23 — PR #96 nutrition **complete**: barcode scanner + AI meal analysis (`e80c76c`) on top of the OFF client (`a13238d`) and five coach tools (`05d8833`); plus the self-hosted-provider schema fix they exposed (`d3d1371`). 2026-08-22 — #130 RWfit JieLi history (`c9be848`), Workout pause intervals (`71f251e`), PR #94 `CoachNotificationDataTrigger` (`9d43227`), PR #93 hardening (`c95b6e8`) | | **Range covered** | **2026-10-14:** 1 first-parent item since `124877f`: PR #140 → ported. **2026-10-07:** 5 first-parent items since `439ca81`: PRs #133, #138, #101 + 2 direct commits (`89024c8` version, `21ff323` docs) → 3 PRs leave Android work, none ported yet (see the Outstanding list). **Previously:** 12 first-parent items since `0d1b965` (2026-07-18): PRs #73, #94–#100, #130, #131, #93 + 1 direct commit (`160c775`) → **all 12 ported** (#130 was backed out as fabricated, then rebuilt from the vendor decompile — see its row below). Verified against a live `git fetch` on 2026-08-23: `origin/main` is `439ca81` and local `main` is 0 commits behind, so upstream is fully triaged and ported | --- +## 2026-11-10 triage (since `8833ee0` → `8d8d8b6`, 2 first-parent) + +| iOS PR | Merge | What | Verdict | Android | +|---|---|---|---|---| +| #139 | `dfd5751` | Colmi Ring 2 Pro: on-demand HRV, stress, temperature | **ALREADY-HAVE** | It is the iOS port of Android #100; `WearableModel.COLMI_RING_2_PRO` is on `main` | +| #122 | `8d8d8b6` | Apple Health export of respiratory rate, VO₂max, glucose, blood pressure (BP as a correlation) | **ALREADY-HAVE** | `VitalsExporter` writes all four to Health Connect; HC's `BloodPressureRecord` holds both halves in one record, so the pairing problem doesn't exist here | + +**Original Android repo (foureight84/PulseLoopAndroid), same day.** This fork split from it at +`fc69ac9` (2026-10-14). Its 8 later merges were ported by hand onto this fork's redesigned UI: +#128 Bedtime without the schedule (v2.15.1), and #125 CRP reconnect after teardown, #127 Gemini +grounding 429 retry, #129 estimated hourly SpO₂ label, #130 extend a sleep record, #133 coach +past conversations, #134 + `3f39c09` scheduled SpO₂ (v2.16.0). One deliberate divergence: hidden +estimated SpO₂ defaults to **off** here (shown, labelled), and the switch shows on every supported +ring. Next upstream-Android triage starts after `3f39c09`. + +--- + ## Outstanding — the single list Everything upstream that is **not yet on Android `main`**, in one place. This replaces reading the