From df9c32288c726b02de90246c23dc8f086d2a70d3 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:30 +0400 Subject: [PATCH 01/18] Weekly recap: the streak line only shows on a week that met the goal Co-Authored-By: Claude Opus 5.5 --- app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt index 660dee66..eb868fb9 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GoalsAndBests.kt @@ -267,7 +267,7 @@ fun WeeklyRecapPage(view: RewardsView?, first: LocalDate, contentPadding: Paddin GoalWeekCard( stringResource(if (week?.met == true) R.string.glow_goals_goal_met else R.string.glow_goals_weekly_goal), count, goal, weekDots(view, first), - if (run > 0) { + if (week?.met == true && run > 0) { pluralStringResource(R.plurals.glow_goals_weekly_streak, run, run) } else { (goal - count).coerceAtLeast(0).let { pluralStringResource(R.plurals.glow_goals_short_of_goal, it, it) } From 49dc072e484c2a16f7b0064b0b10538cf0dc8efe Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:30 +0400 Subject: [PATCH 02/18] Healthspan: an estimate a week old or more says it updates weekly, not next in 0 days Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt index a289afa2..8b1248f7 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowHealthspanScreen.kt @@ -31,7 +31,7 @@ import org.openstrap.app.ui.theme.MetricColors /** The scale on the Healthspan screen's bars: a habit this many years either side of the middle fills its half. */ private const val BAR_FULL_YEARS = 1.5f -/** "Updated Sunday, next in 5 days", from the Sunday the estimate was made. */ +/** "Updated Sunday, next in 5 days", from the Sunday the estimate was made; a week old or more says only that it's weekly. */ @Composable @ReadOnlyComposable private fun updatedText(asOf: Long): String { @@ -40,6 +40,7 @@ private fun updatedText(asOf: Long): String { return when (next) { 7 -> stringResource(R.string.glow_healthspan_updated_today) 1 -> stringResource(R.string.glow_healthspan_updated_tomorrow) + 0 -> stringResource(R.string.glow_healthspan_updated_weekly) else -> pluralStringResource(R.plurals.glow_healthspan_updated_next, next, next) } } From cbd6108b58f3175e577ff2aa48dd3394950e2e03 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:32 +0400 Subject: [PATCH 03/18] Auto backup keeps the day's earlier backup until its replacement is in place Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/export/AutoBackup.kt | 15 ++++++++++++--- .../org/openstrap/app/export/BackupFiles.kt | 5 ++++- .../org/openstrap/app/export/BackupFilesTest.kt | 6 ++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt index 584b2d7e..638267aa 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt @@ -121,9 +121,18 @@ class AutoBackup( var written = false try { (resolver.openOutputStream(temp.uri, "w") ?: throw Failed(BackupFailure.CantWrite)).use { backups.writeZip(it) } - // A second run on the same day replaces the first. - dir.findFile(name)?.delete() - if (!temp.renameTo(name)) copyAs(dir, temp, name) + // A second run on the same day replaces the first, but only once the new one is in place: the old one is + // moved aside, and put back if the new one can't be written. + val previous = dir.findFile(name) + val aside = BackupFiles.asideName(today) + if (previous != null && !previous.renameTo(aside)) throw Failed(BackupFailure.CantWrite) + try { + if (!temp.renameTo(name)) copyAs(dir, temp, name) + } catch (e: Throwable) { + if (previous != null) runCatching { dir.findFile(aside)?.renameTo(name) } + throw e + } + dir.findFile(aside)?.let(::deleteQuietly) written = true } finally { // Failed or cancelled part way: the temp copy goes, and the failure itself is what's reported. diff --git a/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt b/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt index 23261e70..da3b3da3 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/BackupFiles.kt @@ -16,7 +16,7 @@ object BackupFiles { // Before the app was renamed unstrap its backups were "OpenStrap-backup-". Both stay ours, so old backups are // still found, kept in the count and deleted in turn. private val BACKUP = Regex("""^(?:unstrap|OpenStrap)-backup-(\d{4}-\d{2}-\d{2})\.zip$""") - private val TEMP = Regex("""^(?:unstrap|OpenStrap)-backup-\d{4}-\d{2}-\d{2}\.part$""") + private val TEMP = Regex("""^(?:unstrap|OpenStrap)-backup-\d{4}-\d{2}-\d{2}(?:-previous)?\.part$""") /** "unstrap-backup-2026-10-29.zip". */ fun name(date: LocalDate): String = "unstrap-backup-$date.zip" @@ -24,6 +24,9 @@ object BackupFiles { /** The name a backup is written under until it is complete. Not .zip, so no provider adds an extension to it. */ fun tempName(date: LocalDate): String = "unstrap-backup-$date.part" + /** The name the earlier backup of the same day waits under while its replacement is put in place. Counts as a temp. */ + fun asideName(date: LocalDate): String = "unstrap-backup-$date-previous.part" + /** The day a backup file was made, or null when [name] isn't one of ours. */ fun dateOf(name: String): LocalDate? = BACKUP.matchEntire(name)?.groupValues?.get(1)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } diff --git a/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt b/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt index 95b8b842..ee97de0f 100644 --- a/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/export/BackupFilesTest.kt @@ -21,6 +21,12 @@ class BackupFilesTest { assertFalse(BackupFiles.isTemp(BackupFiles.name(day))) } + @Test fun `the name an old backup waits under is a temp, never a backup`() { + assertTrue(BackupFiles.isTemp(BackupFiles.asideName(day))) + assertNull(BackupFiles.dateOf(BackupFiles.asideName(day))) + assertTrue(BackupFiles.toDelete(listOf(BackupFiles.asideName(day))).isEmpty()) + } + @Test fun `only our own names count as backups`() { for (name in listOf( "unstrap-backup-2026-10-29 (1).zip", "Unstrap-backup-2026-10-29.zip", "unstrap-backup-2026-10-29.zip.bak", From 55552da1663263afb6a85c5b658ba0987648c6c2 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:40 +0400 Subject: [PATCH 04/18] A calorie goal the strap refused is not marked as sent, so it is tried again on the next connect Co-Authored-By: Claude Opus 5.5 --- app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt index 6b195149..c3a423ac 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt @@ -388,7 +388,8 @@ class StrapManager( val write = SettingsCodec.calorieTargetFor(group, kcal) if (write != null) { val ack = commands.command(Endpoints.SETTINGS, write) - log(if (SettingsCodec.isWriteSuccess(ack)) "calorie goal sent: $kcal" else "calorie goal refused: ${ack.toHex()}") + if (!SettingsCodec.isWriteSuccess(ack)) return@catching log("calorie goal refused: ${ack.toHex()}") + log("calorie goal sent: $kcal") } settings.setSentToStrap(SENT_CALORIE_GOAL, kcal.toLong()) }.onFailure { log("calorie goal send failed: $it") } From e03020d0d9591f95b2131f4e055ca1c110dd5bf4 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:44 +0400 Subject: [PATCH 05/18] A phone workout's distance keeps the steps walked before GPS found its first fix, not dropping when it does Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/WorkoutDistance.kt | 15 +++++++- .../app/device/WorkoutDistanceTest.kt | 38 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt index 1351d606..7bdf36fe 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutDistance.kt @@ -37,7 +37,7 @@ internal object WorkoutDistance { val lo = maxOf(from, since) val memory = when { lo >= to -> null - gps -> route(track.route, lo, to, w.pauseRanges) to false + gps -> withSteps(w, track, lo, to) else -> steps(w, track, lo, to)?.let { it to true } } // Before a restart only the stored total is left, so the part of it the range keeps is its share of the time. @@ -48,6 +48,19 @@ internal object WorkoutDistance { return (memory?.first ?: 0f) + (earlier?.first ?: 0f) to (memory?.second == true || earlier?.second == true) } + /** + * The route's metres from [lo] to [to], with the steps walked before its first fix in front of them, since GPS + * takes a while to settle and those metres are real. Counted as from steps only when they are most of the + * distance, so a run GPS followed nearly all the way stays a GPS run. + */ + private fun withSteps(w: AppWorkout, track: Track, lo: Long, to: Long): Pair { + val metres = route(track.route, lo, to, w.pauseRanges) + val fix = Route.clean(track.route).first().t + val start = maxOf(lo, track.stepsSince) + val before = if (fix > start) steps(w, track, start, minOf(fix, to)) ?: 0f else 0f + return metres + before to (before > metres) + } + /** [w] with its distance over the range it shows ([shown]), or as it was when nothing says. */ fun withShown(w: AppWorkout, now: Long, track: Track): AppWorkout = shown(w, now, track)?.let { (m, steps) -> w.copy(distanceMeters = m, distanceFromSteps = steps) } ?: w diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt index 379df352..62460850 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutDistanceTest.kt @@ -53,6 +53,44 @@ class WorkoutDistanceTest { assertEquals(500f, WorkoutDistance.shown(early, t0 + 900, track(steps = totals(since, 5), since = since, before = stored))!!.first, 0.01f) } + @Test + fun stepsBeforeTheFirstFixAreKeptWhenGpsTakesOver() { + // 3 minutes of steps, then a fix every 10 s for 10 minutes: the route adds to them, it doesn't replace them. + val fix = t0 + 180 + val route = line(600).map { it.copy(t = it.t + 180) } + val w = AppWorkout(t0, t0 + 780, SportTypes.WALK) + val gps = WorkoutDistance.shown(w, t0 + 780, track(route))!! + val both = WorkoutDistance.shown(w, t0 + 780, track(route, totals(t0, 13)))!! + val before = 300 * Activity.stepLength(100, 175) + assertEquals(gps.first + before, both.first, 0.01f) + // The route is nearly all of it, so it is still a GPS run. + assertEquals(false, both.second) + // Before the first fix settles the figure is the steps, and it doesn't drop when the fix arrives. + val early = WorkoutDistance.shown(w.copy(end = null), fix - 10, track(steps = totals(t0, 13)))!! + assertTrue(early.second) + assertTrue(both.first >= early.first) + } + + @Test + fun withMostlyStepsBeforeTheFirstFixItStaysFromSteps() { + val route = line(60).map { it.copy(t = it.t + 540) } + val w = AppWorkout(t0, t0 + 600, SportTypes.WALK) + val m = WorkoutDistance.shown(w, t0 + 600, track(route, totals(t0, 10)))!! + assertTrue(m.second) + assertTrue(m.first > 500 * Activity.stepLength(100, 175) * 0.8f) + } + + @Test + fun aTrimmedStartAfterTheFirstFixCountsNoStepsAndABikeNeverDoes() { + val route = line(600).map { it.copy(t = it.t + 180) } + val trimmed = AppWorkout(t0, t0 + 780, SportTypes.WALK, shownStart = t0 + 300) + val gps = WorkoutDistance.shown(trimmed, t0 + 780, track(route))!! + assertEquals(gps, WorkoutDistance.shown(trimmed, t0 + 780, track(route, totals(t0, 13)))) + // A bike has no steps to add. + val bike = AppWorkout(t0, t0 + 780, SportTypes.OUTDOOR_CYCLING) + assertEquals(WorkoutDistance.shown(bike, t0 + 780, track(route))!!, WorkoutDistance.shown(bike, t0 + 780, track(route, totals(t0, 13)))!!) + } + @Test fun theTotalGoingBackToZeroAtMidnightCostsOnlyTheStepsBeforeIt() { assertEquals(200, WorkoutDistance.taken(listOf(0L to 9_000, 60L to 9_100, 120L to 50, 180L to 150), 0, 180)) From ebf1c15928e3b6b1a208d07ba1e560a4efae871b Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:50 +0400 Subject: [PATCH 06/18] A failed alarms read no longer hides the health switches, and the reverse; each page shows its own read error Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/ui/alarms/AlarmsScreen.kt | 4 +-- .../app/ui/alarms/AlarmsViewModel.kt | 34 +++++++++++++------ .../app/ui/alarms/AlarmsViewModelTest.kt | 29 ++++++++++++++-- 3 files changed, 52 insertions(+), 15 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt index f6a0375f..912a4454 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsScreen.kt @@ -174,7 +174,7 @@ fun AlarmsScreen( } ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.you_alarms_title), onBack) } - state.error?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } + (state.error ?: state.alarmsError)?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } if (state.loading) { item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } } return@ScreenList @@ -195,7 +195,7 @@ fun HealthAlertsScreen(vm: AlarmsViewModel, state: AlarmsUiState, contentPadding BackHandler(onBack = onBack) ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.you_health_title), onBack) } - state.error?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } + (state.error ?: state.healthError)?.let { msg -> item { ErrorPanel(msg, state.busy, vm::refresh) } } if (state.loading) { item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } } return@ScreenList diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt index aab7ec08..c32ab974 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt @@ -32,12 +32,17 @@ sealed interface AlarmsRead { data class AlarmsUiState( /** * Loading until the first read ends. Failed means no read has ever worked, so [caps] and [alarms] are unknown and the - * screen must not show them as "no alarms". Once Loaded it stays Loaded: a later failed read only sets [error]. + * screen must not show them as "no alarms". Once Loaded it stays Loaded: a later failed read only sets [alarmsError]. */ val read: AlarmsRead = AlarmsRead.Loading, /** A write is in flight; controls are disabled meanwhile. */ val busy: Boolean = false, + /** A failed write's reason. */ val error: String? = null, + /** Why the alarms read failed, if it did; shown on the Alarms page only. */ + val alarmsError: String? = null, + /** Why the health settings read failed, if it did; shown on the Health page only. */ + val healthError: String? = null, val caps: AlarmCapabilities? = null, val alarms: List = emptyList(), val health: SettingsGroup? = null, @@ -155,25 +160,32 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { } } - /** Re-reads alarms and health from the strap. [error] is the failed write's reason, if any, and wins over a read failure's. */ + /** + * Re-reads alarms and health from the strap, each on its own so one failing doesn't hide the other. [error] is the + * failed write's reason, if any; a read failure is kept apart from it ([AlarmsUiState.alarmsError], [AlarmsUiState.healthError]). + */ private suspend fun readAll(error: String?) { // The raw failure goes to Diagnostics, and the screen says it in plain words ([ErrorCopy.strap]). - val read = catching { + val alarmsRead = catching { val (caps, alarms) = strap.readAlarms() - Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings()) + caps to alarms.sortedWith(compareBy({ it.hour }, { it.minute })) }.onFailure { (strap as? StrapManager)?.log("alarms: read from the strap failed: $it") } + val healthRead = catching { strap.readHealthSettings() } + .onFailure { (strap as? StrapManager)?.log("alarms: health settings read from the strap failed: $it") } _state.update { s -> - read.fold( - { (caps, alarms, health) -> - s.copy(read = AlarmsRead.Loaded, busy = false, error = error, caps = caps, alarms = alarms, health = health) - }, + val withAlarms = alarmsRead.fold( + { (caps, alarms) -> s.copy(read = AlarmsRead.Loaded, caps = caps, alarms = alarms, alarmsError = null) }, { e -> - val failed = error ?: ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed)) + val failed = ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed)) // Without an earlier good read there is nothing to show; with one, keep showing it beside the error. - val next = if (s.read is AlarmsRead.Loaded) s.read else AlarmsRead.Failed(failed) - s.copy(read = next, busy = false, error = failed) + s.copy(read = if (s.read is AlarmsRead.Loaded) s.read else AlarmsRead.Failed(failed), alarmsError = failed) }, ) + // A failed re-read keeps the last good settings. + healthRead.fold( + { health -> withAlarms.copy(health = health, healthError = null) }, + { e -> withAlarms.copy(healthError = ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed))) }, + ).copy(busy = false, error = error) } } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt index 33e9d860..655823e5 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt @@ -116,11 +116,36 @@ class AlarmsViewModelTest { assertEquals("Slot taken", vm.state.value.error) } + @Test fun `a failed alarms read leaves the health settings read and its own error on the Alarms page`() { + val strap = FakeStrap().apply { alarmsFailure = StrapCommandException("Alarms unreadable") } + val vm = AlarmsViewModel(strap.controller).also { models += it } + val state = vm.state.value + assertEquals("Alarms unreadable", state.alarmsError) + assertNull(state.healthError) + assertTrue(state.health != null) + } + + @Test fun `a failed health read leaves the alarms read and keeps the last good settings`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + assertTrue(vm.state.value.health != null) + strap.healthFailure = StrapCommandException("Settings unreadable") + vm.refresh() + val state = vm.state.value + assertEquals("Settings unreadable", state.healthError) + assertNull(state.alarmsError) + assertEquals(AlarmsRead.Loaded, state.read) + assertEquals(1, state.alarms.size) + assertTrue(state.health != null) + } + /** A strap that holds one alarm, can hold a save until [release], and counts its reads. */ private class FakeStrap { var reads = 0 var holdSave = false var saveFailure: Throwable? = null + var alarmsFailure: Throwable? = null + var healthFailure: Throwable? = null private var held: Continuation? = null private val caps = AlarmCapabilities(version = 1, maxCount = 10, titles = false, smartSupported = false) private val flows = mutableMapOf() @@ -141,8 +166,8 @@ class AlarmsViewModelTest { method.name == "hashCode" -> System.identityHashCode(proxy) method.name == "equals" -> proxy === args?.firstOrNull() method.name == "toString" -> "fake strap" - method.name == "readAlarms" -> { reads++; done(Result.success(caps to listOf(Alarm(0, 6, 0, Alarm.WEEKDAYS, enabled = true)))) } - method.name == "readHealthSettings" -> done(Result.success(SettingsGroup(0, 1, emptyMap()))) + method.name == "readAlarms" -> { reads++; done(alarmsFailure?.let { Result.failure(it) } ?: Result.success(caps to listOf(Alarm(0, 6, 0, Alarm.WEEKDAYS, enabled = true)))) } + method.name == "readHealthSettings" -> done(healthFailure?.let { Result.failure(it) } ?: Result.success(SettingsGroup(0, 1, emptyMap()))) method.name == "saveAlarm" -> when { saveFailure != null -> done(Result.failure(saveFailure!!)) holdSave -> { held = args.last() as Continuation; COROUTINE_SUSPENDED } From 83df5db7df7763bb4838c1661d987fed029fe11a Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:54 +0400 Subject: [PATCH 07/18] A failed write's reason stays on screen when a refresh was queued behind it Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/ui/alarms/AlarmsViewModel.kt | 3 ++- .../app/ui/alarms/AlarmsViewModelTest.kt | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt index c32ab974..dd8bb0fa 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModel.kt @@ -154,7 +154,8 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { refreshPending = false if (again) { _state.update { it.copy(busy = true) } - readAll(null) + // The write's reason stays up: the queued read isn't what the user is waiting to hear about. + readAll(error) } error == null } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt index 655823e5..4fdef88c 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt @@ -139,6 +139,18 @@ class AlarmsViewModelTest { assertTrue(state.health != null) } + @Test fun `a failed save's reason survives the refresh that was queued meanwhile`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + strap.holdSave = true + val writing = vm.save(Alarm(0, 7, 0, 0, enabled = true), isNew = true) + vm.refresh() + strap.release(StrapCommandException("Slot taken")) + assertFalse(writing.getCompleted()) + assertEquals("Slot taken", vm.state.value.error) + assertFalse(vm.state.value.busy) + } + /** A strap that holds one alarm, can hold a save until [release], and counts its reads. */ private class FakeStrap { var reads = 0 @@ -150,8 +162,8 @@ class AlarmsViewModelTest { private val caps = AlarmCapabilities(version = 1, maxCount = 10, titles = false, smartSupported = false) private val flows = mutableMapOf() - fun release() { - held?.resumeWith(Result.success(Unit)) + fun release(failure: Throwable? = null) { + held?.resumeWith(failure?.let { Result.failure(it) } ?: Result.success(Unit)) held = null holdSave = false } From 1d78b8836057cb9f1a8d5a96bc99e9f141385c20 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:11:59 +0400 Subject: [PATCH 08/18] Sleep edits that match no session are cleared in a new migration, so one left by a deleted minute night can't move or hide a real strap night Co-Authored-By: Claude Opus 5.5 --- .../32.json | 1968 +++++++++++++++++ .../app/data/db/OpenStrapDatabase.kt | 4 +- .../app/data/db/OrphanSleepEditMigration.kt | 24 + .../app/data/db/MigrationChainTest.kt | 2 +- .../data/db/OrphanSleepEditMigrationTest.kt | 62 + 5 files changed, 2057 insertions(+), 3 deletions(-) create mode 100644 app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json create mode 100644 app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt create mode 100644 app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt diff --git a/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json b/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json new file mode 100644 index 00000000..178ce099 --- /dev/null +++ b/app/schemas/org.openstrap.app.data.db.OpenStrapDatabase/32.json @@ -0,0 +1,1968 @@ +{ + "formatVersion": 1, + "database": { + "version": 32, + "identityHash": "4c98ef956993353c8c59be4837dd05ba", + "entities": [ + { + "tableName": "heart_rate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, `source` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "activity_minute", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `steps` INTEGER NOT NULL, `intensity` INTEGER NOT NULL, `kind` INTEGER NOT NULL, `heartRate` INTEGER, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "intensity", + "columnName": "intensity", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "heartRate", + "columnName": "heartRate", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "sleep_session", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `day` INTEGER NOT NULL DEFAULT 0, `nap` INTEGER NOT NULL DEFAULT 0, `score` INTEGER, `averageHeartRate` INTEGER, `deepMinutes` INTEGER, `lightMinutes` INTEGER, `remMinutes` INTEGER, `awakeMinutes` INTEGER, `wakeCount` INTEGER, `source` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "nap", + "columnName": "nap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "score", + "columnName": "score", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "deepMinutes", + "columnName": "deepMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "lightMinutes", + "columnName": "lightMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "remMinutes", + "columnName": "remMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "awakeMinutes", + "columnName": "awakeMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "wakeCount", + "columnName": "wakeCount", + "affinity": "INTEGER" + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_sleep_session_day", + "unique": false, + "columnNames": [ + "day" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_session_day` ON `${TABLE_NAME}` (`day`)" + }, + { + "name": "index_sleep_session_nap_end", + "unique": false, + "columnNames": [ + "nap", + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_session_nap_end` ON `${TABLE_NAME}` (`nap`, `end`)" + } + ] + }, + { + "tableName": "sleep_stage", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `sessionStart` INTEGER NOT NULL, `stage` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sessionStart", + "columnName": "sessionStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "stage", + "columnName": "stage", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_sleep_stage_sessionStart", + "unique": false, + "columnNames": [ + "sessionStart" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_sleep_stage_sessionStart` ON `${TABLE_NAME}` (`sessionStart`)" + } + ] + }, + { + "tableName": "spo2", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `percent` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percent", + "columnName": "percent", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "stress", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `value` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "hrv", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `milliseconds` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "milliseconds", + "columnName": "milliseconds", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "resting_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "skin_temperature", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `celsius` REAL NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "celsius", + "columnName": "celsius", + "affinity": "REAL", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "breath_rate", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `perMinute` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "perMinute", + "columnName": "perMinute", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "pai", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `daily` REAL NOT NULL, `total` REAL NOT NULL, `restingHeartRate` INTEGER NOT NULL, `maxHeartRate` INTEGER NOT NULL, `tomorrowTotal` REAL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "daily", + "columnName": "daily", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "total", + "columnName": "total", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "restingHeartRate", + "columnName": "restingHeartRate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tomorrowTotal", + "columnName": "tomorrowTotal", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "hrv_sdnn", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `milliseconds` REAL NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "milliseconds", + "columnName": "milliseconds", + "affinity": "REAL", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, `sportType` INTEGER NOT NULL, `exerciseSeconds` INTEGER, `calories` INTEGER, `averageHeartRate` INTEGER, `maxHeartRate` INTEGER, `minHeartRate` INTEGER, `aerobicTrainingEffect` REAL, `anaerobicTrainingEffect` REAL, `trainingLoad` INTEGER, `vo2max` INTEGER, `steps` INTEGER, `subtype` INTEGER, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sportType", + "columnName": "sportType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "exerciseSeconds", + "columnName": "exerciseSeconds", + "affinity": "INTEGER" + }, + { + "fieldPath": "calories", + "columnName": "calories", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "minHeartRate", + "columnName": "minHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "aerobicTrainingEffect", + "columnName": "aerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "anaerobicTrainingEffect", + "columnName": "anaerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "trainingLoad", + "columnName": "trainingLoad", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "INTEGER" + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER" + }, + { + "fieldPath": "subtype", + "columnName": "subtype", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + } + }, + { + "tableName": "workout_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "sport_effect", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`end` INTEGER NOT NULL, `recoveryMinutes` INTEGER, `vo2max` REAL, `epoc` REAL, `weeklyLoad` REAL, `monthlyLoad` REAL, `optimalLoadMin` INTEGER, `optimalLoadMax` INTEGER, `maximalHeartRate` INTEGER, PRIMARY KEY(`end`))", + "fields": [ + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "recoveryMinutes", + "columnName": "recoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "REAL" + }, + { + "fieldPath": "epoc", + "columnName": "epoc", + "affinity": "REAL" + }, + { + "fieldPath": "weeklyLoad", + "columnName": "weeklyLoad", + "affinity": "REAL" + }, + { + "fieldPath": "monthlyLoad", + "columnName": "monthlyLoad", + "affinity": "REAL" + }, + { + "fieldPath": "optimalLoadMin", + "columnName": "optimalLoadMin", + "affinity": "INTEGER" + }, + { + "fieldPath": "optimalLoadMax", + "columnName": "optimalLoadMax", + "affinity": "INTEGER" + }, + { + "fieldPath": "maximalHeartRate", + "columnName": "maximalHeartRate", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "end" + ] + } + }, + { + "tableName": "strap_readiness", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `score` INTEGER, `hrvScore` INTEGER, `restingHrScore` INTEGER, `skinTemperatureScore` INTEGER, `breathingScore` INTEGER, `sleepHrv` INTEGER, `sleepRestingHr` INTEGER, `algorithmVersion` TEXT NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "score", + "columnName": "score", + "affinity": "INTEGER" + }, + { + "fieldPath": "hrvScore", + "columnName": "hrvScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "restingHrScore", + "columnName": "restingHrScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "skinTemperatureScore", + "columnName": "skinTemperatureScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "breathingScore", + "columnName": "breathingScore", + "affinity": "INTEGER" + }, + { + "fieldPath": "sleepHrv", + "columnName": "sleepHrv", + "affinity": "INTEGER" + }, + { + "fieldPath": "sleepRestingHr", + "columnName": "sleepRestingHr", + "affinity": "INTEGER" + }, + { + "fieldPath": "algorithmVersion", + "columnName": "algorithmVersion", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "sleep_spo2", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `percent` INTEGER NOT NULL, `time` INTEGER, `high` BLOB, `low` BLOB, `signalQuality` BLOB, `extend` BLOB, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "percent", + "columnName": "percent", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER" + }, + { + "fieldPath": "high", + "columnName": "high", + "affinity": "BLOB" + }, + { + "fieldPath": "low", + "columnName": "low", + "affinity": "BLOB" + }, + { + "fieldPath": "signalQuality", + "columnName": "signalQuality", + "affinity": "BLOB" + }, + { + "fieldPath": "extend", + "columnName": "extend", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "osa_event", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `drop` INTEGER NOT NULL, `spo2` BLOB, `heartRate` BLOB, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "drop", + "columnName": "drop", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "spo2", + "columnName": "spo2", + "affinity": "BLOB" + }, + { + "fieldPath": "heartRate", + "columnName": "heartRate", + "affinity": "BLOB" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "osa_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`belongTime` INTEGER NOT NULL, `validTime` INTEGER NOT NULL, `odiRaw` INTEGER NOT NULL, `odiScore` INTEGER NOT NULL, `dispCode` INTEGER NOT NULL, `eventCount` INTEGER NOT NULL, `version` INTEGER NOT NULL, PRIMARY KEY(`belongTime`))", + "fields": [ + { + "fieldPath": "belongTime", + "columnName": "belongTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "validTime", + "columnName": "validTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "odiRaw", + "columnName": "odiRaw", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "odiScore", + "columnName": "odiScore", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dispCode", + "columnName": "dispCode", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "eventCount", + "columnName": "eventCount", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "version", + "columnName": "version", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "belongTime" + ] + } + }, + { + "tableName": "daily_max_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "recovery_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `samples` BLOB NOT NULL, PRIMARY KEY(`workoutStart`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "samples", + "columnName": "samples", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart" + ] + } + }, + { + "tableName": "activity_extended", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `floors` INTEGER NOT NULL, `run` INTEGER NOT NULL, `fatBurn` INTEGER NOT NULL, `stand` INTEGER NOT NULL, `walk` INTEGER NOT NULL, `sit` INTEGER NOT NULL, `steps` INTEGER NOT NULL, `calories` INTEGER NOT NULL, `distanceCm` INTEGER NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "floors", + "columnName": "floors", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "run", + "columnName": "run", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fatBurn", + "columnName": "fatBurn", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "stand", + "columnName": "stand", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "walk", + "columnName": "walk", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sit", + "columnName": "sit", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "steps", + "columnName": "steps", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "calories", + "columnName": "calories", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "distanceCm", + "columnName": "distanceCm", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "raw_record", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`type` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `payload` BLOB NOT NULL, PRIMARY KEY(`type`, `timestamp`))", + "fields": [ + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "payload", + "columnName": "payload", + "affinity": "BLOB", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "type", + "timestamp" + ] + } + }, + { + "tableName": "health_alert", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL, `value` INTEGER NOT NULL, PRIMARY KEY(`timestamp`, `type`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp", + "type" + ] + } + }, + { + "tableName": "check_in", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `feeling` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "feeling", + "columnName": "feeling", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "day_tag", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `tag` TEXT NOT NULL, PRIMARY KEY(`day`, `tag`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "tag", + "columnName": "tag", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day", + "tag" + ] + } + }, + { + "tableName": "night_metrics", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `hrvLn` REAL, `hrvSamples` INTEGER NOT NULL, `rhrLowest30` REAL, `rhrMeanSleep` REAL, `rhrP10` REAL, `hrMinutes` INTEGER NOT NULL, `strapHrv` INTEGER, `strapRestingHr` INTEGER, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hrvLn", + "columnName": "hrvLn", + "affinity": "REAL" + }, + { + "fieldPath": "hrvSamples", + "columnName": "hrvSamples", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "rhrLowest30", + "columnName": "rhrLowest30", + "affinity": "REAL" + }, + { + "fieldPath": "rhrMeanSleep", + "columnName": "rhrMeanSleep", + "affinity": "REAL" + }, + { + "fieldPath": "rhrP10", + "columnName": "rhrP10", + "affinity": "REAL" + }, + { + "fieldPath": "hrMinutes", + "columnName": "hrMinutes", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "strapHrv", + "columnName": "strapHrv", + "affinity": "INTEGER" + }, + { + "fieldPath": "strapRestingHr", + "columnName": "strapRestingHr", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "app_workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER, `sportType` INTEGER NOT NULL, `source` INTEGER NOT NULL, `pauses` TEXT NOT NULL, `pausedAt` INTEGER, `endReason` INTEGER, `averageHeartRate` INTEGER, `maxHeartRate` INTEGER, `askToEnd` INTEGER NOT NULL DEFAULT 1, `recordedEnd` INTEGER, `shownStart` INTEGER, `target` TEXT, `useGps` INTEGER NOT NULL DEFAULT 0, `keepRoute` INTEGER NOT NULL DEFAULT 0, `distanceMeters` REAL, `distanceFromSteps` INTEGER NOT NULL DEFAULT 0, `rest` TEXT, `setsTarget` INTEGER, `laps` TEXT NOT NULL DEFAULT '', `epoc` REAL, `aerobicTrainingEffect` REAL, `recoveryMinutes` INTEGER, `vo2max` REAL, `anaerobicTrainingEffect` REAL, `effectFromStrap` INTEGER NOT NULL DEFAULT 0, `ownRecoveryMinutes` INTEGER, `activeKcal` REAL, `totalKcal` REAL, `targetReachedAt` INTEGER, `structure` TEXT, `stretches` TEXT, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "sportType", + "columnName": "sportType", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "source", + "columnName": "source", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pauses", + "columnName": "pauses", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pausedAt", + "columnName": "pausedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "endReason", + "columnName": "endReason", + "affinity": "INTEGER" + }, + { + "fieldPath": "averageHeartRate", + "columnName": "averageHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "maxHeartRate", + "columnName": "maxHeartRate", + "affinity": "INTEGER" + }, + { + "fieldPath": "askToEnd", + "columnName": "askToEnd", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "recordedEnd", + "columnName": "recordedEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "shownStart", + "columnName": "shownStart", + "affinity": "INTEGER" + }, + { + "fieldPath": "target", + "columnName": "target", + "affinity": "TEXT" + }, + { + "fieldPath": "useGps", + "columnName": "useGps", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "keepRoute", + "columnName": "keepRoute", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "distanceMeters", + "columnName": "distanceMeters", + "affinity": "REAL" + }, + { + "fieldPath": "distanceFromSteps", + "columnName": "distanceFromSteps", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "rest", + "columnName": "rest", + "affinity": "TEXT" + }, + { + "fieldPath": "setsTarget", + "columnName": "setsTarget", + "affinity": "INTEGER" + }, + { + "fieldPath": "laps", + "columnName": "laps", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "epoc", + "columnName": "epoc", + "affinity": "REAL" + }, + { + "fieldPath": "aerobicTrainingEffect", + "columnName": "aerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "recoveryMinutes", + "columnName": "recoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "vo2max", + "columnName": "vo2max", + "affinity": "REAL" + }, + { + "fieldPath": "anaerobicTrainingEffect", + "columnName": "anaerobicTrainingEffect", + "affinity": "REAL" + }, + { + "fieldPath": "effectFromStrap", + "columnName": "effectFromStrap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "ownRecoveryMinutes", + "columnName": "ownRecoveryMinutes", + "affinity": "INTEGER" + }, + { + "fieldPath": "activeKcal", + "columnName": "activeKcal", + "affinity": "REAL" + }, + { + "fieldPath": "totalKcal", + "columnName": "totalKcal", + "affinity": "REAL" + }, + { + "fieldPath": "targetReachedAt", + "columnName": "targetReachedAt", + "affinity": "INTEGER" + }, + { + "fieldPath": "structure", + "columnName": "structure", + "affinity": "TEXT" + }, + { + "fieldPath": "stretches", + "columnName": "stretches", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_app_workout_end", + "unique": false, + "columnNames": [ + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_app_workout_end` ON `${TABLE_NAME}` (`end`)" + } + ] + }, + { + "tableName": "app_workout_hr", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `bpm` INTEGER NOT NULL, `fromHistory` INTEGER NOT NULL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bpm", + "columnName": "bpm", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "fromHistory", + "columnName": "fromHistory", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "app_workout_dismissed", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `end` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + }, + "indices": [ + { + "name": "index_app_workout_dismissed_end", + "unique": false, + "columnNames": [ + "end" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_app_workout_dismissed_end` ON `${TABLE_NAME}` (`end`)" + } + ] + }, + { + "tableName": "app_workout_route", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL, `accuracy` REAL NOT NULL, `speed` REAL, `bearing` REAL, `altitude` REAL, `speedAccuracy` REAL, `bearingAccuracy` REAL, PRIMARY KEY(`workoutStart`, `timestamp`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "lat", + "columnName": "lat", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "lon", + "columnName": "lon", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "accuracy", + "columnName": "accuracy", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "speed", + "columnName": "speed", + "affinity": "REAL" + }, + { + "fieldPath": "bearing", + "columnName": "bearing", + "affinity": "REAL" + }, + { + "fieldPath": "altitude", + "columnName": "altitude", + "affinity": "REAL" + }, + { + "fieldPath": "speedAccuracy", + "columnName": "speedAccuracy", + "affinity": "REAL" + }, + { + "fieldPath": "bearingAccuracy", + "columnName": "bearingAccuracy", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "timestamp" + ] + } + }, + { + "tableName": "app_workout_set", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `index` INTEGER NOT NULL, `start` INTEGER NOT NULL, `end` INTEGER, `restEnd` INTEGER, `exercise` TEXT, `reps` INTEGER, `weightKg` REAL, PRIMARY KEY(`workoutStart`, `index`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "restEnd", + "columnName": "restEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "exercise", + "columnName": "exercise", + "affinity": "TEXT" + }, + { + "fieldPath": "reps", + "columnName": "reps", + "affinity": "INTEGER" + }, + { + "fieldPath": "weightKg", + "columnName": "weightKg", + "affinity": "REAL" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "index" + ] + } + }, + { + "tableName": "wear_event", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `worn` INTEGER, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "worn", + "columnName": "worn", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "timestamp" + ] + } + }, + { + "tableName": "habit_age_week", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`asOf` INTEGER NOT NULL, `estimate` REAL NOT NULL, `low` INTEGER NOT NULL, `high` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`asOf`))", + "fields": [ + { + "fieldPath": "asOf", + "columnName": "asOf", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "estimate", + "columnName": "estimate", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "low", + "columnName": "low", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "high", + "columnName": "high", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "asOf" + ] + } + }, + { + "tableName": "workout_deleted", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`start` INTEGER NOT NULL, `effectEnd` INTEGER, `deletedAt` INTEGER NOT NULL, PRIMARY KEY(`start`))", + "fields": [ + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "effectEnd", + "columnName": "effectEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "start" + ] + } + }, + { + "tableName": "daily_energy", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`day` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `totalKcal` REAL NOT NULL, `activeKcal` REAL NOT NULL, `bmrKcal` REAL NOT NULL, `minutesWithData` INTEGER NOT NULL, `partial` INTEGER NOT NULL, `workoutKcal` REAL NOT NULL, `walkingKcal` REAL NOT NULL, `hourly` TEXT NOT NULL, PRIMARY KEY(`day`))", + "fields": [ + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "totalKcal", + "columnName": "totalKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "activeKcal", + "columnName": "activeKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bmrKcal", + "columnName": "bmrKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "minutesWithData", + "columnName": "minutesWithData", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "partial", + "columnName": "partial", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutKcal", + "columnName": "workoutKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "walkingKcal", + "columnName": "walkingKcal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "hourly", + "columnName": "hourly", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "day" + ] + } + }, + { + "tableName": "sleep_edit", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`strapStart` INTEGER NOT NULL, `nap` INTEGER NOT NULL DEFAULT 0, `start` INTEGER, `end` INTEGER, `deleted` INTEGER NOT NULL DEFAULT 0, `editedAt` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`strapStart`))", + "fields": [ + { + "fieldPath": "strapStart", + "columnName": "strapStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "nap", + "columnName": "nap", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "start", + "columnName": "start", + "affinity": "INTEGER" + }, + { + "fieldPath": "end", + "columnName": "end", + "affinity": "INTEGER" + }, + { + "fieldPath": "deleted", + "columnName": "deleted", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "editedAt", + "columnName": "editedAt", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "strapStart" + ] + } + }, + { + "tableName": "app_workout_round", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`workoutStart` INTEGER NOT NULL, `index` INTEGER NOT NULL, `workStart` INTEGER NOT NULL, `workEnd` INTEGER, `restEnd` INTEGER, `peakBpm` INTEGER, PRIMARY KEY(`workoutStart`, `index`))", + "fields": [ + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "index", + "columnName": "index", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workStart", + "columnName": "workStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workEnd", + "columnName": "workEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "restEnd", + "columnName": "restEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "peakBpm", + "columnName": "peakBpm", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "workoutStart", + "index" + ] + } + }, + { + "tableName": "saved_workout", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `sport` INTEGER NOT NULL, `structure` TEXT NOT NULL, `goal` TEXT, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sport", + "columnName": "sport", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "structure", + "columnName": "structure", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "goal", + "columnName": "goal", + "affinity": "TEXT" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "exercise", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `lastReps` INTEGER, `lastKg` REAL, `usedAt` INTEGER NOT NULL, PRIMARY KEY(`name`))", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastReps", + "columnName": "lastReps", + "affinity": "INTEGER" + }, + { + "fieldPath": "lastKg", + "columnName": "lastKg", + "affinity": "REAL" + }, + { + "fieldPath": "usedAt", + "columnName": "usedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "name" + ] + } + }, + { + "tableName": "personal_best", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `value` REAL NOT NULL, `date` INTEGER NOT NULL, `workoutStart` INTEGER, PRIMARY KEY(`kind`))", + "fields": [ + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "kind" + ] + } + }, + { + "tableName": "badge", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `earnedAt` INTEGER NOT NULL, `workoutStart` INTEGER, `day` INTEGER, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "earnedAt", + "columnName": "earnedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "workoutStart", + "columnName": "workoutStart", + "affinity": "INTEGER" + }, + { + "fieldPath": "day", + "columnName": "day", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "week_result", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`weekStart` INTEGER NOT NULL, `goal` INTEGER NOT NULL, `count` INTEGER NOT NULL, `met` INTEGER NOT NULL, PRIMARY KEY(`weekStart`))", + "fields": [ + { + "fieldPath": "weekStart", + "columnName": "weekStart", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "goal", + "columnName": "goal", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "count", + "columnName": "count", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "met", + "columnName": "met", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "weekStart" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '4c98ef956993353c8c59be4837dd05ba')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt b/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt index 58f7a494..dafb73f5 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/db/OpenStrapDatabase.kt @@ -55,7 +55,7 @@ import java.time.ZoneId BadgeRow::class, WeekResult::class, ], - version = 31, + version = 32, autoMigrations = [ AutoMigration(from = 1, to = 2), AutoMigration(from = 2, to = 3), AutoMigration(from = 3, to = 4), AutoMigration(from = 4, to = 5), AutoMigration(from = 5, to = 6), @@ -81,7 +81,7 @@ abstract class OpenStrapDatabase : RoomDatabase() { * converted ([DayKeyMigration]), so it is the phone's zone when the database first opens after the upgrade. */ fun migrations(zone: () -> ZoneId = ZoneId::systemDefault): Array = - arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration) + arrayOf(WorkoutsMigration, IndicesMigration, DayKeyMigration(zone), MinuteSleepMigration, OrphanSleepEditMigration) /** [migrations] in the phone's zone. */ val MIGRATIONS = migrations() diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt new file mode 100644 index 00000000..ad7e77ab --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt @@ -0,0 +1,24 @@ +package org.openstrap.app.data.db + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import org.openstrap.app.data.SleepEdits + +/** + * Version 31 to 32: the edits left behind by the nights [MinuteSleepMigration] deleted go. An edit finds a session of + * its kind within [SleepEdits.MATCH_SECONDS], so one of those could have moved or hidden a real strap night near it. + * An edit with no session that close goes, except a marker for a deleted sleep whose time to restore has run out + * ([SleepEdits.marker]), which has none by design. No schema change. + */ +@Suppress("MagicNumber") // The versions it runs between are what the migration is. +object OrphanSleepEditMigration : Migration(31, 32) { + override fun migrate(db: SupportSQLiteDatabase) { + val keptBefore = System.currentTimeMillis() / 1000 - SleepEdits.KEEP_DAYS * 86_400L + db.execSQL( + "DELETE FROM `sleep_edit` WHERE NOT (`deleted` = 1 AND `start` IS NULL AND `editedAt` < ?) AND NOT EXISTS " + + "(SELECT 1 FROM `sleep_session` WHERE `sleep_session`.`nap` = `sleep_edit`.`nap` AND " + + "ABS(`sleep_session`.`start` - `sleep_edit`.`strapStart`) <= ${SleepEdits.MATCH_SECONDS})", + arrayOf(keptBefore), + ) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt index 93ecb4b7..7e3f06fc 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/db/MigrationChainTest.kt @@ -30,7 +30,7 @@ class MigrationChainTest { @Test fun `every exported version opens at the current one`() = runTest { val versions = SourceTree.schemas.listFiles()!!.filter { it.extension == "json" }.map { it.nameWithoutExtension.toInt() }.sorted() assertEquals((1..current).toList(), versions) - assertEquals(31, current) + assertEquals(32, current) for (v in 1 until current) { val db = harness.open(harness.create(v)) // Any read opens it, running the migrations and Room's check of the result. diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt new file mode 100644 index 00000000..c833b6f0 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt @@ -0,0 +1,62 @@ +package org.openstrap.app.data.db + +import android.database.sqlite.SQLiteDatabase +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.test.runTest +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +/** A version 31 database opens at 32 without the sleep edits that match no session, those of a real night and the markers of an expired delete kept. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class OrphanSleepEditMigrationTest { + @Test + fun orphanEditsGoOthersStay() = runTest { + val file = File(System.getProperty("java.io.tmpdir"), "openstrap-migration-${System.nanoTime()}.db") + // Built from the exported schema, so it's the database version 31 really made. + val schema = JSONObject(File("schemas/org.openstrap.app.data.db.OpenStrapDatabase/31.json").readText()).getJSONObject("database") + SQLiteDatabase.openOrCreateDatabase(file, null).use { db -> + val entities = schema.getJSONArray("entities") + for (i in 0 until entities.length()) { + val e = entities.getJSONObject(i) + val table = e.getString("tableName") + db.execSQL(e.getString("createSql").replace("\${TABLE_NAME}", table)) + val indices = e.optJSONArray("indices") ?: continue + for (j in 0 until indices.length()) db.execSQL(indices.getJSONObject(j).getString("createSql").replace("\${TABLE_NAME}", table)) + } + val setup = schema.getJSONArray("setupQueries") + for (i in 0 until setup.length()) db.execSQL(setup.getString(i)) + val old = System.currentTimeMillis() / 1000 - 8 * 86_400L + val now = System.currentTimeMillis() / 1000 + db.execSQL("INSERT INTO sleep_session (start, `end`, day, nap, source) VALUES (100000, 130000, 86400, 0, 0)") + // Exact and resent 10 minutes off stay; a nap edit near a main sleep has no nap near and goes. + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (100000, 0, 99000, 131000, 0, $now)") + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (99400, 0, NULL, NULL, 1, $now)") + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (100500, 1, 100000, 103000, 0, $now)") + // Left by a minute night: a move and a delete with no session near, and an old delete marker that stays. + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (500000, 0, 499000, 530000, 0, $now)") + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (600000, 0, NULL, NULL, 1, $now)") + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (700000, 0, NULL, NULL, 1, $old)") + db.version = 31 + } + + val room = Room.databaseBuilder(ApplicationProvider.getApplicationContext(), OpenStrapDatabase::class.java, file.absolutePath) + .addMigrations(*OpenStrapDatabase.MIGRATIONS).allowMainThreadQueries().build() + try { + val db = room.openHelper.readableDatabase + assertEquals( + listOf(99400L, 100000L, 700000L), + db.query("SELECT strapStart FROM sleep_edit ORDER BY strapStart").use { c -> List(c.count) { c.moveToNext(); c.getLong(0) } }, + ) + } finally { + room.close() + listOf("", "-wal", "-shm", "-journal").forEach { File(file.path + it).delete() } + } + } +} From e290aecd37fd770a8fe7c444e10847f86b8966ee Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:12:02 +0400 Subject: [PATCH 09/18] A deleted phone workout is taken out of Health Connect too, with its session and distance Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/OpenStrapApp.kt | 1 + .../app/device/SavedWorkoutEditor.kt | 7 +++- .../openstrap/app/device/WorkoutSession.kt | 4 +- .../openstrap/app/health/AutoHealthConnect.kt | 10 +++++ .../app/health/HealthConnectExporter.kt | 23 +++++++++++ .../openstrap/app/health/RecordStoreTest.kt | 41 +++++++++++++++++++ 6 files changed, 84 insertions(+), 2 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt index b59af8cf..bae906a8 100644 --- a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt +++ b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt @@ -50,6 +50,7 @@ class AppContainer(val app: Application) { val autoHealthConnect = org.openstrap.app.health.HealthConnectAutoSync(app, settings, healthConnect, strap, scope = appScope) val workout = org.openstrap.app.device.WorkoutSession( app, database.healthDao(), settings, strap, maxHeartRates, callRinging = { phoneAlerts.callRinging }, onSaved = autoHealthConnect::workoutSaved, + onRemoved = autoHealthConnect::workoutDiscarded, scope = appScope, ) /** Saved and the Keep recording notice, from the session's state, on the app scope (audit S10). */ diff --git a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt index 65f68453..8b5a6299 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt @@ -32,6 +32,8 @@ internal class SavedWorkoutEditor( private val scope: CoroutineScope, /** The route and step totals still in memory for the workout [start] (the last one recorded), else null. */ private val track: (start: Long) -> WorkoutDistance.Track? = { null }, + /** The workout [start] was deleted, with all it was recorded over, [from] to [to]: auto sync takes it out of Health Connect. */ + private val onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, ) { /** * Deletes a phone workout, and closes its summary if it is the one showing. The strap's own records of it @@ -44,7 +46,10 @@ internal class SavedWorkoutEditor( // One transaction: not deleted, nothing is, its summary stays, and Discard can be tried again. val w = catching { dao.discardAppWorkout(start, clock()) } .onFailure { log("workout not discarded: ${it.message}") }.getOrElse { return@withLock } - if (w?.end != null) refreshDays(w.start, w.recordedEnd ?: w.end) + if (w?.end != null) { + refreshDays(w.start, w.recordedEnd ?: w.end) + onRemoved(w.start, w.start, w.recordedEnd ?: w.end) + } onDiscarded(start) } } diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt index e7c73a6b..95378a33 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -136,6 +136,8 @@ class WorkoutSession( private val callRinging: () -> Boolean = { false }, /** A finished workout was saved or changed, by its start: auto sync writes it to Health Connect. Returns at once. */ private val onSaved: (start: Long) -> Unit = {}, + /** A saved workout was deleted, by its start and the range it was recorded over: auto sync takes it out of Health Connect. */ + private val onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, /** Epoch seconds now. Tests pass a clock they move by hand. */ private val clock: () -> Long = { System.currentTimeMillis() / 1000 }, /** Where the workout's long-lived work runs: the app's scope, `AppContainer.appScope`. */ @@ -150,7 +152,7 @@ class WorkoutSession( /** Discard, trim and save from history: changes to workouts already saved, under the same [lock]. */ private val editor = SavedWorkoutEditor( dao, settings, lock, onSaved, onDiscarded = ::closeDiscarded, log = { log(it) }, clock = clock, scope = scope, - track = { start -> if (start == trackStart) track() else null }, + track = { start -> if (start == trackStart) track() else null }, onRemoved = onRemoved, ) /** diff --git a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt index 12d6432c..aef22ef7 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt @@ -116,6 +116,16 @@ class HealthConnectAutoSync( } } + /** A phone workout was deleted: takes its session and distance out of Health Connect now, as it is saved now. */ + fun workoutDiscarded(start: Long, from: Long, to: Long) { + scope.launch { + guarded("workout $start deleted") { + exporter.deleteWorkout(start, from, to) + Log.i(TAG, "health connect: took out workout $start") + } + } + } + /** * A sleep or nap the strap started at [strapStart] was moved, deleted or brought back: writes its night again now * ([AutoHealthConnect.sleepRange]), not on the next sync, so Health Connect moves or drops it too. diff --git a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt index f8c05881..8f1f76d2 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -305,6 +305,14 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt return records.size } + /** + * The phone workout [start], deleted, taken out of Health Connect: its exercise session and distance, found within + * [from, to], all it was recorded over. Its days' calories are written again by the next sync, as any change to them. + */ + suspend fun deleteWorkout(start: Long, from: Long, to: Long) { + writeLock.withLock { store.dropPhoneWorkout(start, from, to) } + } + /** * Active kcal an hour and each finished full day's total ([CalorieRecords]) over the whole local days [from] to * [to] are in, from the stored days, each only with its permission granted. A day worked out again can lose an @@ -665,6 +673,21 @@ internal suspend fun RecordStore.dropStaleStrapWorkouts(from: Long, to: Long, wr stale.chunked(HC_BATCH).forEach { deleteIds(androidx.health.connect.client.records.ExerciseSessionRecord::class, it) } } +/** + * Takes out OpenStrap's own exercise session and distance records of the phone workout [start], found within + * [from, to] (all it was recorded over): the workout was deleted. Nothing is taken out when the records can't be read. + */ +internal suspend fun RecordStore.dropPhoneWorkout(start: Long, from: Long, to: Long) { + val range = TimeRangeFilter.between(Instant.ofEpochSecond(from), Instant.ofEpochSecond(to)) + for ((type, id) in listOf( + androidx.health.connect.client.records.ExerciseSessionRecord::class to "openstrap:workout:$start", + androidx.health.connect.client.records.DistanceRecord::class to "openstrap:distance:$start", + )) { + val stale = ownRecords(type, range).orEmpty().filter { it.metadata.clientRecordId == id }.map { it.metadata.id } + stale.chunked(HC_BATCH).forEach { deleteIds(type, it) } + } +} + /** The blood oxygen percents that are kept, and so exported: Zepp's range. */ private val SPO2_KEPT = 80..100 diff --git a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt index ed7b99cf..129015fe 100644 --- a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt @@ -1,9 +1,12 @@ package org.openstrap.app.health +import androidx.health.connect.client.records.DistanceRecord +import androidx.health.connect.client.records.ExerciseSessionRecord import androidx.health.connect.client.records.Record import androidx.health.connect.client.records.SleepSessionRecord import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.time.TimeRangeFilter +import androidx.health.connect.client.units.Length import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.sync.Mutex @@ -107,4 +110,42 @@ class RecordStoreTest { writers.awaitAll() assertTrue(!overlapped) } + + private val device = androidx.health.connect.client.records.metadata.Device(type = 0) + + private fun session(start: Long, id: String, recordId: String) = ExerciseSessionRecord( + startTime = Instant.ofEpochSecond(start), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(start + 1800), endZoneOffset = ZoneOffset.UTC, + exerciseType = ExerciseSessionRecord.EXERCISE_TYPE_RUNNING, + metadata = Metadata.autoRecorded(device = device, clientRecordId = id), + ).also { setId(it.metadata, recordId) } + + private fun distance(start: Long, id: String, recordId: String) = DistanceRecord( + startTime = Instant.ofEpochSecond(start), startZoneOffset = ZoneOffset.UTC, + endTime = Instant.ofEpochSecond(start + 1800), endZoneOffset = ZoneOffset.UTC, + distance = Length.meters(5000.0), metadata = Metadata.autoRecorded(device = device, clientRecordId = id), + ).also { setId(it.metadata, recordId) } + + private fun setId(metadata: Metadata, recordId: String) { + Metadata::class.java.getDeclaredField("id").apply { isAccessible = true }.set(metadata, recordId) + } + + @Test fun `a deleted phone workout takes its session and distance out, and no other`() = runTest { + val store = FakeStore( + listOf( + session(1000, "openstrap:workout:1000", "a"), distance(1000, "openstrap:distance:1000", "b"), + session(9000, "openstrap:workout:9000", "c"), distance(9000, "openstrap:distance:9000", "d"), + session(1000, "openstrap:strapworkout:1000", "e"), + ), + ) + store.dropPhoneWorkout(1000, 1000, 2800) + assertEquals(listOf("c", "d", "e"), store.records.map { it.metadata.id }) + } + + @Test fun `a deleted phone workout stays when its records can't be read`() = runTest { + val held = listOf(session(1000, "openstrap:workout:1000", "a")) + val store = FakeStore(held, readable = false) + store.dropPhoneWorkout(1000, 1000, 2800) + assertEquals(held, store.records) + } } From c8bf4f17f86116744d1203a3f1c492cfeec22d98 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:12:20 +0400 Subject: [PATCH 10/18] The oldest of the fourteen nights now averages its HRV, skin temperature, SpO2 and breathing from the evening it began, not from that day's midnight Co-Authored-By: Claude Opus 5.5 --- .../org/openstrap/app/data/RoomDayRepository.kt | 14 ++++++++------ .../openstrap/app/data/RoomDayRepositoryTest.kt | 13 +++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt index cea1ae26..ce7e4114 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/RoomDayRepository.kt @@ -52,10 +52,12 @@ class RoomDayRepository( val span = DayWindow( SleepHistory.endingOn(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, SleepHistory.endingOn(date, zone).to, ) + // The oldest night began the evening before its day, so its readings start there, not at that midnight. + val readings = DayWindow(SleepHistory.readingsOf(date.minusDays(SleepHistory.NIGHTS - 1L), zone).from, span.to) val extras = combine(health.skinTemperature(day), health.breathRate(night), health.latestPai(day.to)) { skin, breath, pai -> Triple(skin, breath, pai?.takeIf { it.timestamp >= day.from }) } - val sleepAndExtras = combine(nights(date, night, span, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) } + val sleepAndExtras = combine(nights(date, night, span, readings, zone), extras, baselines(date)) { s, e, b -> Triple(s, e, b) } // The strap's own running total covers steps whose minute records were already taken by another app. val todayLive = if (isToday) strapSteps else flowOf(null) @@ -117,13 +119,13 @@ class RoomDayRepository( } /** - * The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each, and - * the night's own readings for the charts of the night-scoped details. + * The day's sleep ([sleep]), the [SleepHistory.NIGHTS] nights over [span] with the vitals averaged over each (read over + * [readings], from the oldest night's evening), and the night's own readings for the charts of the night-scoped details. */ - private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, zone: ZoneId): Flow = combine( + private fun nights(date: LocalDate, night: DayWindow, span: DayWindow, readings: DayWindow, zone: ZoneId): Flow = combine( sleep(date, span, zone), - combine(health.hrv(span), health.skinTemperature(span)) { h, s -> h to s }, - combine(health.spo2(span), health.breathRate(span)) { o, b -> o to b }, + combine(health.hrv(readings), health.skinTemperature(readings)) { h, s -> h to s }, + combine(health.spo2(readings), health.breathRate(readings)) { o, b -> o to b }, health.heartRate(night), ) { sleepParts, (hrv, skin), (spo2, breath), hr -> val (parts, sessions, osa) = sleepParts diff --git a/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt b/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt index e8fafeff..71953dca 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/RoomDayRepositoryTest.kt @@ -16,6 +16,7 @@ import org.openstrap.app.data.db.ActivityMinute import org.openstrap.app.data.db.HrvSample import org.openstrap.app.data.db.OpenStrapDatabase import org.openstrap.app.data.db.SleepSession +import org.openstrap.app.data.db.Spo2Sample import org.openstrap.app.testing.ZoneRule import org.openstrap.app.testing.inMemoryDb import org.openstrap.protocol.services.StepTotals @@ -91,6 +92,18 @@ class RoomDayRepositoryTest { assertEquals(listOf(60), d.sleepHrv.map { it.milliseconds }) } + @Test fun `the oldest night's averages include its evening, from before that midnight`() { + val oldest = date.minusDays(SleepHistory.NIGHTS - 1L) + // It began at 23:00 the evening before its day, so the reading at 23:30 is before the midnight its day starts at. + runBlocking { + db.healthDao().insertSleepSessions(listOf(SleepSession(at(oldest.minusDays(1), 23), at(oldest, 7)))) + db.healthDao().insertSpo2(listOf(Spo2Sample(at(oldest.minusDays(1), 23, 30), 95))) + } + val d = day { n -> n.nights.first().spo2 != null } + assertEquals(oldest, d.nights.first().date) + assertEquals(95f, d.nights.first().spo2) + } + @Test fun `the week's trends run to the day shown, with nothing where a day has no data`() { val d = day() assertEquals((6L downTo 0L).map { date.minusDays(it) }, d.hrvTrend.map { it.date }) From 276760e873703de5aa9758a88f186834c5336597 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:12:35 +0400 Subject: [PATCH 11/18] A trimmed or untrimmed workout works its fastest 1k, 5k and 10k out again from its kept route Co-Authored-By: Claude Opus 5.5 --- .../app/device/SavedWorkoutEditor.kt | 34 ++++++++++++++----- .../app/device/WorkoutSessionTest.kt | 26 ++++++++++++++ 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt index 8b5a6299..f548dba8 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt @@ -98,7 +98,9 @@ internal class SavedWorkoutEditor( scope.launch { lock.withLock { val w = catching { dao.appWorkoutOnce(start) }.getOrNull()?.takeIf { it.end != null } ?: return@withLock - val changed = change(w).let { c -> if (c.from == w.from && c.end == w.end) c else withDistance(w, c) } + val changed = change(w).let { c -> + if (c.from == w.from && c.end == w.end) c else trackOf(w).let { withStretches(withDistance(w, c, it), it) } + } if (changed == w) return@withLock catching { dao.upsertAppWorkout(withEffect(changed, dao.appWorkoutHeartRateOnce(start))) } .onFailure { log("workout edit not saved: ${it.message}") } @@ -110,21 +112,35 @@ internal class SavedWorkoutEditor( } } + /** What [old]'s distance and stretches are worked out from again: the route and step totals in memory, or a kept route. */ + private suspend fun trackOf(old: AppWorkout): WorkoutDistance.Track? = track(old.start) ?: run { + if (!old.keepRoute) return@run null + catching { dao.routeOnce(old.start).map { it.point } }.getOrNull() + ?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) } + } + /** - * [new], a new range of [old], with the distance over it ([WorkoutDistance]): from the route and step totals in - * memory, or a kept route, and without either [old]'s by the share of moving time kept. + * [new], a new range of [old], with the distance over it ([WorkoutDistance]): from [track], and without it + * [old]'s by the share of moving time kept. */ - private suspend fun withDistance(old: AppWorkout, new: AppWorkout): AppWorkout { - val track = track(old.start) ?: run { - if (!old.keepRoute) return@run null - catching { dao.routeOnce(old.start).map { it.point } }.getOrNull() - ?.let { WorkoutDistance.Track(it, emptyList(), null, routeSince = old.start, stepsSince = old.start) } - } + private fun withDistance(old: AppWorkout, new: AppWorkout, track: WorkoutDistance.Track?): AppWorkout { val shown = track?.let { WorkoutDistance.shown(new, clock(), it) } return if (shown != null) new.copy(distanceMeters = shown.first, distanceFromSteps = shown.second) else new.copy(distanceMeters = WorkoutDistance.scaledTo(old, new)) } + /** + * [w] with its fastest stretches worked out again over the range it shows, as when it was saved: a trim can leave a + * stretch that started outside it, and an undo needs ones never worked out. Left as they are without the whole route. + */ + private fun withStretches(w: AppWorkout, track: WorkoutDistance.Track?): AppWorkout { + val end = w.end ?: return w + if (track == null || track.routeSince > w.start || track.route.isEmpty()) return w + val stretches = org.openstrap.app.data.Rewards.stretches(track.route.filter { it.t in w.from..end }, w.pauseRanges) + .let(org.openstrap.app.data.Rewards.Stretch::format) + return w.copy(stretches = stretches) + } + /** Writes the daily calories rows from [from] to [to] again ([org.openstrap.app.data.DailyCaloriesHistory.updateDays]). */ suspend fun refreshDays(from: Long, to: Long) { catching { org.openstrap.app.data.DailyCaloriesHistory(dao).updateDays(from, to, settings.profile.first()) } diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt index dcd3ab89..fcf5e416 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -700,6 +700,32 @@ class WorkoutSessionTest { assertEquals(full, storedOnce(t0) { it?.end == t0 + 600 }!!.distanceMeters!!, 0.5f) } + @Test + fun aTrimWorksTheFastestStretchesOutAgainFromTheKeptRoute() { + val t0 = clock.now - 7200 + // A straight line at 3 m/s for twenty minutes, a fix every 10 s: 3.6 km. + val route = (0L..1200L step 10).map { Route.Point(t0 + it, 51.5 + it * 3 / 111_195.0, -0.1, 5f) } + val first = org.openstrap.app.data.Rewards.Stretch(1000, 333, t0) + runBlocking { + db.healthDao().upsertAppWorkout( + AppWorkout( + start = t0, end = t0 + 1200, sportType = SportTypes.WALK, useGps = true, keepRoute = true, + distanceMeters = Route.distance(route).toFloat(), stretches = first.code, + ), + ) + db.healthDao().insertRoutePoints(route.map { AppWorkoutRoutePoint.of(t0, it) }) + } + val s = session() + s.trim(t0, from = t0 + 300, to = t0 + 1200) + val trimmed = storedOnce(t0) { it?.shownStart == t0 + 300 }!! + val kept = org.openstrap.app.data.Rewards.Stretch.parse(trimmed.stretches).single { it.meters == 1000 } + assertTrue(kept.start >= t0 + 300) + assertEquals(333f, kept.seconds.toFloat(), 5f) + s.undoTrim(t0) + val back = storedOnce(t0) { it?.shownStart == null }!! + assertTrue(org.openstrap.app.data.Rewards.Stretch.parse(back.stretches).any { it.meters == 1000 }) + } + @Test fun aTrimWithNoRouteLeftKeepsTheShareOfTheDistance() { val t0 = clock.now - 3600 From cc896ffee7496e09029d10a0b166ea5890141ead Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:13:05 +0400 Subject: [PATCH 12/18] Step badges and bests come without workouts, follow each sync, and the last workout deleted takes its bests The rewards were only worked out with a workout in the list, so with none recorded the step badges and the most steps never came, and deleting the only workout left its bests and its week as they were. Now an empty list waits only while workouts are stored (the list still loading). The refresh also runs after each sync, which writes the days' steps. The rewards page shows what it had when working it out fails, and tries again, instead of Loading. Co-Authored-By: Claude Opus 5.5 --- .../org/openstrap/app/data/RewardsKeeper.kt | 9 +++--- .../openstrap/app/ui/root/AppRootViewModel.kt | 32 +++++++++++++++---- .../openstrap/app/data/RewardsKeeperTest.kt | 28 ++++++++++++++++ 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt b/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt index 039798ae..d000ed2f 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/RewardsKeeper.kt @@ -85,11 +85,10 @@ class RewardsKeeper( /** Works everything out again from [workouts] against [goal] and stores it. */ suspend fun refresh(workouts: List, goal: Int) = refreshLock.withLock { - // The list starts empty before it loads: only a database with no workouts at all starts the rewards empty. - if (workouts.isEmpty()) { - if (!settings.rewardsStarted.first() && !dao.anyWorkoutOnce()) settings.startRewards(historyBadges = false) - return@withLock - } + // The list starts empty before it loads, so an empty list waits while workouts are stored. With none stored it + // is worked out all the same: the step badges and bests need no workout, and deleting the last workout takes + // its bests and its week with it. + if (workouts.isEmpty() && dao.anyWorkoutOnce()) return@withLock val f = facts(workouts) withContext(Dispatchers.Default) { val today = LocalDate.now(f.zone) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt index fe84f616..d8a33e69 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt @@ -5,6 +5,7 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -14,13 +15,13 @@ import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.distinctUntilChangedBy -import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onSubscription import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -175,11 +176,27 @@ class AppRootViewModel( val rewardsView: StateFlow = combine(workouts, goals.map { it.workoutsPerWeek }, dao.personalBests(), dao.badges()) { list, goal, bests, earned -> RewardsInputs(list, goal, bests, earned) - }.filter { it.workouts.isNotEmpty() || !dao.anyWorkoutOnce() } - .mapLatest { i -> catching { rewards.view(i.workouts, i.goal, i.bests, i.earned) }.getOrNull() } + }.mapLatest { i -> viewOf(i, dao) } + // Null is the list still loading, or a view that couldn't be worked out: what showed before stays. + .filterNotNull() .flowOn(work) .state(null) + /** + * The rewards page for [i], tried [VIEW_TRIES] times [VIEW_RETRY_MS] apart, as a read can hit a locked database. + * Null while the list is still loading (empty with workouts stored), or when every try failed. + */ + private suspend fun viewOf(i: RewardsInputs, dao: HealthDao): RewardsView? { + repeat(VIEW_TRIES) { n -> + if (n > 0) delay(VIEW_RETRY_MS) + catching { + if (i.workouts.isEmpty() && dao.anyWorkoutOnce()) return null + return rewards.view(i.workouts, i.goal, i.bests, i.earned) + }.onFailure { Log.w(TAG, "rewards page not worked out", it) } + } + return null + } + private class RewardsInputs( val workouts: List, val goal: Int, @@ -199,11 +216,12 @@ class AppRootViewModel( // (workouts spec 4), and on a new goal. The one recording isn't in it until it ends. Started at once, as the // weekly recap notification reads what's stored. val recording = workout.state.map { (it as? WorkoutState.Recording)?.workout?.start }.distinctUntilChanged() + // Each sync too: the step badges and the most steps follow the days' steps, which only a sync writes. viewModelScope.launch(work) { - combine(workouts, recording, settings.goals) { list, start, g -> + val inputs = combine(workouts, recording, settings.goals) { list, start, g -> list.filter { it.workout.start != start } to g.workoutsPerWeek - } - .distinctUntilChangedBy { (list, goal) -> list.map { Triple(it.workout.start, it.shownStart, it.end) } to goal } + }.distinctUntilChangedBy { (list, goal) -> list.map { Triple(it.workout.start, it.shownStart, it.end) } to goal } + combine(inputs, strap.syncEnded.onSubscription { emit(Unit) }) { i, _ -> i } .collectLatest { (list, goal) -> catching { rewards.refresh(list, goal) }.onFailure { Log.w(TAG, "rewards failed", it) } } } } @@ -289,5 +307,7 @@ class AppRootViewModel( private companion object { const val TAG = "unstrap" const val STOP_MS = 5_000L + const val VIEW_TRIES = 3 + const val VIEW_RETRY_MS = 2_000L } } diff --git a/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt b/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt index 15c34581..fd1f4c69 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/RewardsKeeperTest.kt @@ -115,6 +115,34 @@ class RewardsKeeperTest { assertTrue(settings.rewardsStarted.first()) } + @Test fun `steps earn their badge and best with no workout at all`() = runBlocking { + val dao = db.healthDao() + // 10,000 steps in one day: 100 minutes of 100, from 10:00 local so they never cross midnight. + val morning = java.time.LocalDate.of(2026, 10, 15).atTime(10, 0).atZone(java.time.ZoneId.systemDefault()).toEpochSecond() + dao.insertActivity((0 until 100).map { ActivityMinute(morning + it * 60L, 100, 0, 0, null) }) + RewardsKeeper(dao, settings).refresh(emptyList(), 3) + assertTrue(dao.badgesOnce().any { it.id == "first_10k_steps" }) + assertTrue(dao.personalBestsOnce().any { it.kind == Rewards.Kind.MOST_STEPS }) + // Earned before the rewards started, so it waits with the history badges. + assertTrue(settings.historyBadgesWaiting.first()) + } + + @Test fun `deleting the last workout takes its bests and its week, and the badges stay`() = runBlocking { + val dao = db.healthDao() + val keeper = RewardsKeeper(dao, settings) + val w = workout(0) + dao.insertAppWorkouts(listOf(w)) + keeper.refresh(listOf(WorkoutRecorder.analyse(w, emptyList(), 190, HeartZones.STANDARD)), 3) + assertTrue(dao.personalBestsOnce().isNotEmpty()) + assertEquals(1, dao.weekResultsOnce().sumOf { it.count }) + val badges = dao.badgesOnce() + dao.deleteAppWorkout(w.start) + keeper.refresh(emptyList(), 3) + assertTrue(dao.personalBestsOnce().isEmpty()) + assertEquals(0, dao.weekResultsOnce().sumOf { it.count }) + assertEquals(badges, dao.badgesOnce()) + } + @Test fun `a strap workout is history, so the empty list waits for it`() = runBlocking { val dao = db.healthDao() dao.insertWorkouts(listOf(org.openstrap.app.testing.workout(start))) From f99283e3534ce75da1ba87228ed7857869028a7b Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:13:26 +0400 Subject: [PATCH 13/18] Auto backup: a provider that can't rename still replaces the day's earlier backup, as before Co-Authored-By: Claude Opus 5.5 --- .../main/kotlin/org/openstrap/app/export/AutoBackup.kt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt index 638267aa..07cb5849 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt @@ -122,14 +122,16 @@ class AutoBackup( try { (resolver.openOutputStream(temp.uri, "w") ?: throw Failed(BackupFailure.CantWrite)).use { backups.writeZip(it) } // A second run on the same day replaces the first, but only once the new one is in place: the old one is - // moved aside, and put back if the new one can't be written. - val previous = dir.findFile(name) + // moved aside, and put back if the new one can't be written. A provider that can't rename deletes it first, + // as before: the new one is complete by then. val aside = BackupFiles.asideName(today) - if (previous != null && !previous.renameTo(aside)) throw Failed(BackupFailure.CantWrite) + val previous = dir.findFile(name) + val movedAside = previous != null && previous.renameTo(aside) + if (previous != null && !movedAside && !previous.delete()) throw Failed(BackupFailure.CantWrite) try { if (!temp.renameTo(name)) copyAs(dir, temp, name) } catch (e: Throwable) { - if (previous != null) runCatching { dir.findFile(aside)?.renameTo(name) } + if (movedAside) runCatching { dir.findFile(aside)?.renameTo(name) } throw e } dir.findFile(aside)?.let(::deleteQuietly) From 72ca7e3ab619008a8fbd5dd523392544cdd184c9 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:14:02 +0400 Subject: [PATCH 14/18] Health Connect: a deleted workout's records are looked for a day either side of it Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/health/HealthConnectExporter.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt index 8f1f76d2..c13336d8 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -678,7 +678,9 @@ internal suspend fun RecordStore.dropStaleStrapWorkouts(from: Long, to: Long, wr * [from, to] (all it was recorded over): the workout was deleted. Nothing is taken out when the records can't be read. */ internal suspend fun RecordStore.dropPhoneWorkout(start: Long, from: Long, to: Long) { - val range = TimeRangeFilter.between(Instant.ofEpochSecond(from), Instant.ofEpochSecond(to)) + // A day wider each side: the ids pick the records, so the range only has to hold them, however the filter treats + // a session's ends. + val range = TimeRangeFilter.between(Instant.ofEpochSecond(from).minus(Duration.ofDays(1)), Instant.ofEpochSecond(to).plus(Duration.ofDays(1))) for ((type, id) in listOf( androidx.health.connect.client.records.ExerciseSessionRecord::class to "openstrap:workout:$start", androidx.health.connect.client.records.DistanceRecord::class to "openstrap:distance:$start", From 9088b5d1b47e81efa49c5de3a6eb5f0cb9550e29 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:18:54 +0400 Subject: [PATCH 15/18] Orphan sleep edits: only main sleeps in the weeks minute nights were made for, and tests follow version 32 and the alarms read error The cleanup took any edit with no session near, which reached nap edits and old databases' edits that other migrations keep. Now it only touches main sleep edits from 20 October to 12 November 2026. Co-Authored-By: Claude Opus 5.5 --- .../app/data/db/OrphanSleepEditMigration.kt | 22 +++++++++++----- .../app/data/db/DayKeyMigrationTest.kt | 4 +-- .../data/db/OrphanSleepEditMigrationTest.kt | 26 ++++++++++++------- .../app/ui/alarms/AlarmsViewModelTest.kt | 3 ++- 4 files changed, 36 insertions(+), 19 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt index ad7e77ab..4778aef1 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigration.kt @@ -7,18 +7,28 @@ import org.openstrap.app.data.SleepEdits /** * Version 31 to 32: the edits left behind by the nights [MinuteSleepMigration] deleted go. An edit finds a session of * its kind within [SleepEdits.MATCH_SECONDS], so one of those could have moved or hidden a real strap night near it. - * An edit with no session that close goes, except a marker for a deleted sleep whose time to restore has run out - * ([SleepEdits.marker]), which has none by design. No schema change. + * + * Only where those nights could be: main sleeps from [FROM] to [TO], the two weeks 3.0.0 to 3.0.2 looked back over and + * the days they ran. Such an edit with no main sleep that close goes, except a marker for a deleted sleep whose time + * to restore has run out ([SleepEdits.marker]), which has none by design. Every other edit stays as it was. No schema + * change. */ -@Suppress("MagicNumber") // The versions it runs between are what the migration is. +@Suppress("MagicNumber") // The versions it runs between, and the dates the minute nights were made for, are what it is. object OrphanSleepEditMigration : Migration(31, 32) { + /** 2026-10-20 00:00 UTC, before the earliest night 3.0.0 (7 November) could make from the minutes. */ + const val FROM = 1_792_454_400L + + /** 2026-11-12 00:00 UTC, after 3.0.3 (10 November) deleted them and made no more. */ + const val TO = 1_794_441_600L + override fun migrate(db: SupportSQLiteDatabase) { val keptBefore = System.currentTimeMillis() / 1000 - SleepEdits.KEEP_DAYS * 86_400L db.execSQL( - "DELETE FROM `sleep_edit` WHERE NOT (`deleted` = 1 AND `start` IS NULL AND `editedAt` < ?) AND NOT EXISTS " + - "(SELECT 1 FROM `sleep_session` WHERE `sleep_session`.`nap` = `sleep_edit`.`nap` AND " + + "DELETE FROM `sleep_edit` WHERE `nap` = 0 AND `strapStart` BETWEEN ? AND ? " + + "AND NOT (`deleted` = 1 AND `start` IS NULL AND `editedAt` < ?) AND NOT EXISTS " + + "(SELECT 1 FROM `sleep_session` WHERE `sleep_session`.`nap` = 0 AND " + "ABS(`sleep_session`.`start` - `sleep_edit`.`strapStart`) <= ${SleepEdits.MATCH_SECONDS})", - arrayOf(keptBefore), + arrayOf(FROM, TO, keptBefore), ) } } diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt index 2e69654a..a73d33ef 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/db/DayKeyMigrationTest.kt @@ -135,7 +135,7 @@ class DayKeyMigrationTest { assertEquals(wakes.flatMap { listOf(listOf(it, 61L, 0L), listOf(it + 60, 64L, 1L)) }, rows(db, "SELECT * FROM heart_rate ORDER BY timestamp")) assertEquals(wakes.map { it - 9 * 3600 }, keys(db, "osa_result", "belongTime")) assertEquals(listOf(listOf(1_780_000_000L, 1_780_000_600L, 1_780_028_800L)), rows(db, "SELECT strapStart, start, `end` FROM sleep_edit")) - assertEquals(31, db.openHelper.readableDatabase.version) + assertEquals(32, db.openHelper.readableDatabase.version) // Room reads them as the dates. val dao = db.healthDao() assertEquals(dates, dao.restingHrAll().map { it.day }) @@ -220,7 +220,7 @@ class DayKeyMigrationTest { put("INSERT INTO personal_best (kind, value, date, workoutStart) VALUES ('MOST_STEPS', 15000, 1790000000, NULL)") } val db = harness.open(file, newYork) - assertEquals(31, db.openHelper.readableDatabase.version) + assertEquals(32, db.openHelper.readableDatabase.version) assertEquals(listOf(d), db.healthDao().restingHrAll().map { it.day }) assertEquals(listOf(listOf("steps_10k", 1_790_000_000L, null, d.toEpochDay())), rows(db, "SELECT * FROM badge")) assertEquals(listOf(listOf(d.toEpochDay(), 3L, 4L, 1L)), rows(db, "SELECT * FROM week_result")) diff --git a/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt index c833b6f0..136e87a9 100644 --- a/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/data/db/OrphanSleepEditMigrationTest.kt @@ -34,15 +34,21 @@ class OrphanSleepEditMigrationTest { for (i in 0 until setup.length()) db.execSQL(setup.getString(i)) val old = System.currentTimeMillis() / 1000 - 8 * 86_400L val now = System.currentTimeMillis() / 1000 - db.execSQL("INSERT INTO sleep_session (start, `end`, day, nap, source) VALUES (100000, 130000, 86400, 0, 0)") - // Exact and resent 10 minutes off stay; a nap edit near a main sleep has no nap near and goes. - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (100000, 0, 99000, 131000, 0, $now)") - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (99400, 0, NULL, NULL, 1, $now)") - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (100500, 1, 100000, 103000, 0, $now)") - // Left by a minute night: a move and a delete with no session near, and an old delete marker that stays. - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (500000, 0, 499000, 530000, 0, $now)") - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (600000, 0, NULL, NULL, 1, $now)") - db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES (700000, 0, NULL, NULL, 1, $old)") + // 21 October 2026 22:00 UTC, inside the weeks minute nights were made for. + val night = 1_792_620_000L + fun edit(strapStart: Long, nap: Int, start: Long?, end: Long?, deleted: Int, at: Long) = + db.execSQL("INSERT INTO sleep_edit (strapStart, nap, start, `end`, deleted, editedAt) VALUES ($strapStart, $nap, $start, $end, $deleted, $at)") + db.execSQL("INSERT INTO sleep_session (start, `end`, day, nap, source) VALUES ($night, ${night + 30_000}, 86400, 0, 0)") + // A strap night's edits stay: exact, and resent 10 minutes off. A nap edit is never touched. + edit(night, 0, night - 1000, night + 31_000, 0, now) + edit(night - 600, 0, null, null, 1, now) + edit(night + 500, 1, night, night + 3000, 0, now) + // Left by minute nights: a move and a delete with no night near go; an expired delete marker stays. + edit(night + 400_000, 0, night + 399_000, night + 430_000, 0, now) + edit(night + 500_000, 0, null, null, 1, now) + edit(night + 600_000, 0, null, null, 1, old) + // Outside those weeks nothing is touched, with a night near or not. + edit(100_000, 0, 99_000, 130_000, 0, now) db.version = 31 } @@ -51,7 +57,7 @@ class OrphanSleepEditMigrationTest { try { val db = room.openHelper.readableDatabase assertEquals( - listOf(99400L, 100000L, 700000L), + listOf(100_000L, 1_792_620_000L - 600, 1_792_620_000L, 1_792_620_000L + 500, 1_792_620_000L + 600_000), db.query("SELECT strapStart FROM sleep_edit ORDER BY strapStart").use { c -> List(c.count) { c.moveToNext(); c.getLong(0) } }, ) } finally { diff --git a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt index 4fdef88c..e4d30ee6 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/alarms/AlarmsViewModelTest.kt @@ -53,7 +53,8 @@ class AlarmsViewModelTest { val vm = AlarmsViewModel(failingStrap(failure)).also { models += it } val state = vm.state.value assertFalse(state.loading) - return state.error + // A failed read is the Alarms page's own error, apart from a failed write's. + return state.alarmsError } /** A strap whose alarm read fails with [failure]. Everything else answers empty. */ From f34faba7eed1bc8a103158e611c6e970198928e4 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:21:42 +0400 Subject: [PATCH 16/18] A workout left recording is never deleted for looking short, and a rest never ends while paused A restored workout took its last moment from its heart rate only, so one recorded without the strap was ended at its start and deleted with its route. Its last moment now comes from everything stored: heart rate, kept route, sets, rounds, laps and pauses. An end the app works out that would still leave under a minute doesn't end it: it records on (or comes back paused) for the wearer to end or delete, and End tapped then ends it where it was recorded to. A rest is now ended under the lock on the state as it is, never while paused, so a set started or +10 s tapped meanwhile wins and the rest over cue only plays for a rest it ended. Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/WorkoutSession.kt | 100 ++++++++++++++---- .../app/device/WorkoutSessionTest.kt | 69 ++++++++++++ 2 files changed, 146 insertions(+), 23 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt index 95378a33..ce726b7b 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -268,15 +268,21 @@ class WorkoutSession( val w = dao.activeAppWorkout() ?: return@withLock null val now = now() val stored = dao.appWorkoutHeartRateOnce(w.start) - val last = maxOf(w.start, stored.maxOfOrNull { it.timestamp } ?: w.start) + // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step totals. + val restored = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList() + val sets = dao.setsOnce(w.start) + val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList() + val last = lastKnown(w, stored, restored, sets, rounds) val waits = now - last > LEFT_RECORDING_S - // Paused, nothing the strap measured since is part of it. - if (waits && w.pausedAt != null) { + // Paused, nothing the strap measured since is part of it. Ending it then would leave under a minute only + // when nothing of it was stored: it comes back paused instead, for the wearer to end or delete. + if (waits && w.pausedAt != null && keptEndingAt(w, last)) { endLeftRecording(w, last) return@withLock null } - // Set before it shows as recording, so an End tapped at once already waits for the strap. - left = if (waits) LeftRecording.Left(w.start, last, now) else null + // Set before it shows as recording, so an End tapped at once already waits for the strap. One left paused + // only gets here when ending it would delete it: it doesn't wait. + left = if (waits && w.pausedAt == null) LeftRecording.Left(w.start, last, now) else null _recent.value = stored.filter { !it.fromHistory && it.timestamp >= now - RECENT_S }.map { it.timestamp to it.bpm } sum = stored.sumOf { it.bpm.toLong() } count = stored.size.toLong() @@ -297,20 +303,16 @@ class WorkoutSession( synchronized(allReadings) { allReadings.clear(); allReadings.addAll(live) } _history.value = live window = live.filter { it.first >= now - STOP_WINDOW_S } - // A kept route comes back. One that wasn't kept was only ever in memory, and so were the step - // totals. What was stored then stands for the time before now, and the distance adds to it. - val restored = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList() + // What was stored stands for the time before now, and the distance adds to it. _route.update { restored } savedPoints = _route.value.size trackFrom(w, routeSince = if (w.keepRoute) w.start else now, stepsSince = now, before = w) // A restart mustn't ask at once about a stop it can't see the start of. askSince = now - val sets = dao.setsOnce(w.start) val restUntil = sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null }?.let { it.end!! + restRule(w).seconds } // Logging is the sport's setting at its start, which Ready saved then. val log = catching { settings.sportSettings.first()[org.openstrap.app.data.Workouts.tileType(w.sportType)]?.log } .onFailure { log("workout: sport settings not read: $it") }.getOrNull() == true - val rounds = if (w.structure != null) dao.roundsOnce(w.start) else emptyList() begin(w, maxHr) { it.copy( sets = sets, restUntil = restUntil, exercise = sets.lastOrNull()?.exercise, logSets = log, rounds = rounds, @@ -542,7 +544,7 @@ class WorkoutSession( val l = left ?: return finish(null, AppWorkout.END_USER, toStrap) scope.launch { val v = judge(l, final = true) - if (v is LeftRecording.Verdict.End) finish(v.at, AppWorkout.END_AUTO, toStrap, startOf = l.start) + if (v is LeftRecording.Verdict.End) finish(v.at, AppWorkout.END_AUTO, toStrap, startOf = l.start, ifShort = IfShort.EndAsRecorded) else finish(null, AppWorkout.END_USER, toStrap) } } @@ -559,8 +561,21 @@ class WorkoutSession( _state.update { s -> (s as? WorkoutState.Recording)?.takeIf { it.endPrompt != null }?.copy(endPrompt = null, inCar = false) ?: s } } - /** [toStrap] false when the strap ended its session itself. [startOf]: only if it is still that workout recording. */ - private fun finish(at: Long?, reason: Int, toStrap: Boolean = true, startOf: Long? = null) { + /** What an end the app worked out ([LeftRecording]) does when it would leave under a minute, which deletes it. */ + private enum class IfShort { + /** Deleted, as any workout under a minute. */ + Delete, + /** Not ended: it records on for the wearer to end or delete (an end nobody chose). */ + RecordOn, + /** Ended where it was recorded to (End was tapped, so it ends, but not by deleting it). */ + EndAsRecorded, + } + + /** + * [toStrap] false when the strap ended its session itself. [startOf]: only if it is still that workout recording. + * [ifShort]: what an end at [at] that would leave under a minute does instead. + */ + private fun finish(at: Long?, reason: Int, toStrap: Boolean = true, startOf: Long? = null, ifShort: IfShort = IfShort.Delete) { scope.launch { lock.withLock { val r = _state.value as? WorkoutState.Recording ?: return@withLock @@ -573,10 +588,20 @@ class WorkoutSession( saveDistance() val w = r.workout val recorded = w.pausedAt ?: now() - val end = at?.coerceIn(w.start, recorded) ?: recorded + // Nothing said how long a workout left recording ran: deleting it would lose one the wearer started. + val asked = at?.coerceIn(w.start, recorded) ?: recorded + val short = !keptEndingAt(w, asked) + if (short && ifShort == IfShort.RecordOn) { + log("workout left recording: ending at ${java.time.Instant.ofEpochSecond(asked)} would delete it, it records on") + ending = false + left = null + return@withLock + } + val end = if (short && ifShort == IfShort.EndAsRecorded) recorded else asked + val endReason = if (end == asked) reason else AppWorkout.END_USER // Its distance written here, over the range it shows: an update() queued behind this lock would find // the workout already ended, and an early End leaves out what came after. - val ended = w.copy(end = end, pausedAt = null, endReason = reason, recordedEnd = recorded.takeIf { it > end }) + val ended = w.copy(end = end, pausedAt = null, endReason = endReason, recordedEnd = recorded.takeIf { it > end }) .let { WorkoutDistance.withShown(it, recorded, track()) } val kept = WorkoutRecorder.activeSeconds(ended, end) >= MIN_SAVED_S closeLast(r.sets, r.rounds, end) @@ -635,6 +660,23 @@ class WorkoutSession( } } + /** + * The last moment anything stored says [w] went on: its heart rate [stored], its kept [route], its [sets] and + * [rounds], its laps and pauses. Never before its start. Without the strap's heart rate a GPS run still has its + * route, so it isn't taken as ended at its start. + */ + private fun lastKnown( + w: AppWorkout, stored: List, route: List, + sets: List, rounds: List, + ): Long = ( + stored.map { it.timestamp } + route.map { it.t } + w.lapMarks + w.pauseRanges.map { it.last } + listOfNotNull(w.pausedAt) + + sets.flatMap { listOfNotNull(it.start, it.end, it.restEnd) } + rounds.flatMap { listOfNotNull(it.workStart, it.workEnd, it.restEnd) } + ).fold(w.start, ::maxOf) + + /** Whether [w] ended at [end] would be kept: [MIN_SAVED_S] active, or it is deleted as a mis-tap. */ + private fun keptEndingAt(w: AppWorkout, end: Long): Boolean = + WorkoutRecorder.activeSeconds(w.copy(end = end, pausedAt = null), end) >= MIN_SAVED_S + /** * A workout the app was killed during while paused, with no reading for [LEFT_RECORDING_S]: ended at its [last] * reading, as End then would have, and its summary shows. Nothing after [last] is part of it, so a gap fill has @@ -684,7 +726,7 @@ class WorkoutSession( when (v) { is LeftRecording.Verdict.End -> { log("workout left recording: ${v.why}, ended at ${java.time.Instant.ofEpochSecond(v.at)}") - finish(v.at, AppWorkout.END_AUTO, startOf = l.start) + finish(v.at, AppWorkout.END_AUTO, startOf = l.start, ifShort = IfShort.RecordOn) } LeftRecording.Verdict.CarryOn -> { log("workout left recording: still under way, it records on") @@ -842,7 +884,8 @@ class WorkoutSession( /** "+30 s". */ fun extendRest() = editSets { r -> r.restUntil?.let { r.copy(restUntil = it + org.openstrap.app.data.Strength.EXTEND_S) } ?: r } - private fun editSets(change: (WorkoutState.Recording) -> WorkoutState.Recording) { + /** [change] to the sets under the lock, saved; [then] runs once it is applied, not when it changed nothing. */ + private fun editSets(then: (() -> Unit)? = null, change: (WorkoutState.Recording) -> WorkoutState.Recording) { scope.launch { lock.withLock { val r = _state.value as? WorkoutState.Recording ?: return@withLock @@ -857,18 +900,29 @@ class WorkoutSession( ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise) ?.withSave(SavePart.Sets, failed) ?: it } + then?.invoke() } } } - /** Once a second while resting: rest is over at its time, or once heart rate holds below the chosen level. */ + /** + * Once a second while resting: rest is over at its time, or once heart rate holds below the chosen level. Never + * while paused. Decided again under the lock, so a set started or +10 s tapped meanwhile wins, and the cue only + * plays for a rest it really ended. + */ private fun checkRest() { val r = _state.value as? WorkoutState.Recording ?: return - val until = r.restUntil ?: return - val last = r.sets.lastOrNull()?.end ?: return - if (!org.openstrap.app.data.Strength.restOver(restRule(r.workout), last, until, window, now())) return - editSets { it.copy(sets = it.sets.dropLast(1) + it.sets.last().copy(restEnd = now()), restUntil = null) } - cue(org.openstrap.app.data.Cue.RestOver) + if (restEnded(r) == null) return + editSets(then = { cue(org.openstrap.app.data.Cue.RestOver) }) { restEnded(it) ?: it } + } + + /** [r] with its rest ended now, when a finished set's rest is under way, not paused, and over; else null. */ + private fun restEnded(r: WorkoutState.Recording): WorkoutState.Recording? { + if (r.paused) return null + val until = r.restUntil ?: return null + val last = r.sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null } ?: return null + if (!org.openstrap.app.data.Strength.restOver(restRule(r.workout), last.end!!, until, window, now())) return null + return r.copy(sets = r.sets.dropLast(1) + last.copy(restEnd = now()), restUntil = null) } /* ------------------------------------------- Rounds -------------------------------------------- */ diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt index fcf5e416..8fac6ebe 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -648,6 +648,53 @@ class WorkoutSessionTest { assertNull(saved.recordedEnd) } + @Test + fun aGpsRunLeftRecordingWithNoHeartRateEndsAtItsLastRoutePoint() { + // The strap was off: a 20 minute run with its route kept and no heart rate, and the app back five hours on. + val t0 = clock.now - 5 * 3600 + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1, useGps = true, keepRoute = true)) + db.healthDao().insertRoutePoints( + (0..1200 step 5).map { AppWorkoutRoutePoint.of(t0, org.openstrap.app.data.Route.Point(t0 + it, 51.5 + it * 1e-5, -0.1, 5f)) }, + ) + } + val s = session(leftWaitMs = SHORT_WAIT_MS) + s.restore() + assertEquals(WorkoutState.Ended(t0), s.state.await { it is WorkoutState.Ended }) + val saved = stored(t0)!! + assertEquals(t0 + 1200, saved.end) + assertEquals(241, runBlocking { db.healthDao().routeOnce(t0) }.size) + } + + @Test + fun aWorkoutLeftRecordingWithNothingStoredRecordsOnInsteadOfBeingDeleted() { + val t0 = clock.now - 5 * 3600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) } + val s = session(leftWaitMs = SHORT_WAIT_MS) + s.restore() + s.restored.await { it } + // Past the wait, with nothing from the strap: still there and still recording, for the wearer to end. + runBlocking { delay(SHORT_WAIT_MS * 3) } + assertEquals(t0, s.recording().workout.start) + assertNull(stored(t0)!!.end) + // End tapped then ends it where it was recorded to, not by deleting it. + s.end() + assertEquals(WorkoutState.Ended(t0), s.state.await { it is WorkoutState.Ended }) + assertEquals(clock.now, stored(t0)!!.end) + } + + @Test + fun aWorkoutLeftPausedWithNothingStoredComesBackPaused() { + val t0 = clock.now - 5 * 3600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1, pausedAt = t0 + 30)) } + val s = session() + s.restore() + s.restored.await { it } + val r = s.recording() + assertTrue(r.paused) + assertNull(stored(t0)!!.end) + } + @Test fun aRestartAddsToTheDistanceStoredBeforeIt() { val settings = SettingsStore(context) @@ -836,6 +883,28 @@ class WorkoutSessionTest { assertNotNull(stored(t0)?.end) } + @Test + fun aRestDoesNotEndWhilePausedAndEndsOnceResumed() { + val s = session() + s.start(sportType = 1) + s.startSet() + s.recording { it.inSet } + clock.advance(Duration.ofSeconds(40)) + s.setDone() + s.recording { it.restUntil != null } + s.pause() + s.recording { it.paused } + // Well past the 90 s rest, paused: the once a second check leaves it alone. + clock.advance(Duration.ofSeconds(120)) + runBlocking { delay(2_500) } + val paused = s.recording() + assertNotNull(paused.restUntil) + assertNull(paused.sets.last().restEnd) + s.resume() + val resumed = s.recording { it.restUntil == null } + assertEquals(clock.now, resumed.sets.last().restEnd) + } + @Test fun aLaterSuccessDoesNotHideUnsavedSets() { val s = session() From fa47841aa59419dc652fd033f03b72ee26ef17db Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:23:03 +0400 Subject: [PATCH 17/18] An unreadable workout no longer stops workout syncing, and a chunk that can't be read fails its type A workout summary the parser couldn't read ended the workout loop with nothing stored, so every later sync stopped at the same workout and no new one came. Zepp keeps the raw bytes and parses after its loop, so one it can't read never stops it: now it is left out and the loop goes on, asking the same STARTs as before. A failed detail still stores nothing, as Zepp's receiver drops what a failed job fetched. A history chunk whose size doesn't fit, or whose records can't be read, still ends its type but now fails it, so the sync no longer says Done while that type gets no further. Co-Authored-By: Claude Opus 5.5 --- .../org/openstrap/app/device/HistorySync.kt | 21 ++++++++++++++++--- .../openstrap/protocol/history/GdspClient.kt | 8 +++++-- .../protocol/history/GdspClientTest.kt | 16 ++++++++++++++ 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt index a0614cae..25ff39cd 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt @@ -420,8 +420,11 @@ class HistorySync internal constructor( val headerTime = chunk.headerTime val payload = chunk.payload // The size field counts records, not bytes (activity: size 4 = four 8-byte minutes). + // A chunk it can't read ends the type as before, and the type fails, so a stop here shows instead of + // the sync saying Done while this type gets no further. What goes to the strap is the same. val unit = chunk.unit ?: run { log("history ${spec.type}: got ${payload.size} bytes for size ${chunk.sizeField}, not read") + ok = false break@loop } log( @@ -433,6 +436,7 @@ class HistorySync internal constructor( // Zepp parses after the ACK and tells the strap nothing of a parse failure. if (result is ParseResult.Failure) { log("history ${spec.type}: parse failed: ${result.reason}") + ok = false break@loop } val records = (result as ParseResult.Success).records @@ -492,13 +496,17 @@ class HistorySync internal constructor( /** * Workouts as Zepp's `pxk`: the summary, then its detail from the same cursor (04 ยง3.16), the next pair from the * summary's header + 1 s. The pairs are stored when the loop ends, then the cursor goes to the last workout + 1 s - * (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays. + * (at most now) for both 5 and 6. A failed detail fails the job and stores nothing, so the cursor stays, as Zepp's + * receiver drops what a failed job fetched. A summary that can't be read is left out and the loop goes on, as + * Zepp's, which only parses once it ends: the type fails so it shows, and the cursor passes it once a later one + * is stored. */ // Each return or break ends the loop for a reason of its own. @Suppress("ReturnCount", "LoopWithTooManyJumpStatements") private suspend fun syncWorkouts(spec: HistoryTypeSpec): Boolean { var cursor = startOf(spec.type, System.currentTimeMillis() / 1000) val pairs = mutableListOf() + var unreadable = 0 while (true) { if (fastRecharge) return false when (val w = client.fetchWorkout(cursor, zone)) { @@ -508,6 +516,13 @@ class HistorySync internal constructor( if (w.fastRecharge) fastRecharge = true return false } + // Left out, and the ones after it still come: the type fails, so it shows, but nothing is held up. + is WorkoutFetch.Unreadable -> { + log("history workout from ${Instant.ofEpochSecond(w.nextCursor - 1)}: ${w.reason}, left out") + unreadable++ + if (w.nextCursor <= cursor) break + cursor = w.nextCursor + } is WorkoutFetch.Workout -> { if (w.retryDetail) { log("history workout: detail failed, nothing stored"); return false } pairs += w @@ -516,14 +531,14 @@ class HistorySync internal constructor( } } } - if (pairs.isEmpty()) return true + if (pairs.isEmpty()) return unreadable == 0 for (w in pairs) storeWorkout(w) val now = System.currentTimeMillis() / 1000 val last = pairs.maxOf { it.summary.trackId } + 1 val saved = if (last > now) now else last save(HistoryDataType.SPORT_SUMMARY, saved, now) save(HistoryDataType.SPORT_DETAIL, saved, now) - return true + return unreadable == 0 } private suspend fun storeWorkout(w: WorkoutFetch.Workout) { diff --git a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt index bda6e0ac..c504c7b4 100644 --- a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt +++ b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt @@ -218,10 +218,12 @@ class GdspClient( val parsed = WorkoutParsers.summary.parse(s.payload, ParseContext(s.headerTime)) // The detail is asked for whether or not the summary parses, as Zepp does. val d = fetch(HistoryDataType.SPORT_DETAIL.code, since, zone) - if (parsed !is ParseResult.Success) return WorkoutFetch.Failed("summary: ${(parsed as ParseResult.Failure).reason}") - val summary = parsed.records.singleOrNull() ?: return WorkoutFetch.None // Zepp's next START: the summary's header time + 1000 ms. val next = s.headerTime + 1 + // Zepp keeps the raw bytes and parses after the loop, so a summary it can't read never stops it: on to the next. + if (parsed !is ParseResult.Success) return WorkoutFetch.Unreadable("summary: ${(parsed as ParseResult.Failure).reason}", next) + if (parsed.records.isEmpty()) return WorkoutFetch.None + val summary = parsed.records.singleOrNull() ?: return WorkoutFetch.Unreadable("summary: ${parsed.records.size} workouts in one", next) var retry = false val detail = when (d) { is GdspFetch.Chunk -> when (val r = WorkoutParsers.detail.parse(d.payload, ParseContext(summary.trackId))) { @@ -250,6 +252,8 @@ class GdspClient( sealed interface WorkoutFetch { data object None : WorkoutFetch data class Failed(val reason: String, val fastRecharge: Boolean = false) : WorkoutFetch + /** A summary fetched whole that couldn't be read ([reason]); the next one is asked from [nextCursor]. */ + data class Unreadable(val reason: String, val nextCursor: Long) : WorkoutFetch /** [retryDetail] is set when the detail exchange failed (worth fetching again), not when it was empty or unreadable. */ data class Workout(val summary: WorkoutSummary, val detail: WorkoutDetail?, val nextCursor: Long, val retryDetail: Boolean = false) : WorkoutFetch } diff --git a/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt b/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt index 4361f5fa..8ed931ec 100644 --- a/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt +++ b/protocol/src/test/kotlin/org/openstrap/protocol/history/GdspClientTest.kt @@ -113,6 +113,22 @@ class GdspClientTest { assertEquals(3, strap.acks.size) } + @Test + fun anUnreadableSummaryIsLeftOutAndTheNextOneStillComes() = runTest { + val odd = trackId - 3600 + // Version 1, not protobuf: fetched whole, but not read. + val strap = SimulatedGdspStrap( + mapOf(odd to (byteArrayOf(1, 0, 0, 0) to fixture("detail_6.bin")), trackId to (fixture("summary_5.bin") to fixture("detail_6.bin"))), + ) + val client = GdspClient(strap::send, strap.control, strap.data) + val u = client.fetchWorkout(odd - 60, zone) as WorkoutFetch.Unreadable + assertEquals(odd + 1, u.nextCursor) + // Its detail is asked for too, as Zepp does, so the traffic is the same. + assertEquals(listOf(5 to odd - 60, 6 to odd - 60), strap.starts) + val w = client.fetchWorkout(u.nextCursor, zone) as WorkoutFetch.Workout + assertEquals(trackId, w.summary.trackId) + } + @Test fun fastRechargeIsAcknowledgedWith33() = runTest { val strap = strap().apply { fastRecharge = true } From cf5472d2e3749593c37af3ad30ae925455880b6b Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Fri, 13 Nov 2026 00:39:29 +0400 Subject: [PATCH 18/18] Detekt and the rest test: shorter lines and conditions, no !!, a try/finally for the backup, and the rest test on a strength workout Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/SavedWorkoutEditor.kt | 8 +++++--- .../org/openstrap/app/device/WorkoutSession.kt | 17 ++++++++++------- .../org/openstrap/app/export/AutoBackup.kt | 7 ++++--- .../app/health/HealthConnectExporter.kt | 4 +++- .../openstrap/app/ui/root/AppRootViewModel.kt | 2 ++ .../openstrap/app/device/WorkoutSessionTest.kt | 4 +++- .../openstrap/protocol/history/GdspClient.kt | 7 +++++-- 7 files changed, 32 insertions(+), 17 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt index f548dba8..006eeb9d 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt @@ -134,9 +134,11 @@ internal class SavedWorkoutEditor( * stretch that started outside it, and an undo needs ones never worked out. Left as they are without the whole route. */ private fun withStretches(w: AppWorkout, track: WorkoutDistance.Track?): AppWorkout { - val end = w.end ?: return w - if (track == null || track.routeSince > w.start || track.route.isEmpty()) return w - val stretches = org.openstrap.app.data.Rewards.stretches(track.route.filter { it.t in w.from..end }, w.pauseRanges) + val end = w.end + // Only a route from the start: one picked up after a restart would lose the stretches before it. + val whole = track?.takeIf { it.routeSince <= w.start && it.route.isNotEmpty() } + if (end == null || whole == null) return w + val stretches = org.openstrap.app.data.Rewards.stretches(whole.route.filter { it.t in w.from..end }, w.pauseRanges) .let(org.openstrap.app.data.Rewards.Stretch::format) return w.copy(stretches = stretches) } diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt index ce726b7b..4789a2ba 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -137,7 +137,7 @@ class WorkoutSession( /** A finished workout was saved or changed, by its start: auto sync writes it to Health Connect. Returns at once. */ private val onSaved: (start: Long) -> Unit = {}, /** A saved workout was deleted, by its start and the range it was recorded over: auto sync takes it out of Health Connect. */ - private val onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, + onRemoved: (start: Long, from: Long, to: Long) -> Unit = { _, _, _ -> }, /** Epoch seconds now. Tests pass a clock they move by hand. */ private val clock: () -> Long = { System.currentTimeMillis() / 1000 }, /** Where the workout's long-lived work runs: the app's scope, `AppContainer.appScope`. */ @@ -669,8 +669,9 @@ class WorkoutSession( w: AppWorkout, stored: List, route: List, sets: List, rounds: List, ): Long = ( - stored.map { it.timestamp } + route.map { it.t } + w.lapMarks + w.pauseRanges.map { it.last } + listOfNotNull(w.pausedAt) + - sets.flatMap { listOfNotNull(it.start, it.end, it.restEnd) } + rounds.flatMap { listOfNotNull(it.workStart, it.workEnd, it.restEnd) } + stored.map { it.timestamp } + route.map { it.t } + w.lapMarks + w.pauseRanges.map { it.last } + + listOfNotNull(w.pausedAt) + sets.flatMap { listOfNotNull(it.start, it.end, it.restEnd) } + + rounds.flatMap { listOfNotNull(it.workStart, it.workEnd, it.restEnd) } ).fold(w.start, ::maxOf) /** Whether [w] ended at [end] would be kept: [MIN_SAVED_S] active, or it is deleted as a mis-tap. */ @@ -918,10 +919,12 @@ class WorkoutSession( /** [r] with its rest ended now, when a finished set's rest is under way, not paused, and over; else null. */ private fun restEnded(r: WorkoutState.Recording): WorkoutState.Recording? { - if (r.paused) return null - val until = r.restUntil ?: return null - val last = r.sets.lastOrNull()?.takeIf { it.end != null && it.restEnd == null } ?: return null - if (!org.openstrap.app.data.Strength.restOver(restRule(r.workout), last.end!!, until, window, now())) return null + val until = r.restUntil.takeIf { !r.paused } + val last = r.sets.lastOrNull()?.takeIf { it.restEnd == null } + val setEnd = last?.end + val over = until != null && setEnd != null && + org.openstrap.app.data.Strength.restOver(restRule(r.workout), setEnd, until, window, now()) + if (!over || last == null) return null return r.copy(sets = r.sets.dropLast(1) + last.copy(restEnd = now()), restUntil = null) } diff --git a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt index 07cb5849..a45fd5e0 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt @@ -128,11 +128,12 @@ class AutoBackup( val previous = dir.findFile(name) val movedAside = previous != null && previous.renameTo(aside) if (previous != null && !movedAside && !previous.delete()) throw Failed(BackupFailure.CantWrite) + var installed = false try { if (!temp.renameTo(name)) copyAs(dir, temp, name) - } catch (e: Throwable) { - if (movedAside) runCatching { dir.findFile(aside)?.renameTo(name) } - throw e + installed = true + } finally { + if (!installed && movedAside) runCatching { dir.findFile(aside)?.renameTo(name) } } dir.findFile(aside)?.let(::deleteQuietly) written = true diff --git a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt index c13336d8..777815dc 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -680,7 +680,9 @@ internal suspend fun RecordStore.dropStaleStrapWorkouts(from: Long, to: Long, wr internal suspend fun RecordStore.dropPhoneWorkout(start: Long, from: Long, to: Long) { // A day wider each side: the ids pick the records, so the range only has to hold them, however the filter treats // a session's ends. - val range = TimeRangeFilter.between(Instant.ofEpochSecond(from).minus(Duration.ofDays(1)), Instant.ofEpochSecond(to).plus(Duration.ofDays(1))) + val range = TimeRangeFilter.between( + Instant.ofEpochSecond(from).minus(Duration.ofDays(1)), Instant.ofEpochSecond(to).plus(Duration.ofDays(1)), + ) for ((type, id) in listOf( androidx.health.connect.client.records.ExerciseSessionRecord::class to "openstrap:workout:$start", androidx.health.connect.client.records.DistanceRecord::class to "openstrap:distance:$start", diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt index d8a33e69..21aaae3c 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppRootViewModel.kt @@ -186,6 +186,8 @@ class AppRootViewModel( * The rewards page for [i], tried [VIEW_TRIES] times [VIEW_RETRY_MS] apart, as a read can hit a locked database. * Null while the list is still loading (empty with workouts stored), or when every try failed. */ + // Each return is a way it ends: still loading, worked out, or every try failed. + @Suppress("ReturnCount") private suspend fun viewOf(i: RewardsInputs, dao: HealthDao): RewardsView? { repeat(VIEW_TRIES) { n -> if (n > 0) delay(VIEW_RETRY_MS) diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt index 8fac6ebe..780bf5fc 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -886,7 +886,9 @@ class WorkoutSessionTest { @Test fun aRestDoesNotEndWhilePausedAndEndsOnceResumed() { val s = session() - s.start(sportType = 1) + // Strength: only its rest is checked each second. + s.start(sportType = SportTypes.STRENGTH_TRAINING) + s.recording() s.startSet() s.recording { it.inSet } clock.advance(Duration.ofSeconds(40)) diff --git a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt index c504c7b4..f44cb8fa 100644 --- a/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt +++ b/protocol/src/main/kotlin/org/openstrap/protocol/history/GdspClient.kt @@ -221,9 +221,12 @@ class GdspClient( // Zepp's next START: the summary's header time + 1000 ms. val next = s.headerTime + 1 // Zepp keeps the raw bytes and parses after the loop, so a summary it can't read never stops it: on to the next. - if (parsed !is ParseResult.Success) return WorkoutFetch.Unreadable("summary: ${(parsed as ParseResult.Failure).reason}", next) + if (parsed !is ParseResult.Success) { + return WorkoutFetch.Unreadable("summary: ${(parsed as ParseResult.Failure).reason}", next) + } if (parsed.records.isEmpty()) return WorkoutFetch.None - val summary = parsed.records.singleOrNull() ?: return WorkoutFetch.Unreadable("summary: ${parsed.records.size} workouts in one", next) + val summary = parsed.records.singleOrNull() + ?: return WorkoutFetch.Unreadable("summary: ${parsed.records.size} workouts in one", next) var retry = false val detail = when (d) { is GdspFetch.Chunk -> when (val r = WorkoutParsers.detail.parse(d.payload, ParseContext(summary.trackId))) {