From edeeab6d8549862eeb83bbfdeb02bfa22bcc1a3a Mon Sep 17 00:00:00 2001 From: Khoa Truong Date: Thu, 19 Nov 2026 02:07:47 -0800 Subject: [PATCH 1/3] Sleep: prompt to extend early-ended night records bounded by Bedtime When the ring closes its last sleep record early while Android Bedtime stays active for 15-120 minutes with no steps after a post-Bedtime full sync, surface a confirmable prompt on the Sleep screen ("Were you still asleep?") instead of extending silently. Tapping Extend opens the existing SleepRecordEditDialog pre-filled with the Bedtime end time (snapped to the record's minute grid and clamped to 7 PM / 120m limits); tapping No dismisses the prompt for that ring record (pruned at 45d). --- .../pulseloop/service/SleepTailSuggestion.kt | 180 ++++++++ .../java/com/pulseloop/ui/PulseLoopApp.kt | 12 + .../com/pulseloop/ui/screens/SleepScreen.kt | 150 ++++++- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 66 ++- app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values/strings.xml | 4 + .../service/SleepTailSuggestionTest.kt | 409 ++++++++++++++++++ 7 files changed, 815 insertions(+), 10 deletions(-) create mode 100644 app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt create mode 100644 app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt diff --git a/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt new file mode 100644 index 00000000..5f199459 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt @@ -0,0 +1,180 @@ +package com.pulseloop.service + +import android.content.Context +import com.pulseloop.data.DemoDataPolicy +import com.pulseloop.data.entity.ActivityBucketEntity +import com.pulseloop.data.entity.SleepSessionEntity +import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.settings.QuietHoursPrefs +import com.pulseloop.settings.ZenWindow +import java.time.ZoneId + +/** + * A prompt to extend the ring's last sleep record forward to the end of Android Bedtime (#148). + * + * When a YCBT ring closes its sleep record early while Bedtime stays active and no steps were + * logged before Bedtime ended, the wearer may have fallen back asleep rather than lain awake. + * Because lying still looks identical to an idle ring sensor, this stays a confirmable prompt + * that hands off to `SleepRecordEditDialog` (#106) pre-filled with [suggestedEndAt] rather than + * editing the night silently. + */ +data class SleepTailSuggestion( + val sessionId: String, + val sessionDate: Long, + val run: SleepRecordRun, + val previousRun: SleepRecordRun?, + val ringEndedAt: Long, + val bedtimeEndedAt: Long, + val suggestedEndAt: Long, + val gapMinutes: Int, +) + +/** + * Pure detector for an unrecorded sleep tail bounded by Android Bedtime/DND (issue #148). + * + * All timing, sync, step-bucket, and record-edit limit rules live here so JVM unit tests exercise + * the full decision matrix without Android or Room. + */ +object SleepTailSuggestionDetector { + const val MIN_GAP_MINUTES = 15 + const val MAX_GAP_MINUTES = MAX_OUTWARD_EXTENSION_MINUTES + + /** Activity buckets span 15 minutes from [ActivityBucketEntity.startEpoch]; a bucket starting + * in the final 15 minutes before Bedtime turns off straddles waking up and ending Bedtime. */ + const val STEP_BUCKET_TAIL_MARGIN_MS = 15 * 60_000L + + private const val MINUTE_MS = 60_000L + + fun detect( + daySessions: List, + dayBlocks: Map>, + bedtimeWindows: List?, + stepBuckets: List, + lastFullSyncAt: Long?, + isDismissed: (sessionDate: Long, recordStartAt: Long) -> Boolean, + isEdited: (sessionDate: Long, recordStartAt: Long) -> Boolean, + zone: ZoneId = ZoneId.systemDefault(), + ): SleepTailSuggestion? { + if (bedtimeWindows.isNullOrEmpty() || daySessions.isEmpty()) return null + + val realSessions = daySessions + .filterNot { DemoDataPolicy.isDemo(it.sourceRaw) } + .sortedBy { it.endAt } + if (realSessions.isEmpty()) return null + + // Check from latest session backward (an afternoon nap won't match a morning Bedtime tail, + // while an overlapping later morning session blocks extending an earlier one across it). + for (session in realSessions.asReversed()) { + val runs = sleepRecordRuns(dayBlocks[session.id].orEmpty()) + if (runs.isEmpty()) continue + val lastRun = runs.last() + val previousRun = runs.getOrNull(runs.lastIndex - 1) + + // Do not second-guess a record the user already extended/edited or explicitly dismissed. + if (lastRun.addedMinutes > 0) continue + if (isEdited(session.date, lastRun.recordStartAt)) continue + if (isDismissed(session.date, lastRun.recordStartAt)) continue + + val matchingWindow = QuietHoursPrefs.nightWindows(bedtimeWindows, session.startAt, zone) + .filter { w -> + val end = w.end + end != null && w.start <= lastRun.endAt && end > lastRun.endAt + } + .maxByOrNull { it.end!! } + ?: continue + val windowEnd = matchingWindow.end ?: continue + + // Never extend across another recorded session of the same day. + val overlapsOtherSession = realSessions.any { other -> + other.id != session.id && other.endAt > lastRun.endAt && other.startAt < windowEnd + } + if (overlapsOtherSession) continue + + // Wait for a full sync after Bedtime turned off so morning steps and any second ring + // sleep record have had a chance to import. + if (lastFullSyncAt != null && lastFullSyncAt < windowEnd) continue + + val rawGapMinutes = ((windowEnd - lastRun.endAt) / MINUTE_MS).toInt() + if (rawGapMinutes < MIN_GAP_MINUTES || rawGapMinutes > MAX_GAP_MINUTES) continue + + // Any step bucket wholly inside (lastRun.endAt .. windowEnd] shows real wakefulness. + // Buckets starting before lastRun.endAt belong to the brief get-up when the ring + // stopped; buckets straddling windowEnd capture turning Bedtime off. + val hasStepsInGap = stepBuckets.any { b -> + b.steps > 0 && + b.startEpoch >= lastRun.endAt && + b.startEpoch + STEP_BUCKET_TAIL_MARGIN_MS <= windowEnd + } + if (hasStepsInGap) continue + + val limits = recordEditLimits( + run = lastRun, + previous = previousRun, + next = null, + wakingDay = session.date, + zone = zone, + ) + val suggestedEndAt = clampEndPick(windowEnd, limits).at + if (suggestedEndAt <= lastRun.endAt) continue + + val suggestedGapMinutes = ((suggestedEndAt - lastRun.endAt) / MINUTE_MS).toInt() + if (suggestedGapMinutes < MIN_GAP_MINUTES) continue + + return SleepTailSuggestion( + sessionId = session.id, + sessionDate = session.date, + run = lastRun, + previousRun = previousRun, + ringEndedAt = lastRun.endAt, + bedtimeEndedAt = windowEnd, + suggestedEndAt = suggestedEndAt, + gapMinutes = suggestedGapMinutes, + ) + } + return null + } +} + +/** + * Per-record dismissal persistence for [SleepTailSuggestion] (issue #148). + * + * Keys by `sessionDate_recordStartAt` so tapping "No" hides the prompt for that ring record only, + * while later nights (or another morning record) remain eligible. + */ +object SleepTailSuggestionStore { + private const val PREFS = "sleep_tail_suggestions" + private const val KEY_DISMISSED = "dismissed_keys" + internal const val RETENTION_DAYS = 45L + + private fun key(sessionDate: Long, recordStartAt: Long): String = "${sessionDate}_$recordStartAt" + + fun isDismissed(context: Context, sessionDate: Long, recordStartAt: Long): Boolean { + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val keys = prefs.getStringSet(KEY_DISMISSED, null) ?: return false + return key(sessionDate, recordStartAt) in keys + } + + fun dismiss( + context: Context, + sessionDate: Long, + recordStartAt: Long, + nowMillis: Long = System.currentTimeMillis(), + ) { + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + // Never mutate the StringSet returned by getStringSet; rebuild via pruneKeys first. + val current = prefs.getStringSet(KEY_DISMISSED, null).orEmpty() + val updated = pruneKeys(current + key(sessionDate, recordStartAt), nowMillis) + prefs.edit().putStringSet(KEY_DISMISSED, updated).apply() + } + + internal fun pruneKeys( + keys: Set, + nowMillis: Long = System.currentTimeMillis(), + ): Set { + val cutoff = nowMillis - RETENTION_DAYS * 86_400_000L + return keys.filterTo(HashSet()) { entry -> + val datePart = entry.substringBefore('_').toLongOrNull() + datePart != null && datePart >= cutoff + } + } +} diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index db70b578..65a934b9 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -140,6 +140,18 @@ fun PulseLoopApp() { db, gapBridge = { com.pulseloop.service.SleepGapBridge.fromSettings(appContext) }, stepSourcePrefs = stepSourcePrefs, + bedtimeWindows = { + com.pulseloop.settings.QuietHoursPrefs.activeBedtimeWindows( + com.pulseloop.settings.QuietHoursPrefs(appContext), + appContext, + ) + }, + isTailDismissed = { date, recordStartAt -> + com.pulseloop.service.SleepTailSuggestionStore.isDismissed(appContext, date, recordStartAt) + }, + onDismissTail = { date, recordStartAt -> + com.pulseloop.service.SleepTailSuggestionStore.dismiss(appContext, date, recordStartAt) + }, ) } val activityVM = remember { ActivityViewModel(db, stepSourcePrefs) } 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 03c8b436..bba4bb84 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -21,6 +21,7 @@ import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.DeleteOutline import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.ExperimentalMaterial3Api @@ -85,8 +86,14 @@ fun SleepScreen( topBarPadding: androidx.compose.ui.unit.Dp = 0.dp, bottomBarPadding: androidx.compose.ui.unit.Dp = 0.dp, ) { - LaunchedEffect(Unit) { onOpen() } + LaunchedEffect(Unit) { + viewModel?.refreshReferenceNight() + onOpen() + } val state by (viewModel?.state?.collectAsState() ?: remember { mutableStateOf(SleepViewModel.SleepState()) }) + var confirmingTail by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + val context = androidx.compose.ui.platform.LocalContext.current LazyColumn( modifier = Modifier.fillMaxSize(), @@ -99,10 +106,44 @@ fun SleepScreen( item { SleepRangeSelector(state.range) { viewModel?.setRange(it) } } - if (state.range == SleepRangeKey.DAY) dayItems(state, navController, viewModel) + if (state.range == SleepRangeKey.DAY) dayItems(state, navController, viewModel, onExtendTail = { confirmingTail = it }) else aggregateItems(state, navController) item { Spacer(Modifier.height(64.dp)) } } + + confirmingTail?.let { suggestion -> + SleepRecordEditDialog( + run = suggestion.run, + limits = remember(suggestion) { + com.pulseloop.service.recordEditLimits( + run = suggestion.run, + previous = suggestion.previousRun, + next = null, + wakingDay = suggestion.sessionDate, + ) + }, + initialEndAt = suggestion.suggestedEndAt, + onDismiss = { confirmingTail = null }, + onSave = { newStart, newEnd -> + confirmingTail = null + scope.launch { + val updated = viewModel?.editSleepRecord( + suggestion.sessionId, + suggestion.run.recordStartAt, + newStart, + newEnd, + ) ?: false + if (!updated) { + android.widget.Toast.makeText( + context, + context.getString(R.string.sleep_update_failed), + android.widget.Toast.LENGTH_SHORT, + ).show() + } + } + }, + ) + } } // ─────────────────────────── Day view ─────────────────────────── @@ -111,6 +152,7 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( state: SleepViewModel.SleepState, navController: androidx.navigation.NavController?, viewModel: SleepViewModel?, + onExtendTail: (com.pulseloop.service.SleepTailSuggestion) -> Unit = {}, ) { // Date stepper: ‹ older · date · newer › (iOS #84). item { SleepDayNavHeader(state, viewModel) } @@ -138,9 +180,23 @@ private fun androidx.compose.foundation.lazy.LazyListScope.dayItems( item { SleepStageSummaryCards(deep = "—", light = "—", awake = "—") } } // Single session: render exactly as before, no carousel chrome. - sessions.size == 1 -> sessionPageItems(sessions[0], state.dayBlocks[sessions[0].id] ?: emptyList(), viewModel) + sessions.size == 1 -> sessionPageItems( + session = sessions[0], + blocks = state.dayBlocks[sessions[0].id] ?: emptyList(), + viewModel = viewModel, + tailSuggestion = state.tailSuggestion, + onExtendTail = onExtendTail, + ) // Multiple sessions (night + naps): horizontal paged carousel with dot indicators. - else -> item { SleepCarousel(sessions, state.dayBlocks, viewModel) } + else -> item { + SleepCarousel( + sessions = sessions, + blocksBySession = state.dayBlocks, + viewModel = viewModel, + tailSuggestion = state.tailSuggestion, + onExtendTail = onExtendTail, + ) + } } item { @@ -161,8 +217,24 @@ private fun androidx.compose.foundation.lazy.LazyListScope.sessionPageItems( session: SleepSessionEntity, blocks: List, viewModel: SleepViewModel? = null, + tailSuggestion: com.pulseloop.service.SleepTailSuggestion? = null, + onExtendTail: (com.pulseloop.service.SleepTailSuggestion) -> Unit = {}, ) { item { SessionHero(session, blocks) } + if (tailSuggestion?.sessionId == session.id) { + item { + SleepTailSuggestionCard( + suggestion = tailSuggestion, + onExtend = { onExtendTail(tailSuggestion) }, + onDismiss = { + viewModel?.dismissTailSuggestion( + tailSuggestion.sessionDate, + tailSuggestion.run.recordStartAt, + ) + }, + ) + } + } item { VisualizationCard(eyebrow = stringResource(R.string.sleep_stages), title = stringResource(R.string.sleep_architecture), legend = true) { SleepHypnogram(blocks = remember(blocks) { com.pulseloop.service.hypnogramBlocks(blocks) }, spanMin = session.spanMinutes, startTs = session.startAt) @@ -205,6 +277,8 @@ private fun SleepCarousel( sessions: List, blocksBySession: Map>, viewModel: SleepViewModel? = null, + tailSuggestion: com.pulseloop.service.SleepTailSuggestion? = null, + onExtendTail: (com.pulseloop.service.SleepTailSuggestion) -> Unit = {}, ) { // Reset to the first page whenever the day's session set changes (a different day / fewer // pages): keying the composable recreates the pager state. @@ -227,6 +301,18 @@ private fun SleepCarousel( letterSpacing = 0.8.sp, color = PulseColors.textSecondary, ) SessionHero(s, blocks) + if (tailSuggestion?.sessionId == s.id) { + SleepTailSuggestionCard( + suggestion = tailSuggestion, + onExtend = { onExtendTail(tailSuggestion) }, + onDismiss = { + viewModel?.dismissTailSuggestion( + tailSuggestion.sessionDate, + tailSuggestion.run.recordStartAt, + ) + }, + ) + } VisualizationCard(eyebrow = stringResource(R.string.sleep_stages), title = stringResource(R.string.sleep_architecture), legend = true) { SleepHypnogram(blocks = remember(blocks) { com.pulseloop.service.hypnogramBlocks(blocks) }, spanMin = s.spanMinutes, startTs = s.startAt) } @@ -1204,17 +1290,69 @@ private fun SleepRecordsCard( } } +/** + * Suggests extending the night's final ring record forward to Bedtime's end when morning steps are + * absent (issue #148). Hands off to [SleepRecordEditDialog] pre-filled with the suggested end time + * rather than mutating the record silently. + */ +@Composable +private fun SleepTailSuggestionCard( + suggestion: com.pulseloop.service.SleepTailSuggestion, + onExtend: () -> Unit, + onDismiss: () -> Unit, +) { + val shape = RoundedCornerShape(18.dp) + val endLabel = SleepFormat.clockTime(suggestion.suggestedEndAt) + Column( + Modifier + .fillMaxWidth() + .clip(shape) + .background(PulseColors.card) + .border(1.dp, PulseColors.borderSubtle, shape) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + stringResource(R.string.sleep_tail_title), + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + color = PulseColors.textPrimary, + ) + Text( + stringResource( + R.string.sleep_tail_body, + SleepFormat.clockTime(suggestion.ringEndedAt), + endLabel, + ), + fontSize = 13.sp, + color = PulseColors.textSecondary, + ) + Row( + modifier = Modifier.padding(top = 4.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(onClick = onExtend) { + Text(stringResource(R.string.sleep_tail_extend, endLabel)) + } + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.action_no)) + } + } + } +} + @OptIn(ExperimentalMaterial3Api::class) @Composable private fun SleepRecordEditDialog( run: com.pulseloop.service.SleepRecordRun, limits: com.pulseloop.service.RecordEditLimits, + initialEndAt: Long = run.endAt, onDismiss: () -> Unit, onSave: (newStartAt: Long, newEndAt: Long) -> Unit, ) { val zone = remember { java.time.ZoneId.systemDefault() } - var currentStart by remember { mutableStateOf(run.startAt) } - var currentEnd by remember { mutableStateOf(run.endAt) } + var currentStart by remember(run.recordStartAt, initialEndAt) { mutableStateOf(run.startAt) } + var currentEnd by remember(run.recordStartAt, initialEndAt) { mutableStateOf(initialEndAt) } var pickingTime by remember { mutableStateOf(null) } // "start" or "end" // The limit the last pick ran past, named rather than silently snapped back to (issue #106). var limitMessage by remember { mutableStateOf(null) } 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 03ba50dd..8eecd7ef 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -222,6 +222,9 @@ class SleepViewModel( /** The night-bridging rule a record delete/edit re-segments with — the sync's own (issue #105). */ private val gapBridge: () -> com.pulseloop.service.SleepGapBridge = { com.pulseloop.service.SleepGapBridge.NONE }, private val stepSourcePrefs: StepSourcePrefs, + private val bedtimeWindows: () -> List? = { null }, + private val isTailDismissed: (sessionDate: Long, recordStartAt: Long) -> Boolean = { _, _ -> false }, + private val onDismissTail: (sessionDate: Long, recordStartAt: Long) -> Unit = { _, _ -> }, ) : ViewModel() { data class SleepState( val range: SleepRangeKey = SleepRangeKey.DAY, @@ -254,6 +257,8 @@ class SleepViewModel( // LLM summaries when present (fallback = the scripted coach above) val daySummary: CoachSummaryEntity? = null, val rangeSummary: CoachSummaryEntity? = null, + // Prompt to extend the night's final record to Bedtime's end when morning steps are absent (#148). + val tailSuggestion: com.pulseloop.service.SleepTailSuggestion? = null, ) private val _state = MutableStateFlow(SleepState()) @@ -272,13 +277,14 @@ class SleepViewModel( init { // Any sleep-table change retriggers a rebuild of the selected range. viewModelScope.launch { - // Combined with the step-source preference (review item 7, PR #98) so the sleep - // coach's step figure follows the toggle without waiting for a sleep-table write. - // rebuild() reads preferPhone() fresh each call, so the emit is the entire fix. + // Combined with stepSourcePrefs (PR #98) and lastFullSyncAt (#148) so a morning sync + // that logs only step buckets (no new sleep rows) still re-evaluates the sleep coach + // and the Bedtime tail-extension prompt immediately once sync completes. combine( db.sleepSessionDao().recentFlow(7), stepSourcePrefs.preferPhoneFlow(), - ) { sessions, _ -> sessions }.collect { sessions -> + db.deviceDao().currentFlow().map { it?.lastFullSyncAt }.distinctUntilChanged(), + ) { sessions, _, _ -> sessions }.collect { sessions -> _state.update { it.copy(recentSessions = sessions) } try { rebuild(_state.value.range) } catch (_: Exception) {} } @@ -371,6 +377,44 @@ class SleepViewModel( db.coachSummaryDao().latest(CoachSummaryKind.sleepRange(range).rawValue) } catch (_: Exception) { null } + val tailSuggestion = if (range == SleepRangeKey.DAY && daySessions.isNotEmpty()) { + val windows = bedtimeWindows() + if (windows.isNullOrEmpty()) { + null + } else { + val bucketDays = daySessions.flatMap { s -> + listOf( + TimeUtil.startOfDayLocal(s.date), + TimeUtil.startOfDayLocal(s.endAt), + TimeUtil.startOfDayLocal(s.endAt + 2 * 3_600_000L), + ) + }.distinct() + val buckets = bucketDays.flatMap { day -> + try { db.activityBucketDao().byDay(day) } catch (_: Exception) { emptyList() } + } + val lastFullSyncAt = try { db.deviceDao().current()?.lastFullSyncAt } catch (_: Exception) { null } + val editedRecords = daySessions.mapNotNull { s -> + val lastRun = com.pulseloop.service.sleepRecordRuns(dayBlocks[s.id].orEmpty()).lastOrNull() + ?: return@mapNotNull null + val edited = try { + db.measurementDeletionDao().getSleepEdit(s.date, lastRun.recordStartAt) != null + } catch (_: Exception) { false } + if (edited) s.date to lastRun.recordStartAt else null + }.toSet() + com.pulseloop.service.SleepTailSuggestionDetector.detect( + daySessions = daySessions, + dayBlocks = dayBlocks, + bedtimeWindows = windows, + stepBuckets = buckets, + lastFullSyncAt = lastFullSyncAt, + isDismissed = isTailDismissed, + isEdited = { date, recordStartAt -> (date to recordStartAt) in editedRecords }, + ) + } + } else { + null + } + _state.update { it.copy( lastNight = night, @@ -391,6 +435,7 @@ class SleepViewModel( goalMinutes = goal, daySummary = daySummary, rangeSummary = rangeSummary, + tailSuggestion = tailSuggestion, ) } } @@ -438,6 +483,19 @@ class SleepViewModel( updated } catch (_: Exception) { false } + /** Persist dismissal of the Bedtime sleep-tail prompt for this ring record (issue #148). */ + fun dismissTailSuggestion(sessionDate: Long, recordStartAt: Long) { + onDismissTail(sessionDate, recordStartAt) + _state.update { state -> + val current = state.tailSuggestion + if (current != null && current.sessionDate == sessionDate && current.run.recordStartAt == recordStartAt) { + state.copy(tailSuggestion = null) + } else { + state + } + } + } + /** Jump to the day at [dayMillis] (a local-midnight key), clamped to the valid range. */ fun jumpToDay(dayMillis: Long) { val today = TimeUtil.startOfTodayLocal() diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index b587c08a..8e449c1d 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -156,6 +156,7 @@ Получайте ежедневную сводку от коуча. Это можно изменить в любой момент в разделе «Сводки коуча». Включить Не сейчас + Нет Сводки коуча ИИ-коуч выключен Включите ИИ-коуча, чтобы изменить эти настройки: ежедневные сводки коуч пишет на основе ваших недавних показателей. @@ -527,6 +528,9 @@ Оставить Изменить запись сна Обрежьте запись или продлите её на время, которое кольцо пропустило. Добавленное время считается сном без фазы, поэтому не учитывается в разбивке по фазам и в оценке. + Вы ещё спали? + Кольцо остановило запись в %1$s, но режим сна оставался включённым до %2$s, и шагов не было. + Продлить до %1$s Начало: %1$s Конец: %1$s Время начала должно быть раньше времени окончания. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0c52ec06..0bb9deac 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -162,6 +162,7 @@ Get a daily check-in from your coach. You can change this anytime in Coach Check-Ins. Enable Not now + No Coach Check-Ins AI Coach is off Enable the AI Coach to change these — daily check-ins are written by the coach from your recent trends. @@ -519,6 +520,9 @@ Keep Edit sleep record 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. + Were you still asleep? + The ring stopped at %1$s, but Bedtime stayed on until %2$s with no steps. + Extend to %1$s Start: %1$s End: %1$s Start time must be before end time. diff --git a/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt new file mode 100644 index 00000000..99d2c276 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt @@ -0,0 +1,409 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.ActivityBucketEntity +import com.pulseloop.data.entity.SleepSessionEntity +import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.ring.SleepStage +import com.pulseloop.settings.ZenWindow +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.ZoneId +import java.time.ZonedDateTime + +/** + * Tests for Bedtime-bounded sleep tail suggestion detection and dismissal pruning (issue #148). + */ +class SleepTailSuggestionTest { + + private val zone = ZoneId.of("UTC") + private val wakingDay = ZonedDateTime.of(2025, 11, 15, 0, 0, 0, 0, zone).toInstant().toEpochMilli() + + private fun at(h: Int, m: Int, s: Int = 0): Long = wakingDay + ((h * 60L + m) * 60 + s) * 1000L + + private fun ringBlocks( + sessionId: String = "s1", + startAt: Long, + durationMinutes: Int, + addedTailMinutes: Int = 0, + ): List { + val measured = buildStageBlocks( + sessionId = sessionId, + startTs = startAt, + stages = List(durationMinutes) { SleepStage.LIGHT }, + recordStartAt = startAt, + ) + if (addedTailMinutes <= 0) return measured + val measuredEnd = measured.maxOf { it.startAt + it.durationMinutes * 60_000L } + return measured + SleepStageBlockEntity( + sessionId = sessionId, + startAt = measuredEnd, + startMinute = 0, + durationMinutes = addedTailMinutes, + stageRaw = SleepStage.ADDED.name, + recordStartAt = startAt, + ) + } + + private fun session( + id: String = "s1", + blocks: List, + sourceRaw: String = "ring", + ) = SleepSessionEntity( + id = id, + date = wakingDay, + startAt = blocks.minOf { it.startAt }, + endAt = blocks.maxOf { it.startAt + it.durationMinutes * 60_000L }, + totalMinutes = asleepMinutes(blocks), + sourceRaw = sourceRaw, + ) + + private fun detect( + sessions: List, + blocksBySession: Map>, + windows: List? = listOf(ZenWindow(start = at(2, 0), end = at(9, 27))), + buckets: List = emptyList(), + lastFullSyncAt: Long? = at(9, 30), + isDismissed: (Long, Long) -> Boolean = { _, _ -> false }, + isEdited: (Long, Long) -> Boolean = { _, _ -> false }, + ): SleepTailSuggestion? = SleepTailSuggestionDetector.detect( + daySessions = sessions, + dayBlocks = blocksBySession, + bedtimeWindows = windows, + stepBuckets = buckets, + lastFullSyncAt = lastFullSyncAt, + isDismissed = isDismissed, + isEdited = isEdited, + zone = zone, + ) + + @Test + fun `reporter Oct 12 example — 28m zero-step gap triggers prompt`() { + val blocks = ringBlocks(startAt = at(0, 10), durationMinutes = 408) // 00:10 -> 06:58 + val s = session(blocks = blocks) + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(7, 26))), + lastFullSyncAt = at(7, 30), + ) + + assertNotNull(suggestion) + assertEquals(at(6, 58), suggestion!!.ringEndedAt) + assertEquals(at(7, 26), suggestion.bedtimeEndedAt) + assertEquals(at(7, 26), suggestion.suggestedEndAt) + assertEquals(28, suggestion.gapMinutes) + } + + @Test + fun `reporter Nov 3 example — 75m gap ignores pre-end get-up and post-bedtime buckets`() { + val blocks = ringBlocks(startAt = at(0, 4), durationMinutes = 450) // 00:04 -> 07:34 + val s = session(blocks = blocks) + val buckets = listOf( + // Get-up at 07:34 sits in the 07:30 bucket (< 07:34 startEpoch). + ActivityBucketEntity(startEpoch = at(7, 30), date = wakingDay, steps = 38), + // Turning off Bedtime / getting out of bed at 08:49 sits in 08:45 bucket (straddles 08:49). + ActivityBucketEntity(startEpoch = at(8, 45), date = wakingDay, steps = 54), + ) + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 49))), + buckets = buckets, + lastFullSyncAt = at(9, 0), + ) + + assertNotNull(suggestion) + assertEquals(at(7, 34), suggestion!!.ringEndedAt) + assertEquals(at(8, 49), suggestion.suggestedEndAt) + assertEquals(75, suggestion.gapMinutes) + } + + @Test + fun `reporter Nov 15 example — 99m zero-step gap triggers prompt`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) // 02:59 -> 07:48 + val s = session(blocks = blocks) + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(1, 0), end = at(9, 27))), + lastFullSyncAt = at(9, 30), + ) + + assertNotNull(suggestion) + assertEquals(at(7, 48), suggestion!!.ringEndedAt) + assertEquals(at(9, 27), suggestion.suggestedEndAt) + assertEquals(99, suggestion.gapMinutes) + } + + @Test + fun `interior steps inside tail suppress prompt`() { + val blocks = ringBlocks(startAt = at(0, 4), durationMinutes = 450) // -> 07:34 + val s = session(blocks = blocks) + val buckets = listOf( + ActivityBucketEntity(startEpoch = at(7, 45), date = wakingDay, steps = 12), + ) + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 49))), + buckets = buckets, + lastFullSyncAt = at(9, 0), + ) + + assertNull(suggestion) + } + + @Test + fun `bucket ending right at Bedtime end suppresses while straddling tail bucket does not`() { + val blocks = ringBlocks(startAt = at(0, 4), durationMinutes = 450) // -> 07:34 + val s = session(blocks = blocks) + val bucketAt0830 = listOf( + ActivityBucketEntity(startEpoch = at(8, 30), date = wakingDay, steps = 20), + ) + + // 08:30..08:45 lies wholly inside 07:34..08:45 -> suppressed. + assertNull( + detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 45))), + buckets = bucketAt0830, + lastFullSyncAt = at(9, 0), + ), + ) + + // With Bedtime ending at 08:44, 08:30..08:45 straddles wake-up -> ignored, prompt fires. + assertNotNull( + detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 44))), + buckets = bucketAt0830, + lastFullSyncAt = at(9, 0), + ), + ) + } + + @Test + fun `null empty or open Bedtime windows produce no prompt`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) + val s = session(blocks = blocks) + + assertNull(detect(listOf(s), mapOf(s.id to blocks), windows = null)) + assertNull(detect(listOf(s), mapOf(s.id to blocks), windows = emptyList())) + assertNull(detect(listOf(s), mapOf(s.id to blocks), windows = listOf(ZenWindow(start = at(2, 0), end = null)))) + } + + @Test + fun `full sync must be at or after Bedtime end unless null`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) // -> 07:48 + val s = session(blocks = blocks) + val windows = listOf(ZenWindow(start = at(1, 0), end = at(9, 27))) + + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = windows, + lastFullSyncAt = at(9, 26), + ), + ) + assertNotNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = windows, + lastFullSyncAt = at(9, 27), + ), + ) + assertNotNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = windows, + lastFullSyncAt = null, + ), + ) + } + + @Test + fun `gap must fall inside 15 to 120 minutes inclusive`() { + val blocks = ringBlocks(startAt = at(1, 0), durationMinutes = 360) // -> 07:00 + val s = session(blocks = blocks) + + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 30), end = at(7, 14))), + lastFullSyncAt = at(10, 0), + ), + ) + assertNotNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 30), end = at(7, 15))), + lastFullSyncAt = at(10, 0), + ), + ) + assertNotNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 30), end = at(9, 0))), + lastFullSyncAt = at(10, 0), + ), + ) + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 30), end = at(9, 1))), + lastFullSyncAt = at(10, 0), + ), + ) + } + + @Test + fun `already extended record with ADDED block suppresses prompt`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289, addedTailMinutes = 20) + val s = session(blocks = blocks) + + assertNull(detect(listOf(s), mapOf(s.id to blocks))) + } + + @Test + fun `manually edited or dismissed record suppresses prompt`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) + val s = session(blocks = blocks) + + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + isEdited = { date, start -> date == wakingDay && start == at(2, 59) }, + ), + ) + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + isDismissed = { date, start -> date == wakingDay && start == at(2, 59) }, + ), + ) + } + + @Test + fun `demo session never triggers prompt`() { + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) + val s = session(blocks = blocks, sourceRaw = "demo") + + assertNull(detect(listOf(s), mapOf(s.id to blocks))) + } + + @Test + fun `multi-session day blocks overlap across sessions while keeping unrelated afternoon nap`() { + val nightBlocks = ringBlocks("night", startAt = at(2, 0), durationMinutes = 300) // 02:00..07:00 + val nightSession = session("night", nightBlocks) + + // Case A: a second morning session overlaps (07:00, 08:30) -> must suppress. + val lateMorningBlocks = ringBlocks("late", startAt = at(7, 20), durationMinutes = 80) // 07:20..08:40 + val lateMorningSession = session("late", lateMorningBlocks) + assertNull( + detect( + sessions = listOf(nightSession, lateMorningSession), + blocksBySession = mapOf("night" to nightBlocks, "late" to lateMorningBlocks), + windows = listOf(ZenWindow(start = at(1, 0), end = at(8, 30))), + lastFullSyncAt = at(9, 0), + ), + ) + + // Case B: an unrelated afternoon nap 15:00..16:00 does not block the 07:00 -> 08:30 morning prompt. + val napBlocks = ringBlocks("nap", startAt = at(15, 0), durationMinutes = 60) + val napSession = session("nap", napBlocks) + val suggestion = detect( + sessions = listOf(nightSession, napSession), + blocksBySession = mapOf("night" to nightBlocks, "nap" to napBlocks), + windows = listOf(ZenWindow(start = at(1, 0), end = at(8, 30))), + lastFullSyncAt = at(16, 30), + ) + assertNotNull(suggestion) + assertEquals("night", suggestion!!.sessionId) + } + + @Test + fun `multi-record session carries previousRun and snaps end onto record minute grid`() { + val rec1 = ringBlocks("s1", startAt = at(0, 51, 23), durationMinutes = 293) // 00:51:23..05:44:23 + val rec2 = ringBlocks("s1", startAt = at(6, 56, 23), durationMinutes = 71) // 06:56:23..08:07:23 + val allBlocks = rec1 + rec2 + val s = session("s1", allBlocks) + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf("s1" to allBlocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 50, 10))), + lastFullSyncAt = at(9, 0), + ) + + assertNotNull(suggestion) + assertEquals(at(6, 56, 23), suggestion!!.run.recordStartAt) + assertNotNull(suggestion.previousRun) + assertEquals(at(0, 51, 23), suggestion.previousRun!!.recordStartAt) + // Wall-clock 08:50:10 -> minute floor 08:50:00 -> ceiled onto :23s grid -> 08:50:23. + assertEquals(at(8, 50, 23), suggestion.suggestedEndAt) + assertEquals(43, suggestion.gapMinutes) + } + + @Test + fun `extension is clamped at 7 PM night boundary and suppressed if clamped gap drops below 15m`() { + val blocks1 = ringBlocks("s1", startAt = at(16, 0), durationMinutes = 130) // 16:00..18:10 + val s1 = session("s1", blocks1) + val clamped = detect( + sessions = listOf(s1), + blocksBySession = mapOf("s1" to blocks1), + windows = listOf(ZenWindow(start = at(15, 0), end = at(19, 30))), + lastFullSyncAt = at(20, 0), + ) + assertNotNull(clamped) + assertEquals(at(19, 0), clamped!!.suggestedEndAt) + assertEquals(50, clamped.gapMinutes) + + // Ending at 18:55 leaves only 5m before 19:00 night boundary (< 15m) -> no prompt. + val blocks2 = ringBlocks("s2", startAt = at(17, 0), durationMinutes = 115) // 17:00..18:55 + val s2 = session("s2", blocks2) + assertNull( + detect( + sessions = listOf(s2), + blocksBySession = mapOf("s2" to blocks2), + windows = listOf(ZenWindow(start = at(15, 0), end = at(19, 30))), + lastFullSyncAt = at(20, 0), + ), + ) + } + + @Test + fun `store pruneKeys drops expired and malformed keys while keeping 45 day entries`() { + val now = wakingDay + 45L * 86_400_000L + val justInside = "${wakingDay}_12345" + val expired = "${wakingDay - 86_400_000L}_99999" + val recent = "${wakingDay + 10L * 86_400_000L}_54321" + val malformed = "not-a-date" + + val pruned = SleepTailSuggestionStore.pruneKeys( + setOf(justInside, expired, recent, malformed), + nowMillis = now, + ) + + assertEquals(setOf(justInside, recent), pruned) + assertTrue(expired !in pruned) + assertTrue(malformed !in pruned) + } +} From 3471f0cdbb188c592952ca75611fcde0ab374078 Mon Sep 17 00:00:00 2001 From: Khoa Truong Date: Fri, 20 Nov 2026 04:16:09 -0800 Subject: [PATCH 2/3] Sleep: keep outward extensions score-neutral and show in-gap HR on tail prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix SleepScore.calculate's span calculation when ADDED blocks are present: measure span across the ring's own measured blocks instead of session.spanMinutes, so outward extensions keep the same coverage ratio on 0-awake nights (fixing the 81 -> 75 score drop on Nov 16) and don't dilute awakePct, while preserving interior between-record gaps (#106). Enrich SleepTailSuggestion with non-demo heart-rate samples inside the suggested extension gap and the night's mean HR so SleepTailSuggestionCard can surface readings like "Heart rate at 08:00: 58 bpm · night avg 59 bpm" (or compact list / avg+range summary when denser HR sampling is present). --- .../com/pulseloop/service/SleepInsights.kt | 22 ++-- .../pulseloop/service/SleepTailSuggestion.kt | 50 +++++++++ .../com/pulseloop/ui/screens/SleepScreen.kt | 30 +++++ .../com/pulseloop/ui/viewmodels/ViewModels.kt | 18 ++- app/src/main/res/values-ru/strings.xml | 6 + app/src/main/res/values/strings.xml | 6 + .../service/SleepRecordExtensionTest.kt | 46 ++++++++ .../service/SleepTailSuggestionTest.kt | 106 ++++++++++++++++++ 8 files changed, 276 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/com/pulseloop/service/SleepInsights.kt b/app/src/main/java/com/pulseloop/service/SleepInsights.kt index de90db77..cc6f0321 100644 --- a/app/src/main/java/com/pulseloop/service/SleepInsights.kt +++ b/app/src/main/java/com/pulseloop/service/SleepInsights.kt @@ -78,13 +78,22 @@ object SleepScore { // 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. // - // 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. + // Minutes the wearer added over time the ring missed (issue #106, #148) 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 `span` stays the span across + // the ring's own measured blocks (preserving interior between-record gaps while keeping + // outward extensions score-neutral even when a night has no AWAKE blocks). 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 + val measured = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name } + val measuredSpan = if (added > 0 && measured.isNotEmpty() && measured.all { it.startAt > 0L }) { + val first = measured.minOf { it.startAt } + val last = measured.maxOf { it.startAt + it.durationMinutes * 60_000L } + ((last - first) / 60_000L).toInt().coerceAtLeast(0).toDouble() + } else { + 0.0 + } + val span = measuredSpan.takeIf { it > 0 } ?: session.spanMinutes.toDouble().takeIf { it > 0 } ?: total // stageRaw is persisted as the SleepStage enum name (uppercase) — match it exactly. // Some rings report REM in big-data sleep; the score model has no REM band, so fold // REM into deep (both are restorative sleep the deep band rewards). @@ -93,8 +102,7 @@ object SleepScore { val deep = minutesFor(SleepStage.DEEP, SleepStage.REM) val light = minutesFor(SleepStage.LIGHT) val awake = minutesFor(SleepStage.AWAKE) - val coveredStageMin = blocks.filterNot { it.stageRaw == SleepStage.ADDED.name } - .sumOf { it.durationMinutes.toDouble() } + val coveredStageMin = measured.sumOf { it.durationMinutes.toDouble() } val hasAwakeSignal = blocks.any { it.stageRaw == SleepStage.AWAKE.name } || awake > 0 || (span > 0 && coveredStageMin >= span * 0.95) diff --git a/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt index 5f199459..8774b4be 100644 --- a/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt +++ b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt @@ -3,11 +3,19 @@ package com.pulseloop.service import android.content.Context import com.pulseloop.data.DemoDataPolicy import com.pulseloop.data.entity.ActivityBucketEntity +import com.pulseloop.data.entity.MeasurementEntity import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.settings.ZenWindow import java.time.ZoneId +import kotlin.math.roundToInt + +/** A single recorded ring heart-rate sample inside the suggested extension gap (#148). */ +data class TailHeartRateReading( + val timestamp: Long, + val bpm: Int, +) /** * A prompt to extend the ring's last sleep record forward to the end of Android Bedtime (#148). @@ -27,6 +35,8 @@ data class SleepTailSuggestion( val bedtimeEndedAt: Long, val suggestedEndAt: Long, val gapMinutes: Int, + val gapHeartRates: List = emptyList(), + val nightAvgHeartRate: Int? = null, ) /** @@ -133,6 +143,46 @@ object SleepTailSuggestionDetector { } return null } + + private const val MIN_VALID_BPM = 30 + private const val MAX_VALID_BPM = 220 + + /** + * Enrich [suggestion] with plausible non-demo heart-rate readings inside `(ringEndedAt, + * suggestedEndAt)` and the night's mean HR across `sessionStartAt..ringEndedAt` (#148). + */ + fun withHeartRateContext( + suggestion: SleepTailSuggestion, + sessionStartAt: Long, + hrSamples: List, + ): SleepTailSuggestion { + val plausible = hrSamples.mapNotNull { sample -> + if (DemoDataPolicy.isDemo(sample.sourceRaw)) return@mapNotNull null + if (sample.value.isNaN()) return@mapNotNull null + val bpm = sample.value.roundToInt() + if (bpm !in MIN_VALID_BPM..MAX_VALID_BPM) return@mapNotNull null + sample.timestamp to bpm + } + + val gapReadings = plausible + .asSequence() + .filter { (ts, _) -> ts > suggestion.ringEndedAt && ts < suggestion.suggestedEndAt } + .sortedBy { (ts, _) -> ts } + .associateBy { (ts, _) -> ts / MINUTE_MS } + .values + .map { (ts, bpm) -> TailHeartRateReading(timestamp = ts, bpm = bpm) } + .sortedBy { it.timestamp } + + val nightValues = plausible + .filter { (ts, _) -> ts in sessionStartAt..suggestion.ringEndedAt } + .map { (_, bpm) -> bpm } + val nightAvg = if (nightValues.isEmpty()) null else nightValues.average().roundToInt() + + return suggestion.copy( + gapHeartRates = gapReadings, + nightAvgHeartRate = nightAvg, + ) + } } /** 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 bba4bb84..94ce34ca 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -1327,6 +1327,36 @@ private fun SleepTailSuggestionCard( fontSize = 13.sp, color = PulseColors.textSecondary, ) + if (suggestion.gapHeartRates.isNotEmpty()) { + val hrSummary = when (suggestion.gapHeartRates.size) { + 1 -> { + val r = suggestion.gapHeartRates.first() + stringResource(R.string.sleep_tail_hr_single, SleepFormat.clockTime(r.timestamp), r.bpm) + } + in 2..3 -> { + val items = suggestion.gapHeartRates.map { r -> + stringResource(R.string.sleep_tail_hr_item, r.bpm, SleepFormat.clockTime(r.timestamp)) + }.joinToString(", ") + stringResource(R.string.sleep_tail_hr_list, items) + } + else -> { + val bpms = suggestion.gapHeartRates.map { it.bpm } + val avg = bpms.average().roundToInt() + val min = bpms.min() + val max = bpms.max() + if (min == max) stringResource(R.string.sleep_tail_hr_summary_flat, avg) + else stringResource(R.string.sleep_tail_hr_summary, avg, min, max) + } + } + val hrLine = suggestion.nightAvgHeartRate?.let { nightAvg -> + "$hrSummary · ${stringResource(R.string.sleep_tail_hr_night_avg, nightAvg)}" + } ?: hrSummary + Text( + hrLine, + fontSize = 12.sp, + color = PulseColors.textMuted, + ) + } Row( modifier = Modifier.padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.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 8eecd7ef..4957f064 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -401,7 +401,7 @@ class SleepViewModel( } catch (_: Exception) { false } if (edited) s.date to lastRun.recordStartAt else null }.toSet() - com.pulseloop.service.SleepTailSuggestionDetector.detect( + val rawSuggestion = com.pulseloop.service.SleepTailSuggestionDetector.detect( daySessions = daySessions, dayBlocks = dayBlocks, bedtimeWindows = windows, @@ -410,6 +410,22 @@ class SleepViewModel( isDismissed = isTailDismissed, isEdited = { date, recordStartAt -> (date to recordStartAt) in editedRecords }, ) + rawSuggestion?.let { suggestion -> + val hrStart = daySessions.firstOrNull { it.id == suggestion.sessionId }?.startAt + ?: suggestion.run.startAt + val hrSamples = try { + db.measurementDao().rangeReal( + MeasurementKind.HEART_RATE.name, + hrStart, + suggestion.suggestedEndAt, + ) + } catch (_: Exception) { emptyList() } + com.pulseloop.service.SleepTailSuggestionDetector.withHeartRateContext( + suggestion = suggestion, + sessionStartAt = hrStart, + hrSamples = hrSamples, + ) + } } } else { null diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 8e449c1d..5e5c115a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -531,6 +531,12 @@ Вы ещё спали? Кольцо остановило запись в %1$s, но режим сна оставался включённым до %2$s, и шагов не было. Продлить до %1$s + Пульс в %1$s: %2$d уд/мин + %1$d уд/мин в %2$s + Пульс: %1$s + Пульс в промежутке: сред. %1$d уд/мин (%2$d–%3$d) + Пульс в промежутке: сред. %1$d уд/мин + ночью в среднем %1$d уд/мин Начало: %1$s Конец: %1$s Время начала должно быть раньше времени окончания. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0bb9deac..3cf98fc0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -523,6 +523,12 @@ Were you still asleep? The ring stopped at %1$s, but Bedtime stayed on until %2$s with no steps. Extend to %1$s + Heart rate at %1$s: %2$d bpm + %1$d bpm at %2$s + Heart rate: %1$s + Heart rate in gap: %1$d bpm avg (%2$d–%3$d) + Heart rate in gap: %1$d bpm avg + night avg %1$d bpm Start: %1$s End: %1$s Start time must be before end time. diff --git a/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt index dc737cb2..fd019391 100644 --- a/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt +++ b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt @@ -292,4 +292,50 @@ class SleepRecordExtensionTest { ) assertTrue(SleepSessionRecord.STAGE_TYPE_SLEEPING != SleepSessionRecord.STAGE_TYPE_UNKNOWN) } + + @Test + fun `outward tail extension on 0-awake night preserves score and awake signal`() { + // Nov 16 shape (#148): 460m light/deep/rem with zero AWAKE blocks, extended +58m past end. + val stages = List(280) { SleepStage.LIGHT } + List(100) { SleepStage.DEEP } + List(80) { SleepStage.REM } + val ringOnly = ring(at(0, 14), stages) // 00:14..07:54 + val extended = editedRecordBlocks(ringOnly, at(0, 14), at(0, 14), at(8, 52))!! + + val without = SleepScore.calculate(session(ringOnly), ringOnly) + val withTail = SleepScore.calculate(session(extended), extended) + + assertEquals(0, without.awakePct) + assertEquals(0, withTail.awakePct) + assertEquals(without.deepPct, withTail.deepPct) + assertEquals(without.lightPct, withTail.lightPct) + assertEquals(without.score, withTail.score) + } + + @Test + fun `outward head extension on 0-awake night preserves score and awake signal`() { + val stages = List(280) { SleepStage.LIGHT } + List(100) { SleepStage.DEEP } + List(80) { SleepStage.REM } + val ringOnly = ring(at(0, 14), stages) + val extendedHead = editedRecordBlocks(ringOnly, at(0, 14), at(-1, 14), end(ringOnly))!! + + val without = SleepScore.calculate(session(ringOnly), ringOnly) + val withHead = SleepScore.calculate(session(extendedHead), extendedHead) + + assertEquals(0, withHead.awakePct) + assertEquals(without.deepPct, withHead.deepPct) + assertEquals(without.lightPct, withHead.lightPct) + assertEquals(without.score, withHead.score) + } + + @Test + fun `outward tail extension on night with awake blocks preserves awakePct and score`() { + val stages = List(250) { SleepStage.LIGHT } + List(100) { SleepStage.DEEP } + + List(20) { SleepStage.AWAKE } + List(90) { SleepStage.LIGHT } + val ringOnly = ring(at(0, 14), stages) + val extended = editedRecordBlocks(ringOnly, at(0, 14), at(0, 14), at(8, 52))!! + + val before = SleepScore.calculate(session(ringOnly), ringOnly) + val after = SleepScore.calculate(session(extended), extended) + + assertEquals(before.awakePct, after.awakePct) + assertEquals(before.score, after.score) + } } diff --git a/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt index 99d2c276..6d650b43 100644 --- a/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt +++ b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt @@ -1,6 +1,7 @@ package com.pulseloop.service import com.pulseloop.data.entity.ActivityBucketEntity +import com.pulseloop.data.entity.MeasurementEntity import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity import com.pulseloop.ring.SleepStage @@ -406,4 +407,109 @@ class SleepTailSuggestionTest { assertTrue(expired !in pruned) assertTrue(malformed !in pruned) } + + private fun hr(ts: Long, bpm: Double, source: String = "ring_history") = MeasurementEntity( + kindRaw = "HEART_RATE", + value = bpm, + unit = "bpm", + timestamp = ts, + sourceRaw = source, + ) + + @Test + fun `withHeartRateContext attaches single hourly reading inside gap and night average`() { + // Nov 16 example: ring stopped 07:54, Bedtime ended 08:52, hourly HR at 08:00 = 58, 09:00 = 104 (outside). + val blocks = ringBlocks(startAt = at(0, 14), durationMinutes = 460) // 00:14..07:54 + val s = session(blocks = blocks) + val base = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 52))), + lastFullSyncAt = at(9, 10), + )!! + + val enriched = SleepTailSuggestionDetector.withHeartRateContext( + suggestion = base, + sessionStartAt = s.startAt, + hrSamples = listOf( + hr(at(1, 0), 56.0), + hr(at(4, 0), 60.0), + hr(at(7, 0), 61.0), + hr(at(8, 0), 58.0), + hr(at(9, 0), 104.0), + ), + ) + + assertEquals(listOf(TailHeartRateReading(at(8, 0), 58)), enriched.gapHeartRates) + assertEquals(59, enriched.nightAvgHeartRate) + } + + @Test + fun `withHeartRateContext respects boundaries filters demo and invalid values and deduplicates per minute`() { + val blocks = ringBlocks(startAt = at(0, 14), durationMinutes = 460) // 00:14..07:54 + val s = session(blocks = blocks) + val base = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 52))), + lastFullSyncAt = at(9, 10), + )!! + + val enriched = SleepTailSuggestionDetector.withHeartRateContext( + suggestion = base, + sessionStartAt = s.startAt, + hrSamples = listOf( + // Exact ringEndedAt counts toward night avg, not gap. + hr(at(7, 54), 60.0), + // Exact suggestedEndAt is excluded from gap. + hr(at(8, 52), 95.0), + // Demo / mock and implausible values ignored. + hr(at(8, 10), 62.0, source = "demo"), + hr(at(8, 12), 63.0, source = "mock"), + hr(at(8, 15), 0.0), + hr(at(8, 20), 25.0), + hr(at(8, 25), 250.0), + // Same-minute duplicate keeps latest (08:30:40 -> 57 bpm). + hr(at(8, 30, 10), 61.0), + hr(at(8, 30, 40), 57.0), + ), + ) + + assertEquals(listOf(TailHeartRateReading(at(8, 30, 40), 57)), enriched.gapHeartRates) + assertEquals(60, enriched.nightAvgHeartRate) + } + + @Test + fun `withHeartRateContext sorts multiple gap readings ascending and handles empty night HR`() { + val blocks = ringBlocks(startAt = at(0, 14), durationMinutes = 460) // 00:14..07:54 + val s = session(blocks = blocks) + val base = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(8, 52))), + lastFullSyncAt = at(9, 10), + )!! + + val enriched = SleepTailSuggestionDetector.withHeartRateContext( + suggestion = base, + sessionStartAt = s.startAt, + hrSamples = listOf( + hr(at(8, 40), 64.0), + hr(at(8, 0), 58.0), + hr(at(8, 20), 59.0), + hr(at(8, 10), 57.0), + ), + ) + + assertEquals( + listOf( + TailHeartRateReading(at(8, 0), 58), + TailHeartRateReading(at(8, 10), 57), + TailHeartRateReading(at(8, 20), 59), + TailHeartRateReading(at(8, 40), 64), + ), + enriched.gapHeartRates, + ) + assertNull(enriched.nightAvgHeartRate) + } } From df0d34344a883ed4d870583aa6e5dc6fbe3104d1 Mon Sep 17 00:00:00 2001 From: Khoa Truong Date: Fri, 20 Nov 2026 04:43:48 -0800 Subject: [PATCH 3/3] Sleep: harden Bedtime tail prompt sync gate, bucket rules, HR dedup, and UI Address independent review findings across YCBT sync, tail detection, ViewModel concurrency, and Sleep UI: - Prevent partial YCBT syncs (syncSleepNow, querySleep, syncVitalsHistory) from emitting HistorySyncFinished so lastFullSyncAt only advances once SPORT and HEART history have synced too. - Require non-null lastFullSyncAt >= bedtimeEnd, intraday step-bucket support with family-aware bucket duration (1m JRing, 15m YCBT/Colmi), at least one aligned observable bucket inside the gap, and no deleted trailing phantom record in the gap. - Prefer primary/longest sleep session over daytime DND naps, check session overlaps through grid-rounded suggestedEndAt, serialize SleepViewModel rebuild() jobs to prevent dismissal resurrection or day/range races, deduplicate night HR per minute, exclude post-Bedtime HR, show raw bedtimeEndedAt in body copy, and use FlowRow for actions. --- .../main/java/com/pulseloop/data/dao/Daos.kt | 10 + .../com/pulseloop/ring/YCBTHistoryTransfer.kt | 10 +- .../java/com/pulseloop/ring/YCBTSyncEngine.kt | 10 +- .../pulseloop/service/SleepTailSuggestion.kt | 77 +++-- .../com/pulseloop/ui/screens/SleepScreen.kt | 7 +- .../com/pulseloop/ui/viewmodels/ViewModels.kt | 51 +++- .../pulseloop/data/MeasurementDeletionTest.kt | 7 + .../pulseloop/data/SleepRecordDeletionTest.kt | 7 + .../pulseloop/ring/YCBTHistoryTransferTest.kt | 48 ++++ .../service/SleepRecordExtensionTest.kt | 69 +++++ .../service/SleepTailSuggestionTest.kt | 272 +++++++++++++++++- 11 files changed, 525 insertions(+), 43 deletions(-) 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 ad73ae52..c8564232 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -201,6 +201,9 @@ interface ActivityBucketDao { @Query("SELECT * FROM activity_buckets WHERE date = :day ORDER BY startEpoch ASC") suspend fun byDay(day: Long): List + @Query("SELECT EXISTS(SELECT 1 FROM activity_buckets)") + suspend fun hasAny(): Boolean + /** Distinct past days that have synced buckets — the DataRepairs recompute scope. */ @Query("SELECT DISTINCT date FROM activity_buckets WHERE date < :day ORDER BY date ASC") suspend fun daysBefore(day: Long): List @@ -866,6 +869,13 @@ interface MeasurementDeletionDao { suspend fun isSleepRecordDeleted(dayStart: Long, recordStartAt: Long): Boolean = isDeleted(sleepRecordDeleteId(dayStart, recordStartAt)) + @Query( + "SELECT timestamp FROM measurement_deletions " + + "WHERE kindRaw = 'SLEEP_RECORD_DELETE' " + + "AND measurementId LIKE 'sleep:record:' || :dayStart || ':%'", + ) + suspend fun deletedSleepRecordStarts(dayStart: Long): List + companion object { /** The prefix `EventPersistenceSubscriber.historyMeasurementId` builds its stable ids from. * A measurement whose id starts with this is one the ring can hand us again. */ diff --git a/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt b/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt index ead919f4..b397443b 100644 --- a/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt +++ b/app/src/main/java/com/pulseloop/ring/YCBTHistoryTransfer.kt @@ -35,6 +35,7 @@ class YCBTHistoryTransfer( private var bufferCap = DEFAULT_BUFFER_CAP private var watchdogJob: Job? = null private var typeDeadline: Long? = null + private var emitFinishedOnComplete = true companion object { private const val DEFAULT_BUFFER_CAP = 64 * 1024 @@ -45,8 +46,9 @@ class YCBTHistoryTransfer( val isActive: Boolean get() = state != State.IDLE @Synchronized - fun start(types: List) { + fun start(types: List, isFullSync: Boolean = true) { if (isActive) return + emitFinishedOnComplete = isFullSync queue = types.filter { !unsupported.contains(it.queryKey) }.toMutableList() advance() } @@ -59,6 +61,7 @@ class YCBTHistoryTransfer( } if (additions.isEmpty()) return if (state == State.IDLE) { + emitFinishedOnComplete = true queue = additions.toMutableList() advance() } else { @@ -73,6 +76,7 @@ class YCBTHistoryTransfer( currentType = null queue.clear() buffer = ByteArray(0) + emitFinishedOnComplete = true } private fun advance(): List { @@ -83,7 +87,9 @@ class YCBTHistoryTransfer( if (queue.isEmpty()) { state = State.IDLE currentType = null - return listOf(RingDecodedEvent.HistorySyncFinished) + val shouldEmit = emitFinishedOnComplete + emitFinishedOnComplete = true + return if (shouldEmit) listOf(RingDecodedEvent.HistorySyncFinished) else emptyList() } val next = queue.removeAt(0) sendQuery(next) diff --git a/app/src/main/java/com/pulseloop/ring/YCBTSyncEngine.kt b/app/src/main/java/com/pulseloop/ring/YCBTSyncEngine.kt index e7c78ef2..1329f1ba 100644 --- a/app/src/main/java/com/pulseloop/ring/YCBTSyncEngine.kt +++ b/app/src/main/java/com/pulseloop/ring/YCBTSyncEngine.kt @@ -63,7 +63,7 @@ class YCBTSyncEngine( )) { writer?.enqueue(command) } - transfer.start(types = supportedHistoryTypes(HISTORY_TYPES)) + transfer.start(types = supportedHistoryTypes(HISTORY_TYPES), isFullSync = true) } @Synchronized @@ -111,22 +111,22 @@ class YCBTSyncEngine( // Ask for current cumulative activity before the slower multi-type history walk. Without // this, pull-to-refresh can leave steps stale until an unsolicited live push arrives. writer?.enqueue(encoder.enableLiveStatus()) - transfer.start(types = supportedHistoryTypes(HISTORY_TYPES)) + transfer.start(types = supportedHistoryTypes(HISTORY_TYPES), isFullSync = true) } @Synchronized override fun querySleep() { - transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP))) + transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)), isFullSync = false) } @Synchronized override fun syncVitalsHistory() { - transfer.start(types = supportedHistoryTypes(VITALS_TYPES)) + transfer.start(types = supportedHistoryTypes(VITALS_TYPES), isFullSync = false) } @Synchronized override fun syncSleepNow() { - transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP))) + transfer.start(types = supportedHistoryTypes(listOf(YCBTHistoryType.SLEEP)), isFullSync = false) } private fun supportedHistoryTypes(types: List): List = diff --git a/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt index 8774b4be..cbfa4ea9 100644 --- a/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt +++ b/app/src/main/java/com/pulseloop/service/SleepTailSuggestion.kt @@ -6,6 +6,7 @@ import com.pulseloop.data.entity.ActivityBucketEntity import com.pulseloop.data.entity.MeasurementEntity import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.ring.RingDeviceType import com.pulseloop.settings.QuietHoursPrefs import com.pulseloop.settings.ZenWindow import java.time.ZoneId @@ -49,12 +50,21 @@ object SleepTailSuggestionDetector { const val MIN_GAP_MINUTES = 15 const val MAX_GAP_MINUTES = MAX_OUTWARD_EXTENSION_MINUTES + /** Default 15-minute bucket size (YCBT, Colmi, RWfit JieLi); JRing emits 1-minute buckets. */ + const val DEFAULT_STEP_BUCKET_DURATION_MS = 15 * 60_000L + /** Activity buckets span 15 minutes from [ActivityBucketEntity.startEpoch]; a bucket starting * in the final 15 minutes before Bedtime turns off straddles waking up and ending Bedtime. */ - const val STEP_BUCKET_TAIL_MARGIN_MS = 15 * 60_000L + const val STEP_BUCKET_TAIL_MARGIN_MS = DEFAULT_STEP_BUCKET_DURATION_MS private const val MINUTE_MS = 60_000L + fun stepBucketDurationMsFor(deviceType: RingDeviceType?): Long = + if (deviceType == RingDeviceType.JRING) MINUTE_MS else DEFAULT_STEP_BUCKET_DURATION_MS + + fun supportsIntradayStepBuckets(deviceType: RingDeviceType?): Boolean = + deviceType != RingDeviceType.CRP && deviceType != RingDeviceType.LUCK_RING + fun detect( daySessions: List, dayBlocks: Map>, @@ -64,17 +74,23 @@ object SleepTailSuggestionDetector { isDismissed: (sessionDate: Long, recordStartAt: Long) -> Boolean, isEdited: (sessionDate: Long, recordStartAt: Long) -> Boolean, zone: ZoneId = ZoneId.systemDefault(), + hasIntradayStepBuckets: Boolean = true, + stepBucketDurationMs: Long = DEFAULT_STEP_BUCKET_DURATION_MS, + hasDeletedRecordInGap: (sessionDate: Long, gapStart: Long, gapEnd: Long) -> Boolean = { _, _, _ -> false }, ): SleepTailSuggestion? { - if (bedtimeWindows.isNullOrEmpty() || daySessions.isEmpty()) return null + if (!hasIntradayStepBuckets || bedtimeWindows.isNullOrEmpty() || daySessions.isEmpty()) return null val realSessions = daySessions .filterNot { DemoDataPolicy.isDemo(it.sourceRaw) } - .sortedBy { it.endAt } if (realSessions.isEmpty()) return null - // Check from latest session backward (an afternoon nap won't match a morning Bedtime tail, - // while an overlapping later morning session blocks extending an earlier one across it). - for (session in realSessions.asReversed()) { + val bucketMs = stepBucketDurationMs.coerceAtLeast(MINUTE_MS) + // Prefer the longest/primary session on days that also hold a short afternoon nap. + val candidates = realSessions.sortedWith( + compareByDescending { it.totalMinutes }.thenByDescending { it.endAt }, + ) + + for (session in candidates) { val runs = sleepRecordRuns(dayBlocks[session.id].orEmpty()) if (runs.isEmpty()) continue val lastRun = runs.last() @@ -94,26 +110,28 @@ object SleepTailSuggestionDetector { ?: continue val windowEnd = matchingWindow.end ?: continue - // Never extend across another recorded session of the same day. - val overlapsOtherSession = realSessions.any { other -> - other.id != session.id && other.endAt > lastRun.endAt && other.startAt < windowEnd - } - if (overlapsOtherSession) continue + // Respect a user's earlier deletion of a trailing phantom record inside Bedtime. + if (hasDeletedRecordInGap(session.date, lastRun.endAt, windowEnd)) continue - // Wait for a full sync after Bedtime turned off so morning steps and any second ring - // sleep record have had a chance to import. - if (lastFullSyncAt != null && lastFullSyncAt < windowEnd) continue + // Require a completed full sync after Bedtime turned off so morning step buckets and + // any second sleep record have had a chance to import. + if (lastFullSyncAt == null || lastFullSyncAt < windowEnd) continue val rawGapMinutes = ((windowEnd - lastRun.endAt) / MINUTE_MS).toInt() if (rawGapMinutes < MIN_GAP_MINUTES || rawGapMinutes > MAX_GAP_MINUTES) continue - // Any step bucket wholly inside (lastRun.endAt .. windowEnd] shows real wakefulness. - // Buckets starting before lastRun.endAt belong to the brief get-up when the ring - // stopped; buckets straddling windowEnd capture turning Bedtime off. + // At least one full aligned bucket must sit inside [lastRun.endAt, windowEnd] so the + // prompt never claims "with no steps" across a gap too short/misaligned to observe any. + val firstAlignedBucket = Math.floorDiv(lastRun.endAt + bucketMs - 1L, bucketMs) * bucketMs + if (firstAlignedBucket + bucketMs > windowEnd) continue + + // Any non-zero step bucket wholly inside [lastRun.endAt, windowEnd] shows wakefulness; + // buckets starting before lastRun.endAt belong to the brief get-up when the ring stopped + // and buckets straddling windowEnd capture turning Bedtime off. val hasStepsInGap = stepBuckets.any { b -> b.steps > 0 && b.startEpoch >= lastRun.endAt && - b.startEpoch + STEP_BUCKET_TAIL_MARGIN_MS <= windowEnd + b.startEpoch + bucketMs <= windowEnd } if (hasStepsInGap) continue @@ -127,6 +145,14 @@ object SleepTailSuggestionDetector { val suggestedEndAt = clampEndPick(windowEnd, limits).at if (suggestedEndAt <= lastRun.endAt) continue + // Never extend across another recorded session of the same day (including up to + // +59s grid rounding past windowEnd). + val extensionEnd = maxOf(windowEnd, suggestedEndAt) + val overlapsOtherSession = realSessions.any { other -> + other.id != session.id && other.endAt > lastRun.endAt && other.startAt < extensionEnd + } + if (overlapsOtherSession) continue + val suggestedGapMinutes = ((suggestedEndAt - lastRun.endAt) / MINUTE_MS).toInt() if (suggestedGapMinutes < MIN_GAP_MINUTES) continue @@ -148,8 +174,9 @@ object SleepTailSuggestionDetector { private const val MAX_VALID_BPM = 220 /** - * Enrich [suggestion] with plausible non-demo heart-rate readings inside `(ringEndedAt, - * suggestedEndAt)` and the night's mean HR across `sessionStartAt..ringEndedAt` (#148). + * Enrich [suggestion] with plausible non-demo heart-rate readings strictly before Bedtime ended + * (`ringEndedAt < ts < min(suggestedEndAt, bedtimeEndedAt)`) and the minute-deduplicated mean + * HR across `sessionStartAt..ringEndedAt` (#148). */ fun withHeartRateContext( suggestion: SleepTailSuggestion, @@ -158,23 +185,29 @@ object SleepTailSuggestionDetector { ): SleepTailSuggestion { val plausible = hrSamples.mapNotNull { sample -> if (DemoDataPolicy.isDemo(sample.sourceRaw)) return@mapNotNull null - if (sample.value.isNaN()) return@mapNotNull null + if (!sample.value.isFinite()) return@mapNotNull null val bpm = sample.value.roundToInt() if (bpm !in MIN_VALID_BPM..MAX_VALID_BPM) return@mapNotNull null sample.timestamp to bpm } + val gapEnd = minOf(suggestion.suggestedEndAt, suggestion.bedtimeEndedAt) val gapReadings = plausible .asSequence() - .filter { (ts, _) -> ts > suggestion.ringEndedAt && ts < suggestion.suggestedEndAt } + .filter { (ts, _) -> ts > suggestion.ringEndedAt && ts < gapEnd } .sortedBy { (ts, _) -> ts } .associateBy { (ts, _) -> ts / MINUTE_MS } .values .map { (ts, bpm) -> TailHeartRateReading(timestamp = ts, bpm = bpm) } .sortedBy { it.timestamp } + // Deduplicate per minute before averaging so 1 Hz live HR streams do not outweigh hourly ring samples. val nightValues = plausible + .asSequence() .filter { (ts, _) -> ts in sessionStartAt..suggestion.ringEndedAt } + .sortedBy { (ts, _) -> ts } + .associateBy { (ts, _) -> ts / MINUTE_MS } + .values .map { (_, bpm) -> bpm } val nightAvg = if (nightValues.isEmpty()) null else nightValues.average().roundToInt() 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 94ce34ca..1b3ef82d 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SleepScreen.kt @@ -1295,6 +1295,7 @@ private fun SleepRecordsCard( * absent (issue #148). Hands off to [SleepRecordEditDialog] pre-filled with the suggested end time * rather than mutating the record silently. */ +@OptIn(ExperimentalLayoutApi::class) @Composable private fun SleepTailSuggestionCard( suggestion: com.pulseloop.service.SleepTailSuggestion, @@ -1303,6 +1304,7 @@ private fun SleepTailSuggestionCard( ) { val shape = RoundedCornerShape(18.dp) val endLabel = SleepFormat.clockTime(suggestion.suggestedEndAt) + val bedtimeEndLabel = SleepFormat.clockTime(suggestion.bedtimeEndedAt) Column( Modifier .fillMaxWidth() @@ -1322,7 +1324,7 @@ private fun SleepTailSuggestionCard( stringResource( R.string.sleep_tail_body, SleepFormat.clockTime(suggestion.ringEndedAt), - endLabel, + bedtimeEndLabel, ), fontSize = 13.sp, color = PulseColors.textSecondary, @@ -1357,9 +1359,10 @@ private fun SleepTailSuggestionCard( color = PulseColors.textMuted, ) } - Row( + FlowRow( modifier = Modifier.padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), ) { Button(onClick = onExtend) { Text(stringResource(R.string.sleep_tail_extend, endLabel)) 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 4957f064..57d72ec8 100644 --- a/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt +++ b/app/src/main/java/com/pulseloop/ui/viewmodels/ViewModels.kt @@ -263,15 +263,29 @@ class SleepViewModel( private val _state = MutableStateFlow(SleepState()) val state: StateFlow = _state.asStateFlow() + private var rebuildJob: kotlinx.coroutines.Job? = null + + private fun scheduleRebuild(range: SleepRangeKey = _state.value.range): kotlinx.coroutines.Job { + rebuildJob?.cancel() + val job = viewModelScope.launch { + try { + rebuild(range) + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (_: Exception) {} + } + rebuildJob = job + return job + } fun setRange(range: SleepRangeKey) { // Returning to Day from an aggregate range always lands on today, not a stale offset. _state.update { it.copy(range = range, dayOffset = if (range == SleepRangeKey.DAY) 0 else it.dayOffset) } - viewModelScope.launch { try { rebuild(range) } catch (_: Exception) {} } + scheduleRebuild(range) } fun refreshReferenceNight() { - viewModelScope.launch { try { rebuild(_state.value.range) } catch (_: Exception) {} } + scheduleRebuild(_state.value.range) } init { @@ -286,7 +300,7 @@ class SleepViewModel( db.deviceDao().currentFlow().map { it?.lastFullSyncAt }.distinctUntilChanged(), ) { sessions, _, _ -> sessions }.collect { sessions -> _state.update { it.copy(recentSessions = sessions) } - try { rebuild(_state.value.range) } catch (_: Exception) {} + scheduleRebuild(_state.value.range) } } } @@ -392,7 +406,16 @@ class SleepViewModel( val buckets = bucketDays.flatMap { day -> try { db.activityBucketDao().byDay(day) } catch (_: Exception) { emptyList() } } - val lastFullSyncAt = try { db.deviceDao().current()?.lastFullSyncAt } catch (_: Exception) { null } + val device = try { db.deviceDao().current() } catch (_: Exception) { null } + val lastFullSyncAt = device?.lastFullSyncAt + val hasIntradayBuckets = + com.pulseloop.service.SleepTailSuggestionDetector.supportsIntradayStepBuckets(device?.deviceType) && + (try { db.activityBucketDao().hasAny() } catch (_: Exception) { false }) + val bucketDurationMs = + com.pulseloop.service.SleepTailSuggestionDetector.stepBucketDurationMsFor(device?.deviceType) + val deletedStartsByDay = daySessions.map { it.date }.distinct().associateWith { day -> + try { db.measurementDeletionDao().deletedSleepRecordStarts(day) } catch (_: Exception) { emptyList() } + } val editedRecords = daySessions.mapNotNull { s -> val lastRun = com.pulseloop.service.sleepRecordRuns(dayBlocks[s.id].orEmpty()).lastOrNull() ?: return@mapNotNull null @@ -409,6 +432,11 @@ class SleepViewModel( lastFullSyncAt = lastFullSyncAt, isDismissed = isTailDismissed, isEdited = { date, recordStartAt -> (date to recordStartAt) in editedRecords }, + hasIntradayStepBuckets = hasIntradayBuckets, + stepBucketDurationMs = bucketDurationMs, + hasDeletedRecordInGap = { date, gapStart, gapEnd -> + deletedStartsByDay[date].orEmpty().any { ts -> ts > gapStart && ts < gapEnd } + }, ) rawSuggestion?.let { suggestion -> val hrStart = daySessions.firstOrNull { it.id == suggestion.sessionId }?.startAt @@ -431,8 +459,10 @@ class SleepViewModel( null } - _state.update { - it.copy( + val activeTail = tailSuggestion?.takeUnless { isTailDismissed(it.sessionDate, it.run.recordStartAt) } + _state.update { current -> + if (current.range != range || current.dayOffset != offset) current + else current.copy( lastNight = night, lastNightBlocks = nightBlocks, score = scoreResult, @@ -451,7 +481,7 @@ class SleepViewModel( goalMinutes = goal, daySummary = daySummary, rangeSummary = rangeSummary, - tailSuggestion = tailSuggestion, + tailSuggestion = activeTail, ) } } @@ -480,7 +510,7 @@ class SleepViewModel( suspend fun deleteSleepRecord(sessionId: String, recordStartAt: Long): Boolean = try { val removed = com.pulseloop.data.SleepRecordDeletion.delete(db, sessionId, recordStartAt, gapBridge()) - if (removed) rebuild(_state.value.range) + if (removed) scheduleRebuild(_state.value.range).join() removed } catch (_: Exception) { false } @@ -495,13 +525,14 @@ class SleepViewModel( ): Boolean = try { val updated = com.pulseloop.data.SleepRecordDeletion.edit(db, sessionId, recordStartAt, newStartAt, newEndAt, gapBridge()) - if (updated) rebuild(_state.value.range) + if (updated) scheduleRebuild(_state.value.range).join() updated } catch (_: Exception) { false } /** Persist dismissal of the Bedtime sleep-tail prompt for this ring record (issue #148). */ fun dismissTailSuggestion(sessionDate: Long, recordStartAt: Long) { onDismissTail(sessionDate, recordStartAt) + rebuildJob?.cancel() _state.update { state -> val current = state.tailSuggestion if (current != null && current.sessionDate == sessionDate && current.run.recordStartAt == recordStartAt) { @@ -525,7 +556,7 @@ class SleepViewModel( val clamped = target.coerceIn(0, _state.value.maxDayOffset) if (clamped == _state.value.dayOffset) return _state.update { it.copy(dayOffset = clamped) } - viewModelScope.launch { try { rebuild(_state.value.range) } catch (_: Exception) {} } + scheduleRebuild(_state.value.range) } } diff --git a/app/src/test/java/com/pulseloop/data/MeasurementDeletionTest.kt b/app/src/test/java/com/pulseloop/data/MeasurementDeletionTest.kt index 485dffcf..efeaaf48 100644 --- a/app/src/test/java/com/pulseloop/data/MeasurementDeletionTest.kt +++ b/app/src/test/java/com/pulseloop/data/MeasurementDeletionTest.kt @@ -37,6 +37,13 @@ class MeasurementDeletionTest { override suspend fun insertAll(rows: List) { rows.forEach { this.rows[it.measurementId] = it } } + override suspend fun deletedSleepRecordStarts(dayStart: Long): List = + rows.values + .filter { + it.kindRaw == MeasurementDeletionDao.SLEEP_RECORD_DELETE_KIND && + it.measurementId.startsWith("${MeasurementDeletionDao.SLEEP_RECORD_DELETE_PREFIX}$dayStart:") + } + .map { it.timestamp } } private fun measurement(id: String, kind: MeasurementKind, timestamp: Long, source: String) = diff --git a/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt b/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt index 22e085cc..1b06d6ad 100644 --- a/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt +++ b/app/src/test/java/com/pulseloop/data/SleepRecordDeletionTest.kt @@ -32,6 +32,13 @@ class SleepRecordDeletionTest { override suspend fun insertAll(rows: List) { rows.forEach { this.rows[it.measurementId] = it } } + override suspend fun deletedSleepRecordStarts(dayStart: Long): List = + rows.values + .filter { + it.kindRaw == MeasurementDeletionDao.SLEEP_RECORD_DELETE_KIND && + it.measurementId.startsWith("${MeasurementDeletionDao.SLEEP_RECORD_DELETE_PREFIX}$dayStart:") + } + .map { it.timestamp } } // The scenario from the issue: a record opened 23:08 that is really sofa time, tombstoned by diff --git a/app/src/test/java/com/pulseloop/ring/YCBTHistoryTransferTest.kt b/app/src/test/java/com/pulseloop/ring/YCBTHistoryTransferTest.kt index 184b80ce..16f35304 100644 --- a/app/src/test/java/com/pulseloop/ring/YCBTHistoryTransferTest.kt +++ b/app/src/test/java/com/pulseloop/ring/YCBTHistoryTransferTest.kt @@ -457,4 +457,52 @@ class YCBTHistoryTransferTest { assertEquals(listOf(RingDecodedEvent.HistorySyncFinished), emitted) assertFalse(transfer.isActive) } + + @Test + fun `syncSleepNow querySleep and syncVitalsHistory do not emit HistorySyncFinished`() = runBlocking { + val emitted = mutableListOf() + val writer = FakeWriter() + val transfer = YCBTHistoryTransfer( + writer = writer, + inactivitySeconds = 0.05, + absoluteCapSeconds = 0.1, + onOutOfBandEvents = { emitted.addAll(it) }, + ) + val engine = YCBTSyncEngine(writer = writer, transfer = transfer) + + // Sleep-only sync draining normally via no-data header must not stamp lastFullSyncAt. + engine.syncSleepNow() + val drainEvents = mutableListOf() + while (true) { + val query = writer.sent.lastOrNull { it.size == 2 && it[0] == 0x05.toByte() } ?: break + writer.sent.clear() + drainEvents += transfer.handle(cmd = query[1].toInt() and 0xFF, payload = byteArrayOf(0x00)) + } + assertTrue(drainEvents.none { it is RingDecodedEvent.HistorySyncFinished }) + assertTrue(emitted.none { it is RingDecodedEvent.HistorySyncFinished }) + + // querySleep timing out via watchdog must also not emit HistorySyncFinished. + engine.querySleep() + delay(200) + assertFalse(transfer.isActive) + assertTrue(emitted.none { it is RingDecodedEvent.HistorySyncFinished }) + + // syncVitalsHistory draining normally must not emit HistorySyncFinished. + engine.syncVitalsHistory() + while (true) { + val query = writer.sent.lastOrNull { it.size == 2 && it[0] == 0x05.toByte() } ?: break + writer.sent.clear() + drainEvents += transfer.handle(cmd = query[1].toInt() and 0xFF, payload = byteArrayOf(0x00)) + } + assertTrue(drainEvents.none { it is RingDecodedEvent.HistorySyncFinished }) + + // Full sync (refresh) restores HistorySyncFinished emission. + engine.refresh() + while (true) { + val query = writer.sent.lastOrNull { it.size == 2 && it[0] == 0x05.toByte() } ?: break + writer.sent.clear() + drainEvents += transfer.handle(cmd = query[1].toInt() and 0xFF, payload = byteArrayOf(0x00)) + } + assertEquals(listOf(RingDecodedEvent.HistorySyncFinished), drainEvents) + } } diff --git a/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt index fd019391..ffae60e4 100644 --- a/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt +++ b/app/src/test/java/com/pulseloop/service/SleepRecordExtensionTest.kt @@ -338,4 +338,73 @@ class SleepRecordExtensionTest { assertEquals(before.awakePct, after.awakePct) assertEquals(before.score, after.score) } + + @Test + fun `multi-record night with both interior gap and outward tail preserves score`() { + val ringOnly = a + b + // Keep the 72m interior gap between `a` and `b`, and extend `b`'s tail outward by 40m. + val withTail = a + editedRecordBlocks(b, bStart, bStart, end(b) + 40 * 60_000L)!! + + val before = SleepScore.calculate(session(ringOnly), ringOnly) + val after = SleepScore.calculate(session(withTail), withTail) + + assertEquals(before.awakePct, after.awakePct) + assertEquals(before.deepPct, after.deepPct) + assertEquals(before.lightPct, after.lightPct) + assertEquals(before.score, after.score) + } + + @Test + fun `collapseByDay combining outward-extended night and afternoon nap preserves score`() { + val stages = List(280) { SleepStage.LIGHT } + List(100) { SleepStage.DEEP } + List(80) { SleepStage.REM } + val nightRingOnly = ring(at(0, 14), stages) + val nightExtended = editedRecordBlocks(nightRingOnly, at(0, 14), at(0, 14), at(8, 52))!! + val nap = ring(at(14, 0), List(45) { SleepStage.LIGHT }).map { it.copy(sessionId = "nap") } + + val collapsedRing = SleepInsights.collapseByDay( + listOf(session(nightRingOnly), session(nap).copy(id = "nap")), + ) { id -> if (id == "nap") nap else nightRingOnly }.single() + val collapsedExtended = SleepInsights.collapseByDay( + listOf(session(nightExtended), session(nap).copy(id = "nap")), + ) { id -> if (id == "nap") nap else nightExtended }.single() + + val before = SleepScore.calculate(collapsedRing.session, collapsedRing.blocks) + val after = SleepScore.calculate(collapsedExtended.session, collapsedExtended.blocks) + + assertEquals(before.deepPct, after.deepPct) + assertEquals(before.lightPct, after.lightPct) + assertEquals(before.score, after.score) + } + + @Test + fun `simultaneous head-trim and tail-extend matches trimmed-only score`() { + val trimmedOnly = editedRecordBlocks(b, bStart, bStart + 10 * 60_000L, end(b))!! + val trimmedAndExtended = editedRecordBlocks(b, bStart, bStart + 10 * 60_000L, end(b) + 35 * 60_000L)!! + + val expected = SleepScore.calculate(session(trimmedOnly), trimmedOnly) + val actual = SleepScore.calculate(session(trimmedAndExtended), trimmedAndExtended) + + assertEquals(expected.deepPct, actual.deepPct) + assertEquals(expected.lightPct, actual.lightPct) + assertEquals(expected.score, actual.score) + } + + @Test + fun `legacy startAt zero measured blocks with ADDED fall back cleanly to session spanMinutes`() { + val legacyBlocks = List(400) { + SleepStageBlockEntity(sessionId = "s", startAt = 0L, startMinute = 0, durationMinutes = 1, stageRaw = SleepStage.LIGHT.name) + } + SleepStageBlockEntity(sessionId = "s", startAt = 0L, startMinute = 0, durationMinutes = 20, stageRaw = SleepStage.ADDED.name) + val s = SleepSessionEntity( + id = "s", + date = wakingDay, + startAt = at(0, 0), + endAt = at(7, 0), + totalMinutes = 420, + score = null, + ) + + val result = SleepScore.calculate(s, legacyBlocks) + assertTrue(result.score in 0..100) + assertEquals(0, result.awakePct) + } } diff --git a/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt index 6d650b43..3981110f 100644 --- a/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt +++ b/app/src/test/java/com/pulseloop/service/SleepTailSuggestionTest.kt @@ -4,9 +4,11 @@ import com.pulseloop.data.entity.ActivityBucketEntity import com.pulseloop.data.entity.MeasurementEntity import com.pulseloop.data.entity.SleepSessionEntity import com.pulseloop.data.entity.SleepStageBlockEntity +import com.pulseloop.ring.RingDeviceType import com.pulseloop.ring.SleepStage import com.pulseloop.settings.ZenWindow import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue @@ -203,7 +205,7 @@ class SleepTailSuggestionTest { } @Test - fun `full sync must be at or after Bedtime end unless null`() { + fun `full sync must be present and at or after Bedtime end`() { val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) // -> 07:48 val s = session(blocks = blocks) val windows = listOf(ZenWindow(start = at(1, 0), end = at(9, 27))) @@ -224,7 +226,7 @@ class SleepTailSuggestionTest { lastFullSyncAt = at(9, 27), ), ) - assertNotNull( + assertNull( detect( listOf(s), mapOf(s.id to blocks), @@ -512,4 +514,270 @@ class SleepTailSuggestionTest { ) assertNull(enriched.nightAvgHeartRate) } + + @Test + fun `intraday step bucket support and bucket duration follow ring family`() { + assertFalse(SleepTailSuggestionDetector.supportsIntradayStepBuckets(RingDeviceType.CRP)) + assertFalse(SleepTailSuggestionDetector.supportsIntradayStepBuckets(RingDeviceType.LUCK_RING)) + assertTrue(SleepTailSuggestionDetector.supportsIntradayStepBuckets(RingDeviceType.YCBT)) + assertTrue(SleepTailSuggestionDetector.supportsIntradayStepBuckets(RingDeviceType.COLMI_R02)) + assertTrue(SleepTailSuggestionDetector.supportsIntradayStepBuckets(RingDeviceType.JRING)) + + assertEquals(60_000L, SleepTailSuggestionDetector.stepBucketDurationMsFor(RingDeviceType.JRING)) + assertEquals(15 * 60_000L, SleepTailSuggestionDetector.stepBucketDurationMsFor(RingDeviceType.YCBT)) + + val blocks = ringBlocks(startAt = at(2, 59), durationMinutes = 289) + val s = session(blocks = blocks) + assertNull( + SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf(s.id to blocks), + bedtimeWindows = listOf(ZenWindow(start = at(1, 0), end = at(9, 27))), + stepBuckets = emptyList(), + lastFullSyncAt = at(9, 30), + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = zone, + hasIntradayStepBuckets = false, + ), + ) + } + + @Test + fun `unaligned 28m gap suppresses on 15m buckets but fires and checks steps on 1m JRing buckets`() { + val blocks = ringBlocks(startAt = at(0, 1), durationMinutes = 420) // 00:01..07:01 + val s = session(blocks = blocks) + val windows = listOf(ZenWindow(start = at(0, 0), end = at(7, 29))) // first aligned 15m slot 07:15..07:30 > 07:29 + + assertNull( + SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf(s.id to blocks), + bedtimeWindows = windows, + stepBuckets = emptyList(), + lastFullSyncAt = at(8, 0), + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = zone, + stepBucketDurationMs = 15 * 60_000L, + ), + ) + + val jringPrompt = SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf(s.id to blocks), + bedtimeWindows = windows, + stepBuckets = emptyList(), + lastFullSyncAt = at(8, 0), + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = zone, + stepBucketDurationMs = 60_000L, + ) + assertNotNull(jringPrompt) + assertEquals(28, jringPrompt!!.gapMinutes) + + assertNull( + SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf(s.id to blocks), + bedtimeWindows = windows, + stepBuckets = listOf(ActivityBucketEntity(startEpoch = at(7, 25), date = wakingDay, steps = 8)), + lastFullSyncAt = at(8, 0), + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = zone, + stepBucketDurationMs = 60_000L, + ), + ) + } + + @Test + fun `midnight crossing sleep in non-UTC timezone and spring-forward DST fires cleanly`() { + val la = ZoneId.of("America/Los_Angeles") + val dstWakingDate = ZonedDateTime.of(2026, 3, 8, 0, 0, 0, 0, la) + val dstDayKey = dstWakingDate.toInstant().toEpochMilli() + val sleepStart = ZonedDateTime.of(2026, 3, 7, 23, 15, 0, 0, la).toInstant().toEpochMilli() + val ringStop = ZonedDateTime.of(2026, 3, 8, 6, 58, 0, 0, la).toInstant().toEpochMilli() + val bedtimeStart = ZonedDateTime.of(2026, 3, 7, 22, 30, 0, 0, la).toInstant().toEpochMilli() + val bedtimeEnd = ZonedDateTime.of(2026, 3, 8, 7, 35, 0, 0, la).toInstant().toEpochMilli() + val durationMin = ((ringStop - sleepStart) / 60_000L).toInt() // 403 elapsed min across spring-forward + + val blocks = ringBlocks(startAt = sleepStart, durationMinutes = durationMin) + val s = SleepSessionEntity( + id = "dst", + date = dstDayKey, + startAt = sleepStart, + endAt = ringStop, + totalMinutes = durationMin, + sourceRaw = "ring", + ) + + val suggestion = SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf(s.id to blocks), + bedtimeWindows = listOf(ZenWindow(start = bedtimeStart, end = bedtimeEnd)), + stepBuckets = emptyList(), + lastFullSyncAt = bedtimeEnd + 60_000L, + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = la, + ) + + assertNotNull(suggestion) + assertEquals(ringStop, suggestion!!.ringEndedAt) + assertEquals(bedtimeEnd, suggestion.suggestedEndAt) + assertEquals(37, suggestion.gapMinutes) + } + + @Test + fun `zero-step bucket does not suppress while bucket starting at ringEndedAt suppresses and non-spanning window is ignored`() { + val blocks = ringBlocks(startAt = at(0, 0), durationMinutes = 420) // 00:00..07:00 + val s = session(blocks = blocks) + val windows = listOf(ZenWindow(start = at(0, 0), end = at(7, 30))) + + // Zero-step row does not count as activity. + assertNotNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = windows, + buckets = listOf(ActivityBucketEntity(startEpoch = at(7, 15), date = wakingDay, steps = 0)), + lastFullSyncAt = at(8, 0), + ), + ) + + // Exact boundary b.startEpoch == lastRun.endAt (07:00..07:15) inside [07:00, 07:30] suppresses. + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = windows, + buckets = listOf(ActivityBucketEntity(startEpoch = at(7, 0), date = wakingDay, steps = 10)), + lastFullSyncAt = at(8, 0), + ), + ) + + // Window starting after lastRun.endAt or ending right at lastRun.endAt never triggers. + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(7, 1), end = at(7, 30))), + lastFullSyncAt = at(8, 0), + ), + ) + assertNull( + detect( + listOf(s), + mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = at(7, 0))), + lastFullSyncAt = at(8, 0), + ), + ) + } + + @Test + fun `overnight Bedtime prompt beats afternoon nap inside daytime DND`() { + val nightBlocks = ringBlocks("night", startAt = at(0, 14), durationMinutes = 460) // 00:14..07:54 + val napBlocks = ringBlocks("nap", startAt = at(14, 0), durationMinutes = 60) // 14:00..15:00 + val night = session("night", nightBlocks) + val nap = session("nap", napBlocks) + + val suggestion = detect( + sessions = listOf(night, nap), + blocksBySession = mapOf("night" to nightBlocks, "nap" to napBlocks), + windows = listOf( + ZenWindow(start = at(0, 0), end = at(8, 52)), + ZenWindow(start = at(13, 50), end = at(15, 30)), + ), + lastFullSyncAt = at(16, 0), + ) + + assertNotNull(suggestion) + assertEquals("night", suggestion!!.sessionId) + assertEquals(at(8, 52), suggestion.suggestedEndAt) + } + + @Test + fun `deleted trailing phantom record inside Bedtime suppresses extension prompt`() { + val rec1 = ringBlocks("s1", startAt = at(0, 30), durationMinutes = 360) // 00:30..06:30 + val s = session("s1", rec1) + + assertNull( + SleepTailSuggestionDetector.detect( + daySessions = listOf(s), + dayBlocks = mapOf("s1" to rec1), + bedtimeWindows = listOf(ZenWindow(start = at(0, 0), end = at(8, 15))), + stepBuckets = emptyList(), + lastFullSyncAt = at(8, 30), + isDismissed = { _, _ -> false }, + isEdited = { _, _ -> false }, + zone = zone, + hasDeletedRecordInGap = { _, gapStart, gapEnd -> at(7, 0) in (gapStart + 1)..(gapEnd - 1) }, + ), + ) + } + + @Test + fun `120m gap with sub-minute remainder keeps raw bedtimeEndedAt while clamping suggestedEndAt`() { + val blocks = ringBlocks(startAt = at(0, 14, 50), durationMinutes = 460) // 00:14:50..07:54:50 + val s = session(blocks = blocks) + val windowEnd = at(9, 55, 10) // rawDiff = 120m 20s -> rawGapMinutes = 120 + + val suggestion = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = windowEnd)), + lastFullSyncAt = windowEnd + 60_000L, + ) + + assertNotNull(suggestion) + assertEquals(windowEnd, suggestion!!.bedtimeEndedAt) + assertEquals(at(9, 54, 50), suggestion.suggestedEndAt) + assertEquals(120, suggestion.gapMinutes) + } + + @Test + fun `withHeartRateContext filters non-finite enforces 30-220 deduplicates 1Hz night burst and excludes post-bedtime`() { + val blocks = ringBlocks(startAt = at(0, 14, 23), durationMinutes = 460) // 00:14:23..07:54:23 + val s = session(blocks = blocks) + val windowEnd = at(8, 50, 10) + // grid-snapped suggestedEndAt = 08:50:23 > bedtimeEndedAt (08:50:10). + val base = detect( + sessions = listOf(s), + blocksBySession = mapOf(s.id to blocks), + windows = listOf(ZenWindow(start = at(0, 0), end = windowEnd)), + lastFullSyncAt = at(9, 10), + )!! + + val burstMinute = (0 until 60).map { sec -> hr(at(4, 0, sec), 80.0, source = "live") } + val enriched = SleepTailSuggestionDetector.withHeartRateContext( + suggestion = base, + sessionStartAt = s.startAt, + hrSamples = burstMinute + listOf( + hr(at(1, 0), 56.0), + hr(at(2, 0), 56.0), + hr(at(3, 0), 56.0), + hr(at(5, 0), Double.NaN), + hr(at(5, 5), Double.POSITIVE_INFINITY), + hr(at(5, 10), Double.NEGATIVE_INFINITY), + hr(at(8, 0), 29.4), // rounds to 29 -> out + hr(at(8, 5), 30.0), // exact min -> in + hr(at(8, 15), 220.0), // exact max -> in + hr(at(8, 25), 220.6), // rounds to 221 -> out + hr(at(8, 50, 15), 99.0), // between bedtimeEndedAt (:10) and suggestedEndAt (:23) -> out! + ), + ) + + assertEquals( + listOf( + TailHeartRateReading(at(8, 5), 30), + TailHeartRateReading(at(8, 15), 220), + ), + enriched.gapHeartRates, + ) + // 60 burst samples at 04:00 collapse to 1 sample (80), averaged equally with 3x 56 -> (80+56*3)/4 = 62. + assertEquals(62, enriched.nightAvgHeartRate) + } }