diff --git a/AGENTS.md b/AGENTS.md index fd1fcd22..2daacfdd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -985,7 +985,8 @@ things to preserve: - **The hypnogram draws the counted gaps** (`hypnogramBlocks`), display-only. Never feed those blocks to `awakeMinutes`, which counts the gaps itself. - **An hour-plus gap inside the wearer's Bedtime window stays one night** (`SleepGapBridge`). Off - unless quiet hours are on; Bedtime windows decide when the night has any, else the clock window. + unless the schedule or Bedtime tracking is on — the two are independent since #126; Bedtime + windows decide when the night has any, else the clock window if the schedule is on. 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. diff --git a/app/src/main/assets/i18n/pt-BR.json b/app/src/main/assets/i18n/pt-BR.json index 84780b1f..e074c70d 100644 --- a/app/src/main/assets/i18n/pt-BR.json +++ b/app/src/main/assets/i18n/pt-BR.json @@ -90,6 +90,7 @@ "A screening questionnaire, not a diagnosis.": "Um questionário de rastreamento, não um diagnóstico.", "A solid active day so far.": "Um dia ativo e consistente até agora.", "A steady week. Keep it up.": "Uma semana estável. Continue assim.", + "A still wrist reads as sleep, so an evening on the sofa can run the night high. Trimmed minutes are never imported — changing these later won't bring them back.": "Um pulso parado parece sono, então uma noite no sofá pode inflar a noite. Minutos cortados nunca são importados — mudar isso depois não os traz de volta.", "A typical daytime stress score.": "Um nível de estresse diurno típico.", "A typical resting heart rate for adults.": "Uma frequência cardíaca em repouso típica para adultos.", "A typical skin-temperature range from the ring.": "Uma faixa típica de temperatura da pele medida pelo anel.", @@ -231,7 +232,6 @@ "Authorize in your browser — you'll return to PulseLoop automatically.": "Autorize no navegador — você voltará ao PulseLoop automaticamente.", "Auto Upload": "Envio automático", "Automatic backups": "Backups automáticos", - "Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode.": "Alinhar automaticamente o horário de silêncio com o modo Hora de dormir ou Não perturbe do Android.", "Average": "Média", "Average difference {0}; 95 % of differences between {1} and {2}": "Diferença média {0}; 95 % das diferenças entre {1} e {2}", "Averaging {0} against a need of {1}": "Média de {0} contra uma necessidade de {1}", @@ -492,6 +492,7 @@ "Daily goals": "Metas diárias", "Daily guidance": "Orientação diária", "Daily or almost daily": "Diariamente ou quase", + "Daily schedule for nights without Bedtime/DND.": "Horário diário para noites sem Hora de dormir/Não perturbe.", "Daily targets": "Metas diárias", "Dance": "Dança", "Data & privacy": "Dados e privacidade", @@ -687,7 +688,6 @@ "Factory reset ring": "Restaurar anel de fábrica", "Factory reset ring?": "Restaurar anel de fábrica?", "Fair": "Razoável", - "Fallback schedule (used when no Bedtime/DND mode was active):": "Horário alternativo (usado quando nenhum modo Hora de dormir/Não perturbe estava ativo):", "Fastest and cheapest": "O mais rápido e barato", "Fasting 100–125 is above the typical range.": "Em jejum, 100–125 está acima da faixa típica.", "Fasting normal is up to 99 mg/dL.": "Em jejum, o normal é até 99 mg/dL.", @@ -890,6 +890,8 @@ "Keep going": "Continue", "Keep it always on?": "Deixar sempre ligado?", "Keep it on": "Deixar ligado", + "Keep only sleep inside Android's Bedtime or Do Not Disturb.": "Manter só o sono dentro do modo Hora de dormir ou Não perturbe do Android.", + "Keep only sleep inside a daily schedule. Naps outside it are skipped.": "Manter só o sono dentro de um horário diário. Cochilos fora dele são ignorados.", "Keep recording": "Continuar gravando", "Keep still — measuring blood oxygen…": "Fique parado — medindo o oxigênio no sangue…", "Keep still — measuring blood pressure, SpO₂, stress, fatigue & blood sugar…": "Fique parado — medindo pressão arterial, SpO₂, estresse, fadiga e glicose…", @@ -1109,6 +1111,8 @@ "Nightly sleep: latest {0}, range {1}–{2}, {3} of {4} nights tracked": "Sono por noite: última {0}, faixa {1}–{2}, {3} de {4} noites registradas", "Nightly sleep: no nights tracked in this range": "Sono por noite: nenhuma noite registrada neste período", "Nights in your baseline": "Noites na sua linha de base", + "Nights without it are kept whole.": "Noites sem ele ficam inteiras.", + "Nights without it use the schedule.": "Noites sem ele usam o horário.", "No HR samples yet — sync your ring to start your trend.": "Ainda não há amostras de HR — sincronize seu anel para começar sua tendência.", "No HRV data yet — HRV builds up over a few hours of wear.": "Ainda não há dados de HRV — a HRV se forma após algumas horas de uso.", "No Health Connect permissions granted — nothing to export.": "Nenhuma permissão do Health Connect concedida — nada para exportar.", @@ -1357,7 +1361,6 @@ "Pão francês com queijo minas": "Pão francês com queijo minas", "Quick Access": "Acesso rápido", "Quiet from": "Silêncio a partir de", - "Quiet hours schedule:": "Horário de silêncio:", "Quiet until": "Silêncio até", "READINGS": "LEITURAS", "RECORDS": "RECORDES", @@ -1589,6 +1592,7 @@ "Sleep stages: {0}": "Estágios do sono: {0}", "Sleep synced": "Sono sincronizado", "Sleep tracking": "Monitoramento do sono", + "Sleep trimming": "Corte do sono", "Sleep {0} a night": "Dormir {0} por noite", "Sleep, steps, heart and more, from a week to a year": "Sono, passos, coração e mais, de uma semana a um ano", "Sleeping less this week": "Dormindo menos nesta semana", @@ -1940,7 +1944,6 @@ "When": "Quando", "When did it end?": "Quando terminou?", "When did it start?": "Quando começou?", - "When on, sleep the ring records outside the window is trimmed off on import — a still wrist reads as sleep, so an evening on the sofa can log a phantom session and run the night high. Set the start to when you actually go to bed. Naps outside the window are skipped too. Already-imported nights are never touched, and what the gate skips while it is narrower stays skipped.": "Quando ativado, o sono que o anel registra fora da janela é cortado na importação — um pulso parado parece sono, então uma noite no sofá pode registrar uma sessão fantasma e inflar a noite. Defina o início para quando você realmente vai para a cama. Cochilos fora da janela também são ignorados. Noites já importadas nunca são alteradas, e o que o filtro ignora enquanto está mais estreito continua ignorado.", "When the ring is at 30% or less a couple of hours before your usual bedtime.": "Quando o anel estiver com 30% ou menos algumas horas antes do seu horário habitual de dormir.", "When the ring says… what {0} says (minutes)": "Quando o anel diz… o que {0} diz (minutos)", "When two or more of last night's signals are outside your usual range.": "Quando dois ou mais sinais da última noite estiverem fora da sua faixa habitual.", diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 8fd3574b..0e6f5c4f 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -26,6 +26,9 @@ class PulseLoopApplication : Application() { override fun onCreate() { super.onCreate() CrashLogger.install(this) + // Before any sync can read them: Bedtime tracking no longer needs the schedule (issue #126), + // so a Bedtime flag left on under a switched-off schedule is cleared rather than reread. + com.pulseloop.settings.QuietHoursPrefs.migrateIndependentBedtime(this) com.pulseloop.service.DrinkPrefs.init(this) com.pulseloop.service.Postpartum.init(this) com.pulseloop.service.LabPrefs.init(this) diff --git a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt index 7ad3e3d4..5232a85e 100644 --- a/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt +++ b/app/src/main/java/com/pulseloop/service/EventPersistenceSubscriber.kt @@ -606,13 +606,12 @@ class EventPersistenceSubscriber( // judged by its start, because the ring often runs the sofa hour and the real night as one // record. Already-imported nights are untouched (this never deletes), and the gate is read // per record so a settings change takes effect on the next packet, not the next launch. - val quiet = QuietHoursPrefs(context) - if (quiet.enabled) { - val kept = quiet.keptMinutesForRecord(effectiveTs, effectiveStages.size, context) - ?: return - effectiveTs = effectiveTs + kept.first * 60_000L - effectiveStages = effectiveStages.subList(kept.first, kept.last + 1) - } + // The schedule and Bedtime tracking are independent (issue #126); with neither on this + // keeps the whole record. + val kept = QuietHoursPrefs(context).keptMinutesForRecord(effectiveTs, effectiveStages.size, context) + ?: return + effectiveTs = effectiveTs + kept.first * 60_000L + effectiveStages = effectiveStages.subList(kept.first, kept.last + 1) // Sleep record deletion gate: drop if the user deleted this entire record (issue #78, #82) val dayStart = com.pulseloop.util.TimeUtil.wakingDayLocal(effectiveTs) diff --git a/app/src/main/java/com/pulseloop/service/SleepGapBridge.kt b/app/src/main/java/com/pulseloop/service/SleepGapBridge.kt index f8fa5905..ceea26f9 100644 --- a/app/src/main/java/com/pulseloop/service/SleepGapBridge.kt +++ b/app/src/main/java/com/pulseloop/service/SleepGapBridge.kt @@ -3,10 +3,7 @@ package com.pulseloop.service import android.content.Context import com.pulseloop.data.entity.SleepStageBlockEntity import com.pulseloop.settings.QuietHoursPrefs -import com.pulseloop.settings.ZenModeListener -import com.pulseloop.settings.ZenModeTracker import com.pulseloop.settings.ZenWindow -import com.pulseloop.util.TimeUtil import java.time.ZoneId /** @@ -38,52 +35,43 @@ fun interface SleepGapBridge { /** The bridge for the user's current quiet-hours settings. Reads them once. */ fun fromSettings(context: Context): SleepGapBridge { val prefs = QuietHoursPrefs(context) - val zenWindows = if (prefs.gateByZenMode && ZenModeListener.isAccessGranted(context)) { - ZenModeTracker.getWindows(context) - } else { - null - } - return forWindows(prefs.enabled, zenWindows, prefs.startMinutes, prefs.endMinutes) + return forWindows( + prefs.enabled, + QuietHoursPrefs.activeBedtimeWindows(prefs, context), + prefs.startMinutes, + prefs.endMinutes, + ) } /** - * The same source order as the import gate ([QuietHoursPrefs.keptMinutesForRecord]): off - * unless quiet hours are on; the recorded Bedtime/DND windows when that gating is on and the - * night has any; otherwise the clock window. A night that has Bedtime windows is judged by - * them alone, so a gap after Bedtime ended is not bridged by a wider clock schedule. + * The same source order as the import gate ([QuietHoursPrefs.resolveKeptMinutes]): the + * recorded Bedtime/DND windows when that tracking is on and the night has any; otherwise + * the clock window if the schedule is on; otherwise nothing is bridged. A night that has + * Bedtime windows is judged by them alone, so a gap after Bedtime ended is not bridged by a + * wider clock schedule. Bedtime tracking bridges with the schedule off (issue #126), as + * the import gate trims with it off. * - * [zenWindows] is null when Bedtime gating is off. + * [zenWindows] is null when Bedtime tracking is off. */ fun forWindows( - enabled: Boolean, + scheduleEnabled: Boolean, zenWindows: List?, startMinutes: Int, endMinutes: Int, zone: ZoneId = ZoneId.systemDefault(), ): SleepGapBridge { - if (!enabled) return NONE + if (!scheduleEnabled && zenWindows == null) return NONE return SleepGapBridge { gapStart, gapEnd -> if (gapEnd <= gapStart) return@SleepGapBridge false - val night = zenWindows?.let { nightWindows(it, gapStart, zone) }.orEmpty() + val night = zenWindows?.let { QuietHoursPrefs.nightWindows(it, gapStart, zone) }.orEmpty() if (night.isNotEmpty()) { - night.any { w -> w.start <= gapStart && gapEnd <= effectiveEnd(w) } + night.any { w -> w.start <= gapStart && gapEnd <= QuietHoursPrefs.effectiveEnd(w) } } else { - clockCovers(gapStart, gapEnd, startMinutes, endMinutes, zone) + scheduleEnabled && clockCovers(gapStart, gapEnd, startMinutes, endMinutes, zone) } } } - /** The windows of the waking day [ts] falls in — the span the import gate reads too. */ - private fun nightWindows(windows: List, ts: Long, zone: ZoneId): List { - val wakingDay = TimeUtil.wakingDayLocal(ts, zone) - val dayStart = wakingDay - 12 * 3_600_000L - val dayEnd = wakingDay + 36 * 3_600_000L - return windows.filter { w -> effectiveEnd(w) > dayStart && w.start < dayEnd } - } - - private fun effectiveEnd(w: ZenWindow): Long = - w.end ?: (w.start + ZenModeTracker.MAX_WINDOW_DURATION_MS) - /** * Every minute of the gap inside the daily clock window. A gap of a day or more never is, and * neither is anything under a window whose start equals its end: for the import gate that diff --git a/app/src/main/java/com/pulseloop/settings/QuietHoursPrefs.kt b/app/src/main/java/com/pulseloop/settings/QuietHoursPrefs.kt index ba1424d2..1e0366f0 100644 --- a/app/src/main/java/com/pulseloop/settings/QuietHoursPrefs.kt +++ b/app/src/main/java/com/pulseloop/settings/QuietHoursPrefs.kt @@ -9,10 +9,9 @@ import java.time.ZoneId * window. A still wrist reads as sleep, so an evening on the sofa lands as a phantom session and * the night runs an hour high; the wearer knows their bedtime, the sensor guesses. * - * Deliberately a time window rather than Android's quiet Modes (the reporter's first choice): - * a Mode gate needs notification-policy access plus a recorded interruption-filter history to - * compare imports against, and the sofa case is mostly caught by a plain window. The Modes - * version stays open as a follow-up — the reporter offered to build it. + * Two sources, each opt-in and independent of the other (issue #126): the daily clock window + * ([enabled]) and the wearer's recorded Android Bedtime / DND windows ([gateByZenMode], issue #83, + * which needs Notification access). [resolveKeptMinutes] is how they combine. * * **Minute-level, not record-level.** A record is trimmed to the minutes that fall inside the * window ([keptMinutes]) rather than accepted or declined by its start minute. The ring often @@ -29,7 +28,10 @@ class QuietHoursPrefs(context: Context) { private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) - /** Off by default: the ring's own behaviour is the right default for everyone else. */ + /** + * The daily clock schedule ("Sleep quiet hours"). Off by default: the ring's own behaviour is + * the right default for everyone else. Independent of [gateByZenMode] since issue #126. + */ var enabled: Boolean get() = prefs.getBoolean(KEY_ENABLED, false) set(value) { prefs.edit().putBoolean(KEY_ENABLED, value).apply() } @@ -44,7 +46,10 @@ class QuietHoursPrefs(context: Context) { get() = prefs.getInt(KEY_END, DEFAULT_END) set(value) { prefs.edit().putInt(KEY_END, value.coerceIn(0, 24 * 60)).apply() } - /** Opt-in: gate quiet hours on Android Bedtime / DND mode (issue #83). */ + /** + * Opt-in: trim to Android Bedtime / DND windows (issue #83). Works on its own since issue #126 + * — before that it was read only while [enabled] was on, and the settings row was hidden with it. + */ var gateByZenMode: Boolean get() = prefs.getBoolean(KEY_GATE_BY_ZEN_MODE, false) set(value) { prefs.edit().putBoolean(KEY_GATE_BY_ZEN_MODE, value).apply() } @@ -62,6 +67,7 @@ class QuietHoursPrefs(context: Context) { private const val KEY_START = "startMinutes" private const val KEY_END = "endMinutes" private const val KEY_GATE_BY_ZEN_MODE = "gate_by_zen_mode" + private const val KEY_INDEPENDENT_BEDTIME_MIGRATED = "independentBedtime.v1" const val DEFAULT_START = 22 * 60 const val DEFAULT_END = 7 * 60 @@ -70,33 +76,109 @@ class QuietHoursPrefs(context: Context) { QuietHoursPrefs(context).gateByZenMode && ZenModeListener.isAccessGranted(context) /** - * Which minutes of a ring record to keep given user preferences. - * If [gateByZenMode] is enabled and Notification access is granted, filters against recorded - * Bedtime/DND quiet windows. If no quiet windows exist for the waking day, falls back - * to the configured clock window. + * The recorded Bedtime/DND windows when that tracking is active, else null — the + * `bedtimeWindows` argument of [resolveKeptMinutes] and [com.pulseloop.service.SleepGapBridge.forWindows]. */ + fun activeBedtimeWindows(prefs: QuietHoursPrefs, context: Context): List? = + if (prefs.gateByZenMode && ZenModeListener.isAccessGranted(context)) { + ZenModeTracker.getWindows(context) + } else { + null + } + + /** + * One-time upgrade step for issue #126, run from [com.pulseloop.PulseLoopApplication] before + * anything reads these prefs. Bedtime=on with the schedule off was reachable before #126 + * (turn both on, then the schedule off: the Bedtime row hid but kept its value) and meant + * *no trimming at all*. Read under the new rules it would mean "Bedtime only" and start + * trimming on the first sync after the update — and trimmed minutes are never imported. + * So that state is cleared to "neither", which is what it did; the wearer re-enables + * Bedtime tracking if they want it. Every other state already means what it meant. + */ + fun migrateIndependentBedtime(context: Context) { + val prefs = QuietHoursPrefs(context) + val raw = prefs.prefs + if (raw.getBoolean(KEY_INDEPENDENT_BEDTIME_MIGRATED, false)) return + val gate = migratedGateByZenMode(prefs.enabled, prefs.gateByZenMode) + if (gate != prefs.gateByZenMode) { + prefs.gateByZenMode = gate + ZenModeListener.setEnabled(context, false) + } + raw.edit().putBoolean(KEY_INDEPENDENT_BEDTIME_MIGRATED, true).apply() + } + + /** The stored Bedtime flag after the #126 upgrade: kept only while the schedule is on. */ + fun migratedGateByZenMode(scheduleEnabled: Boolean, gateByZenMode: Boolean): Boolean = + gateByZenMode && scheduleEnabled + + /** Which minutes of a ring record to keep under the user's current settings; see [resolveKeptMinutes]. */ fun keptMinutesForRecord( ts: Long, minutes: Int, prefs: QuietHoursPrefs, context: Context, zone: ZoneId = ZoneId.systemDefault(), + ): IntRange? = resolveKeptMinutes( + ts, + minutes, + scheduleEnabled = prefs.enabled, + bedtimeWindows = activeBedtimeWindows(prefs, context), + startMinutes = prefs.startMinutes, + endMinutes = prefs.endMinutes, + zone = zone, + ) + + /** + * Which minutes of a ring record to keep (issue #126: the two sources are independent). + * [bedtimeWindows] is null when Bedtime tracking is off or lacks Notification access. + * + * - **Neither:** the whole record. + * - **Schedule only:** trimmed to the clock window ([keptMinutes]). + * - **Bedtime only:** trimmed to the Bedtime/DND windows it overlaps; a record that overlaps + * none — a night Bedtime was forgotten — is kept whole. Forgetting Bedtime must not cost + * the night: the #126 reporter lost 07:00–08:10 to the clock fallback, permanently. + * "Overlaps", not "the waking day has a window": the filter cannot tell Bedtime from a + * DND meeting the next afternoon (same waking day), and dropping the night over that + * would be unrecoverable. The cost is a separate sofa record before Bedtime is kept; the + * hour gap rule still keeps it apart from the night. + * - **Both:** the Bedtime windows when the night has any and they overlap the record; + * otherwise the clock window (unchanged from #83). + * + * Null drops the record. + */ + fun resolveKeptMinutes( + ts: Long, + minutes: Int, + scheduleEnabled: Boolean, + bedtimeWindows: List?, + startMinutes: Int, + endMinutes: Int, + zone: ZoneId = ZoneId.systemDefault(), ): IntRange? { - if (!prefs.enabled) return 0 until minutes - if (prefs.gateByZenMode && ZenModeListener.isAccessGranted(context)) { - val wakingDay = com.pulseloop.util.TimeUtil.wakingDayLocal(ts) - val dayStart = wakingDay - 12 * 3600_000L - val dayEnd = wakingDay + 36 * 3600_000L - val windows = ZenModeTracker.getWindows(context, since = dayStart) - .filter { w -> (w.end ?: (w.start + ZenModeTracker.MAX_WINDOW_DURATION_MS)) > dayStart && w.start < dayEnd } - if (windows.isNotEmpty()) { - val kept = keptMinutesByWindows(ts, minutes, windows) - if (kept != null) return kept - } + if (minutes <= 0) return null + val night = bedtimeWindows?.let { nightWindows(it, ts, zone) }.orEmpty() + if (night.isNotEmpty()) { + val kept = keptMinutesByWindows(ts, minutes, night) + if (kept != null) return kept } - return keptMinutes(ts, minutes, prefs.startMinutes, prefs.endMinutes, zone) + if (scheduleEnabled) return keptMinutes(ts, minutes, startMinutes, endMinutes, zone) + return 0 until minutes } + /** + * The windows of the waking day [ts] falls in — the span both the import gate and + * [com.pulseloop.service.SleepGapBridge] judge a night by. + */ + fun nightWindows(windows: List, ts: Long, zone: ZoneId = ZoneId.systemDefault()): List { + val wakingDay = com.pulseloop.util.TimeUtil.wakingDayLocal(ts, zone) + val dayStart = wakingDay - 12 * 3_600_000L + val dayEnd = wakingDay + 36 * 3_600_000L + return windows.filter { w -> effectiveEnd(w) > dayStart && w.start < dayEnd } + } + + /** A still-open window counts as running for at most [ZenModeTracker.MAX_WINDOW_DURATION_MS]. */ + fun effectiveEnd(w: ZenWindow): Long = w.end ?: (w.start + ZenModeTracker.MAX_WINDOW_DURATION_MS) + /** * Longest contiguous stretch of minutes falling inside any of [windows]. */ @@ -110,10 +192,7 @@ class QuietHoursPrefs(context: Context) { var runStart = -1 for (i in 0..minutes) { val minuteTs = ts + i * 60_000L - val inside = i < minutes && windows.any { w -> - val effectiveEnd = w.end ?: (w.start + ZenModeTracker.MAX_WINDOW_DURATION_MS) - minuteTs >= w.start && minuteTs < effectiveEnd - } + val inside = i < minutes && windows.any { w -> minuteTs >= w.start && minuteTs < effectiveEnd(w) } if (inside && runStart < 0) runStart = i if (!inside && runStart >= 0) { val run = runStart until i 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..aa753f3b 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsSubScreens.kt @@ -1888,69 +1888,75 @@ private fun QuietHoursCard() { SubScreenCard { Column(Modifier.padding(16.dp)) { + Text(tr("Sleep trimming"), style = PulseType.title) + Text( + tr("A still wrist reads as sleep, so an evening on the sofa can run the night high. " + + "Trimmed minutes are never imported — changing these later won't bring them back."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(Modifier.height(12.dp)) + // Independent of the schedule below (issue #126), so the Notification-access prompt + // has to work from here with the schedule off. + Row( + Modifier.fillMaxWidth() + .switchRow(checked = gateByZenMode, onCheckedChange = { desired -> + if (desired) { + ZenModeListener.setEnabled(context, true) + if (ZenModeListener.isAccessGranted(context)) { + gateByZenMode = true + prefs.gateByZenMode = true + } else { + showPermissionDialog = true + } + } else { + gateByZenMode = false + prefs.gateByZenMode = false + ZenModeListener.setEnabled(context, false) + } + }), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f).padding(end = 8.dp)) { + Text( + tr("Track Bedtime / DND mode"), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + ) + Text( + tr("Keep only sleep inside Android's Bedtime or Do Not Disturb.") + " " + + if (enabled) tr("Nights without it use the schedule.") else tr("Nights without it are kept whole."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Switch(checked = gateByZenMode, onCheckedChange = null) + } + Spacer(Modifier.height(12.dp)) Row( Modifier.fillMaxWidth() .switchRow(checked = enabled, onCheckedChange = { enabled = it; prefs.enabled = it }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { - Text(tr("Sleep quiet hours"), style = PulseType.title, modifier = Modifier.weight(1f)) + Column(Modifier.weight(1f).padding(end = 8.dp)) { + Text( + tr("Sleep quiet hours"), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + ) + Text( + if (gateByZenMode) tr("Daily schedule for nights without Bedtime/DND.") + else tr("Keep only sleep inside a daily schedule. Naps outside it are skipped."), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } Switch(checked = enabled, onCheckedChange = null) } - Text( - tr("When on, sleep the ring records outside the window is trimmed off on import — a " + - "still wrist reads as sleep, so an evening on the sofa can log a phantom session " + - "and run the night high. Set the start to when you actually go to bed. Naps " + - "outside the window are skipped too. Already-imported nights are never touched, " + - "and what the gate skips while it is narrower stays skipped."), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) if (enabled) { - Spacer(Modifier.height(12.dp)) - Row( - Modifier.fillMaxWidth() - .switchRow(checked = gateByZenMode, onCheckedChange = { desired -> - if (desired) { - ZenModeListener.setEnabled(context, true) - if (ZenModeListener.isAccessGranted(context)) { - gateByZenMode = true - prefs.gateByZenMode = true - } else { - showPermissionDialog = true - } - } else { - gateByZenMode = false - prefs.gateByZenMode = false - ZenModeListener.setEnabled(context, false) - } - }), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f).padding(end = 8.dp)) { - Text( - tr("Track Bedtime / DND mode"), - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Medium, - ) - Text( - tr("Automatically align quiet hours with Android's Bedtime or Do Not Disturb mode."), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Switch(checked = gateByZenMode, onCheckedChange = null) - } - Spacer(Modifier.height(8.dp)) - Text( - if (gateByZenMode) tr("Fallback schedule (used when no Bedtime/DND mode was active):") - else tr("Quiet hours schedule:"), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(4.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { PulseButton(PulseButtonStyle.Outlined, onClick = { picking = "start" }, modifier = Modifier.weight(1f)) { Text(trf("From {0}", formatMinutesOfDay(start))) diff --git a/app/src/test/java/com/pulseloop/service/SleepGapsTest.kt b/app/src/test/java/com/pulseloop/service/SleepGapsTest.kt index 25e54a53..09454f42 100644 --- a/app/src/test/java/com/pulseloop/service/SleepGapsTest.kt +++ b/app/src/test/java/com/pulseloop/service/SleepGapsTest.kt @@ -2,6 +2,7 @@ package com.pulseloop.service import com.pulseloop.data.entity.SleepStageBlockEntity import com.pulseloop.ring.SleepStage +import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.settings.ZenWindow import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -147,11 +148,48 @@ class SleepGapsTest { } @Test - fun `nothing is bridged while quiet hours are off`() { - val bridge = SleepGapBridge.forWindows(false, listOf(bedtime), 22 * 60, 7 * 60, utc) + fun `nothing is bridged with neither the schedule nor Bedtime tracking on`() { + val bridge = SleepGapBridge.forWindows(false, null, 22 * 60, 7 * 60, utc) assertFalse(bridge.bridges(gapStart, gapEnd)) } + /** Bedtime tracking works without the schedule (issue #126), for bridging as for importing. */ + @Test + fun `Bedtime only bridges a gap inside the Bedtime window`() { + val bridge = SleepGapBridge.forWindows(false, listOf(bedtime), 22 * 60, 7 * 60, utc) + assertTrue(bridge.bridges(gapStart, gapEnd)) + } + + /** No Bedtime that night and no schedule: the hour rule alone decides, as the import keeps all. */ + @Test + fun `Bedtime only bridges nothing on a night without a Bedtime window`() { + val bridge = SleepGapBridge.forWindows(false, emptyList(), 22 * 60, 7 * 60, utc) + assertFalse(bridge.bridges(gapStart, gapEnd)) // 22–07 would cover it + } + + /** + * The bridge and the import gate pick the same source for each of the four settings (issue + * #126): a gap the bridge keeps inside the night is one the import keeps whole as a record. + */ + @Test + fun `the bridge and the import gate agree on the source for every combination`() { + val gapMinutes = ((gapEnd - gapStart) / 60_000L).toInt() + // A gap inside Bedtime (00:25–08:06) but past a 22:00–06:00 schedule tells the sources apart. + val cases = listOf( + Triple(false, null, false), // neither + Triple(true, null, false), // schedule only: past 06:00 + Triple(false, listOf(bedtime), true), // Bedtime only + Triple(true, listOf(bedtime), true), // both: Bedtime decides + ) + for ((schedule, windows, bridged) in cases) { + val bridge = SleepGapBridge.forWindows(schedule, windows, 22 * 60, 6 * 60, utc) + assertEquals("schedule=$schedule windows=$windows", bridged, bridge.bridges(gapStart, gapEnd)) + val kept = QuietHoursPrefs.resolveKeptMinutes(gapStart, gapMinutes, schedule, windows, 22 * 60, 6 * 60, utc) + val active = schedule || windows != null + assertEquals("schedule=$schedule windows=$windows", bridged, active && kept == 0 until gapMinutes) + } + } + @Test fun `a gap that runs past the end of Bedtime is not bridged`() { val earlyEnd = ZenWindow(start = at(0, 25), end = at(6, 0)) diff --git a/app/src/test/java/com/pulseloop/settings/QuietHoursPrefsTest.kt b/app/src/test/java/com/pulseloop/settings/QuietHoursPrefsTest.kt index 146bcd28..1d0d9a0d 100644 --- a/app/src/test/java/com/pulseloop/settings/QuietHoursPrefsTest.kt +++ b/app/src/test/java/com/pulseloop/settings/QuietHoursPrefsTest.kt @@ -181,4 +181,73 @@ class QuietHoursPrefsTest { val kept = QuietHoursPrefs.keptMinutesByWindows(sleepStart, 60, windows) assertEquals(null, kept) } + + // ── #126: Bedtime tracking and the schedule are independent ───────────── + + /** Oct 10–11 2026 UTC wall clock; the #126 night ran 23:40 → 08:10. */ + private fun oct(day: Int, h: Int, m: Int): Long = + java.time.ZonedDateTime.of(2026, 10, day, h, m, 0, 0, utc).toInstant().toEpochMilli() + + private val nightStart = oct(10, 23, 40) + private val nightMinutes = 510 // → 08:10 + private val bedtime126 = listOf(ZenWindow(start = oct(11, 0, 10), end = oct(11, 7, 30))) + + private fun resolve( + schedule: Boolean, + windows: List?, + ts: Long = nightStart, + minutes: Int = nightMinutes, + ) = QuietHoursPrefs.resolveKeptMinutes(ts, minutes, schedule, windows, 22 * 60, 7 * 60, utc) + + @Test + fun `neither keeps the whole record`() { + assertEquals(0 until nightMinutes, resolve(schedule = false, windows = null)) + } + + @Test + fun `schedule only trims to the clock window as before`() { + assertEquals(0 until 440, resolve(schedule = true, windows = null)) // cut at 07:00 + } + + /** The #126 report: Bedtime forgotten, so the night has no window — keep all of it. */ + @Test + fun `Bedtime only keeps a night without a Bedtime window whole`() { + assertEquals(0 until nightMinutes, resolve(schedule = false, windows = emptyList())) + // Windows from another night don't count for this one. + val lastWeek = listOf(ZenWindow(start = oct(4, 0, 10), end = oct(4, 7, 30))) + assertEquals(0 until nightMinutes, resolve(schedule = false, windows = lastWeek)) + } + + @Test + fun `Bedtime only trims to the Bedtime window when the night has one`() { + assertEquals(30 until 470, resolve(schedule = false, windows = bedtime126)) // 00:10–07:30 + } + + /** A DND meeting the next afternoon shares the waking day; it must not drop the night. */ + @Test + fun `Bedtime only keeps a record that overlaps no window`() { + val meeting = listOf(ZenWindow(start = oct(11, 14, 0), end = oct(11, 14, 30))) + assertEquals(0 until nightMinutes, resolve(schedule = false, windows = meeting)) + } + + @Test + fun `both use the Bedtime window and fall back to the schedule`() { + assertEquals(30 until 470, resolve(schedule = true, windows = bedtime126)) + assertEquals(0 until 440, resolve(schedule = true, windows = emptyList())) + // Unchanged from #83: a record outside every window falls back to the clock window. + val sofa = resolve(schedule = true, windows = bedtime126, ts = oct(10, 21, 0), minutes = 90) + assertEquals(60 until 90, sofa) // 22:00–22:30 + } + + /** + * Bedtime on under a switched-off schedule meant "no trimming" before #126 (the row was hidden + * and the gate never read). The upgrade clears it so it does not start meaning "Bedtime only". + */ + @Test + fun `the upgrade keeps Bedtime only where the schedule was on`() { + assertTrue(QuietHoursPrefs.migratedGateByZenMode(scheduleEnabled = true, gateByZenMode = true)) + assertFalse(QuietHoursPrefs.migratedGateByZenMode(scheduleEnabled = false, gateByZenMode = true)) + assertFalse(QuietHoursPrefs.migratedGateByZenMode(scheduleEnabled = true, gateByZenMode = false)) + assertFalse(QuietHoursPrefs.migratedGateByZenMode(scheduleEnabled = false, gateByZenMode = false)) + } } diff --git a/audits/2026-11-10-v2.15.1-bedtime-independent.md b/audits/2026-11-10-v2.15.1-bedtime-independent.md new file mode 100644 index 00000000..46778409 --- /dev/null +++ b/audits/2026-11-10-v2.15.1-bedtime-independent.md @@ -0,0 +1,50 @@ +# Audit: Bedtime tracking without the sleep schedule (v2.15.1) + +Date: 2026-11-10 · Port of upstream foureight84/PulseLoopAndroid#128 (issue #126) · Auditor: +Claude, by reading the code. There is no device in this session, so there are no screenshots. + +## Scope + +- **Settings › Ring & sync, the sleep trimming card.** + - Before: "Track Bedtime / DND mode" was nested under "Sleep quiet hours" and hidden while the + schedule was off. + - Now: one card, "Sleep trimming", with one warning line and two independent switches, + Bedtime/DND first and the schedule second. The From/Until buttons show only while the schedule + is on. +- **Import:** Bedtime-only trims a record to the Bedtime/DND windows it overlaps. A night with no + Bedtime is kept whole. +- **Migration, one time:** a Bedtime flag left on under a switched-off schedule meant "no trimming", + so it is cleared rather than starting to trim. + +## ux-user-flows (§13) + +| # | Question | Result | +|---|---|---| +| 1 | Job | "Don't count the sofa as sleep, using the Bedtime I already set." Pass | +| 2 | Entries | Unchanged: the Ring & sync screen. Pass | +| 3 | Happy path | One switch (Bedtime), plus the Notification access prompt if needed. Pass | +| 4 | Branches | Neither, Bedtime only, schedule only, both. Each switch's helper line says what happens on nights without Bedtime. Pass | +| 5 | States | Permission granted or missing (the existing dialog), schedule times shown only when the schedule is on. Pass | +| 6 | Errors | Trimmed minutes are permanent, and the card now says so in its first line. Pass | +| 7–15 | Control, memory, exits, conventions, speed, accessibility, ethics, evidence | Pass. Upstream's `QuietHoursPrefsTest` and `SleepGapsTest` are carried over | + +## impeccable + +Accessibility 4 · Performance 4 · Theming 4 · Platform 4 · Adaptivity 4. **20/20.** +No findings: a single title (`PulseType.title`) and `switchRow` rows. + +## graphic-design-fundamentals (§13) + +| Item | Result | +|---|---| +| Hierarchy | Pass: title, the warning, then the two switches in the order they take effect | +| Production | Pass: every `tr()` key has a pt-BR entry; four orphaned keys removed | + +## less-is-more + +- The old five-sentence paragraph became one sentence, the warning that matters. +- The "Fallback schedule…" label is gone: the helper lines already say it. + +## Verdict + +Merge. No findings.