diff --git a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt index d9cadb32..461cf267 100644 --- a/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt +++ b/app/src/main/java/com/pulseloop/service/LiveWorkoutManager.kt @@ -52,6 +52,13 @@ class LiveWorkoutManager( init { polling.onPollCompleted = { refreshNotification() } + // A workout left running by a process that died (update install, memory, crash) is + // closed at its last recorded moment, so it shows on the Activity tab (WorkoutRecovery). + val upAt = System.currentTimeMillis() + scope.launch { + runCatching { WorkoutRecovery.recover(db, startedBefore = upAt) } + .onFailure { android.util.Log.w("LiveWorkoutManager", "Workout recovery failed: ${it.message}") } + } // Notification actions (pause/resume/finish) arrive through the bus — the service has no // access to the real workout logic, so it posts and we apply (iOS App Group pattern). scope.launch { @@ -180,9 +187,14 @@ class LiveWorkoutManager( totalPauseSeconds = session.totalPauseSeconds + pauseCarry, updatedAt = now, ) - val summarized = ActivityAggregates.recompute(db, finished) + // Saved as finished first: if the summary below fails, the workout still shows on the + // Activity tab (with its duration) instead of staying "recording" for good. + db.activitySessionDao().upsert(finished) + val summarized = runCatching { ActivityAggregates.recompute(db, finished) } + .onFailure { android.util.Log.w("LiveWorkoutManager", "Workout summary failed: ${it.message}") } + .getOrDefault(finished) db.activitySessionDao().upsert(summarized) - ActivityRollup.credit(db, summarized) + runCatching { ActivityRollup.credit(db, summarized) } coordinator.stopWorkoutHeartRate() finishForegroundService(summarized) _state.value = WorkoutState(finishedSessionId = summarized.id) diff --git a/app/src/main/java/com/pulseloop/service/WorkoutRecovery.kt b/app/src/main/java/com/pulseloop/service/WorkoutRecovery.kt new file mode 100644 index 00000000..2b912d01 --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/WorkoutRecovery.kt @@ -0,0 +1,69 @@ +package com.pulseloop.service + +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.ActivitySessionEntity +import com.pulseloop.ring.MeasurementKind + +/** + * A workout the app was recording when its process died: closed, not left running forever. + * + * Nothing persisted the live workout but its samples, so an update install, Android reclaiming + * memory or a crash mid-workout left the session `recording` (or `paused`) in the database for + * good. The Activity tab lists finished workouts only, so the workout never appeared, and nothing + * ever tried to finish it: `ActivitySessionDao.active()` had no caller. At process start no + * workout can be live (the manager and its foreground service start empty), so any session still + * marked active is one of these. + * + * It ends where the workout's own evidence ends: its last live heart-rate sample or GPS point + * before the first quiet stretch of [MAX_GAP_MS], never more than [MAX_LENGTH_MS] after it + * started. All-day history samples don't count: they keep arriving long after the workout. A + * paused workout ends where it was paused. With no evidence at all there is nothing to report, + * so it is marked cancelled instead of inventing a duration. + */ +object WorkoutRecovery { + const val MAX_GAP_MS = 10 * 60_000L + const val MAX_LENGTH_MS = 6 * 3_600_000L + + /** Where an orphaned workout really ended, or null when nothing shows it ran at all. */ + fun endAt(session: ActivitySessionEntity, evidence: List, now: Long): Long? { + if (session.statusRaw == "paused") return session.endedAt?.takeIf { it > session.startedAt } + val limit = minOf(now, session.startedAt + MAX_LENGTH_MS) + var last: Long? = null + var previous = session.startedAt + for (t in evidence.filter { it in session.startedAt..limit }.sorted()) { + if (t - previous > MAX_GAP_MS) break + last = t + previous = t + } + return last?.takeIf { it > session.startedAt } + } + + /** + * Close every orphaned workout: one still marked active that started before [startedBefore], + * the moment this process's workout manager came up. A workout the user starts while this + * runs started after it, so it is never touched. Returns how many were finished. + */ + suspend fun recover(db: PulseLoopDatabase, startedBefore: Long, now: Long = System.currentTimeMillis()): Int { + var finished = 0 + val orphans = db.activitySessionDao().recent(200) + .filter { (it.statusRaw == "recording" || it.statusRaw == "paused") && it.startedAt < startedBefore } + for (s in orphans) { + val until = minOf(now, s.startedAt + MAX_LENGTH_MS) + val hr = db.measurementDao().range(MeasurementKind.HEART_RATE.name, s.startedAt, until) + .filter { it.sourceRaw !in setOf("history", "demo", "mock") && it.value > 0 } + .map { it.timestamp } + val gps = if (s.useGps) db.activityGpsPointDao().forSession(s.id).map { it.timestamp } else emptyList() + val end = endAt(s, hr + gps, now) + if (end == null) { + db.activitySessionDao().upsert(s.copy(statusRaw = "cancelled", endedAt = now, updatedAt = now)) + } else { + val closed = s.copy(statusRaw = "finished", endedAt = end, updatedAt = now) + val summarized = ActivityAggregates.recompute(db, closed) + db.activitySessionDao().upsert(summarized) + ActivityRollup.credit(db, summarized) + finished++ + } + } + return finished + } +} diff --git a/app/src/test/java/com/pulseloop/service/WorkoutRecoveryTest.kt b/app/src/test/java/com/pulseloop/service/WorkoutRecoveryTest.kt new file mode 100644 index 00000000..aa0d6773 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/WorkoutRecoveryTest.kt @@ -0,0 +1,39 @@ +package com.pulseloop.service + +import com.pulseloop.data.entity.ActivitySessionEntity +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class WorkoutRecoveryTest { + private val start = 1_700_000_000_000L + private val min = 60_000L + private fun session(status: String = "recording", endedAt: Long? = null) = + ActivitySessionEntity(type = "running", statusRaw = status, startedAt = start, endedAt = endedAt, useGps = false) + + @Test + fun `a workout ends at its last sample before a quiet stretch`() { + // Samples every 2 min for 30 min, then all-day monitoring 40 min later. + val samples = (1..15).map { start + it * 2 * min } + (start + 70 * min) + assertEquals(start + 30 * min, WorkoutRecovery.endAt(session(), samples, now = start + 5 * 60 * min)) + } + + @Test + fun `nothing recorded means nothing to report`() { + assertNull(WorkoutRecovery.endAt(session(), emptyList(), now = start + 60 * min)) + // A sample only after a long silence is not this workout's. + assertNull(WorkoutRecovery.endAt(session(), listOf(start + 30 * min), now = start + 60 * min)) + } + + @Test + fun `a paused workout ends where it was paused`() { + assertEquals(start + 20 * min, WorkoutRecovery.endAt(session("paused", endedAt = start + 20 * min), listOf(start + 50 * min), now = start + 90 * min)) + } + + @Test + fun `a workout never runs past six hours or into the future`() { + val samples = (1..600).map { start + it * min } + assertEquals(start + WorkoutRecovery.MAX_LENGTH_MS, WorkoutRecovery.endAt(session(), samples, now = start + 20 * 60 * min)) + assertEquals(start + 45 * min, WorkoutRecovery.endAt(session(), samples, now = start + 45 * min)) + } +}