From 4a6ea0a8470d49ee1c568a3038dd12aa0a934690 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:41:52 +0400 Subject: [PATCH 01/27] Stop retrying a key the strap turned down A wrong or protected key failed the same way on every presence event, Bluetooth restart and phone alert. ConnectErrors.isFinal now counts it, so only the user's own connect or opening the app tries again. Co-Authored-By: Claude Opus 5.5 --- .../org/openstrap/app/device/ConnectErrors.kt | 9 +++++-- .../openstrap/app/device/ConnectionManager.kt | 13 ++++++++-- .../org/openstrap/app/device/PairingErrors.kt | 26 +++++++++++-------- .../org/openstrap/app/device/PhoneAlerts.kt | 7 +++-- .../openstrap/app/device/StrapController.kt | 3 ++- .../org/openstrap/app/device/StrapService.kt | 3 ++- .../org/openstrap/app/device/SetupStepTest.kt | 16 +++++++++++- .../openstrap/app/device/StrapConnectTest.kt | 25 ++++++++++++++++++ 8 files changed, 80 insertions(+), 22 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt index 34618afa..f2d7fa2a 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectErrors.kt @@ -7,6 +7,7 @@ import org.openstrap.app.ble.GattUnusableException import org.openstrap.app.i18n.Strings import org.openstrap.protocol.ProtocolException import org.openstrap.protocol.ProtocolTimeoutException +import org.openstrap.protocol.auth.AuthException /** * Turns a failed connect into what the Device page says. The raw exception text ("Disconnected (status 133)") goes to @@ -24,8 +25,12 @@ object ConnectErrors { }, ) - /** True when trying again can't help until the user acts, so no reconnect is scheduled (audit E4). */ - fun isFinal(e: Throwable): Boolean = e is GattUnusableException || e.isPermission() + /** + * True when trying again can't help until the user acts (grants the permission, pairs again), so no reconnect is + * scheduled (audit E4) and background triggers stop trying. + */ + fun isFinal(e: Throwable): Boolean = + e is GattUnusableException || e.isPermission() || (e is AuthException && PairingErrors.keyRejected(e.status)) private fun Throwable.isPermission(): Boolean = generateSequence(this) { it.cause }.any { it is SecurityException } } diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt index 73990ea1..08d3d10a 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt @@ -84,7 +84,11 @@ internal class ConnectionManager( /** True while the user wants the strap connected; cleared by [disconnect]. */ @Volatile private var wantConnected = false private var retries = 0 - /** Set when a connect failed in a way retrying can't fix (no permission, a bad address): presence events don't retry. */ + /** + * Set when a connect failed in a way retrying can't fix ([ConnectErrors.isFinal]: no permission, a bad address, a + * key the strap turned down): presence events and Bluetooth coming back don't retry. Cleared by the next connect + * the user starts or the app coming to the front ([wantConnection]). + */ @Volatile private var unusable = false @Volatile override var gatt: GattClient? = null private set @@ -206,6 +210,11 @@ internal class ConnectionManager( log("auth failed: ${e.message}") connection.value = PairingErrors.authFailure(e) close() + // Every presence event would otherwise run the handshake again, and fail the same way. + if (ConnectErrors.isFinal(e)) { + unusable = true + log("not retrying: the strap turned the key down") + } } catch (e: Exception) { // Asks the coroutine, not the exception: a timeout is a failure to report, only a cancelled job unwinds. if (!currentCoroutineContext().isActive) { @@ -240,7 +249,7 @@ internal class ConnectionManager( client.lost() } android.bluetooth.BluetoothAdapter.STATE_ON -> onLane { - if (!wantConnected || connection.value is ConnectionState.Connected || connectJob?.isActive == true) return@onLane + if (!wantConnected || unusable || connection.value is ConnectionState.Connected || connectJob?.isActive == true) return@onLane log("bluetooth back on, reconnecting") retries = 0 reconnectJob?.cancel() diff --git a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt index c8699baa..0a1b0487 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt @@ -15,15 +15,19 @@ object PairingErrors { private const val BINDING_PROTECTED = 0x41 private const val CLOUD_BIND_REQUIRED = 0x81 - fun authFailure(e: AuthException, strings: Strings = Strings.app): ConnectionState.Failed = when (e.status) { - WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED -> - ConnectionState.Failed(strings.get(R.string.system_pairing_wrong_key), keyRejected = true) - NO_KEY -> ConnectionState.Failed(strings.get(R.string.system_pairing_no_key), keyRejected = true) - SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED -> - ConnectionState.Failed(strings.get(R.string.system_pairing_cloud_bind), keyRejected = true) - WORKOUT_RUNNING -> ConnectionState.Failed(strings.get(R.string.system_pairing_workout_running)) - else -> ConnectionState.Failed( - strings.format(R.string.system_pairing_failed, e.message ?: strings.get(R.string.system_pairing_unknown_error)), - ) - } + private val KEY_REJECTED = setOf(WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED, NO_KEY, SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED) + + /** True when the strap turned the key down: the same key fails the same way until the user pairs again. */ + fun keyRejected(status: Int): Boolean = status in KEY_REJECTED + + fun authFailure(e: AuthException, strings: Strings = Strings.app): ConnectionState.Failed = ConnectionState.Failed( + when (e.status) { + WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED -> strings.get(R.string.system_pairing_wrong_key) + NO_KEY -> strings.get(R.string.system_pairing_no_key) + SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED -> strings.get(R.string.system_pairing_cloud_bind) + WORKOUT_RUNNING -> strings.get(R.string.system_pairing_workout_running) + else -> strings.format(R.string.system_pairing_failed, e.message ?: strings.get(R.string.system_pairing_unknown_error)) + }, + keyRejected = keyRejected(e.status), + ) } diff --git a/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt b/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt index 608bc777..689afd1e 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/PhoneAlerts.kt @@ -292,12 +292,11 @@ class PhoneAlerts( /** * Reconnects a paired strap that isn't connected. Android can restart the process just to deliver a call or a * notification (or to bind [StrapNotificationListener]); this alert is lost, but the next one reaches the strap. - * A no-op while connected or connecting, while the user's Disconnect holds, and when the strap turned the key - * down (retrying can't help). + * A no-op while connected or connecting, while the user's Disconnect holds, and when retrying can't help (a key + * the strap turned down): [StrapController.backgroundConnect] checks those. */ fun reconnectStrap() { - val c = strap.connection.value - if (c is ConnectionState.Connected || (c as? ConnectionState.Failed)?.keyRejected == true) return + if (strap.connection.value is ConnectionState.Connected) return if (!BlePermissions.granted(context)) return strap.backgroundConnect() } diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt index 46bf43a5..98a6856f 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt @@ -107,7 +107,8 @@ interface StrapController { /** * [autoConnect] for reconnects nobody asked for on screen (companion presence, phone alerts, process start): - * a no-op while the user's Disconnect holds, which lasts until they connect again or open the app. + * a no-op while the user's Disconnect holds, which lasts until they connect again or open the app, and after a + * failure retrying can't fix ([ConnectErrors.isFinal], such as a key the strap turned down). */ fun backgroundConnect() fun disconnect() diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt index 407ef761..2e25c67d 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt @@ -275,7 +275,8 @@ class StrapService : LifecycleService() { text = idleText(c, sync, f, problem), header = idleHeader(connected.takeIf { problem == null }, syncedAt), syncedAt = syncedAt, progress = (sync as? SyncState.Running)?.progress, syncing = sync is SyncState.Running, - retry = c is ConnectionState.Failed, connected = connected != null, sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(), + // A key the strap turned down fails the same way again: the Device page offers pairing again instead. + retry = c is ConnectionState.Failed && !c.keyRejected, connected = connected != null, sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(), problem = when { c is ConnectionState.Failed -> "failed"; low -> "low"; problem != null -> "off"; else -> null }, ) } diff --git a/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt b/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt index f93b26bf..fe075006 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/SetupStepTest.kt @@ -14,6 +14,7 @@ import org.junit.Test import org.openstrap.app.ble.GattTimeoutException import org.openstrap.app.testing.assertCleanCopy import org.openstrap.protocol.ProtocolTimeoutException +import org.openstrap.protocol.auth.AuthException /** afterAuth's steps (audit C5) and the connect failure copy (E4, E6). */ @OptIn(ExperimentalCoroutinesApi::class) @@ -77,10 +78,23 @@ class SetupStepTest { } @Test - fun onlyPermissionAndAddressFailuresAreFinal() { + fun onlyPermissionAddressAndTurnedDownKeyFailuresAreFinal() { assertTrue(ConnectErrors.isFinal(org.openstrap.app.ble.GattUnusableException("bad", IllegalArgumentException()))) assertTrue(ConnectErrors.isFinal(SecurityException("denied"))) assertEquals(false, ConnectErrors.isFinal(GattTimeoutException("slow"))) assertEquals(false, ConnectErrors.isFinal(ProtocolTimeoutException("slow"))) + // Wrong key, cloud bind required: the same key fails again. A workout running on the strap ends. + assertTrue(ConnectErrors.isFinal(AuthException(0x26, "wrong key"))) + assertTrue(ConnectErrors.isFinal(AuthException(0x81, "cloud bind"))) + assertEquals(false, ConnectErrors.isFinal(AuthException(5, "workout running"))) + assertEquals(false, ConnectErrors.isFinal(AuthException(0x99, "unknown"))) + } + + @Test + fun aKeyIsTurnedDownExactlyWhenRetryingCantHelp() { + for (status in listOf(5, 7, 8, 0x23, 0x25, 0x26, 0x41, 0x81, 0x99)) { + val e = AuthException(status, "status $status") + assertEquals("status $status", ConnectErrors.isFinal(e), PairingErrors.authFailure(e).keyRejected) + } } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt index c188fffc..7f5479d2 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt @@ -170,6 +170,31 @@ class StrapConnectTest { assertTrue(strap.log.value.joinToString("\n"), strap.log.value.none { it.contains("reconnecting") }) } + @Test + fun afterAFailureForGoodNeitherPresenceNorBluetoothComingBackRetries() = runTest { + pair("not an address") + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it is ConnectionState.Failed } + // What a key the strap turned down sets too (ConnectErrors.isFinal): before, presence events and Bluetooth + // coming back ran the handshake again every few seconds. + strap.backgroundConnect() + context.sendBroadcast( + android.content.Intent(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED) + .setPackage(context.packageName) + .putExtra(android.bluetooth.BluetoothAdapter.EXTRA_STATE, android.bluetooth.BluetoothAdapter.STATE_ON), + ) + shadowOf(android.os.Looper.getMainLooper()).idle() + delay(10 * 60_000L) + val log = strap.log.value + assertEquals(log.joinToString("\n"), 1, log.count { it.contains("connecting to") }) + assertTrue(log.joinToString("\n"), log.none { it.contains("bluetooth back on") }) + // The user's own connect still tries again. + strap.connect() + delay(1_000) + assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) + } + @Test fun racingConnectsLeaveOneClientOpen() { val address = "AA:BB:CC:00:00:05" From 54792d30d47fc3f5c1a93ae9afdedc7fb7cb4fb9 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:45:14 +0400 Subject: [PATCH 02/27] App shell: launch extras read once, phone alerts re-checked on resume, deleted workout page S8: MainActivity reads notification and widget extras in onCreate (fresh launch only) and onNewIntent, not onResume. S16: onResume refreshes phoneAlerts. S23: workout detail is Loading, Found or Missing by key; Missing shows a deleted message. Co-Authored-By: Claude Sonnet 5.5 --- .../kotlin/org/openstrap/app/MainActivity.kt | 12 ++++++- .../org/openstrap/app/ui/root/DetailHost.kt | 32 +++++++++++++++++-- .../app/ui/workout/WorkoutsViewModel.kt | 27 ++++++++++++++-- .../main/res/values/strings_glow_workout.xml | 2 ++ .../app/ui/workout/OpenedWorkoutTest.kt | 29 +++++++++++++++++ 5 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt diff --git a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt index 9e1ee33c..eb2194aa 100644 --- a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt +++ b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt @@ -131,6 +131,10 @@ class MainActivity : ComponentActivity() { ) val container = (application as OpenStrapApp).container showLiveWorkoutWhenLocked(container) + // Only a fresh launch asks for something. A restored activity (process death, then back from Recents) is + // handed its original launch intent again, extras intact, and nav is restored too: replaying them would + // pile the old request on top of where the user had got to. + if (savedInstanceState == null && !launchedFromHistory(intent)) showWorkoutFromIntent() setContent { OpenStrapTheme { AppRoot(container, navRequests, previews, pendingStrap) @@ -170,8 +174,10 @@ class MainActivity : ComponentActivity() { (application as OpenStrapApp).container.workout.inFront() // The association or battery setting may have changed in system settings meanwhile. (application as OpenStrapApp).container.companion.refresh() + // Call and notification access may have been granted in system settings meanwhile. + (application as OpenStrapApp).container.phoneAlerts.refresh() + // Debug extras only: the real launch extras are read once, in onCreate and onNewIntent. handleDebugIntent(previews) - showWorkoutFromIntent() } override fun onNewIntent(intent: Intent) { @@ -181,6 +187,10 @@ class MainActivity : ComponentActivity() { showWorkoutFromIntent() } + /** A launch from the Recents list: its intent is the original one, not a new request. */ + private fun launchedFromHistory(intent: Intent?): Boolean = + intent != null && intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 + /** * The workout notification opens the live screen, even if it was tucked away. A shortcut or the tile opens the * ready screen, an auto-detected workout's notification that workout, and a health alert or body-signal diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt index 85d89fec..63089be8 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt @@ -7,10 +7,12 @@ import androidx.compose.ui.res.stringResource import org.openstrap.app.R import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.Color import androidx.lifecycle.compose.collectAsStateWithLifecycle import java.time.Instant import java.time.LocalDate @@ -35,10 +37,14 @@ import org.openstrap.app.ui.glow.GlowScoreDetailScreen import org.openstrap.app.ui.glow.GlowSleepScreen import org.openstrap.app.ui.glow.GlowWorkoutDetailScreen import org.openstrap.app.ui.glow.GlowWorkoutsScreen +import org.openstrap.app.ui.dashboard.ScreenList +import org.openstrap.app.ui.glow.GlowLayout +import org.openstrap.app.ui.glow.GlowType import org.openstrap.app.ui.glow.PageHeader import org.openstrap.app.ui.glow.SleepEditing import org.openstrap.app.ui.glow.WeekDetail import org.openstrap.app.ui.glow.dayName +import org.openstrap.app.ui.workout.OpenedWorkout import org.openstrap.app.ui.workout.WorkoutsViewModel /** @@ -87,9 +93,11 @@ internal fun DetailHost( ), ) is Detail.Workout -> { - val openWorkout by workoutsVm.open.collectAsStateWithLifecycle() - WorkoutDetail( - openWorkout?.takeIf { it.workout.start == detail.start }, padding, onBack = pop, + val opened by workoutsVm.opened.collectAsStateWithLifecycle() + // Only the answer for this workout counts: the one before it may still be showing as the new key loads. + val found = (opened as? OpenedWorkout.Found)?.analysis?.takeIf { it.workout.start == detail.start } + if (opened == OpenedWorkout.Missing(detail.start)) WorkoutMissing(padding, onBack = pop) else WorkoutDetail( + found, padding, onBack = pop, onDelete = { container.workout.discard(detail.start); pop() }, workoutsVm = workoutsVm, session = container.workout, bmrPerMinute = EnergyExpenditure.bmrPerMinute(profile, profile.age()), @@ -123,6 +131,24 @@ internal fun DetailHost( } } +/** + * The page for a workout that no longer exists (deleted, with a notification or a restored stack still pointing at + * it): the header with its back button and one line saying so, instead of the loading state, which would never end. + */ +@Composable +private fun WorkoutMissing(contentPadding: PaddingValues, onBack: () -> Unit) { + BackHandler(onBack = onBack) + ScreenList(contentPadding, gutter = GlowLayout.Gutter) { + item { PageHeader(stringResource(R.string.glow_workout_untitled), onBack) } + item { + Text( + stringResource(R.string.glow_workout_deleted), + color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + ) + } + } +} + /** A workout's detail: one page for the strap's and the phone's ([GlowWorkoutDetailScreen]). */ @Composable private fun WorkoutDetail( diff --git a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt index 7b40792a..286a580d 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch @@ -32,6 +33,21 @@ import java.time.LocalDate /** The data layer's summary, kept under its old name for the screens. */ typealias PhoneSummary = org.openstrap.app.data.WorkoutSummaryData +/** What reading the workout open in detail has found so far. */ +sealed interface OpenedWorkout { + /** Nothing has answered yet. */ + data object Loading : OpenedWorkout + + data class Found(val analysis: WorkoutAnalysis) : OpenedWorkout + + /** No workout starts at [start]: it was deleted. */ + data class Missing(val start: Long) : OpenedWorkout + + companion object { + fun of(start: Long, analysis: WorkoutAnalysis?): OpenedWorkout = if (analysis == null) Missing(start) else Found(analysis) + } +} + /** Workouts list (newest first) and the one open in detail. */ @OptIn(ExperimentalCoroutinesApi::class) class WorkoutsViewModel( @@ -77,8 +93,15 @@ class WorkoutsViewModel( private val openStart = MutableStateFlow(null) - val open: StateFlow = openStart.flatMapLatest { start -> if (start == null) flowOf(null) else repo.open(start) } - .flowOn(work).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) + /** + * The workout open in detail, read by its key: [OpenedWorkout.Loading] until the first read answers, + * [OpenedWorkout.Found], or [OpenedWorkout.Missing] when there is none with that start (deleted since a + * notification or a restored stack pointed at it). Each answer carries its key, so the one for the workout before + * is never taken for the one now. + */ + val opened: StateFlow = + openStart.flatMapLatest { start -> if (start == null) flowOf(OpenedWorkout.Loading) else repo.open(start).map { OpenedWorkout.of(start, it) } } + .flowOn(work).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), OpenedWorkout.Loading) /** * A phone workout's summary: its analysis, everything recorded (for trimming), and the strap's own record of it diff --git a/app/src/main/res/values/strings_glow_workout.xml b/app/src/main/res/values/strings_glow_workout.xml index 08591234..0fc8c8e0 100644 --- a/app/src/main/res/values/strings_glow_workout.xml +++ b/app/src/main/res/values/strings_glow_workout.xml @@ -6,6 +6,8 @@ unstrap is the app's name, written in lowercase even at the start of a sentence. Keep it as it is. --> + + This workout was deleted. Workout diff --git a/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt new file mode 100644 index 00000000..fdf817c5 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/workout/OpenedWorkoutTest.kt @@ -0,0 +1,29 @@ +package org.openstrap.app.ui.workout + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Test +import org.openstrap.app.data.db.Workout +import org.openstrap.app.data.WorkoutAnalysis + +/** A workout's detail tells "no such workout" from "still loading", and each answer names its workout. */ +class OpenedWorkoutTest { + private fun analysis(start: Long) = WorkoutAnalysis( + Workout(start, start + 600, 1, 600, 50, 140, 160, 90, null, null, null, null, null), + start + 600, emptyList(), null, null, null, null, List(5) { 0 }, 190, + ) + + @Test fun `no workout at the key is missing, not loading`() { + assertEquals(OpenedWorkout.Missing(100), OpenedWorkout.of(100, null)) + assertNotEquals(OpenedWorkout.Loading, OpenedWorkout.of(100, null)) + } + + @Test fun `a workout at the key is found`() { + val a = analysis(100) + assertEquals(OpenedWorkout.Found(a), OpenedWorkout.of(100, a)) + } + + @Test fun `a missing answer for one key is not the answer for another`() { + assertNotEquals(OpenedWorkout.Missing(100), OpenedWorkout.Missing(200)) + } +} From 84da456297f2e76b66628be8b322fdda75aa4e17 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:45:17 +0400 Subject: [PATCH 03/27] Permissions gates and Health Connect: one answer runs every waiter, auto sync on after first export, one write lock One Bluetooth answer runs the queued workout and the Strap action. The location follow-up is a saved tag. Granted for Health Connect writes means the required permissions only. Auto sync turns on only after its first export succeeds. All Health Connect writes share one Mutex. Co-Authored-By: Claude Sonnet 5.5 --- .../openstrap/app/health/AutoHealthConnect.kt | 8 +++- .../app/health/HealthConnectExporter.kt | 38 ++++++++++++++----- .../openstrap/app/ui/root/AppRootViewModel.kt | 7 +++- .../app/ui/root/HealthConnectActions.kt | 3 +- .../openstrap/app/ui/root/PermissionGates.kt | 31 +++++++++++---- .../openstrap/app/health/RecordStoreTest.kt | 26 +++++++++++++ 6 files changed, 91 insertions(+), 22 deletions(-) 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 c0a34fd4..12d6432c 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/AutoHealthConnect.kt @@ -141,11 +141,15 @@ class HealthConnectAutoSync( } } - /** The user turned auto sync on, with the permissions granted: on, and the last 30 days written at once. Returns the records written. */ + /** + * The user turned auto sync on, with the permissions granted: the last 30 days are written at once, and only when + * that works is it turned on. A failed first write throws and leaves it off, for the caller to show. Returns the + * records written. + */ suspend fun turnOn(): Int { - settings.setHealthConnectAuto(true) val now = System.currentTimeMillis() / 1000 val n = exporter.export(now - AutoHealthConnect.MAX_S, now) + settings.setHealthConnectAuto(true) settings.setHealthConnectSynced(now) return n } 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 d0cade4d..4fd14d97 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -1,5 +1,7 @@ package org.openstrap.app.health +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import android.content.Context import androidx.health.connect.client.HealthConnectClient import androidx.health.connect.client.HealthConnectFeatures @@ -62,6 +64,13 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt override suspend fun deleteRange(type: KClass, range: TimeRangeFilter) = client.deleteRecords(type, range) } + /** + * Every write to Health Connect (the worker, turning auto sync on, a saved workout, an edited sleep, the manual + * copy) goes through this one lock. A write reads its own records, inserts, then deletes the stale ones, so two + * side by side could delete what the other had just inserted. + */ + private val writeLock = Mutex() + /** Every record of [type] in [range] that OpenStrap wrote, a page at a time. */ private suspend fun readAll(type: KClass, range: TimeRangeFilter): List { val out = mutableListOf() @@ -95,7 +104,7 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt HealthPermission.getWritePermission(TotalCaloriesBurnedRecord::class), ) - /** What a write asks Health Connect for. */ + /** What a write asks Health Connect for: the needed ones with the optional calories, so they are offered in the same screen. */ val requestedPermissions: Set get() = permissions + caloriePermissions /** Reading back what was exported; history is the permission to read further back than 30 days. */ @@ -122,10 +131,6 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt suspend fun hasPermissions(): Boolean = client.permissionController.getGrantedPermissions().containsAll(permissions) - /** Every permission a write asks for, the optional calorie ones too: when not, the write asks again first. */ - suspend fun hasRequestedPermissions(): Boolean = - client.permissionController.getGrantedPermissions().containsAll(requestedPermissions) - /** The record reads the user has granted (any of them is enough to import that kind). */ suspend fun hasReadPermissions(): Boolean = client.permissionController.getGrantedPermissions().any { it in readPermissions } @@ -190,8 +195,9 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt val resting = restingHr(from, to, ZoneId.systemDefault()) records += resting - store.write(records, kcalRanges + (SleepSessionRecord::class to sleepRange(from, to))) - store.dropMovedRestingHr(resting) + store.writeSerially(writeLock, records, kcalRanges + (SleepSessionRecord::class to sleepRange(from, to))) { + dropMovedRestingHr(resting) + } return records.size } @@ -216,7 +222,7 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt */ suspend fun exportSleep(from: Long, to: Long, now: Long = System.currentTimeMillis() / 1000): Int { val records = sleep(from, to, now) - store.write(records, listOf(SleepSessionRecord::class to sleepRange(from, to))) + store.writeSerially(writeLock, records, listOf(SleepSessionRecord::class to sleepRange(from, to))) return records.size } @@ -280,7 +286,7 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt val (from, to) = AutoHealthConnect.workoutRange(w.from, end, now) val (kcal, kcalRanges) = calories(w.from, end, now) val records = heartRate(from, to) + steps(from, to) + workouts(listOf(w)) + kcal - store.write(records, kcalRanges) + store.writeSerially(writeLock, records, kcalRanges) return records.size } @@ -523,6 +529,20 @@ internal suspend fun RecordStore.write(records: List, replaced: List, + replaced: List, TimeRangeFilter>>, + after: suspend RecordStore.() -> Unit = {}, +) = lock.withLock { + write(records, replaced) + after() +} + /** The most records one Health Connect call takes. */ internal const val HC_BATCH = 500 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 40217f41..9ced2911 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 @@ -254,9 +254,12 @@ class AppRootViewModel( suspend fun summaryRewards(start: Long): SummaryRewards? = catching { rewards.summary(start, workouts.value, goals.value.workoutsPerWeek) }.getOrNull() - /** The manual copy and auto sync write with these. The calorie ones are optional but asked for until granted. */ + /** + * The manual copy and auto sync write with these. Only the needed permissions decide: the calorie ones are asked + * for in the same screen when the needed ones are missing, and never again by themselves. + */ suspend fun healthConnectWrite(): HcState = HcState.blocked(healthConnect.availability()) ?: when { - healthConnect.hasRequestedPermissions() -> HcState.Granted + healthConnect.hasPermissions() -> HcState.Granted else -> HcState.Needs(healthConnect.requestedPermissions) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt index 773256a7..4cd7cd51 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt @@ -99,8 +99,7 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De // The manual copy, or turning auto sync on ([forAuto]): with the write permissions, asked for first when missing. val write: (Boolean) -> Unit = { forAuto -> scope.launch { - // The calorie permissions are optional, but asked for again until granted: the launcher goes on with the - // ones it needs. + // The calorie permissions are optional and asked for only along with the needed ones. when (val hc = rootVm.healthConnectWrite()) { HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show() HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show() diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt index b57ddddd..15131375 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt @@ -40,11 +40,18 @@ internal class PermissionGates( } } +/** What waits on the location answer besides a workout: a name rather than a closure, so it can be saved. */ +private enum class GateAction { + /** Ready's "Turn on location": the Ready screen reads the phone's location again. */ + REFRESH_READY, +} + /** * The permission gates. A workout waits as saveable data, so the answer still starts it after the activity was - * recreated behind the dialog. A Strap page action waits in [pendingStrap], which outlives a fold. Location for a GPS - * workout is asked only when GPS is on, and the workout starts either way (steps without it). Ready's "Turn on - * location" hands over a closure that only refreshes Ready, so that one isn't saved. + * recreated behind the dialog. A Strap page action waits in [pendingStrap], which outlives a fold, and one Bluetooth + * answer runs both. Location for a GPS workout is asked only when GPS is on, and the workout starts either way (steps + * without it). Ready's "Turn on location" is a saved [GateAction] tag, with the closure that refreshes Ready kept + * beside it. */ @Composable internal fun rememberPermissionGates( @@ -66,7 +73,11 @@ internal fun rememberPermissionGates( pending = null pendingStrap.action = null when { - BlePermissions.granted(result) -> waiting?.let(start) ?: strapAction?.invoke() + // Whoever queued behind this one question gets the answer: the workout and the Strap page action both. + BlePermissions.granted(result) -> { + waiting?.let(start) + strapAction?.invoke() + } activity != null && BlePermissions.turnedDownForGood(activity, BlePermissions.bluetooth) -> blocked.value = true else -> Toast.makeText(context, bluetoothRequired, Toast.LENGTH_LONG).show() } @@ -83,7 +94,11 @@ internal fun rememberPermissionGates( btLauncher.launch(BlePermissions.required()) } } - var afterLocation by remember { mutableStateOf<(() -> Unit)?>(null) } + // Which follow-up waits on the location answer is saved, so it survives a recreate. Ready's closure behind it only + // refreshes the Ready screen that asked, which a recreate replaces: the new Ready reads location itself when it + // shows and on every resume, so a lost closure leaves nothing undone. + var afterLocation by rememberSaveable { mutableStateOf(null) } + var refreshReady by remember { mutableStateOf<(() -> Unit)?>(null) } val locationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> if (result.values.none { it }) { Toast.makeText(context, locationDeclined, Toast.LENGTH_LONG).show() @@ -93,12 +108,14 @@ internal fun rememberPermissionGates( pending = null withBluetooth(waiting) } - afterLocation?.invoke() + if (afterLocation == GateAction.REFRESH_READY) refreshReady?.invoke() afterLocation = null + refreshReady = null } val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) val requestLocation: (() -> Unit) -> Unit = { then -> - afterLocation = then + afterLocation = GateAction.REFRESH_READY + refreshReady = then locationLauncher.launch(locationPermissions) } val startPlan: (WorkoutPlan, SportSettings?) -> Unit = { plan, saved -> 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 ba2026e2..ed7b99cf 100644 --- a/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/health/RecordStoreTest.kt @@ -4,7 +4,11 @@ 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 kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.yield import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @@ -81,4 +85,26 @@ class RecordStoreTest { assertEquals(listOf("deleteRange", "insert"), store.calls) assertEquals(listOf("openstrap:sleep:1000"), store.records.map { it.metadata.clientRecordId }) } + + @Test fun `writers sharing a lock never run side by side`() = runTest { + val lock = Mutex() + var inside = 0 + var overlapped = false + // A store that lets other coroutines run during its insert, as a real Health Connect call does. + val slow = object : RecordStore { + override suspend fun insert(records: List) { + inside++ + if (inside > 1) overlapped = true + yield() + inside-- + } + override suspend fun ownRecords(type: KClass, range: TimeRangeFilter): List? = emptyList() + override suspend fun deleteIds(type: KClass, ids: List) = Unit + override suspend fun deleteRange(type: KClass, range: TimeRangeFilter) = Unit + } + val one = listOf(sleep(1000, "openstrap:sleep:1000")) + val writers = List(4) { async { slow.writeSerially(lock, one, listOf(SleepSessionRecord::class to range)) } } + writers.awaitAll() + assertTrue(!overlapped) + } } From 0f7be021e696f863141a650d27017332e6952136 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:45:44 +0400 Subject: [PATCH 04/27] Sync: one worker for the queue, kept Sync now, ordered widget refreshes S6: requests go through one channel and worker, a Sync now waits for a session or a firmware update, stale auto and type requests are dropped, only an auto failure triggers an immediate retry, dumpRaw takes its turn and never leaves Running. S19: widget refreshes run one at a time, the snapshot reads sync state once, bump uses update. Co-Authored-By: Claude Sonnet 5.5 --- .../openstrap/app/device/SyncCoordinator.kt | 193 +++++++++++++----- .../org/openstrap/app/widget/WidgetRefresh.kt | 5 +- .../openstrap/app/widget/WidgetSnapshot.kt | 4 +- .../org/openstrap/app/widget/WidgetUpdater.kt | 12 +- .../org/openstrap/app/device/SyncPlanTest.kt | 53 +++++ .../openstrap/app/widget/WidgetRefreshTest.kt | 19 ++ 6 files changed, 233 insertions(+), 53 deletions(-) create mode 100644 app/src/test/kotlin/org/openstrap/app/device/SyncPlanTest.kt create mode 100644 app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt diff --git a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt index f76fb97b..abee785e 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt @@ -3,6 +3,7 @@ package org.openstrap.app.device import android.content.Context import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -12,6 +13,8 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.openstrap.app.ble.GattClient import org.openstrap.app.data.catching import org.openstrap.app.data.db.HealthDao import org.openstrap.app.data.settings.SettingsStore @@ -55,79 +58,131 @@ internal class SyncCoordinator( /** * Sync right after connecting (unless one ran recently and didn't fail), then every [AUTO_SYNC_SECONDS] while - * connected. A failed one is retried at once: it was most likely cut off by the link this connect replaces. + * connected. A failed auto sync is retried at once: it was most likely cut off by the link this connect replaces. + * A failed Sync now isn't a reason: the user asked for that one, and the next auto sync isn't owed anything. A Sync + * now kept while there was no session ([held]) runs first. */ fun autoSync(s: ChannelSession) = scope.launch { while (isActive && link.session === s) { + if (held) { + held = false + requests.trySend(SyncRequest.Full(manual = true, session = s)) + } val now = nowSeconds() - val due = now - lastAutoSync >= MIN_SYNC_GAP_SECONDS || sync.value is SyncState.Failed + val due = now - lastAutoSync >= MIN_SYNC_GAP_SECONDS || (autoFailed && sync.value is SyncState.Failed) if (due && sync.value !is SyncState.Running && !firmwareUpdating.value) { lastAutoSync = now log("auto sync") - syncNow() + requests.trySend(SyncRequest.Full(manual = false, session = s)) } delay(AUTO_SYNC_SECONDS * MILLIS_PER_SECOND) } } - fun syncNow() = startSync(full = true) + /** The user's Sync now. Kept, never lost: it waits for a session or a firmware update to end. */ + fun syncNow() { + requests.trySend(SyncRequest.Full(manual = true, session = link.activeSession)) + } /** The strap pushed new data of [types]: sync them now, or after the sync running. */ fun syncPushed(types: Set) { - synchronized(pendingTypes) { pendingTypes += types } - startSync(full = false) + val s = link.activeSession ?: return + requests.trySend(SyncRequest.Types(types, s)) } - /** One sync at a time; a full sync or types asked for meanwhile run when it ends. */ + /** + * Everything asked for, in order. One worker reads it, so there is one sync at a time and a request made meanwhile + * is read when it ends. + */ + private val requests = Channel(Channel.UNLIMITED) + + /** The worker's turn: a sync holds the lock, so a firmware install mustn't start. */ private val syncLock = Mutex() - private val pendingTypes = mutableSetOf() - private val pendingFull = java.util.concurrent.atomic.AtomicBoolean(false) - /** A sync holds the lock, so a firmware install mustn't start. */ + /** A Sync now that found no session: it runs at the next connect ([autoSync]). */ + @Volatile private var held = false + + /** Whether the last sync that ran was an auto sync and failed. */ + @Volatile private var autoFailed = false + val isSyncing: Boolean get() = syncLock.isLocked - private fun takePending(): Set = synchronized(pendingTypes) { pendingTypes.toSet().also { pendingTypes.clear() } } - private fun hasPending(): Boolean = pendingFull.get() || synchronized(pendingTypes) { pendingTypes.isNotEmpty() } + init { + scope.launch { + for (first in requests) { + catching { work(listOf(first) + drain()) }.onFailure { log("sync worker: $it") } + } + } + } - /** What to sync next: null for everything (a full sync covers anything pushed so far), or the pushed types. */ - private fun takeNext(): Set? = if (pendingFull.getAndSet(false)) { takePending(); null } else takePending() + private fun drain(): List { + val out = mutableListOf() + while (true) out += requests.tryReceive().getOrNull() ?: break + return out + } + /** Runs one batch of [asked] requests: the syncs they merge into, then the debug dumps. */ // Each return is a reason not to sync now. @Suppress("ReturnCount") - private fun startSync(full: Boolean) { - if (firmwareUpdating.value) return - val s = link.activeSession ?: return - val client = link.gatt ?: return - if (full) pendingFull.set(true) - scope.launch { - // A sync is running: it picks up what was just queued when it finishes. - if (!syncLock.tryLock()) return@launch - try { - while (link.activeSession === s && !firmwareUpdating.value) { - val only = takeNext() - if (only != null && only.isEmpty()) break - HistorySync(s, client, dao, settings, sync, log, notifiers.autoDetected::show).run(only) - (sync.value as? SyncState.Done)?.let { d -> - catching { settings.setLastSyncDone(d.atEpochSeconds) }.onFailure { log("sync time not kept: $it") } - } + private suspend fun work(asked: List) { + var batch = asked + if (firmwareUpdating.value) { + // The strap is busy installing: keep the user's request, drop what the old firmware pushed. + firmwareUpdating.first { !it } + batch = batch.filter { it is SyncRequest.Full && it.manual || it is SyncRequest.Dump } + drain() + } + val s = link.activeSession + val client = link.gatt + val dumps = batch.filterIsInstance() + if (s == null || client == null) { + if (SyncPlan.of(batch, null).manual) held = true + if (dumps.isNotEmpty()) log("dump: not connected") + return + } + var leftover = false + var ran = false + syncLock.withLock { + var plan = SyncPlan.of(batch, s) + while (!plan.isEmpty) { + ran = true + HistorySync(s, client, dao, settings, sync, log, notifiers.autoDetected::show).run(plan.only) + autoFailed = !plan.manual && sync.value is SyncState.Failed + (sync.value as? SyncState.Done)?.let { d -> + catching { settings.setLastSyncDone(d.atEpochSeconds) }.onFailure { log("sync time not kept: $it") } + } + val more = drain() + if (link.activeSession !== s || firmwareUpdating.value) { + // The session ended or an install began: a kept Sync now goes round again, the rest is stale. + leftover = SyncPlan.of(more, null).manual + break } + plan = SyncPlan.of(more, s) + } + for (d in dumps) dump(s, client, d) + if (ran) { afterSync() // Everything a widget shows may have moved (widgets spec 7): they watch for this. syncEnded.tryEmit(Unit) - } finally { - syncLock.unlock() - } - // A sync cut off by a lost link can end only after the reconnect, which skipped its own sync while this one - // still showed as running. Run it again on the new link. - val current = link.activeSession - if (sync.value is SyncState.Failed && current != null && current !== s) { - log("sync cut off by the old link, syncing again") - startSync(full = true) - } else if (hasPending()) { - // Something queued between the last check and the unlock would otherwise wait for the next trigger. - startSync(full = false) } } + // A sync cut off by a lost link can end only after the reconnect, which skipped its own sync while this one + // still showed as running. Run it again on the new link. + val current = link.activeSession + if (ran && sync.value is SyncState.Failed && current != null && current !== s) { + log("sync cut off by the old link, syncing again") + requests.trySend(SyncRequest.Full(manual = false, session = current)) + } + if (leftover) requests.trySend(SyncRequest.Full(manual = true, session = null)) + } + + /** One debug dump, which writes Running and must not leave it behind. */ + private suspend fun dump(s: ChannelSession, client: GattClient, d: SyncRequest.Dump) { + try { + val since = nowSeconds() - d.days * SECONDS_PER_DAY + HistorySync(s, client, dao, settings, sync, log).dumpRaw(since, java.io.File(context.filesDir, "raw"), d.types) + } finally { + if (sync.value is SyncState.Running) sync.value = SyncState.Idle + } } private suspend fun afterSync() { @@ -183,14 +238,9 @@ internal class SyncCoordinator( if (written > 0) log("daily energy: $written days") } - /** Debug aid, see [HistorySync.dumpRaw]. */ + /** Debug aid, see [HistorySync.dumpRaw]. It takes its turn like any sync. */ fun dumpRaw(days: Int, types: Set? = null) { - val s = link.activeSession ?: return log("dump: not connected") - val client = link.gatt ?: return - scope.launch { - val since = nowSeconds() - days * SECONDS_PER_DAY - HistorySync(s, client, dao, settings, sync, log).dumpRaw(since, java.io.File(context.filesDir, "raw"), types) - } + requests.trySend(SyncRequest.Dump(days, types)) } private fun nowSeconds() = System.currentTimeMillis() / MILLIS_PER_SECOND @@ -214,3 +264,48 @@ internal class SyncCoordinator( const val EFFECT_MODEL = "workout_effect_model" } } + +/** + * What was asked of the sync worker. [session] is the one it was asked on (null for a Sync now that found none): a + * request for another session than the current one is stale, except a user's Sync now. + */ +internal sealed interface SyncRequest { + /** Everything. [manual] for the user's Sync now, false for the hourly one. */ + data class Full(val manual: Boolean, val session: Any?) : SyncRequest + + /** The types the strap pushed. */ + data class Types(val types: Set, val session: Any?) : SyncRequest + + /** Debug: [HistorySync.dumpRaw]. */ + data class Dump(val days: Int, val types: Set?) : SyncRequest +} + +/** A batch of [SyncRequest]s merged into one sync: everything, or just the pushed types. */ +internal class SyncPlan(val full: Boolean, val types: Set, val manual: Boolean) { + val isEmpty: Boolean get() = !full && types.isEmpty() + + /** What [HistorySync.run] takes: null for everything (a full sync covers anything pushed), else the types. */ + val only: Set? get() = if (full) null else types + + companion object { + /** + * The plan for [requests] on the [current] session. A request made on another session is dropped, so it can't + * replay as a surprise sync; a user's Sync now stays whatever session it was made on. With no current session + * only that is left, which is what a caller keeps to run later. + */ + fun of(requests: List, current: Any?): SyncPlan { + val live = requests.filter { + when (it) { + is SyncRequest.Full -> it.manual || (current != null && it.session === current) + is SyncRequest.Types -> current != null && it.session === current + is SyncRequest.Dump -> false + } + } + return SyncPlan( + full = live.any { it is SyncRequest.Full }, + types = live.filterIsInstance().flatMapTo(mutableSetOf()) { it.types }, + manual = live.any { it is SyncRequest.Full && it.manual }, + ) + } + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt index 710167ad..1754a599 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetRefresh.kt @@ -2,6 +2,7 @@ package org.openstrap.app.widget import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.update import org.openstrap.app.BuildConfig import org.openstrap.app.data.WidgetKind import org.openstrap.app.ui.glow.draw.GlowMood @@ -17,7 +18,7 @@ object WidgetRefresh { fun version(kind: WidgetKind): StateFlow = versions.getValue(kind) fun bump(kind: WidgetKind) { - versions.getValue(kind).value++ + versions.getValue(kind).update { it + 1 } } private val resizes = WidgetKind.entries.associateWith { MutableStateFlow(0) } @@ -26,7 +27,7 @@ object WidgetRefresh { fun resized(kind: WidgetKind): StateFlow = resizes.getValue(kind) fun resize(kind: WidgetKind) { - resizes.getValue(kind).value++ + resizes.getValue(kind).update { it + 1 } } /** diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt index ccf6c9b8..ec60b12d 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetSnapshot.kt @@ -114,7 +114,9 @@ class WidgetSnapshot( suspend fun gather(kinds: Set, now: Instant, zone: ZoneId): WidgetData { val today = now.atZone(zone).toLocalDate() val t = now.epochSecond + // The strap's status and whether it is syncing, read together: one moment for the status line. val strap = catching { settings.strapSnapshot.first() }.onFailure { logUnread("strap status", it) }.getOrNull() + val isSyncing = syncing() val workouts = if (kinds.any { it in MOOD_KINDS }) catching { recentWorkouts(t) } else null val span = if (kinds.any { it in NIGHT_KINDS }) catching { sleepSpanSessions(today, zone) } else null val moment = workouts?.let { w -> catching { momentInputs(w.getOrThrow(), span?.getOrNull(), today, t, zone) } } @@ -131,7 +133,7 @@ class WidgetSnapshot( now = now, zone = zone, strap = strap, - syncing = syncing(), + syncing = isSyncing, moment = moment, usualBedtime = bedtime, steps = goal?.takeIf { WidgetKind.Steps in kinds }?.let { StepsRead(it, day) }, diff --git a/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt b/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt index a7e188ae..0cd28e52 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/WidgetUpdater.kt @@ -20,6 +20,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import org.openstrap.app.BuildConfig import org.openstrap.app.OpenStrapApp import org.openstrap.app.data.MomentInputs @@ -197,7 +199,15 @@ class WidgetUpdater( /** [kind]'s receiver and widget, null before it exists: for the debug widget gallery. */ internal fun registration(kind: WidgetKind): Registration? = WIDGETS[kind] - internal suspend fun update(kinds: Set) { + /** + * One refresh at a time, in the order asked: a refresh reads and applies under this lock, so an older read can't + * land after a newer one (a sync's start and end can overlap on a short sync). + */ + private val refreshing = Mutex() + + internal suspend fun update(kinds: Set) = refreshing.withLock { refresh(kinds) } + + private suspend fun refresh(kinds: Set) { val shown = placed().intersect(kinds) if (shown.isEmpty()) return // One read for every widget this refresh updates. A session that can't use it reads for itself. diff --git a/app/src/test/kotlin/org/openstrap/app/device/SyncPlanTest.kt b/app/src/test/kotlin/org/openstrap/app/device/SyncPlanTest.kt new file mode 100644 index 00000000..afc8904f --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/SyncPlanTest.kt @@ -0,0 +1,53 @@ +package org.openstrap.app.device + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** What the sync worker makes of the requests queued: kept, merged or dropped as stale. */ +class SyncPlanTest { + private val now = Any() + private val old = Any() + + @Test fun `a full request covers pushed types`() { + val p = SyncPlan.of(listOf(SyncRequest.Types(setOf(1), now), SyncRequest.Full(manual = false, session = now)), now) + assertTrue(p.full) + assertNull(p.only) + } + + @Test fun `pushed types merge into one sync of those types`() { + val p = SyncPlan.of(listOf(SyncRequest.Types(setOf(1), now), SyncRequest.Types(setOf(2, 3), now)), now) + assertFalse(p.full) + assertEquals(setOf(1, 2, 3), p.only) + } + + @Test fun `stale auto and type requests are dropped on a new session`() { + val p = SyncPlan.of(listOf(SyncRequest.Types(setOf(1), old), SyncRequest.Full(manual = false, session = old)), now) + assertTrue(p.isEmpty) + } + + @Test fun `a kept Sync now runs on whatever session is current`() { + val p = SyncPlan.of(listOf(SyncRequest.Full(manual = true, session = null)), now) + assertTrue(p.full) + assertTrue(p.manual) + } + + @Test fun `with no session only a Sync now is left to keep`() { + val p = SyncPlan.of( + listOf(SyncRequest.Full(manual = true, session = null), SyncRequest.Types(setOf(1), old), SyncRequest.Full(false, old)), + null, + ) + assertTrue(p.manual) + assertTrue(SyncPlan.of(listOf(SyncRequest.Types(setOf(1), old), SyncRequest.Full(false, old)), null).isEmpty) + } + + @Test fun `an auto sync is not manual`() { + assertFalse(SyncPlan.of(listOf(SyncRequest.Full(manual = false, session = now)), now).manual) + } + + @Test fun `a dump is not a sync`() { + assertTrue(SyncPlan.of(listOf(SyncRequest.Dump(1, null)), now).isEmpty) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt b/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt new file mode 100644 index 00000000..3baec848 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/widget/WidgetRefreshTest.kt @@ -0,0 +1,19 @@ +package org.openstrap.app.widget + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Test +import org.openstrap.app.data.WidgetKind + +/** The version a running widget watches: every bump counts, even from several threads at once. */ +class WidgetRefreshTest { + @Test fun `bumps from many threads are all counted`() = runBlocking { + val kind = WidgetKind.Steps + val before = WidgetRefresh.version(kind).value + (1..8).map { async(Dispatchers.Default) { repeat(500) { WidgetRefresh.bump(kind) } } }.awaitAll() + assertEquals(before + 4000, WidgetRefresh.version(kind).value) + } +} From ce55823b78edfc1672f2a5af95af3ac78f9edb13 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:46:25 +0400 Subject: [PATCH 05/27] App update and firmware: reconcile install state, guard firmware steps Update: failures after process death are shown from the saved tag, the tag is reconciled with installer sessions at start and on resume, Installing times out, one Check type, PendingAction.Install always cleared with feedback when installs are denied. Firmware: stale or illegal events are ignored per step, one AccountMode, token kept out of saved state, fields keyed on the account. Co-Authored-By: Claude Sonnet 5.5 --- .../openstrap/app/ui/device/UpdatesPage.kt | 3 +- .../app/ui/firmware/FirmwareScreen.kt | 32 +++--- .../app/ui/firmware/FirmwareViewModel.kt | 39 +++++--- .../org/openstrap/app/ui/root/PagesOverTab.kt | 18 +++- .../org/openstrap/app/update/AppUpdater.kt | 98 ++++++++++++++++--- .../org/openstrap/app/update/UpdateCopy.kt | 6 +- app/src/main/res/values/strings_update.xml | 2 + .../app/presentation/UpdateCopyTest.kt | 9 +- .../app/ui/firmware/FirmwareViewModelTest.kt | 46 +++++++++ .../openstrap/app/update/AppUpdaterTest.kt | 32 ++++++ 10 files changed, 239 insertions(+), 46 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt index 75f95772..715804cc 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/UpdatesPage.kt @@ -35,6 +35,7 @@ import org.openstrap.app.ui.glow.PagePanel import org.openstrap.app.ui.glow.PageRow import org.openstrap.app.ui.glow.PageRows import org.openstrap.app.ui.theme.AppIcons +import org.openstrap.app.update.Check import org.openstrap.app.update.Install import org.openstrap.app.update.NoteBlock import org.openstrap.app.update.NoteSpan @@ -81,7 +82,7 @@ fun UpdatesPage( PageRow( stringResource(R.string.you_updates_check_now), UpdateCopy.checkStatus(state, now), onClick = onCheck, below = true, divider = newest != null, - enabled = !state.checking, icon = AppIcons.Refresh04, + enabled = state.check != Check.Checking, icon = AppIcons.Refresh04, ) PageSwitchRow( stringResource(R.string.you_updates_daily), stringResource(R.string.you_updates_daily_note), auto, onAuto, diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt index 43325bb2..75cb6d9b 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt @@ -248,6 +248,9 @@ fun ZeppAccountScreen(vm: FirmwareViewModel, contentPadding: PaddingValues, onBa } } +/** What the Zepp account panel is doing: one value, so editing the token and signing in can't both be on. */ +private enum class AccountMode { Idle, EditingToken, SigningIn } + @Composable private fun AccountPanel( account: ZeppAccount?, @@ -256,18 +259,17 @@ private fun AccountPanel( onClear: () -> Unit, onSignIn: (DeviceListing, BoundDevice?) -> Unit, ) { - var editing by rememberSaveable { mutableStateOf(false) } - var signIn by rememberSaveable { mutableStateOf(false) } - if (signIn) { + var mode by rememberSaveable { mutableStateOf(AccountMode.Idle) } + if (mode == AccountMode.SigningIn) { ZeppSignInDialog( preferredApiBase = account?.apiBase, confirmLabel = stringResource(R.string.you_zepp_save_sign_in), - onDismiss = { signIn = false }, - onConfirm = { listing, strap -> signIn = false; onSignIn(listing, strap) }, + onDismiss = { mode = AccountMode.Idle }, + onConfirm = { listing, strap -> mode = AccountMode.Idle; onSignIn(listing, strap) }, ) } PagePanel { - if (!editing) { + if (mode != AccountMode.EditingToken) { Body( when { account == null -> stringResource(R.string.you_zepp_account_none) @@ -276,12 +278,12 @@ private fun AccountPanel( }, ) PageButton( - stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), { signIn = true }, + stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), { mode = AccountMode.SigningIn }, Modifier.fillMaxWidth(), enabled = enabled, primary = true, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { PageButton( - stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), { editing = true }, + stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), { mode = AccountMode.EditingToken }, Modifier.weight(1f), enabled = enabled, ) if (account != null) { @@ -292,10 +294,12 @@ private fun AccountPanel( } return@PagePanel } - var token by rememberSaveable { mutableStateOf("") } - var user by rememberSaveable { mutableStateOf(account?.userId.orEmpty()) } - var api by rememberSaveable { mutableStateOf(account?.apiBase ?: ZeppAccount.DEFAULT_API_BASE) } - var china by rememberSaveable { mutableStateOf(account?.china == true) } + // Keyed on the account, so a fresh sign-in or renewed token starts the fields again from it and a stale copy + // can't be written back over it. The pasted token is the secret: plain remember, so it never reaches the saved state. + var token by remember(account) { mutableStateOf("") } + var user by rememberSaveable(account) { mutableStateOf(account?.userId.orEmpty()) } + var api by rememberSaveable(account) { mutableStateOf(account?.apiBase ?: ZeppAccount.DEFAULT_API_BASE) } + var china by rememberSaveable(account) { mutableStateOf(account?.china == true) } PageField( token, { token = it }, stringResource(R.string.you_zepp_app_token), Modifier.fillMaxWidth(), placeholder = if (account != null) stringResource(R.string.you_zepp_keep_token) else null, @@ -310,10 +314,10 @@ private fun AccountPanel( stringResource(R.string.you_zepp_china), stringResource(R.string.you_zepp_china_note), china, { china = it }, divider = false, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { - PageButton(stringResource(R.string.you_action_cancel), { editing = false }, Modifier.weight(1f)) + PageButton(stringResource(R.string.you_action_cancel), { mode = AccountMode.Idle }, Modifier.weight(1f)) PageButton( stringResource(R.string.you_action_save), - { onSave(token.ifBlank { account?.appToken.orEmpty() }, user, api, china); editing = false }, Modifier.weight(1f), + { onSave(token.ifBlank { account?.appToken.orEmpty() }, user, api, china); mode = AccountMode.Idle }, Modifier.weight(1f), enabled = token.isNotBlank() || account != null, primary = true, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt index ed6b6ba0..686fd164 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -103,15 +104,26 @@ class FirmwareViewModel( fun reset() { if (!busy) _step.value = FirmwareStep.Idle } - private val busy get() = _step.value.let { it is FirmwareStep.Checking || it is FirmwareStep.Downloading || it is FirmwareStep.Installing } + private val busy get() = _step.value.isBusy() + + private fun FirmwareStep.isBusy() = this is FirmwareStep.Checking || this is FirmwareStep.Downloading || this is FirmwareStep.Installing + + /** + * Moves to [next] only while the step is still the kind [S] this work started in. Work that outlives its step (a + * late progress callback, a result after the page was reset) is dropped, so it can't pull the step back. + */ + private inline fun settle(next: FirmwareStep) { + _step.update { if (it is S) next else it } + } fun check() { + if (busy) return val acc = account.value ?: return fail(strings.get(R.string.you_firmware_no_account)) val info = strap.info.value val firmware = info?.firmware ?: return fail(strings.get(R.string.you_firmware_no_version)) _step.value = FirmwareStep.Checking viewModelScope.launch { - _step.value = catching { + settle(catching { val identity = StrapIdentity( firmwareVersion = firmware, hardwareVersion = info.hardware, @@ -128,7 +140,7 @@ class FirmwareViewModel( cloud.check(current.apiBase, current.appToken, current.userId, identity) } FirmwareStep.Checked(result) - }.getOrElse { failed("firmware check", it, strings.get(R.string.you_firmware_check_failed)) } + }.getOrElse { failed("firmware check", it, strings.get(R.string.you_firmware_check_failed)) }) } } @@ -147,12 +159,13 @@ class FirmwareViewModel( /** Downloads the first part in install order and stages it. Further parts follow after the strap restarts. */ fun download(part: FirmwarePart) { + if (busy) return val type = part.type ?: return fail(strings.format(R.string.you_firmware_unknown_part, part.prefix)) _step.value = FirmwareStep.Downloading(part, 0f) viewModelScope.launch { - _step.value = catching { + settle(catching { val bytes = cloud.download(part) { done, total -> - if (total > 0) _step.value = FirmwareStep.Downloading(part, done.toFloat() / total) + if (total > 0) settle(FirmwareStep.Downloading(part, done.toFloat() / total)) } val trailer = HmfwTrailer.read(bytes) FirmwareStep.Ready( @@ -162,13 +175,14 @@ class FirmwareViewModel( trailer, trailerWarnings(bytes, trailer, type), ), ) - }.getOrElse { failed("firmware download", it, strings.get(R.string.you_firmware_download_failed)) } + }.getOrElse { failed("firmware download", it, strings.get(R.string.you_firmware_download_failed)) }) } } /** Stages a file the user picked. Only plain firmware images are accepted from files. */ fun loadFile(uri: Uri) = viewModelScope.launch { - _step.value = catching { + if (busy) return@launch + val next = catching { val bytes = withContext(Dispatchers.IO) { val input = openFile(uri) ?: throw FileNotFoundException("no input stream for $uri") input.use { it.readBytes() } @@ -191,6 +205,8 @@ class FirmwareViewModel( log("firmware: file not read: $it") FirmwareStep.Failed(strings.get(R.string.you_firmware_file_unread)) } + // The read takes a while: a check, download or install that began meanwhile keeps the step. + _step.update { if (it.isBusy()) it else next } } /** Problems that make an image look wrong for this strap (docs/protocol/03 §2.2, advisory). */ @@ -219,23 +235,24 @@ class FirmwareViewModel( } fun install(image: ReadyImage) { + if (busy) return val blocking = blockers() if (blocking.isNotEmpty()) return fail(blocking.joinToString(" ")) _step.value = FirmwareStep.Installing(strings.get(R.string.you_firmware_step_starting), null) viewModelScope.launch { - _step.value = catching { + settle(catching { strap.installFirmware(image.bytes, image.type) { p -> - _step.value = when (p) { + settle(when (p) { is DfuProgress.Transferring -> FirmwareStep.Installing( strings.get(R.string.you_firmware_step_sending), p.sent.toFloat() / p.total, ) DfuProgress.Validating -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_validating), null) DfuProgress.Applying -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_applying), null) DfuProgress.Done -> FirmwareStep.Installing(strings.get(R.string.you_firmware_step_restarting), 1f) - } + }) } FirmwareStep.Installed - }.getOrElse { failed("firmware install", it, strings.get(R.string.you_firmware_install_failed)) } + }.getOrElse { failed("firmware install", it, strings.get(R.string.you_firmware_install_failed)) }) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt index f50dc6b8..13107292 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt @@ -38,6 +38,7 @@ import dev.chrisbanes.haze.HazeState import dev.chrisbanes.haze.hazeSource import org.openstrap.app.AppContainer import org.openstrap.app.PendingAction +import org.openstrap.app.R import org.openstrap.app.data.HeartZones import org.openstrap.app.data.Recovery import org.openstrap.app.data.SampleData @@ -403,11 +404,24 @@ private fun UpdatesPageHost(container: AppContainer, rootVm: AppRootViewModel, p val allowLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { (waiting as? PendingAction.Install)?.let { install -> waiting = install.copy(answered = true) } } + val context = LocalContext.current + // Whatever way the wait ends, it is cleared: the install goes ahead, "install unknown apps" stayed off (a toast says + // so), or the release is gone from the list (the list is only empty before the saved one is read, so that waits). LaunchedEffect(waiting, updates.releases) { val install = (waiting as? PendingAction.Install)?.takeIf { it.answered } ?: return@LaunchedEffect - val release = updates.releases.firstOrNull { it.tag == install.tag } ?: return@LaunchedEffect + val release = updates.releases.firstOrNull { it.tag == install.tag } + if (release == null && updates.releases.isEmpty()) return@LaunchedEffect waiting = null - if (updater.canInstall()) updater.install(release) + when { + release == null -> Unit + updater.canInstall() -> updater.install(release) + else -> Toast.makeText(context, R.string.update_install_not_allowed, Toast.LENGTH_LONG).show() + } + } + // Back from Android's confirm screen with nothing installing, the page doesn't stay on Installing. + LifecycleResumeEffect(updater) { + updater.reconcile() + onPauseOrDispose { } } val uri = LocalUriHandler.current UpdatesPage( diff --git a/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt b/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt index 88e14e34..a5aadbf6 100644 --- a/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt +++ b/app/src/main/kotlin/org/openstrap/app/update/AppUpdater.kt @@ -20,6 +20,7 @@ import androidx.work.WorkManager import androidx.work.WorkerParameters import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow @@ -56,14 +57,20 @@ sealed interface Install { data class Failed(val tag: String, val failure: InstallFailure, val detail: String? = null) : Install } +/** Where reading the release list stands: one value, so "checking" and "failed" can't both be true. */ +sealed interface Check { + data object Idle : Check + data object Checking : Check + /** The last check couldn't reach GitHub or read its reply. */ + data object Failed : Check +} + data class UpdateState( /** Every release GitHub listed at the last check (kept across restarts), newest first. */ val releases: List = emptyList(), /** When that check was, epoch seconds. */ val checkedAt: Long? = null, - val checking: Boolean = false, - /** The last check couldn't reach GitHub or read its reply. */ - val checkFailed: Boolean = false, + val check: Check = Check.Idle, val install: Install = Install.Idle, ) @@ -110,8 +117,43 @@ class AppUpdater( /** Sets the daily check going, or stops it, as the switch says; each app start. */ fun start() { scope.launch { if (settings.updateAuto.first()) schedule(app) else cancel(app) } + reconcile() } + /** True from creating the installer session until it is committed, when no session is yet there to find. */ + @Volatile private var committing = false + + /** + * Brings the saved "installing" tag and [Install.Installing] in line with what Android has. Each app start, and when the + * Updates page comes back to the front (the user may have walked away from Android's confirm screen): + * - the tag is for this version or an older one: the update is in, the tag goes; + * - no installer session of ours is open: nothing is installing, so the tag goes and the page is back to Idle; + * - a session is open and memory says Idle (the process died after the commit): the page shows Installing again. + */ + fun reconcile() { + scope.launch { + if (committing) return@launch + val tag = (_state.value.install as? Install.Installing)?.tag ?: settings.updateInstalling() ?: return@launch + val target = Releases.version(tag) + val mine = Releases.version(installed) + val inThere = target != null && mine != null && Releases.compare(target, mine) <= 0 + val live = !inThere && withContext(Dispatchers.IO) { sessionOpen() } + if (committing) return@launch + when { + live -> _state.update { if (it.install is Install.Idle) it.copy(install = Install.Installing(tag)) else it } + else -> { + settings.setUpdateInstalling(null) + _state.update { if (it.install is Install.Installing) it.copy(install = Install.Idle) else it } + } + } + } + } + + /** An installer session of this app is open: committed or not, Android hasn't finished with it. */ + private fun sessionOpen(): Boolean = runCatching { + app.packageManager.packageInstaller.mySessions.any { it.appPackageName == app.packageName } + }.getOrDefault(false) + fun setAuto(on: Boolean) { scope.launch { settings.setUpdateAuto(on) @@ -125,7 +167,7 @@ class AppUpdater( /** Reads the release list from GitHub; true when it got one. */ suspend fun check(): Boolean = checkLock.withLock { - _state.update { it.copy(checking = true) } + _state.update { it.copy(check = Check.Checking) } try { catching { val json = get(Releases.API, github = true) @@ -137,16 +179,16 @@ class AppUpdater( } val now = System.currentTimeMillis() / 1000 settings.setUpdateChecked(now) - _state.update { it.copy(releases = releases, checkedAt = now, checkFailed = false) } + _state.update { it.copy(releases = releases, checkedAt = now, check = Check.Idle) } true }.getOrElse { e -> Log.i(TAG, "Update check failed: $e") - _state.update { it.copy(checkFailed = true) } + _state.update { it.copy(check = Check.Failed) } false } } finally { // Cancelled too: the page doesn't stay on Checking. - _state.update { it.copy(checking = false) } + _state.update { if (it.check == Check.Checking) it.copy(check = Check.Idle) else it } } } @@ -179,14 +221,36 @@ class AppUpdater( checkArchive(file) // The download can outlast a workout's start. if (recording()) throw Stop(InstallFailure.Recording) + committing = true _state.update { it.copy(install = Install.Installing(tag)) } settings.setUpdateInstalling(tag) commit(file) + watchInstalling(tag) }.onFailure { e -> val failure = failureFor(e) if (e !is Stop) Log.i(TAG, "Update install failed ($failure): $e") fail(tag, failure, e.message.takeIf { failure == InstallFailure.Android }) } + committing = false + } + } + + /** + * Installing has a way out: when the user ignores Android's confirm screen nothing is ever reported, so after + * [INSTALL_TIMEOUT_MS] the open session is abandoned and the page goes back to Idle. + */ + private fun watchInstalling(tag: String) { + scope.launch { + delay(INSTALL_TIMEOUT_MS) + if ((_state.value.install as? Install.Installing)?.tag != tag) return@launch + withContext(Dispatchers.IO) { + runCatching { + val installer = app.packageManager.packageInstaller + installer.mySessions.filter { it.appPackageName == app.packageName }.forEach { installer.abandonSession(it.sessionId) } + } + } + settings.setUpdateInstalling(null) + _state.update { if ((it.install as? Install.Installing)?.tag == tag) it.copy(install = Install.Idle) else it } } } @@ -195,14 +259,16 @@ class AppUpdater( _state.update { if (it.install is Install.Failed) it.copy(install = Install.Idle) else it } } - /** What Android's package installer reported ([UpdateReceiver]). */ + /** + * What Android's package installer reported ([UpdateReceiver]). The tag is the one in memory, or the saved one when the + * process died after the commit, so a failure then is shown and the saved tag cleared instead of lost. + */ internal fun installResult(context: Context, status: Int, message: String?, confirm: Intent?) { - val tag = (_state.value.install as? Install.Installing)?.tag when (status) { // Android asks the user first: its own confirmation screen. PackageInstaller.STATUS_PENDING_USER_ACTION -> confirm?.let { runCatching { context.startActivity(it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } - .onFailure { e -> tag?.let { t -> fail(t, InstallFailure.Android, e.message) } } + .onFailure { e -> withTag { t -> fail(t, InstallFailure.Android, e.message) } } } // On success Android closes the app, so this is rarely seen. PackageInstaller.STATUS_SUCCESS -> _state.update { it.copy(install = Install.Idle) } @@ -217,11 +283,18 @@ class AppUpdater( else -> InstallFailure.Android } Log.i(TAG, "Update install failed: status $status, $message") - fail(tag ?: return, failure, message) + withTag { t -> fail(t, failure, message) } } } } + /** Runs [block] with the tag being installed: from memory, or else the saved one. Nothing when neither is there. */ + private fun withTag(block: (String) -> Unit) { + val tag = (_state.value.install as? Install.Installing)?.tag + if (tag != null) return block(tag) + scope.launch { settings.updateInstalling()?.let(block) } + } + private fun fail(tag: String, failure: InstallFailure, detail: String? = null) { _state.update { it.copy(install = Install.Failed(tag, failure, detail)) } scope.launch { settings.setUpdateInstalling(null) } @@ -358,6 +431,9 @@ class AppUpdater( private const val TAG = "unstrap" private const val DAILY = "update-check" + /** How long Installing waits for Android's report before the page goes back to Idle. */ + internal const val INSTALL_TIMEOUT_MS = 10 * 60 * 1000L + /** Starts the daily check; a no-op when it's already scheduled. Runs only with a network. */ fun schedule(context: Context) { val request = PeriodicWorkRequestBuilder(1, TimeUnit.DAYS) diff --git a/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt b/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt index 60c44bd9..f4db953d 100644 --- a/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt +++ b/app/src/main/kotlin/org/openstrap/app/update/UpdateCopy.kt @@ -24,7 +24,7 @@ object UpdateCopy { ): String { val newest = Releases.newer(state.releases, installed).firstOrNull() if (newest != null) return strings.format(R.string.update_summary_ready, newest.versionName) - if (state.checking) return strings.get(R.string.update_summary_checking) + if (state.check == Check.Checking) return strings.get(R.string.update_summary_checking) val checked = state.checkedAt ?: return strings.format(R.string.update_summary_version, installed) return strings.format(R.string.update_summary_up_to_date, DayWords.whenDone(checked, now, zone, locale = locale)) } @@ -37,9 +37,9 @@ object UpdateCopy { locale: Locale = Locale.getDefault(), strings: Strings = Strings.app, ): String { - if (state.checking) return strings.get(R.string.update_check_checking) + if (state.check == Check.Checking) return strings.get(R.string.update_check_checking) val checked = state.checkedAt?.let { DayWords.whenDone(it, now, zone, locale = locale) } - if (state.checkFailed) { + if (state.check == Check.Failed) { return if (checked != null) { strings.format(R.string.update_check_failed_last, checked) } else { diff --git a/app/src/main/res/values/strings_update.xml b/app/src/main/res/values/strings_update.xml index 09a5c798..5633dc47 100644 --- a/app/src/main/res/values/strings_update.xml +++ b/app/src/main/res/values/strings_update.xml @@ -30,6 +30,8 @@ Downloading, %1$s Installing. unstrap closes when it\'s done + + unstrap isn\'t allowed to install apps, so it wasn\'t updated No app file in this release. Open it on GitHub diff --git a/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt b/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt index e3462e15..0026fc7d 100644 --- a/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/presentation/UpdateCopyTest.kt @@ -2,6 +2,7 @@ package org.openstrap.app.presentation import org.junit.Assert.assertEquals import org.junit.Test +import org.openstrap.app.update.Check import org.openstrap.app.update.Install import org.openstrap.app.update.InstallFailure import org.openstrap.app.update.Release @@ -21,20 +22,20 @@ class UpdateCopyTest { @Test fun `the You page's row says a new version, checking, up to date, or just the version`() { assertEquals("unstrap 2.2.0 is ready to install", UpdateCopy.summary(UpdateState(listOf(r220, r210), checkedAt = now), "2.1.0", now, utc, Locale.UK)) - assertEquals("Checking…", UpdateCopy.summary(UpdateState(listOf(r210), checking = true), "2.1.0", now, utc, Locale.UK)) + assertEquals("Checking…", UpdateCopy.summary(UpdateState(listOf(r210), check = Check.Checking), "2.1.0", now, utc, Locale.UK)) assertEquals("Up to date. Checked today at 19:00", UpdateCopy.summary(UpdateState(listOf(r210), checkedAt = now - 3600), "2.1.0", now, utc, Locale.UK)) assertEquals("Version 2.1.0", UpdateCopy.summary(UpdateState(), "2.1.0", now, utc, Locale.UK)) } @Test fun `Check now says when it last looked, and when GitHub couldn't be reached`() { assertEquals("Never checked", UpdateCopy.checkStatus(UpdateState(), now, utc, Locale.UK)) - assertEquals("Checking GitHub…", UpdateCopy.checkStatus(UpdateState(checking = true), now, utc, Locale.UK)) + assertEquals("Checking GitHub…", UpdateCopy.checkStatus(UpdateState(check = Check.Checking), now, utc, Locale.UK)) assertEquals("Last checked yesterday at 23:50", UpdateCopy.checkStatus(UpdateState(checkedAt = 1792195200L - 600), now, utc, Locale.UK)) assertEquals( "Couldn't reach GitHub. Last checked today at 19:00", - UpdateCopy.checkStatus(UpdateState(checkedAt = now - 3600, checkFailed = true), now, utc, Locale.UK), + UpdateCopy.checkStatus(UpdateState(checkedAt = now - 3600, check = Check.Failed), now, utc, Locale.UK), ) - assertEquals("Couldn't reach GitHub", UpdateCopy.checkStatus(UpdateState(checkFailed = true), now, utc, Locale.UK)) + assertEquals("Couldn't reach GitHub", UpdateCopy.checkStatus(UpdateState(check = Check.Failed), now, utc, Locale.UK)) } @Test fun `the install row follows the download and says why it stopped`() { diff --git a/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt index 5a538e29..e1d0e8bd 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModelTest.kt @@ -19,6 +19,7 @@ import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith @@ -31,6 +32,11 @@ import org.robolectric.annotation.Config import java.io.ByteArrayInputStream import java.io.InputStream import java.lang.reflect.Proxy +import kotlin.coroutines.Continuation +import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED +import kotlin.coroutines.resume +import org.openstrap.protocol.firmware.DfuProgress +import org.openstrap.protocol.firmware.FirmwareType /** The firmware view model stands on the strap, the settings, a cache folder and a file reader, not the whole app (audit A3). */ @OptIn(ExperimentalCoroutinesApi::class) @@ -76,6 +82,38 @@ class FirmwareViewModelTest { assertEquals(connection.value, vm.connection.value) } + @Test fun `events that don't fit the step are ignored, and late progress can't revive an install`() = runBlocking { + connection.value = ConnectionState.Connected(50, "3.25") + val vm = vm { ByteArrayInputStream(ByteArray(10)) } + val image = ReadyImage(ByteArray(2048), FirmwareType.FIRMWARE, "Firmware", null, fromCloud = false, trailer = null, warnings = emptyList()) + vm.install(image) + val installing = vm.step.value + assertTrue(installing is FirmwareStep.Installing) + + // A file picked, a check, or a second install during the install change nothing. + vm.loadFile(picked).join() + vm.check() + vm.install(image) + vm.reset() + assertEquals(installing, vm.step.value) + + // Progress is applied while installing, then the install ends. + progress!!(DfuProgress.Applying) + assertTrue(vm.step.value is FirmwareStep.Installing) + installDone!!.resume(Unit) + assertEquals(FirmwareStep.Installed, vm.step.value) + + // A callback that arrives after the end doesn't start it again. + progress!!(DfuProgress.Validating) + assertEquals(FirmwareStep.Installed, vm.step.value) + vm.reset() + progress!!(DfuProgress.Validating) + assertEquals(FirmwareStep.Idle, vm.step.value) + } + + private var progress: ((DfuProgress) -> Unit)? = null + private var installDone: Continuation? = null + /** A strap whose link is [connection] and that does nothing else. */ private fun strap(): StrapController { val flows = mutableMapOf() @@ -85,6 +123,14 @@ class FirmwareViewModelTest { method.name == "equals" -> proxy === args?.firstOrNull() method.name == "toString" -> "test strap" method.name == "getConnection" -> connection + // An install that stays open until the test ends it. + method.name == "installFirmware" -> { + @Suppress("UNCHECKED_CAST") + progress = args!![2] as (DfuProgress) -> Unit + @Suppress("UNCHECKED_CAST") + installDone = args[3] as Continuation + COROUTINE_SUSPENDED + } StateFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableStateFlow(null) } SharedFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableSharedFlow() } method.returnType == java.lang.Boolean.TYPE -> false diff --git a/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt b/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt index 11994d9b..ff4332c7 100644 --- a/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/update/AppUpdaterTest.kt @@ -86,4 +86,36 @@ class AppUpdaterTest { assertTrue(thrown.toString(), thrown is FileNotFoundException) assertEquals(emptyList(), installer.allSessions) } + + @Test fun `a failure after the process died is shown from the saved tag and clears it`() = runBlocking { + val settings = SettingsStore(app) + settings.setUpdateInstalling("v9.0.0") + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + updater.installResult(app, android.content.pm.PackageInstaller.STATUS_FAILURE_STORAGE, "full", null) + val failed = withTimeout(10_000) { updater.state.first { it.install is Install.Failed }.install as Install.Failed } + assertEquals("v9.0.0", failed.tag) + assertEquals(InstallFailure.Storage, failed.failure) + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + } + + @Test fun `a saved tag with no installer session open is cleared at start`() = runBlocking { + val settings = SettingsStore(app) + settings.setUpdateInstalling("v9.0.0") + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + updater.reconcile() + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + assertEquals(Install.Idle, updater.state.value.install) + } + + @Test fun `a saved tag for the version running is cleared`() = runBlocking { + val settings = SettingsStore(app) + val updater = AppUpdater(app, settings, recording = { false }, scope = scope) + settings.setUpdateInstalling("v${updater.installed}") + updater.reconcile() + withTimeout(10_000) { while (settings.updateInstalling() != null) kotlinx.coroutines.delay(20) } + } + + @Test fun `the check state is one value`() { + assertEquals(Check.Idle, UpdateState().check) + } } From 484a394b305accc43b1aeac27856b1f79a669d64 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:46:55 +0400 Subject: [PATCH 06/27] Workout core: atomic discard, safer start and restore, no stray readings after End Discard is one DAO transaction. Start rolls back if it fails half way and honours a missing GPS. Readings after the last flush are dropped, the loop flushes under the lock, and a failed restore is retried. Starting a workout no longer overrides Disconnect. Co-Authored-By: Claude Sonnet 5.5 --- .../kotlin/org/openstrap/app/data/db/Daos.kt | 21 ++ .../app/device/SavedWorkoutEditor.kt | 20 +- .../openstrap/app/device/WorkoutSession.kt | 179 ++++++++++++------ .../app/device/WorkoutSessionTest.kt | 71 ++++++- 4 files changed, 217 insertions(+), 74 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt b/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt index f747b6ea..c84a48f2 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/db/Daos.kt @@ -388,6 +388,27 @@ interface HealthDao : RangedReads { deleteAppWorkoutRow(start) } + /** + * Discards the phone workout [start] whole: the workout, the strap's own records of it + * ([org.openstrap.app.data.Workouts.strapTwins]) and its time as "Not a workout", in one transaction. Its time range + * is read before anything is deleted, and a failure undoes all of it, so a retry finds the workout still there and + * does the twin cleanup too. [now] is when it happens. Returns the workout as it was, null if it was gone already. + */ + @androidx.room.Transaction + suspend fun discardAppWorkout(start: Long, now: Long): AppWorkout? { + val w = appWorkoutOnce(start) + val range = w?.takeIf { it.end != null }?.let { org.openstrap.app.data.Workouts.phoneRange(it, now) } + val twins = range?.let { org.openstrap.app.data.Workouts.strapTwins(workoutsOnce(it.first, it.last), it) }.orEmpty() + // Gone before its twins: a start trimmed into a twin would make it another owner of the strap's effect, and the + // effect would stay, its recovery carried into the next workout. + deleteAppWorkout(start) + twins.forEach { deleteStrapWorkout(it.start, now) } + // The strap's copy usually syncs after the summary shows: its time is remembered, and the sync leaves out a + // strap workout over it. + range?.let { insertDismissedWorkouts(listOf(DismissedWorkout(it.first, it.last))) } + return w + } + @Query("SELECT * FROM sport_effect WHERE `end` BETWEEN :from AND :to ORDER BY `end`") suspend fun sportEffectsOnce(from: Long, to: Long): List 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 a115f040..65f68453 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SavedWorkoutEditor.kt @@ -41,23 +41,9 @@ internal class SavedWorkoutEditor( fun discard(start: Long) { scope.launch { lock.withLock { - // Not deleted, its summary stays, so Discard can be tried again. - val w = catching { - dao.appWorkoutOnce(start).also { w -> - // Gone before its twins: a start trimmed into a twin would make it another owner of the - // strap's effect, and the effect would stay, its recovery carried into the next workout. - dao.deleteAppWorkout(start) - if (w?.end != null) { - val t = clock() - val range = org.openstrap.app.data.Workouts.phoneRange(w, t) - org.openstrap.app.data.Workouts.strapTwins(dao.workoutsOnce(range.first, range.last), range) - .forEach { dao.deleteStrapWorkout(it.start, t) } - // The strap's copy usually syncs after the summary shows, so after a Discard tapped there: - // its time is remembered, and the sync leaves out a strap workout over it. - dao.insertDismissedWorkouts(listOf(org.openstrap.app.data.db.DismissedWorkout(range.first, range.last))) - } - } - }.onFailure { log("workout not discarded: ${it.message}") }.getOrElse { return@withLock } + // 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) 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 2338fa98..045ef23a 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -115,6 +115,8 @@ class WorkoutSession( private val scope: CoroutineScope = fallbackScope(), /** How long a workout left recording waits for the strap's history ([LeftRecording]). Tests shorten it. */ private val leftWaitMs: Long = LEFT_WAIT_MS, + /** How long a failed [restore] waits before trying again. Tests shorten it. */ + private val restoreRetryMs: Long = RESTORE_RETRY_MS, ) { private val lock = LOCK @@ -182,6 +184,9 @@ class WorkoutSession( private var recordJob: Job? = null private val buffer = mutableListOf() private var lastSecond = -1L + + /** The workout is being ended: its last flush is made, and a reading now would be written under no workout. */ + @Volatile private var ending = false private var wake: PowerManager.WakeLock? = null /** @@ -191,61 +196,90 @@ class WorkoutSession( */ fun restore() { scope.launch { + var failed = false try { - val waiting = lock.withLock { - if (_state.value is WorkoutState.Recording) return@withLock null - 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) - val waits = now - last > LEFT_RECORDING_S - // Paused, nothing the strap measured since is part of it. - if (waits && w.pausedAt != null) { - 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 - _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() - _stats.value = WorkoutRecorder.stats(stored) - val live = stored.filter { !it.fromHistory }.map { it.timestamp to it.bpm } - val maxHr = maxHeartRate() - _zoneSeconds.value = WorkoutRecorder.liveZoneSeconds(live, maxHr, heartZones.value).toList() - lastReading = live.lastOrNull() - _kcal.value = null - stepTotals = emptyList() - 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. - _route.value = if (w.keepRoute) dao.routeOnce(w.start).map { it.point } else emptyList() - 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) + catching { restoreLocked() } + .onSuccess { waiting -> waiting?.let { scope.launch { awaitStrap(it) } } } + .onFailure { + // The active row is still stored, so it is tried again below rather than ended: ending would + // cost a workout that only hit a bad moment (a locked database, say). + log("workout not restored, trying again: ${it.message}") + failed = true } - left - } - waiting?.let { scope.launch { awaitStrap(it) } } } finally { + // Marked either way: the service and the backups wait on it, and an unrestored workout mustn't hold them. _restored.value = true // After the restore, so a workout left recording isn't offered as a new one. autoStart.watch() } + if (failed) retryRestore() } } + /** A failed [restore] tried again, up to [RESTORE_TRIES] times, [restoreRetryMs] apart; then the row stays for the next start. */ + private suspend fun retryRestore() { + repeat(RESTORE_TRIES) { + delay(restoreRetryMs) + val done = catching { restoreLocked()?.let { l -> scope.launch { awaitStrap(l) } } } + .onFailure { log("workout not restored, ${it.message}") }.isSuccess + if (done) return + } + log("workout not restored: left as stored for the next start") + } + + /** The picking up of [restore], under [lock]: the workout waiting for the strap's history ([LeftRecording]), if any. */ + private suspend fun restoreLocked(): LeftRecording.Left? = + lock.withLock { + if (_state.value is WorkoutState.Recording) return@withLock null + 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) + val waits = now - last > LEFT_RECORDING_S + // Paused, nothing the strap measured since is part of it. + if (waits && w.pausedAt != null) { + 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 + _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() + _stats.value = WorkoutRecorder.stats(stored) + val live = stored.filter { !it.fromHistory }.map { it.timestamp to it.bpm } + val maxHr = maxHeartRate() + _zoneSeconds.value = WorkoutRecorder.liveZoneSeconds(live, maxHr, heartZones.value).toList() + lastReading = live.lastOrNull() + // Never down: kept when this very workout's figure is still in memory (a second try after a failure), + // else it starts over, as a figure of another workout would be wrong. Rest time added, a question + // open and "in a car" live only in the state and are not stored, so they start afresh: a restart + // mustn't ask at once ([askSince]). + if (trackStart != w.start) _kcal.value = null + stepTotals = emptyList() + 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() + _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) + } + left + } + fun start( sportType: Int, askToEnd: Boolean = true, target: org.openstrap.app.data.WorkoutTarget? = null, useGps: Boolean = false, keepRoute: Boolean = false, @@ -263,10 +297,13 @@ class WorkoutSession( useGps = useGps, keepRoute = useGps && keepRoute, rest = rest?.code, setsTarget = setsTarget, structure = structure, ) - _route.value = emptyList() + _route.update { emptyList() } savedPoints = 0 trackFrom(w, routeSince = w.start, stepsSince = w.start, before = null) synchronized(allReadings) { allReadings.clear() } + // Nothing of an earlier workout is written under this one's start. + synchronized(buffer) { buffer.clear() } + lastSecond = -1L _history.value = emptyList() dao.upsertAppWorkout(w) _recent.value = emptyList() @@ -281,7 +318,11 @@ class WorkoutSession( window = emptyList() askSince = w.start minimized.value = false - begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) } + // Half started is not started: begin undid what it took, and the row goes too. + catching { begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) } }.onFailure { + log("workout not started: $it") + catching { dao.deleteAppWorkout(w.start) }.onFailure { e -> log("workout row not removed: ${e.message}") } + } } } } @@ -437,6 +478,9 @@ class WorkoutSession( lock.withLock { val r = _state.value as? WorkoutState.Recording ?: return@withLock if (startOf != null && r.workout.start != startOf) return@withLock + // Readings after this one are dropped ([record]): they would be written after the last flush, under + // the next workout's start or as rows of one just deleted. + ending = true flush() saveDistance() val w = r.workout @@ -456,6 +500,8 @@ class WorkoutSession( stored.exceptionOrNull()?.let { log("workout ${if (kept) "not saved" else "not deleted"}, still recording: ${it.message}") _state.update { s -> (s as? WorkoutState.Recording)?.copy(saveFailed = true) ?: s } + // Recording on, so readings count again. + ending = false return@withLock } left = null @@ -883,7 +929,7 @@ class WorkoutSession( private val allReadings = mutableListOf>() private val location = WorkoutLocation(context) { p -> val r = _state.value as? WorkoutState.Recording ?: return@WorkoutLocation - if (!r.paused) _route.value = _route.value + p + if (!r.paused) _route.update { it + p } } private var heightCm: Int? = null @@ -933,21 +979,37 @@ class WorkoutSession( * before the live readings start, so [record] only ever runs on one coroutine at a time. */ private suspend fun begin( - w: AppWorkout, maxHr: Int, seed: List> = emptyList(), + w0: AppWorkout, maxHr: Int, seed: List> = emptyList(), setup: (WorkoutState.Recording) -> WorkoutState.Recording = { it }, ) { // Waited for, so the calm down's own switch-off can't land after this workout turns the stream on. calmJob?.cancelAndJoin() calmJob = null - coach = org.openstrap.app.data.Coach(org.openstrap.app.data.WorkoutTarget.parse(w.target), w.targetReachedAt) + coach = org.openstrap.app.data.Coach(org.openstrap.app.data.WorkoutTarget.parse(w0.target), w0.targetReachedAt) strapSessions = catching { settings.strapSessions.first() } .onFailure { log("workout: strap sessions setting not read: $it") }.getOrDefault(true) heightCm = catching { settings.profile.first().heightCm }.onFailure { log("workout: height not read: $it") }.getOrNull() - if (w.useGps) location.start() + // No permission or no GPS provider: the workout says it doesn't use GPS, and measures from the strap's steps. + val w = if (w0.useGps && !location.start()) { + log("workout: GPS not available, distance from the strap's steps") + w0.copy(useGps = false).also { catching { dao.upsertAppWorkout(it) }.onFailure { e -> log("workout not saved: ${e.message}") } } + } else w0 + ending = false _state.update { setup(WorkoutState.Recording(w, maxHr)) } + // Anything that fails from here on undoes the start, so a workout is never left Recording with nothing behind it. + catching { startRecording(w, maxHr, seed) }.onFailure { + _state.update { WorkoutState.Idle } + stop() + throw it + } + } + + /** What recording [w] needs, after its state is set: the strap, the service, the wake lock and the readings. */ + private suspend fun startRecording(w: AppWorkout, maxHr: Int, seed: List>) { strap.setWorkoutActive(true) startService(w.sportType) - strap.autoConnect() + // Not autoConnect: a Disconnect the user chose holds, and the Ready screen offers Connect. + strap.backgroundConnect() // The CPU must keep up with the strap's readings and the flushes while the screen is off. wake = context.getSystemService(PowerManager::class.java) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "unstrap:workout").apply { acquire(MAX_WAKE_MS) } @@ -997,8 +1059,11 @@ class WorkoutSession( var tick = 0 while (isActive) { delay(FLUSH_MS) - flush() - saveDistance() + // Under the lock finish takes, so a flush here can't run alongside the one that ends the workout. + lock.withLock { + flush() + saveDistance() + } _history.value = synchronized(allReadings) { allReadings.toList() } if (++tick % STOP_CHECK_TICKS == 0) checkStopped() } @@ -1135,6 +1200,7 @@ class WorkoutSession( carRegistered = false recordJob?.cancel() recordJob = null + synchronized(buffer) { buffer.clear() } if (!keepLive) strap.setWorkoutActive(false) wake?.takeIf { it.isHeld }?.release() wake = null @@ -1149,7 +1215,7 @@ class WorkoutSession( val r = _state.value as? WorkoutState.Recording ?: return if (r.paused || !WorkoutRecorder.isValid(bpm)) return synchronized(buffer) { - if (t == lastSecond) return + if (ending || t == lastSecond) return lastSecond = t buffer += AppWorkoutHeartRate(r.workout.start, t, bpm) } @@ -1218,6 +1284,9 @@ class WorkoutSession( ) const val FLUSH_MS = 10_000L + /** A failed [restore] is tried again this many times, this far apart. */ + const val RESTORE_TRIES = 3 + const val RESTORE_RETRY_MS = 30_000L /** Live readings held while the database refuses them: two hours, one a second. */ const val MAX_UNSAVED = 7_200 /** The live kcal is worked out again this often. */ 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 1cd461a0..45f98e0d 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -101,9 +101,10 @@ class WorkoutSessionTest { private fun session( leftWaitMs: Long = WorkoutSession.LEFT_WAIT_MS, on: Context = context, settings: SettingsStore = SettingsStore(context), + restoreRetryMs: Long = WorkoutSession.RESTORE_RETRY_MS, ) = WorkoutSession( on, dao, settings, strap, MaxHeartRates(dao, flowOf(profile())), clock = { clock.now }, scope = scope, - leftWaitMs = leftWaitMs, + leftWaitMs = leftWaitMs, restoreRetryMs = restoreRetryMs, ) private fun StateFlow.await(what: String = "state", predicate: (T) -> Boolean): T = runBlocking { @@ -228,6 +229,64 @@ class WorkoutSessionTest { } } + @Test + fun discardTakesTheTwinsAndDismissesInOneStep() { + val t0 = clock.now + runBlocking { + db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = t0 + 300, sportType = 1)) + db.healthDao().insertWorkouts(listOf(Workout(t0 + 3, t0 + 304, 1, 300, null, null, null, null, null, null, null, null, null, 6))) + val gone = db.healthDao().discardAppWorkout(t0, clock.now) + assertEquals(t0, gone?.start) + assertNull(db.healthDao().appWorkoutOnce(t0)) + assertNull(db.healthDao().workoutOnce(t0 + 3)) + assertTrue(db.healthDao().dismissedWorkoutsAll().any { it.start == t0 && it.end == t0 + 300 }) + // A second call finds nothing and changes nothing. + assertNull(db.healthDao().discardAppWorkout(t0, clock.now)) + } + } + + @Test + fun aStartWithoutGpsAvailableDoesNotClaimGps() { + val s = session() + val t0 = clock.now + s.start(sportType = 1, useGps = true, keepRoute = true) + // No location permission in the test: the workout records from steps and says so. + assertEquals(false, s.recording().workout.useGps) + assertEquals(false, stored(t0)!!.useGps) + } + + @Test + fun aStartThatFailsHalfWayLeavesNothingBehind() { + val s = session() + val t0 = clock.now + strap.failActive = true + s.start(sportType = 1) + runBlocking { + withTimeout(WAIT_MS) { + while (strap.refused == 0 || stored(t0) != null || s.state.value !is WorkoutState.Idle) delay(POLL_MS) + } + } + assertNull(stored(t0)) + // And the next one starts as usual. + strap.failActive = false + s.start(sportType = 1) + assertEquals(t0, s.recording().workout.start) + } + + @Test + fun aRestoreThatFailsIsTriedAgainAndKeepsTheRow() { + val t0 = clock.now - 600 + runBlocking { db.healthDao().upsertAppWorkout(AppWorkout(start = t0, end = null, sportType = 1)) } + strap.failActive = true + val s = session(restoreRetryMs = POLL_MS) + s.restore() + s.restored.await { it } + // Marked restored so nothing waits on it, yet the workout is not ended. + assertNull(stored(t0)!!.end) + strap.failActive = false + assertEquals(t0, s.recording().workout.start) + } + @Test fun aWorkoutLeftRecordingComesBackAfterProcessDeath() { val t0 = clock.now - 600 @@ -762,7 +821,15 @@ class WorkoutSessionTest { override fun disconnect() = Unit override fun syncNow() = Unit override fun setAppVisible(visible: Boolean) = Unit - override fun setWorkoutActive(active: Boolean) = Unit + /** Turning the live stream on fails, as a start that throws half way does. */ + @Volatile var failActive = false + @Volatile var refused = 0 + override fun setWorkoutActive(active: Boolean) { + if (failActive && active) { + refused++ + throw IllegalStateException("strap refused") + } + } override fun setEffortWatch(active: Boolean) = Unit override suspend fun installFirmware(file: ByteArray, type: Int, onProgress: (org.openstrap.protocol.firmware.DfuProgress) -> Unit) = Unit override suspend fun readAlarms(): Pair> = throw StrapCommandException("not connected") From 302c82e5ba85f14244d8c9d0fe819bef5964b085 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:47:35 +0400 Subject: [PATCH 07/27] Small screens: alarms edits, share photo, sleep undo, backup lock, recap sent flag (S15, S23) Alarms: write results close the sheet only on success, queued refresh, Loading/Failed/Loaded read state. Share card: photo state, saveable result. Sleep detail: saveable sheets, Undo only after delete shows. Backups: one DataJobs lock and a snapshot file per call. Recap marked sent only after it is shown. Co-Authored-By: Claude Sonnet 5.5 --- .../org/openstrap/app/device/WeeklyRecap.kt | 12 ++- .../org/openstrap/app/export/AutoBackup.kt | 11 +-- .../openstrap/app/export/BackupSnapshot.kt | 49 ++++++++-- .../org/openstrap/app/export/CsvBackups.kt | 7 +- .../openstrap/app/ui/alarms/AlarmsScreen.kt | 43 +++++++-- .../app/ui/alarms/AlarmsViewModel.kt | 90 ++++++++++++++----- .../org/openstrap/app/ui/glow/ShareScreen.kt | 45 ++++++++-- .../org/openstrap/app/ui/glow/SleepDetail.kt | 35 +++++--- .../main/res/values/strings_glow_share.xml | 2 + .../app/export/BackupSnapshotTest.kt | 34 ++++++- .../app/ui/alarms/AlarmsViewModelTest.kt | 83 +++++++++++++++++ .../openstrap/app/ui/glow/SharePhotoTest.kt | 34 +++++++ 12 files changed, 375 insertions(+), 70 deletions(-) create mode 100644 app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt diff --git a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt index f98702ec..c4f73672 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt @@ -61,13 +61,19 @@ object WeeklyRecap { catching { container.rewards.refreshNow(recordingStart) }.onFailure { Log.w("unstrap", "weekly recap: weeks not refreshed: $it") } val weeks = container.database.healthDao().weekResultsOnce() val week = weeks.firstOrNull { it.weekStart == lastWeek.toEpochDay() } - settings.setRecapWeek(lastWeek.toEpochDay()) - if (week == null || week.count == 0) return + // Nothing to say about a week without a workout, and nothing will change that: done with it. + if (week == null || week.count == 0) { + settings.setRecapWeek(lastWeek.toEpochDay()) + return + } // Android 13 brought the notification permission. Before it, the check would always read as denied. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED ) return - show(context, RewardsCopy.weekRange(lastWeek), RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek))) + // Sent once it has been shown: a denied permission or a failed post leaves the week for the next look this morning. + val shown = catching { show(context, RewardsCopy.weekRange(lastWeek), RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek))) } + .onFailure { Log.w("unstrap", "weekly recap: not shown: $it") } + if (shown.isSuccess) settings.setRecapWeek(lastWeek.toEpochDay()) } private fun show(context: Context, range: String, text: String) { 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 85f0ee4d..584b2d7e 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/AutoBackup.kt @@ -19,8 +19,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.first -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import org.openstrap.app.OpenStrapApp @@ -59,11 +57,11 @@ class AutoBackup( data class Failed(val failure: BackupFailure) : Outcome } - suspend fun run(): Outcome = lock.withLock { - val folder = settings.backup.first().folder ?: return@withLock Outcome.Off + suspend fun run(): Outcome = DataJobs.exclusive { + val folder = settings.backup.first().folder ?: return@exclusive Outcome.Off // Until the session has looked for a workout left recording, Idle doesn't mean none. withTimeoutOrNull(10_000) { restored.first { it } } - if (workout.value is WorkoutState.Recording) return@withLock Outcome.Recording + if (workout.value is WorkoutState.Recording) return@exclusive Outcome.Recording val now = System.currentTimeMillis() / 1000 catching { val name = withContext(Dispatchers.IO) { write(Uri.parse(folder)) } @@ -161,9 +159,6 @@ class AutoBackup( } companion object { - /** One backup at a time, the daily one and Back up now alike. */ - private val lock = Mutex() - private const val DAILY = "auto-backup" private const val AFTER_WORKOUT = "auto-backup-retry" private const val TEMP_MIME = "application/octet-stream" diff --git a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt index 85d3f2e1..e8bfb7e5 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt @@ -4,14 +4,40 @@ import android.content.Context import android.database.sqlite.SQLiteDatabase import androidx.room.Room import org.openstrap.app.data.db.OpenStrapDatabase +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext import java.io.Closeable import java.io.File +import java.util.UUID +import kotlin.coroutines.AbstractCoroutineContextElement +import kotlin.coroutines.CoroutineContext +import kotlin.coroutines.coroutineContext + +/** + * The one lock for jobs that read or replace the whole database: the automatic backup, Save a copy and restore. Two of + * them at once would copy a half restored database or restore over a running backup. A job that already holds the lock + * and calls another (the automatic backup calling the zip writer) goes straight through instead of waiting on itself. + */ +object DataJobs { + private val mutex = Mutex() + + /** Marks a coroutine that holds [mutex], and passes on to everything it starts in its context. */ + private object Holding : AbstractCoroutineContextElement(Key) { + object Key : CoroutineContext.Key + } + + /** Runs [block] when no other data job is running; a block already inside one runs at once. */ + suspend fun exclusive(block: suspend () -> T): T = + if (coroutineContext[Holding.Key] != null) block() else mutex.withLock { withContext(Holding) { block() } } +} /** * A copy of the database as it was at one moment, for a backup to read (data integrity item 23): a sync that writes * while the zip is being written can't leave one table in it from before and another from after. `VACUUM INTO` makes * the copy from committed data only, and holds the database only while it copies (a second or two for a year of - * minutes), not while the zip is written, so a sync waits that long at most. [close] deletes the copy. + * minutes), not while the zip is written, so a sync waits that long at most. Each copy has its own file, so two never + * share one. [close] deletes the copy. */ class BackupSnapshot private constructor(private val file: File, val database: OpenStrapDatabase) : Closeable { override fun close() { @@ -20,17 +46,22 @@ class BackupSnapshot private constructor(private val file: File, val database: O } companion object { - /** The copy's file in the app's cache, made again for every backup. */ - private const val FILE = "backup-snapshot.db" + /** The start of a copy's file name in the app's cache; every copy adds its own id, so no two share a file. */ + private const val PREFIX = "backup-snapshot-" /** Copies [source] into the cache and opens the copy. Blocking: call it off the main thread. */ fun take(context: Context, source: OpenStrapDatabase): BackupSnapshot { - val file = File(context.cacheDir, FILE) - SQLiteDatabase.deleteDatabase(file) - // VACUUM takes no bind arguments, so the path, which is the app's own, goes in quoted. - source.openHelper.writableDatabase.execSQL("VACUUM INTO '${file.path.replace("'", "''")}'") - val copy = Room.databaseBuilder(context, OpenStrapDatabase::class.java, file.path).build() - return BackupSnapshot(file, copy) + val file = File(context.cacheDir, "$PREFIX${UUID.randomUUID()}.db") + try { + // VACUUM takes no bind arguments, so the path, which is the app's own, goes in quoted. + source.openHelper.writableDatabase.execSQL("VACUUM INTO '${file.path.replace("'", "''")}'") + val copy = Room.databaseBuilder(context, OpenStrapDatabase::class.java, file.path).build() + return BackupSnapshot(file, copy) + } catch (e: Throwable) { + // A copy that never opened is not left behind. + SQLiteDatabase.deleteDatabase(file) + throw e + } } } } diff --git a/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt b/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt index 34e36e16..0b01f1ca 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/CsvBackups.kt @@ -39,16 +39,17 @@ class CsvBackups( */ override suspend fun writeZip(out: OutputStream) { val json = SettingsBackup.toJson(settings.backupValues(SettingsBackup::carries)) - withContext(io) { + // The same lock as the automatic backup and restore (the automatic one calls this while holding it). + DataJobs.exclusive { withContext(io) { val snapshot = catching { BackupSnapshot.take(context, database) } .onFailure { warn("backup: no copy of the database to read, reading it as it goes: $it") } .getOrNull() snapshot.use { (it?.let { s -> CsvExporter(s.database.healthDao()) } ?: csv).exportZip(out, settings = json) } - } + } } } override suspend fun importCsv(from: Uri): BackupResult = catching { - val result = withContext(io) { input(from).use { CsvImporter(database).importZip(it) } } + val result = DataJobs.exclusive { withContext(io) { input(from).use { CsvImporter(database).importZip(it) } } } // A damaged settings file costs the settings only, not the records already restored. val restored = result.settings?.let { json -> catching { settings.restoreValues(SettingsBackup.fromJson(json), SettingsBackup::missing) } 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 2d1770b7..0ae0ffaf 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 @@ -17,6 +17,10 @@ import androidx.compose.material3.TimePickerDefaults import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.key +import androidx.compose.runtime.rememberCoroutineScope +import kotlinx.coroutines.launch import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf @@ -140,13 +144,32 @@ fun AlarmsScreen( onDismiss = { confirmDeleteAll = false }, ) } + // A refresh can change the alarm under an open sheet (a one-time alarm switching itself off, say). Saving the old copy + // would undo that, so the sheet moves to the refreshed alarm and starts from its values; if the alarm is gone, or the + // free slot of a new one was taken, there is nothing left to edit and the sheet closes. + LaunchedEffect(state.alarms, state.read) { + val open = editing ?: return@LaunchedEffect + if (state.read !is AlarmsRead.Loaded) return@LaunchedEffect + val (alarm, isNew) = open + val now = state.alarms.firstOrNull { it.index == alarm.index } + editing = when { + isNew -> if (now == null) open else null + now == null -> null + now != alarm -> now to false + else -> open + } + } + val scope = rememberCoroutineScope() editing?.let { (alarm, isNew) -> - AlarmSheet( - alarm, isNew, - onSave = { vm.save(it, isNew); editing = null }, - onDelete = { vm.delete(alarm); editing = null }, - onDismiss = { editing = null }, - ) + // The sheet closes only when the strap took the change; a failure or a busy strap leaves it open for another try. + key(alarm, isNew) { + AlarmSheet( + alarm, isNew, busy = state.busy, + onSave = { edited -> scope.launch { if (vm.save(edited, isNew).await()) editing = null } }, + onDelete = { scope.launch { if (vm.delete(alarm).await()) editing = null } }, + onDismiss = { editing = null }, + ) + } } ScreenList(contentPadding, gutter = GlowLayout.Gutter) { item { PageHeader(stringResource(R.string.you_alarms_title), onBack) } @@ -155,6 +178,8 @@ fun AlarmsScreen( item { PagePanel { PageNote(stringResource(R.string.you_alarms_reading)) } } return@ScreenList } + // Never read: the alarms are unknown, not empty, so the error above is all there is to show. + if (state.read is AlarmsRead.Failed) return@ScreenList item { AlarmsPanel(state, onToggle = vm::setEnabled, onEdit = { editing = it to false }, onAdd = { vm.freeIndex()?.let { editing = Alarm(it, 7, 0, Alarm.WEEKDAYS, enabled = true) to true } @@ -278,7 +303,7 @@ private fun HeartAlertsPanel(state: AlarmsUiState, vm: AlarmsViewModel) { */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable -private fun AlarmSheet(alarm: Alarm, isNew: Boolean, onSave: (Alarm) -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) { +private fun AlarmSheet(alarm: Alarm, isNew: Boolean, busy: Boolean, onSave: (Alarm) -> Unit, onDelete: () -> Unit, onDismiss: () -> Unit) { val time = rememberTimePickerState(alarm.hour, alarm.minute, is24Hour = ClockSetting.use24Hour) var days by remember { mutableIntStateOf(alarm.days) } PageSheet(onDismiss, stringResource(if (isNew) R.string.you_alarms_new else R.string.you_alarms_edit), note = daysLabel(days)) { @@ -297,12 +322,12 @@ private fun AlarmSheet(alarm: Alarm, isNew: Boolean, onSave: (Alarm) -> Unit, on PageButton( stringResource(R.string.you_action_save), { onSave(alarm.copy(hour = time.hour, minute = time.minute, days = days, enabled = true)) }, Modifier.weight(1f), - primary = true, + enabled = !busy, primary = true, ) } if (!isNew) { PageTextButton( - stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally), color = DestructiveInk, + stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally), enabled = !busy, color = DestructiveInk, ) } } 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 33071f6c..e3274c3a 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 @@ -4,6 +4,9 @@ import org.openstrap.app.R import org.openstrap.app.i18n.Strings import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update @@ -19,8 +22,19 @@ import org.openstrap.protocol.services.Setting import org.openstrap.protocol.services.SettingsCodec import org.openstrap.protocol.services.SettingsGroup +/** What the screen knows about the strap's alarms: not yet read, never read (the first read failed), or read. */ +sealed interface AlarmsRead { + data object Loading : AlarmsRead + data class Failed(val message: String) : AlarmsRead + data object Loaded : AlarmsRead +} + data class AlarmsUiState( - val loading: Boolean = true, + /** + * 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]. + */ + val read: AlarmsRead = AlarmsRead.Loading, /** A write is in flight; controls are disabled meanwhile. */ val busy: Boolean = false, val error: String? = null, @@ -28,6 +42,8 @@ data class AlarmsUiState( val alarms: List = emptyList(), val health: SettingsGroup? = null, ) { + val loading: Boolean get() = read is AlarmsRead.Loading + val canAdd: Boolean get() = caps != null && alarms.size < caps.maxCount /** The strap only raises HR alerts while it measures often enough; Zepp allows continuous or every minute. */ @@ -51,13 +67,21 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { } } - fun refresh() = run(loading = true) { } + /** A refresh asked for while a write or read was running; it runs when that one ends, so it isn't lost. */ + private var refreshPending = false + + fun refresh() { + // A retry after a failed first read goes back to "reading"; a refresh of a shown list keeps showing it. + _state.update { if (it.read is AlarmsRead.Failed) it.copy(read = AlarmsRead.Loading) else it } + run { } + } fun setEnabled(alarm: Alarm, enabled: Boolean) = run { strap.saveAlarm(alarm.copy(enabled = enabled), isNew = false) } - fun save(alarm: Alarm, isNew: Boolean) = run { strap.saveAlarm(alarm, isNew) } + /** Completes with true when the strap took the change, false when it failed or was busy (the screen keeps the sheet then). */ + fun save(alarm: Alarm, isNew: Boolean): Deferred = run { strap.saveAlarm(alarm, isNew) } - fun delete(alarm: Alarm) = run { strap.deleteAlarm(alarm.index) } + fun delete(alarm: Alarm): Deferred = run { strap.deleteAlarm(alarm.index) } fun deleteAll() = run { strap.clearAlarms() } @@ -91,31 +115,53 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { strap.writeHealthSettings(g.version, build(g)) } - /** Runs [action] against the strap, then re-reads everything so the screen shows what the strap holds. */ - private fun run(loading: Boolean = false, action: suspend () -> Unit) { - if (_state.value.busy) return - _state.update { it.copy(busy = true, loading = loading || it.loading, error = null) } - viewModelScope.launch { + /** + * Runs [action] against the strap, then re-reads everything so the screen shows what the strap holds. Completes with + * whether [action] worked. While another run is going, a refresh (an [action] that does nothing) is queued to run + * after it, and a write is refused (false) so the caller doesn't close its sheet as if it had been saved. + */ + private fun run(action: suspend () -> Unit): Deferred { + if (_state.value.busy) { + // Only a plain refresh can wait: a write the user asked for is shown as not done, and the controls are disabled anyway. + refreshPending = true + return CompletableDeferred(false) + } + _state.update { it.copy(busy = true, error = null) } + return viewModelScope.async { val error = try { action() null } catch (e: StrapCommandException) { e.message } - // The raw failure goes to Diagnostics, and the screen says it in plain words ([ErrorCopy.strap]). - val read = catching { - val (caps, alarms) = strap.readAlarms() - Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings()) - }.onFailure { (strap as? StrapManager)?.log("alarms: read from the strap failed: $it") } - _state.update { s -> - read.fold( - { (caps, alarms, health) -> s.copy(loading = false, busy = false, error = error, caps = caps, alarms = alarms, health = health) }, - { e -> - val failed = error ?: ErrorCopy.strap(e, Strings.app.get(R.string.you_alarms_read_failed)) - s.copy(loading = false, busy = false, error = failed) - }, - ) + readAll(error) + val again = refreshPending + refreshPending = false + if (again) { + _state.update { it.copy(busy = true) } + readAll(null) } + error == null + } + } + + /** Re-reads alarms and health from the strap. [error] is the failed write's reason, if any, and wins over a read failure's. */ + 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 (caps, alarms) = strap.readAlarms() + Triple(caps, alarms.sortedWith(compareBy({ it.hour }, { it.minute })), strap.readHealthSettings()) + }.onFailure { (strap as? StrapManager)?.log("alarms: 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) }, + { e -> + val failed = error ?: 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) + }, + ) } } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt index 3b0af06a..92aa1e86 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt @@ -42,6 +42,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.Color @@ -85,6 +86,25 @@ private val PhotoRoom = 64.dp /** How long "Saved" stays on the button. */ private const val SAVED_MS = 2_000L +/** + * The photo behind the card: none picked, being read (Save waits, or the card would export without it), ready, or + * unreadable. Ready and Failed remember which [uri] they answer, so a newer pick reads as Loading at once. + */ +internal sealed interface SharePhoto { + data object None : SharePhoto + data object Loading : SharePhoto + data class Ready(val uri: Uri, val bitmap: ImageBitmap) : SharePhoto + data class Failed(val uri: Uri) : SharePhoto +} + +/** What to show for the picked [uri], given the latest [decoded] answer (which may still be for an earlier pick). */ +internal fun sharePhotoFor(uri: Uri?, decoded: SharePhoto): SharePhoto = when { + uri == null -> SharePhoto.None + decoded is SharePhoto.Ready && decoded.uri == uri -> decoded + decoded is SharePhoto.Failed && decoded.uri == uri -> decoded + else -> SharePhoto.Loading +} + /** What the card is being drawn for. */ private enum class Export { Save, Share } @@ -132,7 +152,12 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str } val context = LocalContext.current var photoUri by rememberSaveable { mutableStateOf(null) } - val photo by produceState(null, photoUri) { value = photoUri?.let { decodePhoto(context, it) } } + val decoded by produceState(SharePhoto.None, photoUri) { + value = photoUri?.let { uri -> decodePhoto(context, uri)?.let { SharePhoto.Ready(uri, it) } ?: SharePhoto.Failed(uri) } ?: SharePhoto.None + } + val photoState = sharePhotoFor(photoUri, decoded) + val photo = (photoState as? SharePhoto.Ready)?.bitmap + val canExport = photoState !is SharePhoto.Loading var routeMode by rememberSaveable { mutableStateOf(StoryRoute.Line) } var hideEnds by rememberSaveable { mutableStateOf(true) } val hasRoute = card is StoryCard.Run && Route.mappable(route) @@ -143,7 +168,8 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str // Save and Share draw the card again off screen at 1080 by 1920, record it, and turn the recording into a PNG. var export by remember { mutableStateOf(null) } - var saved by remember { mutableStateOf(null) } + // Saveable: a turn of the phone while the picture is written keeps the answer to show. + var saved by rememberSaveable { mutableStateOf(null) } val layer = rememberGraphicsLayer() val recorded = remember(export) { CompletableDeferred() } fun save() { @@ -186,10 +212,13 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str null -> R.string.glow_save }, ) - WorkoutButton(saveLabel, Raised, Color.White, { if (export == null) save() }, Modifier.weight(1f), icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple) + // Not while the photo is still being read (the card would save without it) or another export is running. + val ready = canExport && export == null + val dim = Modifier.alpha(if (canExport) 1f else 0.4f) + WorkoutButton(saveLabel, Raised, Color.White, { if (ready) save() }, Modifier.weight(1f).then(dim), icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple) WorkoutButton( - stringResource(R.string.glow_share), Color.White, Color.Black, { if (export == null) export = Export.Share }, - Modifier.weight(1f), icon = AppIcons.UploadSimple, + stringResource(R.string.glow_share), Color.White, Color.Black, { if (ready) export = Export.Share }, + Modifier.weight(1f).then(dim), icon = AppIcons.UploadSimple, ) } }, @@ -231,6 +260,12 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str stringResource(if (photo != null) R.string.glow_share_change_photo else R.string.glow_share_add_photo), { pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) }, icon = AppIcons.Image, ) + if (photoState is SharePhoto.Failed) { + Text( + stringResource(R.string.glow_share_photo_failed), color = Color.White.copy(alpha = 0.6f), style = GlowType.secondary, + modifier = Modifier.padding(top = 8.dp), + ) + } } } if (hasRoute) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt index e947036c..76070cbb 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt @@ -25,6 +25,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf @@ -136,10 +137,18 @@ internal fun SleepScoreDetail( val session = state.sleep val score = session?.score val color = MetricColors.sleepDeep - var adjusting by remember(state.date) { mutableStateOf(false) } - var deleting by remember(state.date) { mutableStateOf(false) } - // The strap's session just deleted, while its Undo shows. - var undo by remember { mutableStateOf(null) } + // Saveable, so turning the phone doesn't close the sheet being used. + var adjusting by rememberSaveable(state.date) { mutableStateOf(false) } + var deleting by rememberSaveable(state.date) { mutableStateOf(false) } + // The strap's session just asked to be deleted, and once the day shows it gone, the same session while its Undo + // shows. Both are for this day only, so Undo never names another day, and Undo is never offered for a delete that + // didn't happen. + var pendingDelete by remember(state.date) { mutableStateOf(null) } + var undo by remember(state.date) { mutableStateOf(null) } + LaunchedEffect(pendingDelete, session) { + val gone = pendingDelete ?: return@LaunchedEffect + if (session == null) { undo = gone; pendingDelete = null } + } // TODO(step 6): Month and Year wait for a stored history of the strap's sleep scores; the day loads only 14 nights. val ranges = listOf(Range.Day, Range.Week) var rangeIndex by rememberSaveable { mutableIntStateOf(0) } @@ -276,7 +285,7 @@ internal fun SleepScoreDetail( ) if (deleting && session != null && detected != null) DeleteSleepSheet( SleepCopy.deleteTitle(false, isToday), Ranges.of(clock(session.start), clock(session.end)), - onDelete = { deleting = false; editing.delete(detected); undo = detected }, onDismiss = { deleting = false }, + onDelete = { deleting = false; editing.delete(detected); pendingDelete = detected }, onDismiss = { deleting = false }, ) } @@ -553,10 +562,16 @@ internal fun NapsDetail( ) { val naps = state.naps.sortedBy { it.start } // The nap whose times are being adjusted, or that's being deleted, by its start as shown. - var adjusting by remember(state.date) { mutableStateOf(null) } - var deleting by remember(state.date) { mutableStateOf(null) } - // The strap's nap just deleted and its start as shown, while its Undo shows. - var undo by remember { mutableStateOf?>(null) } + var adjusting by rememberSaveable(state.date) { mutableStateOf(null) } + var deleting by rememberSaveable(state.date) { mutableStateOf(null) } + // As in the Sleep score: the nap asked to be deleted with its start as shown, then, once the day no longer has it, + // the same while its Undo shows. For this day only. + var pendingDelete by remember(state.date) { mutableStateOf?>(null) } + var undo by remember(state.date) { mutableStateOf?>(null) } + LaunchedEffect(pendingDelete, state.napsAsDetected) { + val gone = pendingDelete ?: return@LaunchedEffect + if (state.napsAsDetected[gone.second] == null) { undo = gone; pendingDelete = null } + } val total = naps.sumOf { it.end - it.start } val color = MetricColors.sleepDeep val today = LocalDate.now() @@ -665,7 +680,7 @@ internal fun NapsDetail( if (nap == null || detected == null) androidx.compose.runtime.SideEffect { deleting = null } else DeleteSleepSheet( SleepCopy.deleteTitle(true, isToday), Ranges.of(clock(nap.start), clock(nap.end)), - onDelete = { deleting = null; editing.delete(detected); undo = detected to nap.start }, onDismiss = { deleting = null }, + onDelete = { deleting = null; editing.delete(detected); pendingDelete = detected to nap.start }, onDismiss = { deleting = null }, ) } } diff --git a/app/src/main/res/values/strings_glow_share.xml b/app/src/main/res/values/strings_glow_share.xml index 3eb28385..4ff028db 100644 --- a/app/src/main/res/values/strings_glow_share.xml +++ b/app/src/main/res/values/strings_glow_share.xml @@ -70,6 +70,8 @@ Change photo Add a photo + + Couldn\'t read that photo Route diff --git a/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt b/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt index 506cddc0..3578f511 100644 --- a/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/export/BackupSnapshotTest.kt @@ -7,6 +7,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals @@ -88,8 +90,38 @@ class BackupSnapshotTest { assertEquals(10, lines(zip, "activity_minute.csv").size) // The copy was made and is gone again. assertFalse(logged.toString(), logged.any { "no copy" in it }) - assertFalse(File(context.cacheDir, "backup-snapshot.db").exists()) + assertEquals(emptyList(), snapshotFiles()) // The sync's rows are in the database itself. assertEquals(11, db.healthDao().heartRateOnce(t, t + 7200).size) } + + /** The snapshot files left in the cache. */ + private fun snapshotFiles() = context.cacheDir.listFiles { f -> f.name.startsWith("backup-snapshot") }.orEmpty().map { it.name } + + @Test fun `two copies at once use different files and each cleans up its own`() { + val a = BackupSnapshot.take(context, db) + val b = BackupSnapshot.take(context, db) + assertEquals(2, snapshotFiles().filter { it.endsWith(".db") }.size) + a.close() + assertEquals(1, snapshotFiles().filter { it.endsWith(".db") }.size) + b.close() + assertEquals(emptyList(), snapshotFiles()) + } + + @Test fun `data jobs run one at a time and a job inside a job doesn't wait on itself`() = runBlocking { + val order = java.util.Collections.synchronizedList(mutableListOf()) + val first = scope.launch { + DataJobs.exclusive { + order += "a start" + // Calling another data job from inside one goes straight through. + DataJobs.exclusive { order += "a inner" } + delay(100) + order += "a end" + } + } + delay(30) + val second = scope.launch { DataJobs.exclusive { order += "b" } } + first.join(); second.join() + assertEquals(listOf("a start", "a inner", "a end", "b"), order) + } } 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 1ad05762..33e9d860 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 @@ -13,12 +13,17 @@ import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.openstrap.app.ble.GattTimeoutException import org.openstrap.app.device.StrapCommandException import org.openstrap.app.device.StrapController import org.openstrap.app.testing.endMain +import org.openstrap.protocol.services.Alarm +import org.openstrap.protocol.services.AlarmCapabilities +import org.openstrap.protocol.services.SettingsGroup import java.lang.reflect.Proxy import kotlin.coroutines.Continuation import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED @@ -72,4 +77,82 @@ class AlarmsViewModelTest { } } as StrapController } + + @Test fun `a failed first read is Failed, not an empty list, and there is nothing to add to`() { + val vm = AlarmsViewModel(failingStrap(StrapCommandException("The strap isn't connected"))).also { models += it } + val state = vm.state.value + assertEquals(AlarmsRead.Failed("The strap isn't connected"), state.read) + assertNull(state.caps) + assertFalse(state.canAdd) + } + + @Test fun `a save during a refresh is refused and the refresh that was asked for still runs after`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + assertEquals(AlarmsRead.Loaded, vm.state.value.read) + // A write is in flight and waiting on the strap. + strap.holdSave = true + val writing = vm.save(Alarm(0, 7, 0, Alarm.WEEKDAYS, enabled = true), isNew = true) + assertTrue(vm.state.value.busy) + // A push asks for a refresh meanwhile, and a second save comes in. + vm.refresh() + val second = vm.save(Alarm(1, 8, 0, 0, enabled = true), isNew = true) + assertTrue(second.isCompleted) + assertFalse(second.getCompleted()) + val readsBefore = strap.reads + strap.release() + assertTrue(writing.getCompleted()) + // One read for the write, one more for the refresh that was waiting. + assertEquals(readsBefore + 2, strap.reads) + assertFalse(vm.state.value.busy) + } + + @Test fun `a failed save completes false so the sheet stays open`() { + val strap = FakeStrap() + val vm = AlarmsViewModel(strap.controller).also { models += it } + strap.saveFailure = StrapCommandException("Slot taken") + val done = vm.save(Alarm(0, 7, 0, 0, enabled = true), isNew = true) + assertFalse(done.getCompleted()) + assertEquals("Slot taken", vm.state.value.error) + } + + /** 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 + private var held: Continuation? = null + private val caps = AlarmCapabilities(version = 1, maxCount = 10, titles = false, smartSupported = false) + private val flows = mutableMapOf() + + fun release() { + held?.resumeWith(Result.success(Unit)) + held = null + holdSave = false + } + + @Suppress("UNCHECKED_CAST") + val controller: StrapController = Proxy.newProxyInstance(StrapController::class.java.classLoader, arrayOf(StrapController::class.java)) { proxy, method, args -> + fun done(r: Result): Any? { + (args.last() as Continuation).resumeWith(r) + return COROUTINE_SUSPENDED + } + when { + 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 == "saveAlarm" -> when { + saveFailure != null -> done(Result.failure(saveFailure!!)) + holdSave -> { held = args.last() as Continuation; COROUTINE_SUSPENDED } + else -> done(Result.success(Unit)) + } + StateFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableStateFlow(null) } + SharedFlow::class.java.isAssignableFrom(method.returnType) -> flows.getOrPut(method.name) { MutableSharedFlow() } + method.returnType == java.lang.Boolean.TYPE -> false + else -> Unit + } + } as StrapController + } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt new file mode 100644 index 00000000..8a76bd14 --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt @@ -0,0 +1,34 @@ +package org.openstrap.app.ui.glow + +import android.net.Uri +import androidx.compose.ui.graphics.ImageBitmap +import org.junit.Assert.assertEquals +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** The share screen's photo: a fresh pick reads as Loading until its own answer arrives, so Save never exports without it. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class SharePhotoTest { + private val first = Uri.parse("content://photos/1") + private val second = Uri.parse("content://photos/2") + private val bitmap = ImageBitmap(1, 1) + + @Test fun `no pick is None whatever was decoded before`() { + assertEquals(SharePhoto.None, sharePhotoFor(null, SharePhoto.Ready(first, bitmap))) + } + + @Test fun `a pick waits as Loading until its own answer comes`() { + assertEquals(SharePhoto.Loading, sharePhotoFor(first, SharePhoto.None)) + assertEquals(SharePhoto.Loading, sharePhotoFor(second, SharePhoto.Ready(first, bitmap))) + assertEquals(SharePhoto.Loading, sharePhotoFor(second, SharePhoto.Failed(first))) + } + + @Test fun `the answer for the picked photo is shown, ready or failed`() { + val ready = SharePhoto.Ready(first, bitmap) + assertEquals(ready, sharePhotoFor(first, ready)) + assertEquals(SharePhoto.Failed(second), sharePhotoFor(second, SharePhoto.Failed(second))) + } +} From 47a7aa45a19a40eae7cb2591031f7e80c8c81d0a Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:48:22 +0400 Subject: [PATCH 08/27] Connection state machine: race-free hold, one live HR coroutine, per-connection facts, find strap start order Background connects never clear the user's Disconnect and read it on the lane. Live HR follows reasons, the connection and firmwareUpdating in one ordered coroutine. NotPaired follows the paired flow, Forget clears the old strap's facts, and Find strap is set before its start goes out. Co-Authored-By: Claude Sonnet 5.5 --- .../openstrap/app/device/BuzzCoordinator.kt | 28 ++++- .../openstrap/app/device/ConnectionManager.kt | 88 +++++++++++--- .../app/device/LiveHeartRateStream.kt | 115 +++++++++++------- .../org/openstrap/app/device/StrapCommands.kt | 7 +- .../openstrap/app/device/StrapController.kt | 12 +- .../org/openstrap/app/device/StrapManager.kt | 38 ++++-- .../org/openstrap/app/ui/glow/ReadyScreen.kt | 25 ++++ .../org/openstrap/app/widget/SyncNowAction.kt | 2 +- .../main/res/values/strings_glow_ready.xml | 4 + .../org/openstrap/app/device/FindStrapTest.kt | 15 +++ .../app/device/LiveHeartRateStreamTest.kt | 42 +++++++ .../openstrap/app/device/StrapConnectTest.kt | 42 +++++++ 12 files changed, 346 insertions(+), 72 deletions(-) create mode 100644 app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt diff --git a/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt b/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt index 9d6199f7..cce873c0 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/BuzzCoordinator.kt @@ -35,7 +35,7 @@ internal class BuzzCoordinator( @Volatile private var callHold = false /** When the last motor pattern ends: one still playing then cuts off a `03` sent meanwhile (seen 2026-10-20). */ @Volatile private var motorBusyUntil = 0L - private var pulseJob: Job? = null + @Volatile private var pulseJob: Job? = null // Each return is a buzz given way to a call. @Suppress("ReturnCount") @@ -154,9 +154,23 @@ internal class BuzzCoordinator( /** The same `03` … `06` as a ringing call, with Zepp's 60 s limit (03 §3.16). */ suspend fun findStrap() { - startBuzzing() - log("find strap: buzzing") + // Set before the start goes out, so a stop that lands meanwhile (endFind) is seen below and wins. findingStrap.value = true + var started = false + try { + startBuzzing() + started = true + } finally { + // Rolled back, whatever ended the start (a refusal, no link, a cancelled caller). + if (!started) findingStrap.value = false + } + if (!findingStrap.value) { + // The stop got in first, so its 06 may have gone out before this 03: send another. + log("find strap: stopped while starting") + catching { stopBuzzing() } + return + } + log("find strap: buzzing") findJob?.cancel() findJob = scope.launch { delay(FindDevice.FIND_TIMEOUT_MS) @@ -167,6 +181,14 @@ internal class BuzzCoordinator( } } + /** The link ended: nothing is buzzing, so Find strap, a steady buzz and the pulses stop with it. */ + fun linkEnded() { + findBuzzOn = false + pulseJob?.cancel() + pulseJob = null + endFind() + } + fun endFind() { findJob?.cancel() findJob = null diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt index 08d3d10a..6095eea8 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt @@ -10,7 +10,9 @@ import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -99,47 +101,78 @@ internal class ConnectionManager( override val activeSession: ChannelSession? get() = session?.takeIf { connection.value is ConnectionState.Connected } - /** Connect if a strap is paired and nothing is connected or in progress. Safe to call often. */ + /** + * The user opened the app: clear their Disconnect and connect if a strap is paired and nothing is connected or in + * progress. Safe to call often. Reconnects nobody asked for on screen are [backgroundConnect], which never clears + * the hold. + */ // On the lane, and checking connectJob: callers race at process start (app start-up, the companion presence // service, phone alerts), before the connect coroutine has moved the state off Disconnected. fun autoConnect() { onLane { - when (connection.value) { - is ConnectionState.Connected, ConnectionState.Connecting, ConnectionState.Authenticating -> return@onLane - else -> Unit - } - if (reconnectJob?.isActive == true || connectJob?.isActive == true) return@onLane + if (busy()) return@onLane hold(false) wantConnection() } } - /** The user's Disconnect, kept across process restarts; null until read from settings. See [backgroundConnect]. */ + /** On the lane: connected, connecting or waiting to retry. */ + private fun busy(): Boolean { + when (connection.value) { + is ConnectionState.Connected, ConnectionState.Connecting, ConnectionState.Authenticating -> return true + else -> Unit + } + return reconnectJob?.isActive == true || connectJob?.isActive == true + } + + /** + * The user's Disconnect, kept across process restarts; null until read from settings. Changed on the lane only (by + * [hold] and [isHeld]), so a Disconnect can't be undone by a command queued before it. + */ @Volatile private var held: Boolean? = null // One at a time, in order, so a quick Disconnect then Connect can't land the other way round. // A lane of its own for the hold writes, so they can't queue behind the strap's traffic on the app scope. @Suppress("InjectDispatcher") private val heldWriter = CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(1)) + /** On the lane. */ private fun hold(value: Boolean) { if (held == value) return held = value heldWriter.launch { settings.setHeldDisconnected(value) } } + /** + * On the lane: the hold, read from settings once. A Disconnect or Connect landing while it is read wins over the + * stored value. + */ + private suspend fun isHeld(): Boolean { + val stored = held ?: settings.heldDisconnected.first() + if (held == null) held = stored + return held == true + } + + /** + * Reconnects nobody asked for on screen (companion presence, phone alerts, process start, a workout starting, the + * widget's Sync now). Never clears the hold: after the user's Disconnect only [connect] or opening the app + * ([autoConnect]) connects. + */ fun backgroundConnect() { - scope.launch { + onLane { // Presence events repeat every few seconds while the strap advertises, so a skip isn't logged. - if (held ?: settings.heldDisconnected.first().also { held = it }) return@launch + if (isHeld()) return@onLane // Every try would fail the same way until the user acts (grants the permission, pairs again). - if (unusable) return@launch - autoConnect() + if (unusable) return@onLane + if (busy()) return@onLane + wantConnection() } } fun connect() { - hold(false) - onLane { wantConnection() } + onLane { + hold(false) + wantConnection() + } } /** On the lane. */ @@ -264,6 +297,33 @@ internal class ConnectionManager( context, bluetoothChanged, android.content.IntentFilter(android.bluetooth.BluetoothAdapter.ACTION_STATE_CHANGED), androidx.core.content.ContextCompat.RECEIVER_NOT_EXPORTED, ) + watchPaired() + } + + /** + * NotPaired follows the paired strap, so after Forget the state is NotPaired and not a Disconnected the UI has to + * patch. Nothing is connected then: whatever is left of a link is ended here, in case Forget came without a + * Disconnect. Runs on the lane; the first value is the strap paired at start-up. + */ + private fun watchPaired() = onLane { + settings.pairedDevice.map { it != null }.distinctUntilChanged().collect { paired -> + if (paired) { + if (connection.value == ConnectionState.NotPaired) connection.value = ConnectionState.Disconnected + return@collect + } + wantConnected = false + reconnectJob?.cancel() + connectJob?.cancel() + // Nothing to end at start-up, and the facade's hooks may not be wired yet. + val state = connection.value + if (gatt != null || (state != ConnectionState.Disconnected && state != ConnectionState.NotPaired)) { + hooks.onLinkEnded() + close() + } + connection.value = ConnectionState.NotPaired + // Forget removes the hold from settings; the next strap starts without it. + if (held == true) hold(false) + } } private fun watchDisconnect(client: GattClient) = onLane { @@ -288,8 +348,8 @@ internal class ConnectionManager( } fun disconnect() { - hold(true) onLane { + hold(true) wantConnected = false reconnectJob?.cancel() connectJob?.cancel() diff --git a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt index e5864652..8b213cd3 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt @@ -1,15 +1,23 @@ package org.openstrap.app.device import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.openstrap.app.ble.GattClient import org.openstrap.app.ble.StrapUuids import org.openstrap.app.data.catching @@ -22,7 +30,7 @@ import org.openstrap.protocol.u8 /** * Live heart rate from the strap, on the channel push, or the standard 2A37 characteristic without it. It streams - * only while the app is on screen, a workout records it, or workout auto-start watches for effort ([wanted]). There is + * only while the app is on screen, a workout records it, or workout auto-start watches for effort (one reason each in [reasons]). There is * no switch for it, as in Zepp: the strap's own measuring is set by its monitor frequency. */ // One setter per reason to stream, as StrapController has them, plus start, stop and the reading. @@ -38,80 +46,104 @@ internal class LiveHeartRateStream( val liveHeartRate = MutableStateFlow(null) val heartRateReadings = MutableSharedFlow(extraBufferCapacity = 64, onBufferOverflow = BufferOverflow.DROP_OLDEST) - private var liveJob: Job? = null - /** Which of the strap's heart rate sources is shown and recorded ([HeartRateSources]); guarded by itself. */ private val sources = HeartRateSources() - /** Live HR streams only while the app is on screen, where it's shown, or while a workout records it. */ - @Volatile private var appVisible = false - @Volatile private var workoutActive = false + /** Why live HR is wanted. It streams while any holds: the app on screen, a workout recording, or the effort watch. */ + private enum class Reason { AppVisible, Workout, EffortWatch } + + private val reasons = MutableStateFlow>(emptySet()) - @Volatile private var effortWatch = false + /** Bumped by each new connection, so a stream is opened again even when the link dropped and came back unseen. */ + private val connects = MutableStateFlow(0) - private fun wanted() = workoutActive || effortWatch || appVisible + /** True from the first command of a stream to the end of its stop, so a stop is sent only for a stream that opened. */ + private val wireOpen = MutableStateFlow(false) - val isRunning: Boolean get() = liveJob?.isActive == true + /** The session and client the open stream was sent on, for its stop. Touched by the one coroutine in [follow] only. */ + private var openSession: ChannelSession? = null + private var openClient: GattClient? = null - fun setAppVisible(visible: Boolean) { - if (visible == appVisible) return - appVisible = visible - refresh() + /** What [follow] acts on: stream or not, on which connection. */ + private data class Plan(val stream: Boolean, val connect: Int) + + init { + // One ordered coroutine owns the wire: collectLatest ends a stream (cancelled, then joined) before the next + // block starts, so a stop and a start can't cross, and a failed flash that ends firmwareUpdating restarts it. + scope.launch { + combine(reasons, connection, firmwareUpdating, connects) { r, c, fw, n -> + Plan(r.isNotEmpty() && c is ConnectionState.Connected && !fw, n) + }.distinctUntilChanged().collectLatest { follow(it) } + } } + fun setAppVisible(visible: Boolean) = set(Reason.AppVisible, visible) + fun setWorkoutActive(active: Boolean) { - if (active == workoutActive) return - workoutActive = active - log(if (active) "workout started: live hr stays on in the background" else "workout ended") - refresh() + if (set(Reason.Workout, active)) log(if (active) "workout started: live hr stays on in the background" else "workout ended") } - fun setEffortWatch(active: Boolean) { - if (active == effortWatch) return - effortWatch = active - refresh() + fun setEffortWatch(active: Boolean) = set(Reason.EffortWatch, active) + + /** True when [reason] changed. */ + private fun set(reason: Reason, on: Boolean): Boolean { + var changed = false + reasons.update { current -> + changed = (reason in current) != on + if (on) current + reason else current - reason + } + return changed } - /** A new connection: starts streaming if [wanted]. */ + /** A new connection: streams again if wanted. */ fun onConnected() { - if (wanted()) start() + connects.update { it + 1 } } /** The link ended: the stream with it. */ fun onLinkEnded() { - liveJob?.cancel() liveHeartRate.value = null synchronized(sources) { sources.reset() } sessionLogged = false } - /** Starts or stops streaming to match [wanted]; a stream already running is left alone. */ - private fun refresh() { - if (!wanted()) { - if (liveJob?.isActive == true) pause() - } else if (liveJob?.isActive != true && !firmwareUpdating.value && connection.value is ConnectionState.Connected) { - start() - } + /** + * Stops streaming and returns once the strap has been told (or a few seconds passed), for a firmware update, which + * sets [firmwareUpdating] first: the stream follows it on its own, and starts again if the update fails. + */ + suspend fun pause() { + withTimeoutOrNull(PAUSE_WAIT_MS) { wireOpen.first { !it } } } - /** Stops streaming for now (e.g. during a firmware update); [refresh] starts it again when it's wanted. */ - fun pause() { - liveJob?.cancel() + private suspend fun follow(plan: Plan) { + if (plan.stream) stream() else closeWire() + } + + /** Tells the strap to stop, if a stream was opened and the link is still up. Not cancellable: both commands go out. */ + private suspend fun closeWire() { liveHeartRate.value = null - val s = link.session - val client = link.gatt - scope.launch { stop(s, client) } + val s = openSession + val client = openClient + openSession = null + openClient = null + if (!wireOpen.value) return + withContext(NonCancellable) { + if (connection.value is ConnectionState.Connected) stop(s, client) + wireOpen.value = false + } } // The catch-all rethrows a cancellation, and a failed stream only stops showing live HR. @Suppress("SuspendFunSwallowedCancellation", "TooGenericExceptionCaught") - private fun start() { - liveJob?.cancel() + private suspend fun stream() { liveHeartRate.value = null val s = link.activeSession ?: return val client = link.gatt ?: return synchronized(sources) { sources.reset() } - liveJob = scope.launch { + openSession = s + openClient = client + wireOpen.value = true + coroutineScope { launch { clearWhenStale() } try { val channel = s.services.has(Endpoints.HEART_RATE) @@ -243,5 +275,6 @@ internal class LiveHeartRateStream( const val OPEN_REPLY = 0x05 const val SUBSCRIBE_REPLY = 0x04 const val STALE_CHECK_MS = 2_000L + const val PAUSE_WAIT_MS = 5_000L } } diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt index a05749fb..3ec37682 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt @@ -48,7 +48,12 @@ internal class StrapCommands( return reply } - private var alarmCaps: AlarmCapabilities? = null + @Volatile private var alarmCaps: AlarmCapabilities? = null + + /** The link ended or the strap was forgotten: the next alarm command asks the strap's limits again (a firmware update can change them). */ + fun forgetAlarmCaps() { + alarmCaps = null + } private suspend fun alarmCaps(): AlarmCapabilities = alarmCaps ?: ( AlarmCodec.parseVersion(command(Endpoints.ALARMS, AlarmCodec.versionRequest)) diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt index 98a6856f..320b8545 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapController.kt @@ -102,13 +102,17 @@ interface StrapController { fun connect() - /** Connect to the paired strap if not already connected; no-op when nothing is paired. */ + /** + * The user opened the app or tapped Retry: clears their Disconnect and connects to the paired strap if not already + * connected or trying; no-op when nothing is paired. Anything the user didn't ask for on screen is [backgroundConnect]. + */ fun autoConnect() /** - * [autoConnect] for reconnects nobody asked for on screen (companion presence, phone alerts, process start): - * a no-op while the user's Disconnect holds, which lasts until they connect again or open the app, and after a - * failure retrying can't fix ([ConnectErrors.isFinal], such as a key the strap turned down). + * [autoConnect] for reconnects nobody asked for on screen (companion presence, phone alerts, process start, a + * workout starting, the widget's Sync now): a no-op while the user's Disconnect holds, which lasts until they + * connect again or open the app (this never clears it), and after a failure retrying can't fix + * ([ConnectErrors.isFinal], such as a key the strap turned down). */ fun backgroundConnect() fun disconnect() 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 44916019..ec81e974 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapManager.kt @@ -90,9 +90,10 @@ class StrapManager( connected(job, session) } override fun onLinkEnded() { - buzzer.endFind() + buzzer.linkEnded() onWear(null) live.onLinkEnded() + commands.forgetAlarmCaps() } }, ) @@ -144,6 +145,10 @@ class StrapManager( /** The setup after auth, as named steps. Each failed step is logged and setup goes on without it. */ private suspend fun afterAuth(client: GattClient, l: GattStrapLink, s: ChannelSession) { + // Facts of the last connection, so a step that fails here shows as unknown rather than as an old value. + battery = null + charging = false + firmware = null queryMtu(l, s) querySettingsVersion(s) val deviceInformation = queryDeviceInformation(s) @@ -351,6 +356,18 @@ class StrapManager( // The app was stopped while it knew the wear state: close that interval now, as nothing is connected yet. val now = System.currentTimeMillis() / 1000 wearEvents.post { if (dao.lastWearEvent()?.worn != null) dao.insertWearEvent(WearEventRow(now, null)) } + // Forget: the old strap's facts go with it, so the Device page can't show them for the next one. + scope.launch { + settings.pairedDevice.map { it != null }.distinctUntilChanged().collect { paired -> + if (paired) return@collect + info.value = null + todaySteps.value = null + battery = null + charging = false + firmware = null + commands.forgetAlarmCaps() + } + } // For the widgets' status line with the strap away: the battery and charging as last connected. scope.launch { connection.mapNotNull { c -> (c as? ConnectionState.Connected)?.let { it.batteryPercent?.let { b -> b to it.charging } } } @@ -450,12 +467,16 @@ class StrapManager( delay(WEAR_POLL_MS) if (firmwareUpdating.value) continue wearPolling = true - catching { - val keys = listOf(SettingsCodec.KEY_WEAR_STATUS) - val reply = commands.settingsQuery(SettingsCodec.GROUP_DEVICE_INFORMATION, keys, withOptions = false) - SettingsCodec.parse(reply, commands.settingsProtocol?.version)?.let(SettingsCodec::wearStatus)?.let { onWear(it) } - }.onFailure { log("wear status poll failed: $it") } - wearPolling = false + try { + catching { + val keys = listOf(SettingsCodec.KEY_WEAR_STATUS) + val reply = commands.settingsQuery(SettingsCodec.GROUP_DEVICE_INFORMATION, keys, withOptions = false) + SettingsCodec.parse(reply, commands.settingsProtocol?.version)?.let(SettingsCodec::wearStatus)?.let { onWear(it) } + }.onFailure { log("wear status poll failed: $it") } + } finally { + // Also when the poll is cancelled with the connection, so a push isn't left unlogged. + wearPolling = false + } } } info.value?.deviceInformation?.let(SettingsCodec::wearStatus)?.let { onWear(it) } @@ -700,7 +721,8 @@ class StrapManager( try { // A failure is logged and handed on to the Firmware page. A cancellation is rethrown by catching as it came. catching { - if (live.isRunning) live.pause() + // The stream follows firmwareUpdating off on its own; this waits until the strap has been told. + live.pause() val link = GattDfuLink(client) if (!link.available) throw DfuException(-1, Strings.app.get(R.string.system_firmware_no_service)) // Bigger ATT packets make the transfer several times faster. Refused, it falls back to 20-byte writes. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt index dcafb01d..62bac567 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt @@ -5,6 +5,7 @@ import android.provider.Settings import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -13,6 +14,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Icon +import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -35,6 +37,8 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import org.openstrap.app.OpenStrapApp import org.openstrap.app.R import org.openstrap.app.data.SportSettings import org.openstrap.app.data.Strength @@ -230,6 +234,7 @@ fun GlowWorkoutReadyScreen( RoundIcon(AppIcons.X, stringResource(R.string.glow_close), onBack, Modifier.align(Alignment.CenterStart)) Box(Modifier.align(Alignment.Center)) { IconPill(Workouts.shortName(type), { picking = true }, caret = true) } } + StrapHeldNotice(connection) if (cardio) { ReadyHeartCard(connection, liveHeartRate) ReadyWhere( @@ -340,6 +345,26 @@ internal fun MinusPlus( } } +/** + * When the strap is away because you disconnected it, nothing reconnects it on its own (starting a workout doesn't): + * says so and offers Connect, which is an explicit connect. Nothing shows while it is connected, connecting, or away + * for any other reason. + */ +@Composable +private fun StrapHeldNotice(connection: ConnectionState) { + if (connection is ConnectionState.Connected || connection == ConnectionState.Connecting || connection == ConnectionState.Authenticating) return + val container = (LocalContext.current.applicationContext as? OpenStrapApp)?.container ?: return + val held by container.settings.heldDisconnected.collectAsStateWithLifecycle(false) + if (!held || connection == ConnectionState.NotPaired) return + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text( + stringResource(R.string.glow_ready_strap_disconnected), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), + style = GlowType.secondary, + ) + PageButton(stringResource(R.string.glow_ready_connect), container.strap::connect, Modifier.fillMaxWidth(), icon = AppIcons.Bluetooth) + } +} + /** The strap in one line with its dot, on Choose: "Strap ready, 72 bpm". */ @Composable internal fun StrapLine(connection: ConnectionState, liveHeartRate: Int?) { diff --git a/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt b/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt index cb160751..c6952869 100644 --- a/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt +++ b/app/src/main/kotlin/org/openstrap/app/widget/SyncNowAction.kt @@ -13,7 +13,7 @@ import org.openstrap.app.device.ConnectionState /** * The strap status button's tap on a stale sync (widgets spec 4, 5): syncs in place, no activity. Connected, it's the same * sync as pulling Today down. Away, it reconnects as the app does in the background (a Disconnect the user tapped - * holds), and connecting syncs on its own. The line reads Syncing while it runs, and [WidgetUpdater] + * holds, and Sync now doesn't end it), and connecting syncs on its own. The line reads Syncing while it runs, and [WidgetUpdater] * refreshes the widgets as it starts and ends. */ class SyncNowAction : ActionCallback { diff --git a/app/src/main/res/values/strings_glow_ready.xml b/app/src/main/res/values/strings_glow_ready.xml index 67d77404..da03201f 100644 --- a/app/src/main/res/values/strings_glow_ready.xml +++ b/app/src/main/res/values/strings_glow_ready.xml @@ -39,6 +39,10 @@ %d sports + + Your strap is disconnected. Recording works without it, but with no live heart rate. + + Connect strap bpm, live from your strap diff --git a/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt b/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt index 3c7f5edf..4c556d1c 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/FindStrapTest.kt @@ -4,6 +4,7 @@ import androidx.room.Room import androidx.test.core.app.ApplicationProvider import kotlinx.coroutines.test.runTest import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.openstrap.app.data.db.OpenStrapDatabase @@ -29,4 +30,18 @@ class FindStrapTest { db.close() } } + + @Test + fun aStartThatFailsLeavesFindingOff() = runTest { + val context = ApplicationProvider.getApplicationContext() + val db = Room.inMemoryDatabaseBuilder(context, OpenStrapDatabase::class.java).allowMainThreadQueries().build() + try { + val strap = StrapManager(context, SettingsStore(context), db.healthDao()) + // Not connected, so the start is refused: Find strap is set before it goes out and rolled back after. + assertTrue(runCatching { strap.findStrap() }.exceptionOrNull() is StrapCommandException) + assertFalse(strap.findingStrap.value) + } finally { + db.close() + } + } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt b/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt new file mode 100644 index 00000000..481432cc --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/LiveHeartRateStreamTest.kt @@ -0,0 +1,42 @@ +package org.openstrap.app.device + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Test +import org.openstrap.app.ble.GattClient +import org.openstrap.app.ble.GattStrapLink +import org.openstrap.protocol.ChannelSession + +/** Live HR's reasons: the workout and the screen are separate, and a pause with nothing open doesn't wait. */ +class LiveHeartRateStreamTest { + private val noLink = object : LiveLink { + override val session: ChannelSession? = null + override val gatt: GattClient? = null + override val link: GattStrapLink? = null + override val activeSession: ChannelSession? = null + } + + @Test + fun theWorkoutAndTheScreenAreSeparateReasons() = runTest { + val log = mutableListOf() + val live = LiveHeartRateStream( + backgroundScope, noLink, MutableStateFlow(ConnectionState.Disconnected), MutableStateFlow(false), { log += it }, clock = { 0L }, + ) + live.setAppVisible(true) + live.setWorkoutActive(true) + live.setWorkoutActive(true) + live.setAppVisible(false) + live.setWorkoutActive(false) + // Each change of the workout is logged once, whatever else is on. + assertEquals(listOf("workout started: live hr stays on in the background", "workout ended"), log) + } + + @Test + fun pauseReturnsAtOnceWhenNothingIsOpen() = runTest { + val live = LiveHeartRateStream( + backgroundScope, noLink, MutableStateFlow(ConnectionState.Disconnected), MutableStateFlow(false), {}, clock = { 0L }, + ) + live.pause() + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt index 7f5479d2..1a6a54f3 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt @@ -195,6 +195,48 @@ class StrapConnectTest { assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) } + @Test + fun afterDisconnectOnlyOpeningTheAppReconnects() = runTest { + val address = "AA:BB:CC:00:00:06" + pair(address) + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it == ConnectionState.Connecting } + strap.disconnect() + strap.connection.first { it == ConnectionState.Disconnected } + // Presence events, a workout starting and the widget's Sync now all come through here. + strap.backgroundConnect() + delay(1_000) + assertEquals(strap.log.value.joinToString("\n"), 1, strap.log.value.count { it.contains("connecting to") }) + assertEquals(ConnectionState.Disconnected, strap.connection.value) + // Opening the app is the user's: it clears the hold and connects. + strap.autoConnect() + delay(1_000) + assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) + } + + @Test + fun aHoldFromBeforeTheProcessRestartStopsBackgroundConnects() = runTest { + pair("AA:BB:CC:00:00:07") + settings.setHeldDisconnected(true) + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.backgroundConnect() + delay(1_000) + assertTrue(strap.log.value.joinToString("\n"), strap.log.value.none { it.contains("connecting to") }) + } + + @Test + fun forgettingTheStrapShowsNotPaired() = runTest { + pair("AA:BB:CC:00:00:08") + val strap = StrapManager(context, settings, db.healthDao(), backgroundScope) + strap.connect() + strap.connection.first { it == ConnectionState.Connecting } + settings.forgetDevice() + strap.connection.first { it == ConnectionState.NotPaired } + assertEquals(null, strap.info.value) + assertTrue(open("AA:BB:CC:00:00:08").isEmpty()) + } + @Test fun racingConnectsLeaveOneClientOpen() { val address = "AA:BB:CC:00:00:05" From 975a757f172cadf8f1bbc6a76e459a590ec4a679 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Sat, 7 Nov 2026 02:57:40 +0400 Subject: [PATCH 09/27] Fix what the merged state machine groups broke Two overrides returned Boolean where the interface wants Unit, a connect test counted log lines after virtual time while the connect reads the paired strap on a real thread, the share photo test built a Compose bitmap Robolectric can't, and detekt's new findings (long lines, three LaunchedEffects that only set state, and two complexity rules). Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/ConnectionManager.kt | 3 ++- .../app/device/LiveHeartRateStream.kt | 4 ++-- .../org/openstrap/app/device/PairingErrors.kt | 4 +++- .../org/openstrap/app/device/StrapCommands.kt | 5 ++++- .../org/openstrap/app/device/StrapService.kt | 3 ++- .../openstrap/app/device/SyncCoordinator.kt | 19 ++++++++++++------- .../org/openstrap/app/device/WeeklyRecap.kt | 3 ++- .../openstrap/app/device/WorkoutSession.kt | 2 +- .../openstrap/app/export/BackupSnapshot.kt | 3 ++- .../openstrap/app/ui/alarms/AlarmsScreen.kt | 11 ++++++----- .../app/ui/alarms/AlarmsViewModel.kt | 4 +++- .../app/ui/firmware/FirmwareScreen.kt | 6 ++++-- .../app/ui/firmware/FirmwareViewModel.kt | 2 ++ .../org/openstrap/app/ui/glow/ReadyScreen.kt | 12 +++++++----- .../org/openstrap/app/ui/glow/ShareScreen.kt | 12 +++++++++--- .../org/openstrap/app/ui/glow/SleepDetail.kt | 12 +++++++----- .../app/ui/workout/WorkoutsViewModel.kt | 4 +++- .../openstrap/app/device/StrapConnectTest.kt | 3 ++- .../openstrap/app/ui/glow/SharePhotoTest.kt | 4 ++-- 19 files changed, 75 insertions(+), 41 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt index 6095eea8..eec8c741 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/ConnectionManager.kt @@ -282,7 +282,8 @@ internal class ConnectionManager( client.lost() } android.bluetooth.BluetoothAdapter.STATE_ON -> onLane { - if (!wantConnected || unusable || connection.value is ConnectionState.Connected || connectJob?.isActive == true) return@onLane + val connected = connection.value is ConnectionState.Connected || connectJob?.isActive == true + if (!wantConnected || unusable || connected) return@onLane log("bluetooth back on, reconnecting") retries = 0 reconnectJob?.cancel() diff --git a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt index 8b213cd3..0eba82f3 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/LiveHeartRateStream.kt @@ -77,13 +77,13 @@ internal class LiveHeartRateStream( } } - fun setAppVisible(visible: Boolean) = set(Reason.AppVisible, visible) + fun setAppVisible(visible: Boolean) { set(Reason.AppVisible, visible) } fun setWorkoutActive(active: Boolean) { if (set(Reason.Workout, active)) log(if (active) "workout started: live hr stays on in the background" else "workout ended") } - fun setEffortWatch(active: Boolean) = set(Reason.EffortWatch, active) + fun setEffortWatch(active: Boolean) { set(Reason.EffortWatch, active) } /** True when [reason] changed. */ private fun set(reason: Reason, on: Boolean): Boolean { diff --git a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt index 0a1b0487..691aedd5 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/PairingErrors.kt @@ -15,7 +15,9 @@ object PairingErrors { private const val BINDING_PROTECTED = 0x41 private const val CLOUD_BIND_REQUIRED = 0x81 - private val KEY_REJECTED = setOf(WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED, NO_KEY, SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED) + private val KEY_REJECTED = setOf( + WRONG_KEY, CIPHERTEXT_MISMATCH, AES_FAILED, NO_KEY, SIGNATURE_FAILED, BINDING_PROTECTED, CLOUD_BIND_REQUIRED, + ) /** True when the strap turned the key down: the same key fails the same way until the user pairs again. */ fun keyRejected(status: Int): Boolean = status in KEY_REJECTED diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt index 3ec37682..12f56df6 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapCommands.kt @@ -50,7 +50,10 @@ internal class StrapCommands( @Volatile private var alarmCaps: AlarmCapabilities? = null - /** The link ended or the strap was forgotten: the next alarm command asks the strap's limits again (a firmware update can change them). */ + /** + * The link ended or the strap was forgotten: the next alarm command asks the strap's limits again (a firmware + * update can change them). + */ fun forgetAlarmCaps() { alarmCaps = null } diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt index 2e25c67d..c7b1c321 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt @@ -276,7 +276,8 @@ class StrapService : LifecycleService() { header = idleHeader(connected.takeIf { problem == null }, syncedAt), syncedAt = syncedAt, progress = (sync as? SyncState.Running)?.progress, syncing = sync is SyncState.Running, // A key the strap turned down fails the same way again: the Device page offers pairing again instead. - retry = c is ConnectionState.Failed && !c.keyRejected, connected = connected != null, sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(), + retry = c is ConnectionState.Failed && !c.keyRejected, connected = connected != null, + sport = f?.sport ?: Workouts.DEFAULT_SPORTS.first(), problem = when { c is ConnectionState.Failed -> "failed"; low -> "low"; problem != null -> "off"; else -> null }, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt index abee785e..0d6adcd1 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/SyncCoordinator.kt @@ -165,16 +165,21 @@ internal class SyncCoordinator( syncEnded.tryEmit(Unit) } } - // A sync cut off by a lost link can end only after the reconnect, which skipped its own sync while this one - // still showed as running. Run it again on the new link. - val current = link.activeSession - if (ran && sync.value is SyncState.Failed && current != null && current !== s) { - log("sync cut off by the old link, syncing again") - requests.trySend(SyncRequest.Full(manual = false, session = current)) - } + if (ran) retryCutOff(s) if (leftover) requests.trySend(SyncRequest.Full(manual = true, session = null)) } + /** + * A sync cut off by a lost link can end only after the reconnect, which skipped its own sync while this one still + * showed as running. Run it again on the new link. + */ + private fun retryCutOff(old: ChannelSession) { + val current = link.activeSession ?: return + if (current === old || sync.value !is SyncState.Failed) return + log("sync cut off by the old link, syncing again") + requests.trySend(SyncRequest.Full(manual = false, session = current)) + } + /** One debug dump, which writes Running and must not leave it behind. */ private suspend fun dump(s: ChannelSession, client: GattClient, d: SyncRequest.Dump) { try { diff --git a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt index c4f73672..ab0756d2 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WeeklyRecap.kt @@ -71,7 +71,8 @@ object WeeklyRecap { context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED ) return // Sent once it has been shown: a denied permission or a failed post leaves the week for the next look this morning. - val shown = catching { show(context, RewardsCopy.weekRange(lastWeek), RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek))) } + val text = RewardsCopy.recapText(week, Rewards.inARow(weeks, lastWeek)) + val shown = catching { show(context, RewardsCopy.weekRange(lastWeek), text) } .onFailure { Log.w("unstrap", "weekly recap: not shown: $it") } if (shown.isSuccess) settings.setRecapWeek(lastWeek.toEpochDay()) } 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 045ef23a..56c73440 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -221,7 +221,7 @@ class WorkoutSession( repeat(RESTORE_TRIES) { delay(restoreRetryMs) val done = catching { restoreLocked()?.let { l -> scope.launch { awaitStrap(l) } } } - .onFailure { log("workout not restored, ${it.message}") }.isSuccess + .onFailure { e -> log("workout not restored, ${e.message}") }.isSuccess if (done) return } log("workout not restored: left as stored for the next start") diff --git a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt index e8bfb7e5..329fc82d 100644 --- a/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt +++ b/app/src/main/kotlin/org/openstrap/app/export/BackupSnapshot.kt @@ -50,6 +50,7 @@ class BackupSnapshot private constructor(private val file: File, val database: O private const val PREFIX = "backup-snapshot-" /** Copies [source] into the cache and opens the copy. Blocking: call it off the main thread. */ + @Suppress("TooGenericExceptionCaught") fun take(context: Context, source: OpenStrapDatabase): BackupSnapshot { val file = File(context.cacheDir, "$PREFIX${UUID.randomUUID()}.db") try { @@ -58,7 +59,7 @@ class BackupSnapshot private constructor(private val file: File, val database: O val copy = Room.databaseBuilder(context, OpenStrapDatabase::class.java, file.path).build() return BackupSnapshot(file, copy) } catch (e: Throwable) { - // A copy that never opened is not left behind. + // A copy that never opened is not left behind, whatever went wrong. Rethrown as it was. SQLiteDatabase.deleteDatabase(file) throw e } 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 0ae0ffaf..23bd4654 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 @@ -17,7 +17,7 @@ import androidx.compose.material3.TimePickerDefaults import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.rememberTimePickerState import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.key import androidx.compose.runtime.rememberCoroutineScope import kotlinx.coroutines.launch @@ -147,9 +147,9 @@ fun AlarmsScreen( // A refresh can change the alarm under an open sheet (a one-time alarm switching itself off, say). Saving the old copy // would undo that, so the sheet moves to the refreshed alarm and starts from its values; if the alarm is gone, or the // free slot of a new one was taken, there is nothing left to edit and the sheet closes. - LaunchedEffect(state.alarms, state.read) { - val open = editing ?: return@LaunchedEffect - if (state.read !is AlarmsRead.Loaded) return@LaunchedEffect + SideEffect { + val open = editing ?: return@SideEffect + if (state.read !is AlarmsRead.Loaded) return@SideEffect val (alarm, isNew) = open val now = state.alarms.firstOrNull { it.index == alarm.index } editing = when { @@ -327,7 +327,8 @@ private fun AlarmSheet(alarm: Alarm, isNew: Boolean, busy: Boolean, onSave: (Ala } if (!isNew) { PageTextButton( - stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally), enabled = !busy, color = DestructiveInk, + stringResource(R.string.you_alarms_delete), onDelete, Modifier.align(Alignment.CenterHorizontally), + enabled = !busy, color = DestructiveInk, ) } } 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 e3274c3a..728793c6 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,9 @@ class AlarmsViewModel(private val strap: StrapController) : ViewModel() { }.onFailure { (strap as? StrapManager)?.log("alarms: 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) }, + { (caps, alarms, health) -> + s.copy(read = AlarmsRead.Loaded, busy = false, error = error, caps = caps, alarms = alarms, health = health) + }, { e -> val failed = error ?: 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. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt index 75cb6d9b..1981b886 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareScreen.kt @@ -278,12 +278,14 @@ private fun AccountPanel( }, ) PageButton( - stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), { mode = AccountMode.SigningIn }, + stringResource(if (account == null) R.string.you_pair_sign_in else R.string.you_zepp_sign_in_again), + { mode = AccountMode.SigningIn }, Modifier.fillMaxWidth(), enabled = enabled, primary = true, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { PageButton( - stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), { mode = AccountMode.EditingToken }, + stringResource(if (account == null) R.string.you_zepp_paste_token else R.string.you_zepp_edit), + { mode = AccountMode.EditingToken }, Modifier.weight(1f), enabled = enabled, ) if (account != null) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt index 686fd164..673c243e 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/firmware/FirmwareViewModel.kt @@ -116,6 +116,8 @@ class FirmwareViewModel( _step.update { if (it is S) next else it } } + // Each return is a reason the check can't start. + @Suppress("ReturnCount") fun check() { if (busy) return val acc = account.value ?: return fail(strings.get(R.string.you_firmware_no_account)) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt index 62bac567..3c6f643e 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ReadyScreen.kt @@ -352,16 +352,18 @@ internal fun MinusPlus( */ @Composable private fun StrapHeldNotice(connection: ConnectionState) { - if (connection is ConnectionState.Connected || connection == ConnectionState.Connecting || connection == ConnectionState.Authenticating) return val container = (LocalContext.current.applicationContext as? OpenStrapApp)?.container ?: return val held by container.settings.heldDisconnected.collectAsStateWithLifecycle(false) - if (!held || connection == ConnectionState.NotPaired) return + val away = connection == ConnectionState.Disconnected || connection is ConnectionState.Failed + if (!held || !away) return Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Text( - stringResource(R.string.glow_ready_strap_disconnected), color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), - style = GlowType.secondary, + stringResource(R.string.glow_ready_strap_disconnected), + color = Color.White.copy(alpha = GlowType.SECONDARY_ALPHA), style = GlowType.secondary, + ) + PageButton( + stringResource(R.string.glow_ready_connect), container.strap::connect, Modifier.fillMaxWidth(), icon = AppIcons.Bluetooth, ) - PageButton(stringResource(R.string.glow_ready_connect), container.strap::connect, Modifier.fillMaxWidth(), icon = AppIcons.Bluetooth) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt index 92aa1e86..a2ae7b14 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ShareScreen.kt @@ -153,7 +153,9 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str val context = LocalContext.current var photoUri by rememberSaveable { mutableStateOf(null) } val decoded by produceState(SharePhoto.None, photoUri) { - value = photoUri?.let { uri -> decodePhoto(context, uri)?.let { SharePhoto.Ready(uri, it) } ?: SharePhoto.Failed(uri) } ?: SharePhoto.None + value = photoUri?.let { uri -> + decodePhoto(context, uri)?.let { SharePhoto.Ready(uri, it) } ?: SharePhoto.Failed(uri) + } ?: SharePhoto.None } val photoState = sharePhotoFor(photoUri, decoded) val photo = (photoState as? SharePhoto.Ready)?.bitmap @@ -215,7 +217,10 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str // Not while the photo is still being read (the card would save without it) or another export is running. val ready = canExport && export == null val dim = Modifier.alpha(if (canExport) 1f else 0.4f) - WorkoutButton(saveLabel, Raised, Color.White, { if (ready) save() }, Modifier.weight(1f).then(dim), icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple) + WorkoutButton( + saveLabel, Raised, Color.White, { if (ready) save() }, Modifier.weight(1f).then(dim), + icon = if (saved == true) AppIcons.Tick02 else AppIcons.DownloadSimple, + ) WorkoutButton( stringResource(R.string.glow_share), Color.White, Color.Black, { if (ready) export = Export.Share }, Modifier.weight(1f).then(dim), icon = AppIcons.UploadSimple, @@ -262,7 +267,8 @@ private fun ShareScreen(card: StoryCard, route: List, fileName: Str ) if (photoState is SharePhoto.Failed) { Text( - stringResource(R.string.glow_share_photo_failed), color = Color.White.copy(alpha = 0.6f), style = GlowType.secondary, + stringResource(R.string.glow_share_photo_failed), + color = Color.White.copy(alpha = 0.6f), style = GlowType.secondary, modifier = Modifier.padding(top = 8.dp), ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt index 76070cbb..04b89ee0 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf @@ -145,8 +146,8 @@ internal fun SleepScoreDetail( // didn't happen. var pendingDelete by remember(state.date) { mutableStateOf(null) } var undo by remember(state.date) { mutableStateOf(null) } - LaunchedEffect(pendingDelete, session) { - val gone = pendingDelete ?: return@LaunchedEffect + SideEffect { + val gone = pendingDelete ?: return@SideEffect if (session == null) { undo = gone; pendingDelete = null } } // TODO(step 6): Month and Year wait for a stored history of the strap's sleep scores; the day loads only 14 nights. @@ -568,8 +569,8 @@ internal fun NapsDetail( // the same while its Undo shows. For this day only. var pendingDelete by remember(state.date) { mutableStateOf?>(null) } var undo by remember(state.date) { mutableStateOf?>(null) } - LaunchedEffect(pendingDelete, state.napsAsDetected) { - val gone = pendingDelete ?: return@LaunchedEffect + SideEffect { + val gone = pendingDelete ?: return@SideEffect if (state.napsAsDetected[gone.second] == null) { undo = gone; pendingDelete = null } } val total = naps.sumOf { it.end - it.start } @@ -680,7 +681,8 @@ internal fun NapsDetail( if (nap == null || detected == null) androidx.compose.runtime.SideEffect { deleting = null } else DeleteSleepSheet( SleepCopy.deleteTitle(true, isToday), Ranges.of(clock(nap.start), clock(nap.end)), - onDelete = { deleting = null; editing.delete(detected); pendingDelete = detected to nap.start }, onDismiss = { deleting = null }, + onDelete = { deleting = null; editing.delete(detected); pendingDelete = detected to nap.start }, + onDismiss = { deleting = null }, ) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt index 286a580d..ccb45c54 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/workout/WorkoutsViewModel.kt @@ -100,7 +100,9 @@ class WorkoutsViewModel( * is never taken for the one now. */ val opened: StateFlow = - openStart.flatMapLatest { start -> if (start == null) flowOf(OpenedWorkout.Loading) else repo.open(start).map { OpenedWorkout.of(start, it) } } + openStart.flatMapLatest { start -> + if (start == null) flowOf(OpenedWorkout.Loading) else repo.open(start).map { OpenedWorkout.of(start, it) } + } .flowOn(work).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), OpenedWorkout.Loading) /** diff --git a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt index 1a6a54f3..d93b4737 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/StrapConnectTest.kt @@ -211,7 +211,8 @@ class StrapConnectTest { assertEquals(ConnectionState.Disconnected, strap.connection.value) // Opening the app is the user's: it clears the hold and connects. strap.autoConnect() - delay(1_000) + // The connect reads the paired strap on a real thread first, so wait for it rather than for virtual time. + strap.connection.first { it == ConnectionState.Connecting } assertEquals(strap.log.value.joinToString("\n"), 2, strap.log.value.count { it.contains("connecting to") }) } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt index 8a76bd14..a417f741 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/glow/SharePhotoTest.kt @@ -1,7 +1,7 @@ package org.openstrap.app.ui.glow import android.net.Uri -import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith @@ -14,7 +14,7 @@ import org.robolectric.annotation.Config class SharePhotoTest { private val first = Uri.parse("content://photos/1") private val second = Uri.parse("content://photos/2") - private val bitmap = ImageBitmap(1, 1) + private val bitmap = android.graphics.Bitmap.createBitmap(1, 1, android.graphics.Bitmap.Config.ARGB_8888).asImageBitmap() @Test fun `no pick is None whatever was decoded before`() { assertEquals(SharePhoto.None, sharePhotoFor(null, SharePhoto.Ready(first, bitmap))) From 43135171da886f147cdde2c8866bb7e03673b077 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 07:14:10 +0400 Subject: [PATCH 10/27] Workout resend to the strap only on a new login, as Zepp The reconnect resend acted on every Connected value, and a battery or charging change is a new one, so each sent the config and state again. Zepp sends it at the workout start (xbc.k) and then only on AUTH_SUCCESS (rbc via yfk); its battery callback sends nothing. It now follows the change into Connected, which the start still sends. Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/WorkoutSession.kt | 9 ++-- .../app/device/WorkoutSessionTest.kt | 51 +++++++++++++++++-- 2 files changed, 54 insertions(+), 6 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 75e12741..6c41bb8f 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onSubscription @@ -1023,10 +1024,12 @@ class WorkoutSession( launch { strap.heartRateReadings.collect(::onReading) } if (strapSessions) { launch { strap.sportSessionPushes.collect(::onStrapPush) } - // On every connect, the workout again as Zepp's `bo60.j(2)`: the config, then one state. + // Connected now, and on each new login, the workout again as Zepp's `bo60.j(2)`: the config, then one + // state. Zepp calls it at the start and on each AUTH_SUCCESS only (`xbc.k`, `rbc`, `yfk`), never on a + // battery change, which here is a new Connected value. Every login passes Connecting first. launch { - strap.connection.collect { c -> - if (c !is ConnectionState.Connected) return@collect + strap.connection.map { it is ConnectionState.Connected }.distinctUntilChanged().collect { connected -> + if (!connected) return@collect val now = (_state.value as? WorkoutState.Recording)?.workout ?: return@collect strapState(reconnectState(now), now, reconnect = true) } 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 61b45786..01294177 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -161,11 +161,13 @@ class WorkoutSessionTest { @Test fun reconnectSendsTheConfigAndOneStateAsZepp() { val s = session() - var battery = 80 - // A new battery level each time, so the state flow can't fold a quick drop and return into no change. + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + // A login always passes Connecting, so the session sees the link go and come back. fun reconnect(): Pair { strap.sportStates.clear() - strap.connection.value = ConnectionState.Connected(battery--, "3.27.0.1") + strap.connection.value = ConnectionState.Connecting + Thread.sleep(SETTLE_MS) + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") return runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.none { it.second }) delay(POLL_MS) @@ -188,6 +190,49 @@ class WorkoutSessionTest { s.state.await { it is WorkoutState.Ended } } + /** + * Zepp sends the workout once at its start and then only on a new login (`xbc.k`, then `rbc` on AUTH_SUCCESS). A + * battery or charging change, a new Connected value here, sends nothing. + */ + @Test + fun aBatteryChangeDoesNotSendTheWorkoutAgain() { + val s = session() + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + s.start(sportType = 1) + s.recording() + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.isEmpty()) delay(POLL_MS) } } + Thread.sleep(SETTLE_MS) + assertEquals("the start sends it once", listOf(SportSession.State.START to true), strap.sportStates.toList()) + + strap.sportStates.clear() + strap.connection.value = ConnectionState.Connected(79, "3.27.0.1") + strap.connection.value = ConnectionState.Connected(79, "3.27.0.1", charging = true) + Thread.sleep(SETTLE_MS) + assertEquals(emptyList>(), strap.sportStates.toList()) + s.end() + // Seconds long, so it ends unsaved: Idle, not Ended. + s.state.await { it !is WorkoutState.Recording } + } + + /** A workout started with the strap away sends it when the strap logs in, as Zepp's connect callback does. */ + @Test + fun aWorkoutStartedWithTheStrapAwaySendsItOnConnect() { + val s = session() + s.start(sportType = 1) + s.recording() + Thread.sleep(SETTLE_MS) + assertEquals(emptyList>(), strap.sportStates.toList()) + strap.connection.value = ConnectionState.Connecting + Thread.sleep(SETTLE_MS) + strap.connection.value = ConnectionState.Connected(80, "3.27.0.1") + runBlocking { withTimeout(WAIT_MS) { while (strap.sportStates.isEmpty()) delay(POLL_MS) } } + Thread.sleep(SETTLE_MS) + assertEquals(listOf(SportSession.State.START to true), strap.sportStates.toList()) + s.end() + // Seconds long, so it ends unsaved: Idle, not Ended. + s.state.await { it !is WorkoutState.Recording } + } + @Test fun endedWhilePausedEndsWhereThePauseBegan() { val s = session() From 55414cb9a77f62231f0eeafd47aeb78a55cd2b9f Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 10:47:36 +0400 Subject: [PATCH 11/27] A history type cut off part way fails the sync, as Zepp A type whose retries ran out, or that hit the cyclic stop, after some chunks counted as ok, so the sync ended Done with that type short. Zepp's type result is its last exchange's status (l59.f, ixi.a), so the type fails and the sync ends with an error. The chunks that came first are still stored and the cursor moves past them, as in Zepp. Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/device/HistorySync.kt | 6 ++++-- .../org/openstrap/app/device/HistorySyncTest.kt | 11 +++++++++++ 2 files changed, 15 insertions(+), 2 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 970f0f41..a0614cae 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/HistorySync.kt @@ -404,14 +404,16 @@ class HistorySync internal constructor( var ok = true loop@ while (true) { check(gatt.connected.value) { Strings.app.get(R.string.system_sync_link_dropped) } - if (fastRecharge) { ok = got.isNotEmpty(); break } + if (fastRecharge) { ok = false; break } val chunk = when (val f = client.fetch(spec.code, cursor, zone, previous)) { is GdspFetch.Chunk -> f GdspFetch.Empty -> break@loop is GdspFetch.Failed -> { log("history ${spec.type}: ${f.reason}") if (f.fastRecharge) fastRecharge = true - if (f.cyclic || --retries <= 0 || fastRecharge) { ok = got.isNotEmpty(); break@loop } + // Zepp's type result is the last exchange's status (`l59.f`, `ixi.a`): chunks that came first are + // still stored, but the type failed, and so does the sync. + if (f.cyclic || --retries <= 0 || fastRecharge) { ok = false; break@loop } continue@loop } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt b/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt index 9961dfc6..432791e5 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/HistorySyncTest.kt @@ -299,6 +299,17 @@ class HistorySyncTest { assertEquals(1, table("SELECT * FROM pai").size) } + @Test fun `a type cut off after its first chunk keeps that chunk and fails the sync, as Zepp`() = runTest { + seedStrap() + // The first HRV START is served, every later one refused. + strap.refuse = { type -> if (type == HistoryDataType.HRV_RMSSD.code && strap.starts.count { it.first == type } > 1) 5 else null } + runSync() + // The first chunk (two records, one a zero) is stored, and the cursor moved past it. + assertEquals(listOf(listOf(base, 41L)), table("SELECT timestamp, milliseconds FROM hrv ORDER BY timestamp")) + assertEquals(base + 301, cursors.values[key(HistoryDataType.HRV_RMSSD)]) + assertEquals(SyncState.Failed("Sync failed"), state.value) + } + @Test fun `fast-charge mode is acknowledged and starts nothing more`() = runTest { seedStrap() strap.fastRecharge = true From c8237d486044c95e30e4d9d0c500dda8a3a6b757 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 10:56:32 +0400 Subject: [PATCH 12/27] Permissions: settings dialog for location and notifications turned down for good, Offer calories again Location and notifications turned down for good get the Bluetooth dialog with its settings button. A notifications denial is now recorded from the Bluetooth ask and checked at workout start. The Health Connect page offers calories again, asking for just those permissions, only while they are not granted. Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/BlePermissions.kt | 13 +++++ .../app/health/HealthConnectExporter.kt | 4 ++ .../app/ui/device/HealthConnectPage.kt | 12 ++++ .../openstrap/app/ui/root/AppRootViewModel.kt | 6 ++ .../app/ui/root/HealthConnectActions.kt | 30 ++++++++++ .../org/openstrap/app/ui/root/PagesOverTab.kt | 2 + .../openstrap/app/ui/root/PermissionGates.kt | 57 ++++++++++++++----- .../res/values-zh-rCN/strings_day_root.xml | 3 + .../res/values-zh-rCN/strings_you_data.xml | 2 + app/src/main/res/values/strings_day_root.xml | 5 ++ app/src/main/res/values/strings_you_data.xml | 3 + .../app/device/BlePermissionsTest.kt | 12 ++++ 12 files changed, 135 insertions(+), 14 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/device/BlePermissions.kt b/app/src/main/kotlin/org/openstrap/app/device/BlePermissions.kt index a8f58f7f..6d9394d1 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/BlePermissions.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/BlePermissions.kt @@ -44,6 +44,19 @@ object BlePermissions { bluetooth.toTypedArray() } + /** Notifications for the foreground service's notification: asked for on Android 13 and later, granted before. */ + val notifications: List + @SuppressLint("InlinedApi") + get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) listOf(Manifest.permission.POST_NOTIFICATIONS) else emptyList() + + /** Whether notifications may be shown now (always, before Android 13). */ + fun notificationsGranted(context: Context): Boolean = + notifications.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED } + + /** Whether a request's [result] turned notifications down. Absent (before Android 13) is not a denial. */ + @SuppressLint("InlinedApi") + fun notificationsDenied(result: Map): Boolean = result[Manifest.permission.POST_NOTIFICATIONS] == false + /** Whether the strap may be scanned for and connected to now. */ fun granted(context: Context): Boolean = bluetooth.all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED } 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 4fd14d97..9d7d2f79 100644 --- a/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt +++ b/app/src/main/kotlin/org/openstrap/app/health/HealthConnectExporter.kt @@ -131,6 +131,10 @@ class HealthConnectExporter(private val context: Context, private val dao: Healt suspend fun hasPermissions(): Boolean = client.permissionController.getGrantedPermissions().containsAll(permissions) + /** Whether the optional calorie permissions are granted, for the Health Connect page's offer to ask again. */ + suspend fun hasCaloriePermissions(): Boolean = + client.permissionController.getGrantedPermissions().containsAll(caloriePermissions) + /** The record reads the user has granted (any of them is enough to import that kind). */ suspend fun hasReadPermissions(): Boolean = client.permissionController.getGrantedPermissions().any { it in readPermissions } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt b/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt index cd351457..b4cdb7ec 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/device/HealthConnectPage.kt @@ -55,6 +55,8 @@ fun HealthConnectPage( onOpen: () -> Unit, onInstall: () -> Unit, onBack: () -> Unit, + caloriesMissing: Boolean = false, + onOfferCalories: () -> Unit = {}, ) { BackHandler(onBack = onBack) ScreenList(contentPadding, gutter = GlowLayout.Gutter) { @@ -86,6 +88,7 @@ fun HealthConnectPage( ) } } + if (caloriesMissing) item { CaloriesOffer(onOfferCalories) } } } @@ -103,6 +106,15 @@ private fun InstallPanel(onInstall: () -> Unit) { } } +/** Calories off: why they are left out, and the button that asks for just those permissions. */ +@Composable +private fun CaloriesOffer(onOffer: () -> Unit) { + Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + PageNote(stringResource(R.string.you_hc_calories_note)) + PageButton(stringResource(R.string.you_hc_calories_offer), onOffer, Modifier.fillMaxWidth(), icon = AppIcons.Plus) + } +} + /** * Opens Health Connect's home, where OpenStrap is one tap away under Your health apps, or its Data and access screen * where the home isn't there. False when neither opens (Health Connect missing or disabled). OpenStrap's own 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 9ced2911..1019cd4a 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 @@ -263,6 +263,12 @@ class AppRootViewModel( else -> HcState.Needs(healthConnect.requestedPermissions) } + /** Just the calorie permissions, for the Health Connect page's "Offer calories again". Granted when nothing is left to ask. */ + suspend fun healthConnectCalories(): HcState = HcState.blocked(healthConnect.availability()) ?: when { + healthConnect.hasCaloriePermissions() -> HcState.Granted + else -> HcState.Needs(healthConnect.caloriePermissions) + } + suspend fun healthConnectRead(): HcState = HcState.blocked(healthConnect.availability()) ?: when { healthConnect.hasReadPermissions() -> HcState.Granted else -> HcState.Needs(healthConnect.readPermissions) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt index 4cd7cd51..d2a34dd7 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/HealthConnectActions.kt @@ -13,13 +13,16 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.health.connect.client.PermissionController +import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.launch +import org.openstrap.app.data.catching import org.openstrap.app.health.HcAvailability import org.openstrap.app.ui.device.BackupCopy import org.openstrap.app.ui.device.DeviceViewModel @@ -47,6 +50,10 @@ internal class HealthConnectActions( val export: () -> Unit, /** Auto sync on or off. */ val auto: (Boolean) -> Unit, + /** True while Health Connect is there and the calorie permissions are not granted: the page offers them again. */ + val caloriesMissing: Boolean, + /** Asks for just the calorie permissions. */ + val offerCalories: () -> Unit, ) internal val HC_UNAVAILABLE: String get() = Strings.app.get(R.string.day_hc_unavailable) @@ -69,6 +76,15 @@ internal fun hcMissingMessage(availability: HcAvailability): String = internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: DeviceViewModel): HealthConnectActions { val context = LocalContext.current val scope = rememberCoroutineScope() + var caloriesMissing by remember { mutableStateOf(false) } + val refreshCalories: () -> Unit = { + scope.launch { caloriesMissing = catching { rootVm.healthConnectCalories() }.getOrNull() is HcState.Needs } + } + // Read again on every return to the app, since the grant can change in Health Connect's own screen. + LifecycleResumeEffect(Unit) { + refreshCalories() + onPauseOrDispose { } + } var hcForAuto by rememberSaveable { mutableStateOf(false) } val hcLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { granted -> val auto = hcForAuto @@ -82,6 +98,9 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De } } } + val hcCalorieLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { + refreshCalories() + } val hcReadLauncher = rememberLauncherForActivityResult(PermissionController.createRequestPermissionResultContract()) { granted -> if (rootVm.healthConnectReadGranted(granted)) deviceVm.importHealthConnect() else Toast.makeText(context, HC_NOT_GRANTED, Toast.LENGTH_LONG).show() @@ -115,6 +134,17 @@ internal fun rememberHealthConnectActions(rootVm: AppRootViewModel, deviceVm: De import = import, export = { write(false) }, auto = { on -> if (on) write(true) else deviceVm.setAutoHealthConnect(false) }, + caloriesMissing = caloriesMissing, + offerCalories = { + scope.launch { + when (val hc = rootVm.healthConnectCalories()) { + HcState.Unavailable -> Toast.makeText(context, HC_UNAVAILABLE, Toast.LENGTH_LONG).show() + HcState.Installable -> Toast.makeText(context, HC_INSTALL_FIRST, Toast.LENGTH_LONG).show() + HcState.Granted -> caloriesMissing = false + is HcState.Needs -> hcCalorieLauncher.launch(hc.permissions) + } + } + }, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt index 13107292..7edb1a07 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PagesOverTab.kt @@ -368,6 +368,8 @@ private fun HealthConnectPageHost(hooks: PageHooks, padding: PaddingValues, onBa if (!installHealthConnect(context)) Toast.makeText(context, HC_STORE_FAILED, Toast.LENGTH_LONG).show() }, onBack = onBack, + caloriesMissing = hooks.healthConnect.caloriesMissing, + onOfferCalories = hooks.healthConnect.offerCalories, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt index 15131375..51cd62b1 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/PermissionGates.kt @@ -22,7 +22,7 @@ import org.openstrap.app.data.WorkoutPlan import org.openstrap.app.device.BlePermissions import org.openstrap.app.ui.glow.PageConfirm -/** The Bluetooth and location gates in front of a workout and the Strap page's actions. */ +/** The Bluetooth, location and notification gates in front of a workout and the Strap page's actions. */ internal class PermissionGates( /** Runs the action once Bluetooth may be used. */ val requestBluetooth: (() -> Unit) -> Unit, @@ -30,16 +30,19 @@ internal class PermissionGates( val startPlan: (WorkoutPlan, SportSettings?) -> Unit, /** Asks for location, then runs the action whatever the answer. */ val requestLocation: (() -> Unit) -> Unit, - private val blocked: MutableState, + private val blocked: MutableState, ) { - /** Bluetooth was turned down for good: Android shows no dialog any more, so the app offers its settings page. */ - val bluetoothBlocked: Boolean get() = blocked.value + /** What was turned down for good: Android shows no dialog any more, so the app offers its settings page. */ + val blockedPermission: BlockedPermission? get() = blocked.value fun dismissBlocked() { - blocked.value = false + blocked.value = null } } +/** A permission turned down for good, saved by name so the dialog survives a recreate. */ +internal enum class BlockedPermission { BLUETOOTH, LOCATION, NOTIFICATIONS } + /** What waits on the location answer besides a workout: a name rather than a closure, so it can be saved. */ private enum class GateAction { /** Ready's "Turn on location": the Ready screen reads the phone's location again. */ @@ -66,7 +69,7 @@ internal fun rememberPermissionGates( val bluetoothRequired = stringResource(if (android11) R.string.day_bluetooth_required_location else R.string.day_bluetooth_required) val locationDeclined = stringResource(R.string.day_location_declined) var pending by rememberSaveable(stateSaver = PendingAction.Saver) { mutableStateOf(null) } - val blocked = rememberSaveable { mutableStateOf(false) } + val blocked = rememberSaveable { mutableStateOf(null) } val btLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> val waiting = pending as? PendingAction.StartPlan val strapAction = pendingStrap.action @@ -77,8 +80,15 @@ internal fun rememberPermissionGates( BlePermissions.granted(result) -> { waiting?.let(start) strapAction?.invoke() + // Notifications are not needed to go ahead, but a no for good leaves the workout notification missing. + if (BlePermissions.notificationsDenied(result) && activity != null && + BlePermissions.turnedDownForGood(activity, BlePermissions.notifications) + ) { + blocked.value = BlockedPermission.NOTIFICATIONS + } } - activity != null && BlePermissions.turnedDownForGood(activity, BlePermissions.bluetooth) -> blocked.value = true + activity != null && BlePermissions.turnedDownForGood(activity, BlePermissions.bluetooth) -> + blocked.value = BlockedPermission.BLUETOOTH else -> Toast.makeText(context, bluetoothRequired, Toast.LENGTH_LONG).show() } } @@ -87,7 +97,8 @@ internal fun rememberPermissionGates( btLauncher.launch(BlePermissions.required()) } val withBluetooth: (PendingAction.StartPlan) -> Unit = { action -> - if (BlePermissions.granted(context)) { + // Asked again while notifications are missing, so a no for good shows its dialog at the start of a workout. + if (BlePermissions.granted(context) && BlePermissions.notificationsGranted(context)) { start(action) } else { pending = action @@ -99,9 +110,14 @@ internal fun rememberPermissionGates( // shows and on every resume, so a lost closure leaves nothing undone. var afterLocation by rememberSaveable { mutableStateOf(null) } var refreshReady by remember { mutableStateOf<(() -> Unit)?>(null) } + val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) val locationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result -> if (result.values.none { it }) { - Toast.makeText(context, locationDeclined, Toast.LENGTH_LONG).show() + if (activity != null && BlePermissions.turnedDownForGood(activity, locationPermissions.asList())) { + blocked.value = BlockedPermission.LOCATION + } else { + Toast.makeText(context, locationDeclined, Toast.LENGTH_LONG).show() + } } val waiting = pending as? PendingAction.StartPlan if (waiting != null) { @@ -112,7 +128,6 @@ internal fun rememberPermissionGates( afterLocation = null refreshReady = null } - val locationPermissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) val requestLocation: (() -> Unit) -> Unit = { then -> afterLocation = GateAction.REFRESH_READY refreshReady = then @@ -130,14 +145,28 @@ internal fun rememberPermissionGates( return PermissionGates(requestBluetooth, startPlan, requestLocation, blocked) } -/** Nearby devices turned down for good: the way to OpenStrap's settings page, where it can be turned on. */ +/** + * Whatever was turned down for good (Nearby devices, location, notifications): the way to unstrap's settings page, + * where it can be turned on. Named for Bluetooth, which it first served. + */ @Composable internal fun BluetoothBlockedDialog(gates: PermissionGates) { - if (!gates.bluetoothBlocked) return + val blocked = gates.blockedPermission ?: return val context = LocalContext.current + val location = BlePermissions.scanNeedsLocationOn + val title = when (blocked) { + BlockedPermission.BLUETOOTH -> if (location) R.string.day_nearby_title_location else R.string.day_nearby_title + BlockedPermission.LOCATION -> R.string.day_nearby_title_location + BlockedPermission.NOTIFICATIONS -> R.string.day_notifications_blocked_title + } + val text = when (blocked) { + BlockedPermission.BLUETOOTH -> if (location) R.string.day_nearby_text_location else R.string.day_nearby_text + BlockedPermission.LOCATION -> R.string.day_location_blocked_text + BlockedPermission.NOTIFICATIONS -> R.string.day_notifications_blocked_text + } PageConfirm( - title = stringResource(if (BlePermissions.scanNeedsLocationOn) R.string.day_nearby_title_location else R.string.day_nearby_title), - text = stringResource(if (BlePermissions.scanNeedsLocationOn) R.string.day_nearby_text_location else R.string.day_nearby_text), + title = stringResource(title), + text = stringResource(text), confirm = stringResource(R.string.day_nearby_open_settings), onConfirm = { gates.dismissBlocked() diff --git a/app/src/main/res/values-zh-rCN/strings_day_root.xml b/app/src/main/res/values-zh-rCN/strings_day_root.xml index 0a840a0d..196ec53a 100644 --- a/app/src/main/res/values-zh-rCN/strings_day_root.xml +++ b/app/src/main/res/values-zh-rCN/strings_day_root.xml @@ -16,6 +16,9 @@ 在 Android 11 上,unstrap 需要位置权限来查找并连接你的手环。应用不会使用你的位置信息。Android 不会再次询问,请在 unstrap 的设置中前往「权限」开启。 打开设置 暂不 + GPS 运动需要位置权限。Android 不会再次询问,请在 unstrap 的系统设置中开启“权限”。 + 允许通知 + unstrap 通过通知显示运动和手环状态。Android 不会再次询问,请在 unstrap 的系统设置中开启“通知”。 无法同步。%1$s 手环未连接。 正在同步手环… diff --git a/app/src/main/res/values-zh-rCN/strings_you_data.xml b/app/src/main/res/values-zh-rCN/strings_you_data.xml index 55d50180..03577567 100644 --- a/app/src/main/res/values-zh-rCN/strings_you_data.xml +++ b/app/src/main/res/values-zh-rCN/strings_you_data.xml @@ -57,6 +57,8 @@ 找回 unstrap 曾保存在那里的数据 打开 Health Connect 权限与数据 + 允许后才会复制卡路里。 + 再次请求卡路里权限 安装 Health Connect 在此手机上 Health Connect 是来自 Play 商店的应用。请安装它以便将数据复制到其中。 无法打开 Play 商店。 diff --git a/app/src/main/res/values/strings_day_root.xml b/app/src/main/res/values/strings_day_root.xml index d80f69a1..52c7fd59 100644 --- a/app/src/main/res/values/strings_day_root.xml +++ b/app/src/main/res/values/strings_day_root.xml @@ -35,6 +35,11 @@ Open settings Not now + + GPS workouts need location access. Android won\'t ask again, so turn it on in unstrap\'s settings, under Permissions. + + Allow notifications + unstrap shows your workout and strap status as a notification. Android won\'t ask again, so turn it on in unstrap\'s settings, under Notifications. Couldn\'t sync. %1$s diff --git a/app/src/main/res/values/strings_you_data.xml b/app/src/main/res/values/strings_you_data.xml index 2d4d47fc..7274a9d8 100644 --- a/app/src/main/res/values/strings_you_data.xml +++ b/app/src/main/res/values/strings_you_data.xml @@ -99,6 +99,9 @@ Bring back what unstrap saved there Open Health Connect Permissions and data + + Calories are left out until you allow them. + Offer calories again Install Health Connect On this phone Health Connect is an app from the Play Store. Install it to copy your data there. diff --git a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt index 2f226b71..baa65fb8 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt @@ -79,6 +79,18 @@ class BlePermissionsTest { assertFalse(BlePermissions.granted(mapOf(Manifest.permission.BLUETOOTH_CONNECT to true))) } + @Test fun `a notifications denial is told apart from no answer`() { + val n = Manifest.permission.POST_NOTIFICATIONS + assertTrue(BlePermissions.notificationsDenied(mapOf(n to false))) + assertFalse(BlePermissions.notificationsDenied(mapOf(n to true))) + assertFalse(BlePermissions.notificationsDenied(emptyMap())) + assertEquals(listOf(n), BlePermissions.notifications) + shadowOf(app).denyPermissions(n) + assertFalse(BlePermissions.notificationsGranted(app)) + shadowOf(app).grantPermissions(n) + assertTrue(BlePermissions.notificationsGranted(app)) + } + @Test fun `turned down for good once Android owes no rationale for any of them`() { val activity = Robolectric.buildActivity(android.app.Activity::class.java).setup().get() val pm = shadowOf(activity.packageManager) From cb0c0e9f162266a5fb89c59ea1ae1ded14d1ac8f Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 10:56:36 +0400 Subject: [PATCH 13/27] Permissions test: pin the notifications test to Android 14 Co-Authored-By: Claude Opus 5.5 --- .../test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt index baa65fb8..0a13c511 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/BlePermissionsTest.kt @@ -79,7 +79,7 @@ class BlePermissionsTest { assertFalse(BlePermissions.granted(mapOf(Manifest.permission.BLUETOOTH_CONNECT to true))) } - @Test fun `a notifications denial is told apart from no answer`() { + @Test @Config(sdk = [34]) fun `a notifications denial is told apart from no answer`() { val n = Manifest.permission.POST_NOTIFICATIONS assertTrue(BlePermissions.notificationsDenied(mapOf(n to false))) assertFalse(BlePermissions.notificationsDenied(mapOf(n to true))) From 5a65921a70cacd55ff69b241f2dd36707f6ffe73 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 10:57:08 +0400 Subject: [PATCH 14/27] Workout: a failed End shows Not saved yet with Try again, saves tracked per part, start returns a result A failed End sets Recording.endFailed and the live screen shows Not saved yet with Try again (End again). saveFailed is now derived from endFailed and a per-part set (Workout, Sets, Rounds, HeartRate), so one success no longer clears another failure. start() returns Deferred, WorkoutSession and the layer share inProgress, the tile no longer sends Ready during a summary or reads the sport back from its subtitle, and a GpsState flow says Off, Searching, Fixed or Unavailable. Co-Authored-By: Claude Opus 5.5 --- .../openstrap/app/device/WorkoutSession.kt | 87 ++++++++++++++++--- .../app/device/WorkoutTileService.kt | 19 ++-- .../openstrap/app/ui/glow/live/LiveFrame.kt | 13 +++ .../org/openstrap/app/ui/root/WorkoutLayer.kt | 3 +- .../values-zh-rCN/strings_workout_live.xml | 4 + .../main/res/values/strings_workout_live.xml | 7 ++ .../app/device/WorkoutSessionTest.kt | 62 ++++++++++++- 7 files changed, 172 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 6c41bb8f..66ab095e 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutSession.kt @@ -4,10 +4,12 @@ import android.content.Context import android.os.PowerManager import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted @@ -59,11 +61,24 @@ sealed interface WorkoutState { val rounds: List = emptyList(), val restExtra: Long = 0, /** - * The last save to the database failed. It records on in memory and the next change saves again, but a - * process death now would lose what is unsaved, so the notification says so. + * The parts whose last save to the database failed, each tracked on its own so one success can't hide another + * failure. It records on in memory and the next change saves again, but a process death now would lose what is + * unsaved. */ - val saveFailed: Boolean = false, + val failing: Set = emptySet(), + /** + * End was tried and its save failed: the workout is still recording, and the live screen says "Not saved yet" + * with Try again, which runs End again. + */ + val endFailed: Boolean = false, ) : WorkoutState { + /** Something isn't saved: the notification and the live screen say so. */ + val saveFailed: Boolean get() = endFailed || failing.isNotEmpty() + + /** This state with [part]'s last save [failed] or not, and the other parts as they were. */ + fun withSave(part: SavePart, failed: Boolean): Recording = + if ((part in failing) == failed) this else copy(failing = if (failed) failing + part else failing - part) + /** Parsed once per state, not on every read: the rounds' clock reads it each second. */ val structure: org.openstrap.app.data.Structure? by lazy { org.openstrap.app.data.Structure.parse(workout.structure) } @@ -84,6 +99,18 @@ sealed interface WorkoutState { data class Ended(val start: Long, val preview: Boolean = false) : WorkoutState } +/** The parts of a recording workout that are saved separately, each with its own failure flag. */ +enum class SavePart { Workout, Sets, Rounds, HeartRate } + +/** A workout is in progress: recording, or ended with its summary still showing. */ +val WorkoutState.inProgress: Boolean get() = this is WorkoutState.Recording || this is WorkoutState.Ended + +/** What [WorkoutSession.start] came to. */ +enum class StartResult { Started, AlreadyRecording, Failed } + +/** What the phone knows of its GPS for the workout: not wanted, waiting for a first fix, fixes coming, or not available. */ +enum class GpsState { Off, Searching, Fixed, Unavailable } + /** * The heart rate after a workout [start] ended at [end], for the summary's heart rate drop: what the strap sent, a * reading a second (epoch seconds, bpm), until [until]. @@ -135,6 +162,13 @@ class WorkoutSession( private val _state = MutableStateFlow(WorkoutState.Idle) val state: StateFlow = _state + /** A workout is recording, or ended with its summary showing: what every "in progress" check asks. */ + val inProgress: Boolean get() = _state.value.inProgress + + /** The GPS of the workout under way: [GpsState.Off] unless it uses GPS. */ + private val _gps = MutableStateFlow(GpsState.Off) + val gps: StateFlow = _gps + /** Live readings of the last [RECENT_S] seconds, oldest first, for the live chart: (epoch seconds, bpm). */ private val _recent = MutableStateFlow>>(emptyList()) val recent: StateFlow>> = _recent @@ -278,6 +312,10 @@ class WorkoutSession( left } + /** + * Starts a workout. The result says what came of it: [StartResult.AlreadyRecording] when one records already, and + * [StartResult.Failed] when its row or its recording couldn't be set up (nothing is left half started). + */ fun start( sportType: Int, askToEnd: Boolean = true, target: org.openstrap.app.data.WorkoutTarget? = null, useGps: Boolean = false, keepRoute: Boolean = false, @@ -286,10 +324,11 @@ class WorkoutSession( from: Long? = null, seed: List> = emptyList(), seedSteps: Int? = null, /** Strength: a log card after each set. Rounds or periods ([AppWorkout.structure]). */ logSets: Boolean = false, structure: String? = null, - ) { - scope.launch { + ): Deferred = scope.async { + // The row's own write failing counts too: nothing was started then. + catching { lock.withLock { - if (_state.value is WorkoutState.Recording) return@withLock + if (_state.value is WorkoutState.Recording) return@withLock StartResult.AlreadyRecording val w = AppWorkout( start = from ?: now(), end = null, sportType = sportType, askToEnd = askToEnd, target = target?.code, useGps = useGps, keepRoute = useGps && keepRoute, @@ -304,6 +343,7 @@ class WorkoutSession( lastSecond = -1L _history.value = emptyList() dao.upsertAppWorkout(w) + _gps.value = GpsState.Off _recent.value = emptyList() _stats.value = null sum = 0 @@ -317,11 +357,15 @@ class WorkoutSession( askSince = w.start minimized.value = false // Half started is not started: begin undid what it took, and the row goes too. - catching { begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) } }.onFailure { + val begun = catching { begin(w, maxHeartRate(), seed) { it.copy(logSets = logSets) } }.onFailure { log("workout not started: $it") catching { dao.deleteAppWorkout(w.start) }.onFailure { e -> log("workout row not removed: ${e.message}") } } + if (begun.isSuccess) StartResult.Started else StartResult.Failed } + }.getOrElse { + log("workout not started: $it") + StartResult.Failed } } @@ -486,6 +530,7 @@ class WorkoutSession( // Readings after this one are dropped ([record]): they would be written after the last flush, under // the next workout's start or as rows of one just deleted. ending = true + _state.update { s -> (s as? WorkoutState.Recording)?.takeIf { it.endFailed }?.copy(endFailed = false) ?: s } flush() saveDistance() val w = r.workout @@ -504,7 +549,7 @@ class WorkoutSession( val stored = store(ended, recorded, kept, _route.value) stored.exceptionOrNull()?.let { log("workout ${if (kept) "not saved" else "not deleted"}, still recording: ${it.message}") - _state.update { s -> (s as? WorkoutState.Recording)?.copy(saveFailed = true) ?: s } + _state.update { s -> (s as? WorkoutState.Recording)?.copy(endFailed = true) ?: s } // Recording on, so readings count again. ending = false return@withLock @@ -771,7 +816,8 @@ class WorkoutSession( // while the save ran stays. _state.update { (it as? WorkoutState.Recording) - ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise, saveFailed = failed) ?: it + ?.copy(sets = changed.sets, restUntil = changed.restUntil, exercise = changed.exercise) + ?.withSave(SavePart.Sets, failed) ?: it } } } @@ -838,7 +884,8 @@ class WorkoutSession( val failed = catching { dao.upsertRounds(step.rounds) }.onFailure { log("rounds not saved: ${it.message}") }.isFailure _state.update { s -> val now = s as? WorkoutState.Recording ?: return@update s - now.copy(rounds = step.rounds, restExtra = if (step.switch != null) 0 else now.restExtra, saveFailed = failed) + now.copy(rounds = step.rounds, restExtra = if (step.switch != null) 0 else now.restExtra) + .withSave(SavePart.Rounds, failed) } } step.switch?.let { buzz(org.openstrap.app.data.WorkoutBuzz.of(it, game = s is org.openstrap.app.data.Structure.Periods), it.name) } @@ -910,7 +957,7 @@ class WorkoutSession( // The whole workout is written each time, and again at its end, so a failed save costs nothing kept. val failed = catching { dao.upsertAppWorkout(w) }.onFailure { log("workout not saved: ${it.message}") }.isFailure // Only the workout is ours: everything else (an end prompt, say) may have changed while the save ran. - _state.update { (it as? WorkoutState.Recording)?.copy(workout = w, saveFailed = failed) ?: it } + _state.update { (it as? WorkoutState.Recording)?.copy(workout = w)?.withSave(SavePart.Workout, failed) ?: it } } } } @@ -931,6 +978,9 @@ class WorkoutSession( private val allReadings = mutableListOf>() private val location = WorkoutLocation(context) { p -> val r = _state.value as? WorkoutState.Recording ?: return@WorkoutLocation + // Nothing after End began: the route is read for the stored workout. + if (ending) return@WorkoutLocation + _gps.value = GpsState.Fixed if (!r.paused) _route.update { it + p } } private var heightCm: Int? = null @@ -992,10 +1042,15 @@ class WorkoutSession( .onFailure { log("workout: strap sessions setting not read: $it") }.getOrDefault(true) heightCm = catching { settings.profile.first().heightCm }.onFailure { log("workout: height not read: $it") }.getOrNull() // No permission or no GPS provider: the workout says it doesn't use GPS, and measures from the strap's steps. + _gps.value = GpsState.Off val w = if (w0.useGps && !location.start()) { log("workout: GPS not available, distance from the strap's steps") + _gps.value = GpsState.Unavailable w0.copy(useGps = false).also { catching { dao.upsertAppWorkout(it) }.onFailure { e -> log("workout not saved: ${e.message}") } } - } else w0 + } else { + if (w0.useGps) _gps.value = GpsState.Searching + w0 + } ending = false _state.update { setup(WorkoutState.Recording(w, maxHr)) } // Anything that fails from here on undoes the start, so a workout is never left Recording with nothing behind it. @@ -1199,6 +1254,7 @@ class WorkoutSession( KeepRecordingNotice.clear(context) _lastCue.value = null location.stop() + _gps.value = GpsState.Off if (carRegistered) runCatching { context.unregisterReceiver(carReceiver) } carRegistered = false recordJob?.cancel() @@ -1249,6 +1305,7 @@ class WorkoutSession( .onSuccess { if (flushFailing) log("heart rate saved again") flushFailing = false + setSaved(SavePart.HeartRate, failed = false) } .onFailure { e -> // Kept for the next flush rather than lost, but only the newest [MAX_UNSAVED]: a database that keeps @@ -1262,6 +1319,7 @@ class WorkoutSession( if (dropped > 0 && !flushDropping) log("heart rate unsaved for too long, the oldest readings are dropped") flushFailing = true flushDropping = dropped > 0 + setSaved(SavePart.HeartRate, failed = true) } } @@ -1269,6 +1327,11 @@ class WorkoutSession( private var flushFailing = false private var flushDropping = false + /** Records that [part]'s last save [failed] or worked, on the state as it is now. */ + private fun setSaved(part: SavePart, failed: Boolean) { + _state.update { s -> (s as? WorkoutState.Recording)?.withSave(part, failed) ?: s } + } + private fun now() = clock() /** To the strap's log, which the Device screen shows. */ diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt index 971b442b..d27d55a2 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutTileService.kt @@ -23,6 +23,9 @@ import org.openstrap.app.data.Workouts class WorkoutTileService : TileService() { private var watching: Job? = null + /** The sport Ready opens on when tapped idle: the last one done, as an id, never read back from the subtitle. */ + @Volatile private var readySport: Int = Workouts.DEFAULT_SPORTS.first() + override fun onStartListening() { super.onStartListening() val container = (application as OpenStrapApp).container @@ -31,12 +34,13 @@ class WorkoutTileService : TileService() { .collect { (state, last) -> val tile = qsTile ?: return@collect val r = state as? WorkoutState.Recording - tile.state = if (r != null) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE + readySport = last?.sportType ?: Workouts.DEFAULT_SPORTS.first() + tile.state = if (state.inProgress) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE tile.label = if (r != null) Workouts.sportName(r.workout.sportType) else getString(R.string.tile_workout) tile.subtitle = when { r?.paused == true -> getString(R.string.system_tile_paused) r != null -> getString(R.string.system_tile_recording) - else -> Workouts.sportName(last?.sportType ?: Workouts.DEFAULT_SPORTS.first()) + else -> Workouts.sportName(readySport) } tile.updateTile() } @@ -52,14 +56,11 @@ class WorkoutTileService : TileService() { override fun onClick() { super.onClick() val container = (application as OpenStrapApp).container - val recording = container.workout.state.value is WorkoutState.Recording + val inProgress = container.workout.inProgress val intent = Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) - if (recording) { - intent.putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true) - } else { - val last = (qsTile?.subtitle?.toString())?.let { name -> Workouts.sports.firstOrNull { it.second == name }?.first } - intent.putExtra(MainActivity.EXTRA_READY_SPORT, last ?: Workouts.DEFAULT_SPORTS.first()) - } + // Recording or showing its summary: the live screen or the summary, never Ready behind it. + if (inProgress) intent.putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true) + else intent.putExtra(MainActivity.EXTRA_READY_SPORT, readySport) val pending = PendingIntent.getActivity(this, REQUEST_TILE, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) if (Build.VERSION.SDK_INT >= 34) startActivityAndCollapse(pending) else @Suppress("DEPRECATION") startActivityAndCollapse(intent) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt index 1fc38c04..aea928dc 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/live/LiveFrame.kt @@ -198,6 +198,7 @@ internal fun LiveFrame( if (!connected && !r.paused) { PageNote(WorkoutCopy.STRAP_GONE_NOTE) } + if (r.endFailed) NotSavedNotice(controls.onEnd) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } if (!fill || r.paused) Spacer(Modifier.weight(1f)) FrameControls(r, controls, lap, labelled, paused != null, quiet, tapHint) @@ -244,6 +245,7 @@ private fun ColumnScope.LandscapePanes( // Beside a shared bar the moving time stays over the page, as it is upright. if (bar && time != null) MovingTime(time) if (!bar && !connected && !r.paused) PageNote(WorkoutCopy.STRAP_GONE_NOTE) + if (!bar && r.endFailed) NotSavedNotice(controls.onEnd) if (!bar) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } if (r.paused && paused != null) paused() else content() } @@ -441,6 +443,7 @@ internal fun LiveBottomBar( val density = androidx.compose.ui.platform.LocalDensity.current val items: @Composable ColumnScope.() -> Unit = { if (!connected) PageNote(WorkoutCopy.STRAP_GONE_NOTE) + if (r.endFailed) NotSavedNotice(controls.onEnd) r.endPrompt?.let { at -> StoppedPrompt(r, at, controls.onEndAtPrompt, controls.onKeepGoing) } val at = position() val view = stringResource(R.string.workout_live_view_of, kotlin.math.round(at).toInt() + 1, count) @@ -522,6 +525,16 @@ internal fun FlatButton(container: Color, size: Dp, modifier: Modifier = Modifie ) { content() } } +/** End was tried and couldn't save: the workout records on, and Try again runs End again. */ +@Composable +internal fun NotSavedNotice(onTryAgain: () -> Unit) { + QuietPanel { + GlowHeader(stringResource(R.string.workout_live_not_saved_title)) + PageNote(stringResource(R.string.workout_live_not_saved_note)) + WorkoutButton(stringResource(R.string.workout_live_try_again), Color.White, Color.Black, onTryAgain) + } +} + /** "Looks like you've stopped": end where the wearer stopped, or keep going. The strap has buzzed already. */ @Composable internal fun StoppedPrompt(r: WorkoutState.Recording, at: Long, onEnd: () -> Unit, onKeep: () -> Unit) { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt index 823a9e0b..92289010 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/WorkoutLayer.kt @@ -44,6 +44,7 @@ import org.openstrap.app.data.db.SavedWorkout import org.openstrap.app.device.ConnectionState import org.openstrap.app.device.WorkoutSession import org.openstrap.app.device.WorkoutState +import org.openstrap.app.device.inProgress import org.openstrap.app.device.locationAvailable import org.openstrap.app.presentation.SummaryRewards import org.openstrap.app.ui.dashboard.DayUiState @@ -228,7 +229,7 @@ internal fun BoxScope.WorkoutLayer( else -> Unit } // The ready screen comes and goes like any other screen, and a workout starting replaces it at once. - val recording = state is WorkoutState.Recording || state is WorkoutState.Ended + val recording = state.inProgress // Read once for both screens, and handed down to be read only there. val saved by remember { container.workout.savedWorkouts() }.collectAsStateWithLifecycle(emptyList()) // Choose sits under Ready, so closing Ready comes back to it. diff --git a/app/src/main/res/values-zh-rCN/strings_workout_live.xml b/app/src/main/res/values-zh-rCN/strings_workout_live.xml index 3899be7b..4e1ae61b 100644 --- a/app/src/main/res/values-zh-rCN/strings_workout_live.xml +++ b/app/src/main/res/values-zh-rCN/strings_workout_live.xml @@ -179,4 +179,8 @@ 使用此名称 当前 不命名,仅按组编号 + + 尚未保存 + 运动未能保存,仍在继续记录。 + 重试 diff --git a/app/src/main/res/values/strings_workout_live.xml b/app/src/main/res/values/strings_workout_live.xml index 0f6e8ba9..f4891f56 100644 --- a/app/src/main/res/values/strings_workout_live.xml +++ b/app/src/main/res/values/strings_workout_live.xml @@ -386,4 +386,11 @@ Now No name, just number the sets + + + Not saved yet + + The workout couldn\'t be saved, so it keeps recording. + + Try again 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 01294177..a28fcaee 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutSessionTest.kt @@ -712,6 +712,64 @@ class WorkoutSessionTest { assertNotNull(stored(t0)?.end) } + @Test + fun aFailedEndShowsOnTheLiveStateAndTryAgainEndsIt() { + val s = session() + val t0 = clock.now + s.start(sportType = 1) + s.recording() + clock.advance(Duration.ofSeconds(300)) + dao.failing = true + s.end() + val failed = s.recording { it.endFailed } + assertTrue(failed.saveFailed) + assertNull(stored(t0)?.end) + + // Try again is End again, and the flag goes once it saves. + dao.failing = false + s.end() + s.state.await { it is WorkoutState.Ended } + assertNotNull(stored(t0)?.end) + } + + @Test + fun aLaterSuccessDoesNotHideUnsavedSets() { + val s = session() + s.start(sportType = 1) + s.recording() + dao.failingSets = true + s.startSet() + s.recording { SavePart.Sets in it.failing } + // A lap saves the workout fine, and the sets are still unsaved. + clock.advance(Duration.ofSeconds(30)) + s.lap() + val r = s.recording { it.workout.lapMarks.isNotEmpty() } + assertTrue(SavePart.Sets in r.failing) + assertTrue(r.saveFailed) + + dao.failingSets = false + clock.advance(Duration.ofSeconds(5)) + s.setDone() + s.recording { it.failing.isEmpty() && !it.saveFailed } + } + + @Test + fun startSaysWhetherItStartedOrAWorkoutRecordsAlready() { + val s = session() + assertEquals(StartResult.Started, runBlocking { s.start(sportType = 1).await() }) + assertTrue(s.inProgress) + assertEquals(StartResult.AlreadyRecording, runBlocking { s.start(sportType = 2).await() }) + } + + @Test + fun startFailsWhenTheRowCantBeWritten() { + val s = session() + dao.failing = true + assertEquals(StartResult.Failed, runBlocking { s.start(sportType = 1).await() }) + assertTrue(!s.inProgress) + assertTrue(s.state.value is WorkoutState.Idle) + } + @Test fun theSeedIsRecordedBeforeTheLiveReadings() { val t0 = clock.now @@ -841,6 +899,8 @@ class WorkoutSessionTest { /** [HealthDao] that can fail every workout save, or hold the next one until released. */ private class SwitchableDao(private val real: HealthDao) : HealthDao by real { @Volatile var failing = false + /** Only the sets' saves fail. */ + @Volatile var failingSets = false @Volatile private var gate: Gate? = null class Gate { @@ -861,7 +921,7 @@ class WorkoutSessionTest { } override suspend fun upsertSets(sets: List) { - if (failing) throw android.database.sqlite.SQLiteException("disk I/O error") + if (failing || failingSets) throw android.database.sqlite.SQLiteException("disk I/O error") real.upsertSets(sets) } From 66e9fb1925c778729c008b25b1faa0512fa84500 Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 10:57:31 +0400 Subject: [PATCH 15/27] One day state: a swipe shows a placeholder until the day loads, and the picked day is saved DayViewModel builds one DayScreenState from one flatMapLatest on the shown day, so the day, Recovery (Loading, Ready or Failed), Healthspan, usual steps and activity carry the same date and start empty on a switch. The picked day goes in SavedStateHandle. The per-screen date checks are gone, and Sleep detail no longer shows No night before load. Co-Authored-By: Claude Sonnet 5.5 --- .../kotlin/org/openstrap/app/MainActivity.kt | 2 +- .../app/ui/dashboard/DayViewModel.kt | 165 +++++++++++------- .../openstrap/app/ui/glow/AllMetricsScreen.kt | 2 +- .../app/ui/glow/GlowActivityScreen.kt | 2 +- .../app/ui/glow/GlowRecoveryScreen.kt | 4 +- .../openstrap/app/ui/glow/GlowSleepScreen.kt | 2 +- .../openstrap/app/ui/glow/GlowTodayScreen.kt | 4 +- .../org/openstrap/app/ui/glow/ScoreDetail.kt | 2 +- .../org/openstrap/app/ui/glow/SleepDetail.kt | 5 +- .../openstrap/app/ui/root/AppRootViewModel.kt | 5 +- .../org/openstrap/app/ui/root/DetailHost.kt | 4 +- .../openstrap/app/ui/root/ShownDayState.kt | 26 ++- .../org/openstrap/app/ui/root/TabsPager.kt | 13 +- .../app/ui/root/ViewModelFactories.kt | 6 +- .../app/ui/dashboard/DeletedNightStateTest.kt | 13 +- .../app/ui/root/AppRootViewModelTest.kt | 2 +- 16 files changed, 165 insertions(+), 92 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt index eb2194aa..03ee49d9 100644 --- a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt +++ b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt @@ -361,7 +361,7 @@ private fun AppRoot( day, previewed.recovery, previewed.recoveryFailure, running != null, forced, workoutsVm, onNewDay = dayVm::select, ) val strap = rememberStrapHeader(strapFacts, day, preview) - val shown = rememberShownDay(previewed, dayVm, rootVm, today.clockDate, strap.now, preview, dataPreview) + val shown = rememberShownDay(previewed, rootVm, today.clockDate, strap.now, preview, dataPreview) val histories = remember(container) { Histories { m, from, to -> container.health.daily(m, from, to) } } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt index d4d22d29..23096031 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt @@ -1,6 +1,7 @@ package org.openstrap.app.ui.dashboard import android.util.Log +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher @@ -16,10 +17,12 @@ import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest +import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -140,10 +143,42 @@ data class DayUiState( /** The day's Recovery couldn't be worked out. [yesterday] is yesterday's score, shown dimmed in its place, when known. */ data class RecoveryFailure(val date: LocalDate, val yesterday: Int?) -/** Recovery worked out, or why not. */ -private sealed interface RecoveryOutcome { - data class Ready(val result: RecoveryResult) : RecoveryOutcome - data class Failed(val failure: RecoveryFailure) : RecoveryOutcome +/** The day's Recovery: being worked out, worked out, or why not. */ +sealed interface RecoveryState { + /** The first read for the day, or a retry after a failure. */ + data object Loading : RecoveryState + data class Ready(val result: RecoveryResult) : RecoveryState + data class Failed(val failure: RecoveryFailure) : RecoveryState +} + +/** + * Everything the screens show of one [date], emitted together so a number never sits under another day's date (audit + * S7). On a day switch it starts as [loading] for the new date: the day's rows, Recovery, Healthspan, usual steps and + * activity are all empty or loading until they arrive, and never the old day's. + */ +data class DayScreenState( + val date: LocalDate, + val day: DayUiState = DayUiState(date = date), + val recoveryState: RecoveryState = RecoveryState.Loading, + /** The weekly Healthspan estimate for [date], or why it's withheld; null while loading or on failure. */ + val healthspan: org.openstrap.app.data.Healthspan.Outcome? = null, + /** Your usual steps by the end of each hour, null until there are enough worn days. */ + val usualSteps: List? = null, + val activity: ActivityHistory = ActivityHistory(), +) { + /** The day's rows have arrived. */ + val loaded: Boolean get() = day.loaded + + /** Readiness and charge for [date]; null while loading or when it failed. */ + val recovery: RecoveryResult? get() = (recoveryState as? RecoveryState.Ready)?.result + + /** The day's Recovery failed to work out (spec 4.3), so the cards can say so instead of waiting forever. */ + val recoveryFailure: RecoveryFailure? get() = (recoveryState as? RecoveryState.Failed)?.failure + + companion object { + /** [date] before anything of it has arrived. */ + fun loading(date: LocalDate) = DayScreenState(date) + } } /** One day's Heart points: those earned that day and the 7-day total. */ @@ -214,13 +249,20 @@ class DayViewModel( dateChanges: Flow = emptyFlow(), /** Where the day's rows are worked into its state, off the main thread (audit C7). */ private val work: CoroutineDispatcher = Dispatchers.Default, + /** Keeps the day picked, so a restore reopens the same day. */ + private val saved: SavedStateHandle = SavedStateHandle(), ) : ViewModel() { /** Today as it moves, so a screen left open past midnight moves on to the new day (audit C10). */ private val today: StateFlow = Today.dates(clock, dateChanges) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), Today.on(clock())) /** The day picked, or null while the screen follows today. */ - private val picked = MutableStateFlow(null) + private val picked = MutableStateFlow(saved.get(PICKED_KEY)?.let(LocalDate::ofEpochDay)) + + private fun pick(date: LocalDate?) { + picked.value = date + saved[PICKED_KEY] = date?.toEpochDay() + } /** The day shown: the one picked while it's before today, else today. */ private val shown: Flow = combine(picked, today) { p, t -> @@ -228,22 +270,29 @@ class DayViewModel( ShownDay(date, date == t) }.distinctUntilChanged() - private val selected: Flow = shown.map { it.date }.distinctUntilChanged() - private fun shownNow(): LocalDate = Today.on(clock()).let { t -> picked.value?.takeIf { it < t } ?: t } - fun previousDay() { picked.value = shownNow().minusDays(1) } - fun nextDay() { picked.value = shownNow().plusDays(1).takeIf { it < Today.on(clock()) } } - fun select(date: LocalDate) { picked.value = date.takeIf { it < Today.on(clock()) } } + fun previousDay() { pick(shownNow().minusDays(1)) } + fun nextDay() { pick(shownNow().plusDays(1).takeIf { it < Today.on(clock()) }) } + fun select(date: LocalDate) { pick(date.takeIf { it < Today.on(clock()) }) } /** Days the calendar lets you pick. */ val daysWithData: StateFlow> = repo.daysWithData() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet()) - val state: StateFlow = shown.flatMapLatest { (date, isToday) -> repo.day(date, isToday) } - .map(::toUiState) + /** The day shown with all it needs, from one flow on the day shown, so it moves to a new day in one step. */ + val screen: StateFlow = shown.flatMapLatest { (date, isToday) -> + combine( + repo.day(date, isToday).map(::toUiState), + recoveryState(date), + healthspanOf(date), + usualStepsOf(date), + activityOf(date), + ) { day, recovery, healthspan, usual, activity -> DayScreenState(date, day, recovery, healthspan, usual, activity) } + .onStart { emit(DayScreenState.loading(date)) } + } .flowOn(work) - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DayUiState(date = Today.on(clock()))) + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DayScreenState.loading(shownNow())) /** Bumped by [retryRecovery], so the same day and data are worked out again. */ private val recoveryRetries = MutableStateFlow(0) @@ -274,33 +323,26 @@ class DayViewModel( @Volatile private var lastRecovery: RecoveryResult? = null /** - * Readiness and charge, recomputed (off the main thread) when the day, profile or synced data change: the result, - * or why there's none. Null while the first is worked out. + * [date]'s Readiness and charge, recomputed (off the main thread) when the profile or synced data change: Loading + * first, and again on a retry, then the result or why there's none. */ @OptIn(FlowPreview::class) - private val recoveryOutcome: StateFlow = - combine(selected, profile, repo.changes().debounce(800), recoveryRetries) { d, p, _, _ -> d to p } - .mapLatest { (d, p) -> + private fun recoveryState(date: LocalDate): Flow = recoveryRetries.flatMapLatest { + combine(profile, repo.changes().debounce(800)) { p, _ -> p } + .mapLatest { p -> withContext(work) { // mapLatest cancels this when newer data arrives. That's not a failure, and catching lets it through. - catching { repo.recovery(d, p) }.fold( - onSuccess = { RecoveryOutcome.Ready(it.also { r -> lastRecovery = r }) }, + catching { repo.recovery(date, p) }.fold( + onSuccess = { RecoveryState.Ready(it.also { r -> lastRecovery = r }) }, onFailure = { e -> Log.w("unstrap", "recovery failed", e) - RecoveryOutcome.Failed(RecoveryFailure(d, yesterdayScore(d, p))) + RecoveryState.Failed(RecoveryFailure(date, yesterdayScore(date, p))) }, ) } } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) - - /** Readiness and charge for the day shown; null while loading or when it failed ([recoveryFailure] tells which). */ - val recovery: StateFlow = recoveryOutcome.map { (it as? RecoveryOutcome.Ready)?.result } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) - - /** The day's Recovery failed to work out (spec 4.3), so the cards can say so instead of waiting forever. */ - val recoveryFailure: StateFlow = recoveryOutcome.map { (it as? RecoveryOutcome.Failed)?.failure } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) + .onStart { emit(RecoveryState.Loading) } + } /** * Yesterday's score for a failed [date]: from the last Recovery worked out when its week covers yesterday, else @@ -318,50 +360,47 @@ class DayViewModel( } /** - * Your usual steps by the end of each hour ([org.openstrap.app.data.UsualSteps]), from the 28 days before the day - * shown; null until there are enough worn days. Past days don't change through the day, so it's read once per day - * shown, off the main thread, not on every sync. + * Your usual steps by the end of each hour ([org.openstrap.app.data.UsualSteps]), from the 28 days before [d]; null + * until there are enough worn days. Past days don't change through the day, so it's read once, off the main thread, + * not on every sync. */ - val usualSteps: StateFlow?> = selected - .mapLatest { d -> + private fun usualStepsOf(d: LocalDate): Flow?> = flow { + emit(null) + emit( withContext(work) { catching { val from = d.minusDays(org.openstrap.app.data.UsualSteps.DAYS.toLong()) org.openstrap.app.data.UsualSteps.byHour(repo.hourlySteps(from, d.minusDays(1)), d) }.onFailure { Log.w("unstrap", "usual steps failed", it) }.getOrNull() - } - } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) + }, + ) + } - /** The weekly Healthspan estimate for the selected day, or why it's withheld; null while loading or on failure. */ + /** The weekly Healthspan estimate for [d], or why it's withheld; null while loading or on failure. */ @OptIn(FlowPreview::class) - val healthspan: StateFlow = - combine(selected, profile, repo.changes().debounce(800)) { d, p, _ -> d to p } - .mapLatest { (d, p) -> + private fun healthspanOf(d: LocalDate): Flow = + combine(profile, repo.changes().debounce(800)) { p, _ -> p } + .mapLatest { p -> withContext(work) { catching { repo.healthspan(d, p) }.onFailure { Log.w("unstrap", "healthspan failed", it) }.getOrNull() } } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null) - - /** Each day's Heart points and stored calories up to the day shown, for the Activity tab and its details. */ - val activityHistory: StateFlow = selected.flatMapLatest { d -> - combine( - repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d), - repo.dailyCalories(d.minusDays(ActivityHistory.CALORIES_DAYS - 1L), d), - stepsAndBest(d), - ) { pai, calories, (steps, best) -> - ActivityHistory( - date = d, - heartPoints = pai.mapValues { (_, p) -> HeartPointsDay(p.daily, p.total) }, - calories = calories.mapValues { (_, e) -> CaloriesDay(e.activeKcal, e.totalKcal, e.workoutKcal, e.partial) }, - steps = steps, - stepsBest = best, - ) - } - } - .flowOn(work) - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ActivityHistory()) + .onStart { emit(null) } + + /** Each day's Heart points and stored calories up to [d], for the Activity tab and its details. */ + private fun activityOf(d: LocalDate): Flow = combine( + repo.dailyPai(d.minusDays(ActivityHistory.HEART_POINTS_DAYS - 1L), d), + repo.dailyCalories(d.minusDays(ActivityHistory.CALORIES_DAYS - 1L), d), + stepsAndBest(d), + ) { pai, calories, (steps, best) -> + ActivityHistory( + date = d, + heartPoints = pai.mapValues { (_, p) -> HeartPointsDay(p.daily, p.total) }, + calories = calories.mapValues { (_, e) -> CaloriesDay(e.activeKcal, e.totalKcal, e.workoutKcal, e.partial) }, + steps = steps, + stepsBest = best, + ) + }.onStart { emit(ActivityHistory()) } /** * [d]'s steps from [ActivityHistory.STEPS_DAYS] days before it to its week's end, and the most steps of a day @@ -384,6 +423,8 @@ class DayViewModel( } companion object { + private const val PICKED_KEY = "pickedDay" + /** * [data] as the screens show it: the heart rate as a chart, the steps by hour, the trends with their weekday * labels and the stages as spans. diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt index 298b6cac..453a20fe 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/AllMetricsScreen.kt @@ -99,7 +99,7 @@ fun metricIndex( strapScore: Int? = null, strings: Strings = Strings.app, ): List { - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val (habitValue, habitStatus) = habitAgeRow(healthspan, strings) val weekFrom = state.date.minusDays(6) // The 7 days up to the day shown, not Your week's Monday to Sunday, so the row says so. The strap's own diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt index ea59e259..41753093 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowActivityScreen.kt @@ -169,7 +169,7 @@ fun GlowActivityScreen( } val stored = activity.heartPointsOn(state.date) val heartPoints = state.pai?.total ?: stored[state.date]?.total - val r = recovery?.takeIf { it.date == state.date } + val r = recovery val live = liveHeartRate?.takeIf { isToday } org.openstrap.app.ui.components.HoldLiveHeartRate(isToday) val slots = activityCards(ActivityFacts(isToday = isToday, suggestion = suggestion != null, live = live != null)) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt index f8b5e14c..f2654ff0 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowRecoveryScreen.kt @@ -118,8 +118,8 @@ fun GlowRecoveryScreen( ) { val list = rememberLazyListState() val signals = rememberSignals(state, history) - val r = recovery?.takeIf { it.date == state.date } - val failure = recoveryFailure?.takeIf { it.date == state.date && r == null } + val r = recovery + val failure = recoveryFailure?.takeIf { r == null } val learning = r?.readiness?.calibrating == true val firstNights = r != null && !r.charge.anchored val waiting = if (firstNights) AFTER_FIRST_NIGHT else NO_READING diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt index 1d02c4fb..2fa2246f 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowSleepScreen.kt @@ -102,7 +102,7 @@ fun GlowSleepScreen( onRestore: (org.openstrap.app.data.db.SleepSession) -> Unit = {}, ) { val list = rememberLazyListState() - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val breathing = rec?.breathingDisturbances // Before the strap has seen a night, cards keep their shape and wait (spec 4.3): breathing disturbances too. val firstNights = rec != null && !rec.charge.anchored && state.sleep == null diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt index bd7e357b..4d5ca2bc 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/GlowTodayScreen.kt @@ -207,7 +207,7 @@ fun GlowTodayScreen( val now = Instant.now() val isToday = state.date == now.atZone(zone).toLocalDate() org.openstrap.app.ui.components.HoldLiveHeartRate(isToday) - val rec = recovery?.takeIf { it.date == state.date } + val rec = recovery val lastWorkout = workouts.maxByOrNull { it.end } val ctx = TodayContext( state, rec, liveHeartRate, workouts, lastWorkout, isToday, now.epochSecond, zone, moment, @@ -216,7 +216,7 @@ fun GlowTodayScreen( stuck = strap.paired && syncStuck(isToday, state.asleepSeconds != null, strap.record.failingSince, now.epochSecond, zone), strapScore = strapScore, stopped = strap.stopped, staleAfter = strap.staleAfter, - recoveryFailure = recoveryFailure?.takeIf { it.date == state.date && rec == null }, + recoveryFailure = recoveryFailure?.takeIf { rec == null }, partial = partialTag.takeIf { wear?.partial == true }, firstScore = firstScore, ) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt index 9f791a69..586a1a10 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/ScoreDetail.kt @@ -75,7 +75,7 @@ fun GlowScoreDetailScreen( /** For the Sleep score and Naps details: moving, deleting and restoring a sleep or nap. */ sleepEditing: SleepEditing = SleepEditing(), ) { - val r = recovery?.takeIf { it.date == state.date } + val r = recovery when (score) { Score.Recovery -> RecoveryDetail(state, r, strapScore, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) Score.Energy -> ChargeDetail(state, r, history, onOpen, onSwitch, onSelectDay, contentPadding, onBack) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt index 04b89ee0..2e879884 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/glow/SleepDetail.kt @@ -173,6 +173,8 @@ internal fun SleepScoreDetail( score != null -> DetailHeadline(score.toString(), SleepCopy.scoreLabel(isToday), TabCopy.sleepScoreWord(score)) session == null && state.deletedSleep != null -> DetailHeadline.none(stringResource(R.string.glow_sleep_no_score), SleepCopy.noScoreDeleted(isToday)) + // The day's rows haven't arrived: nothing yet, not "No score". + !state.loaded -> DetailHeadline.none("", "") else -> SleepCopy.noScore(session != null, isToday).let { (word, why) -> DetailHeadline.none(word, why) } } @@ -194,7 +196,8 @@ internal fun SleepScoreDetail( if (session == null && deleted != null) { item { DeletedNight(SleepCopy.deletedNight(clock(deleted.start), clock(deleted.end), isToday)) { editing.restore(deleted.strap) } } } else if (session == null) { - item { DetailEmpty(TabCopy.noNight(state.naps.isNotEmpty(), isToday)) } + // Not before the day has loaded: an empty state isn't "No night". + if (state.loaded) item { DetailEmpty(TabCopy.noNight(state.naps.isNotEmpty(), isToday)) } } else { val asleep = state.asleepSeconds ?: (session.end - session.start) val detected = state.sleepAsDetected 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 9ced2911..d340e997 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 @@ -74,7 +74,8 @@ sealed interface FirstScoreDay { } /** The day shown's own extras: the check-in. The strap's score comes with its Recovery ([RecoveryResult.strapScore]). */ -data class DayExtras(val checkIn: Int? = null) +/** The check-in of [date], null while that day's is read. */ +data class DayExtras(val date: LocalDate? = null, val checkIn: Int? = null) /** A badge past history earned, with the weekly goal it was earned at when it is a goal badge. */ data class EarnedBadge(val badge: Rewards.Badge, val goal: Int?) @@ -185,7 +186,7 @@ class AppRootViewModel( /** The day shown's check-in, from [dayShown]. */ val dayExtras: StateFlow = shownDay.filterNotNull().flatMapLatest { date -> - health.checkIn(date).map { DayExtras(it?.feeling) } + health.checkIn(date).map { DayExtras(date, it?.feeling) } }.state(DayExtras()) init { diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt index 63089be8..d9b02eb5 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/DetailHost.kt @@ -72,7 +72,7 @@ internal fun DetailHost( val push: (Detail) -> Unit = { nav.push(tab, it) } val onSwitch: (Detail) -> Unit = { nav.replaceTop(tab, it) } val workouts by workoutsVm.workouts.collectAsStateWithLifecycle() - val activity by dayVm.activityHistory.collectAsStateWithLifecycle() + val activity = shown.activity when (detail) { // A night signal's detail is always the night's, as its rows read it (SleepCopy.NIGHT_SIGNALS). is Detail.OfMetric -> GlowMetricDetailScreen( @@ -88,7 +88,7 @@ internal fun DetailHost( ) Detail.Week -> WeekDetail( ActivityDetailContext( - day, shown.recovery?.takeIf { it.date == day.date }, workouts, activity, histories.daily, onOpen = push, onSwitch = {}, + day, shown.recovery, workouts, activity, histories.daily, onOpen = push, onSwitch = {}, onSelectDay = dayVm::select, onEditProfile = onOpenProfile, contentPadding = padding, onBack = pop, ), ) diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt index 0ad3fa59..70fb6236 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/ShownDayState.kt @@ -13,6 +13,7 @@ import java.time.LocalDate import org.openstrap.app.data.Recovery import org.openstrap.app.data.RecoveryResult import org.openstrap.app.ui.dashboard.DataPreview +import org.openstrap.app.ui.dashboard.DayScreenState import org.openstrap.app.ui.dashboard.DayUiState import org.openstrap.app.ui.dashboard.DayViewModel import org.openstrap.app.ui.dashboard.FirstScore @@ -26,7 +27,12 @@ import org.openstrap.app.ui.dashboard.wear private const val S_PER_MIN = 60 /** The day, its Recovery and a failed Recovery as the screens are shown them, the debug previews applied. */ -class PreviewedDay(val day: DayUiState, val recovery: RecoveryResult?, val recoveryFailure: RecoveryFailure?) +class PreviewedDay( + val screen: DayScreenState, + val day: DayUiState, + val recovery: RecoveryResult?, + val recoveryFailure: RecoveryFailure?, +) /** * The day shown with the debug previews applied: a strap [preview] of a failed Recovery shows the day as failed, with @@ -35,9 +41,10 @@ class PreviewedDay(val day: DayUiState, val recovery: RecoveryResult?, val recov */ @Composable internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, data: DataPreview?): PreviewedDay { - val realRecovery by dayVm.recovery.collectAsStateWithLifecycle() - val realRecoveryFailure by dayVm.recoveryFailure.collectAsStateWithLifecycle() - val realDay by dayVm.state.collectAsStateWithLifecycle() + val screen by dayVm.screen.collectAsStateWithLifecycle() + val realRecovery = screen.recovery + val realRecoveryFailure = screen.recoveryFailure + val realDay = screen.day val day = remember(realDay, data) { realDay.previewed(data) } val previewFailure = if (preview == StrapPreview.RecoveryFail) { realRecovery?.let { r -> RecoveryFailure(r.date, r.readinessTrend.firstOrNull { it.first == r.date.minusDays(1) }?.second) } @@ -45,7 +52,7 @@ internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, d null } val recovery = if (previewFailure != null) null else realRecovery?.previewed(data) - return PreviewedDay(day, recovery, previewFailure ?: realRecoveryFailure) + return PreviewedDay(screen, day, recovery, previewFailure ?: realRecoveryFailure) } /** @@ -55,7 +62,6 @@ internal fun rememberPreviewedDay(dayVm: DayViewModel, preview: StrapPreview?, d @Composable internal fun rememberShownDay( shown: PreviewedDay, - dayVm: DayViewModel, rootVm: AppRootViewModel, clockDate: LocalDate, now: Long, @@ -64,14 +70,15 @@ internal fun rememberShownDay( ): ShownDay { val day = shown.day val recovery = shown.recovery - val healthspan by dayVm.healthspan.collectAsStateWithLifecycle() LaunchedEffect(day.date) { rootVm.dayShown(day.date) } val dayExtras by rootVm.dayExtras.collectAsStateWithLifecycle() + // The check-in follows the day by its own flow, so it only counts once it's this day's. + val checkIn = dayExtras.takeIf { it.date == day.date }?.checkIn val dayIsToday = day.date == clockDate val wear = day.wear(recovery, dayIsToday) .previewed(data, (((if (dayIsToday) now else day.dayEnd + 1) - day.dayStart) / S_PER_MIN).toInt()) val firstScoreDay by rootVm.firstScoreDay.collectAsStateWithLifecycle() - val dayRecovery = recovery?.takeIf { it.date == day.date } + val dayRecovery = recovery val first = if (firstScoreDay == FirstScoreDay.Loading) { FirstScore(false) } else { @@ -84,7 +91,8 @@ internal fun rememberShownDay( if (preview == null && data == null) first.remember?.let(rootVm::markFirstScore) } return ShownDay( - day, recovery, shown.recoveryFailure, healthspan, dayExtras.checkIn, wear, + day, recovery, shown.recoveryFailure, shown.screen.healthspan, checkIn, wear, firstScore = first.show || data == DataPreview.FirstScoreShown, + loading = !shown.screen.loaded, usualSteps = shown.screen.usualSteps, activity = shown.screen.activity, ) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt index 0c9bacb5..5426128c 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/TabsPager.kt @@ -45,6 +45,7 @@ import org.openstrap.app.ui.components.sinkBehind import org.openstrap.app.ui.dashboard.DailyHistory import org.openstrap.app.ui.dashboard.DayPicker import org.openstrap.app.ui.dashboard.DayUiState +import org.openstrap.app.ui.dashboard.ActivityHistory import org.openstrap.app.ui.dashboard.DayViewModel import org.openstrap.app.ui.dashboard.Detail import org.openstrap.app.ui.dashboard.LocalScrollToTop @@ -94,9 +95,15 @@ class ShownDay( val wear: Wear?, /** The first real score shows its moment (E4). */ val firstScore: Boolean, + /** The day's rows haven't arrived yet: the screens show their placeholders, never another day's numbers. */ + val loading: Boolean = false, + /** Your usual steps by hour for the day shown, null until there are enough worn days. */ + val usualSteps: List? = null, + /** Heart points, calories and steps up to the day shown. */ + val activity: ActivityHistory = ActivityHistory(), ) { /** The strap's own score for the day shown's night, by the strap session it came from ([RecoveryResult.strapScore]). */ - val strapScore: Int? get() = recovery?.takeIf { it.date == day.date }?.strapScore + val strapScore: Int? get() = recovery?.strapScore } /** The stored histories the charts read. */ @@ -241,8 +248,8 @@ private fun TabRoot( ) { val day = shown.day val workouts by workoutsVm.workouts.collectAsStateWithLifecycle() - val usualSteps by dayVm.usualSteps.collectAsStateWithLifecycle() - val activity by dayVm.activityHistory.collectAsStateWithLifecycle() + val usualSteps = shown.usualSteps + val activity = shown.activity val suggestions by workoutsVm.suggestions.collectAsStateWithLifecycle() // Hidden while a workout records: the strap's history may show the one under way. val suggestion = suggestions.firstOrNull().takeIf { today.running == null } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt index 24018d8f..cb5c15da 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/ViewModelFactories.kt @@ -1,6 +1,7 @@ package org.openstrap.app.ui.root import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.createSavedStateHandle import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import kotlinx.coroutines.flow.StateFlow @@ -24,7 +25,10 @@ internal object ViewModelFactories { /** The day shown, which moves on to the new day as soon as the phone's date, time or time zone changes. */ fun day(c: AppContainer): ViewModelProvider.Factory = viewModelFactory { initializer { - DayViewModel(c.days, c.settings.profile, c.autoHealthConnect::sleepEdited, dateChanges = Today.changes(c.app)) + DayViewModel( + c.days, c.settings.profile, c.autoHealthConnect::sleepEdited, dateChanges = Today.changes(c.app), + saved = createSavedStateHandle(), + ) } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt index bbdfa6a8..2e1d7b17 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/dashboard/DeletedNightStateTest.kt @@ -53,8 +53,8 @@ class DeletedNightStateTest { db.healthDao().insertSleepSessions(listOf(before, night)) val repo = HealthRepository(db.healthDao()) val vm = DayViewModel(RoomDayRepository(repo, LiveSteps())) - val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.state.collect {} } - suspend fun settled(check: (DayUiState) -> Boolean) = vm.state.first { it.loaded && check(it) } + val collector = backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { vm.screen.collect {} } + suspend fun settled(check: (DayUiState) -> Boolean) = vm.screen.first { it.loaded && check(it.day) }.day settled { it.sleep != null }.let { s -> assertEquals(setOf(today.minusDays(1), today), s.nights.filter { it.session != null }.map { it.date }.toSet()) } repo.deleteSleep(night) @@ -69,4 +69,13 @@ class DeletedNightStateTest { } collector.cancel() } + + @Test fun `the picked day is saved, and a restored view model opens on it`() = runTest { + val today = LocalDate.now(ZoneId.systemDefault()) + val repo = RoomDayRepository(HealthRepository(db.healthDao()), LiveSteps()) + val handle = androidx.lifecycle.SavedStateHandle() + DayViewModel(repo, saved = handle).select(today.minusDays(3)) + val restored = DayViewModel(repo, saved = androidx.lifecycle.SavedStateHandle(mapOf("pickedDay" to handle.get("pickedDay")))) + assertEquals(today.minusDays(3), restored.screen.value.date) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt index 0a8908e6..05ae10ac 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/root/AppRootViewModelTest.kt @@ -129,7 +129,7 @@ class AppRootViewModelTest { assertEquals(4, await(vm.dayExtras) { it.checkIn != null }.checkIn) val next = day.plusDays(1) vm.dayShown(next) - assertEquals(DayExtras(), await(vm.dayExtras) { it.checkIn == null }) + assertEquals(DayExtras(next), await(vm.dayExtras) { it.date == next && it.checkIn == null }) } @Test fun `the strap facts follow the connection`() { From 200f3e6a9dab4e37865e87f9e5d1b55e163ff650 Mon Sep 17 00:00:00 2001 From: x Date: Tue, 10 Nov 2026 10:58:10 +0400 Subject: [PATCH 16/27] Workout notifications follow the session, End confirm stays, sticky after restore, Ready cleared on start WorkoutNotifier (app scope) owns Saved and the Keep recording cancel. The notice can no longer be cancelled by the session's late clear after the service's refusal. Undo only applies to the end it was posted for. End keeps its confirmation until end() finishes. START_STICKY follows the restored state and drops once nothing is in progress. Ready and Choose close whenever the session leaves Idle. Co-Authored-By: Claude Sonnet 5.5 --- .../kotlin/org/openstrap/app/MainActivity.kt | 1 + .../kotlin/org/openstrap/app/OpenStrapApp.kt | 3 + .../app/device/KeepRecordingNotice.kt | 30 ++++ .../org/openstrap/app/device/StrapService.kt | 145 ++++++++---------- .../openstrap/app/device/WorkoutNotifier.kt | 140 +++++++++++++++++ .../org/openstrap/app/ui/root/AppNavState.kt | 8 + .../app/ui/root/NavRequestsEffect.kt | 12 +- .../app/device/KeepRecordingNoticeTest.kt | 21 +++ .../app/device/WorkoutNotifierTest.kt | 81 ++++++++++ .../openstrap/app/ui/root/AppNavStateTest.kt | 13 ++ 10 files changed, 376 insertions(+), 78 deletions(-) create mode 100644 app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt create mode 100644 app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt diff --git a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt index eb2194aa..6264c28a 100644 --- a/app/src/main/kotlin/org/openstrap/app/MainActivity.kt +++ b/app/src/main/kotlin/org/openstrap/app/MainActivity.kt @@ -406,6 +406,7 @@ private fun AppRoot( strapOpened = { growFrom = growOrigin.take() }, showWorkout = { container.workout.minimized.value = false }, ), + container.workout.state, ) // Starting a workout closes Ready and Choose. [saved] is what Ready opens on next time for the sport, and Choose's // Start on your usual saves nothing new. diff --git a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt index a5b1cfd0..e1824c5d 100644 --- a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt +++ b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt @@ -52,6 +52,8 @@ class AppContainer(val app: Application) { app, database.healthDao(), settings, strap, maxHeartRates, callRinging = { phoneAlerts.callRinging }, onSaved = autoHealthConnect::workoutSaved, scope = appScope, ) + /** Saved and the Keep recording notice, from the session's state, on the app scope (audit S10). */ + val workoutNotifier = org.openstrap.app.device.WorkoutNotifier(app, workout.state, { database.healthDao().appWorkoutOnce(it) }, appScope) val updater = org.openstrap.app.update.AppUpdater( app, settings, recording = { workout.state.value is org.openstrap.app.device.WorkoutState.Recording }, scope = appScope, ) @@ -112,6 +114,7 @@ class OpenStrapApp : Application(), androidx.work.Configuration.Provider { container.companion.refresh() // A workout still recording when the process died carries on (the service restarts it too). container.workout.restore() + container.workoutNotifier.start() // Android restarts the process on its own (companion presence, a reboot): reconnect without the screen. // A no-op when nothing is paired, a connection is already up, or the user tapped Disconnect. if (BlePermissions.granted(this)) container.strap.backgroundConnect() diff --git a/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt b/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt index cbfc9c98..a4a57317 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/KeepRecordingNotice.kt @@ -73,7 +73,37 @@ object KeepRecordingNotice { context.getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, notification) } + /** + * Set while the service's own refusal is what the notice shows. The session clears the notice when its start call + * returns without throwing, which only says the start was queued: that clear can land after the service's refusal + * and cancel the one notice meant for it (audit S10), so [clear] leaves it alone then. + */ + @Volatile private var refusedByService = false + + /** The service was refused its foreground: asks for the tap, and holds the notice against [clear]. */ + fun serviceRefused(context: Context, sportType: Int) { + refusedByService = true + show(context, sportType) + } + + /** The service is in the foreground: the notice isn't needed. */ + fun serviceUp(context: Context) { + refusedByService = false + cancel(context) + } + + /** A start went through or a workout stopped: goes, unless the service itself was refused ([serviceRefused]). */ fun clear(context: Context) { + if (!refusedByService) cancel(context) + } + + /** Nothing records any more: goes in every case. [WorkoutNotifier] calls it as the session's state leaves Recording. */ + fun end(context: Context) { + refusedByService = false + cancel(context) + } + + private fun cancel(context: Context) { context.getSystemService(NotificationManager::class.java).cancel(NOTIFICATION_ID) } } diff --git a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt index d01b744a..f0f5c3d4 100644 --- a/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt +++ b/app/src/main/kotlin/org/openstrap/app/device/StrapService.kt @@ -18,7 +18,6 @@ import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChangedBy @@ -41,7 +40,6 @@ import org.openstrap.app.data.Workouts import org.openstrap.app.presentation.NotificationCopy import org.openstrap.app.presentation.StrapBands import org.openstrap.app.presentation.TimeOfDay -import org.openstrap.app.presentation.Units import org.openstrap.app.presentation.WorkoutColors import org.openstrap.app.presentation.WorkoutWords @@ -57,6 +55,13 @@ class StrapService : LifecycleService() { private var shown: Notification? = null /** The notification's End asks first: until this time (elapsed realtime) it shows "Yes, end" and "Cancel". */ private val confirmEnd = MutableStateFlow(0L) + /** + * "Yes, end" was tapped and [WorkoutSession.end] hasn't finished: the confirmation stays up so a tap on that spot + * can't land on Pause. Drops when the workout leaves Recording, or after [END_WAIT_MS] if the end failed. + */ + private val ending = MutableStateFlow(false) + /** What the last start command answered, so a workout ending can take the sticky restart back ([syncSticky]). */ + private var sticky = false /** Today's scores for the everyday notification, refreshed after each sync. */ private val figures = MutableStateFlow(null) /** @@ -94,13 +99,13 @@ class StrapService : LifecycleService() { if (!tryForeground(first, withGps, log) && (withGps == base || !tryForeground(first, base, log))) { (workout.state.value as? WorkoutState.Recording)?.let { log("service: no foreground while recording, asking to keep it going") - KeepRecordingNotice.show(this, it.workout.sportType) + KeepRecordingNotice.serviceRefused(this, it.workout.sportType) } stopSelf() return START_NOT_STICKY } foreground = true - KeepRecordingNotice.clear(this) + KeepRecordingNotice.serviceUp(this) } when (intent?.action) { // Debug: the workout card with sample figures as this service's notification, or ("clear") its own back. @@ -113,12 +118,11 @@ class StrapService : LifecycleService() { ACTION_RESUME -> workout.resume() ACTION_END_ASK -> confirmEnd.value = SystemClock.elapsedRealtime() + CONFIRM_MS ACTION_END_CANCEL -> confirmEnd.value = 0 - ACTION_END -> { confirmEnd.value = 0; workout.end() } + ACTION_END -> endConfirmed(workout) ACTION_SYNC -> strap.syncNow() ACTION_RETRY -> strap.autoConnect() - ACTION_UNDO -> intent.getLongExtra(EXTRA_START, 0).takeIf { it > 0 }?.let { - workout.undoTrim(it) - getSystemService(NotificationManager::class.java).cancel(SUMMARY_ID) + ACTION_UNDO -> intent.getLongExtra(EXTRA_START, 0).takeIf { it > 0 }?.let { start -> + undo(workout, dao, start, intent.getLongExtra(EXTRA_END, 0), intent.getLongExtra(EXTRA_RECORDED_END, 0)) } ACTION_END_AT -> workout.endAtPrompt() ACTION_KEEP -> workout.keepGoing() @@ -127,8 +131,7 @@ class StrapService : LifecycleService() { ACTION_SET_DONE -> workout.setDone() ACTION_EXTEND -> workout.extendRest() } - val recording = workout.state.value is WorkoutState.Recording - if (observing) return if (recording) START_STICKY else START_NOT_STICKY + if (observing) return stickiness(workout) observing = true // "End?" falls back to the usual actions if nobody answers. lifecycleScope.launch { confirmEnd.collectLatest { until -> if (until > 0) { delay(CONFIRM_MS); confirmEnd.value = 0 } } } @@ -143,13 +146,12 @@ class StrapService : LifecycleService() { } } } - lifecycleScope.launch { watchEnded(workout.state, dao) } lifecycleScope.launch { // Live HR changes about once a second, and every post wakes the CPU and redraws the system UI. // Connection, battery, charging and workout changes post at once; a bpm-only change waits for the refresh. var status: String? = null var lastPost = 0L - val more = combine(strap.sync, figures, hidden, confirmEnd) { sync, f, h, end -> More(sync, f, h, end) } + val more = combine(strap.sync, figures, hidden, confirmEnd, ending) { sync, f, h, end, asked -> More(sync, f, h, end, asked) } // Until the session has checked for a workout left recording (a restart after the process died), stay up. combine(strap.connection, strap.liveHeartRate, workout.state, workout.restored, more) { c, hr, w, restored, m -> Status(c, hr, w, restored, m) @@ -157,7 +159,9 @@ class StrapService : LifecycleService() { if (c is ConnectionState.Disconnected || c is ConnectionState.NotPaired) { if (w !is WorkoutState.Recording && restored) { stopSelf(); return@collect } } - val confirming = m.confirmEnd > SystemClock.elapsedRealtime() + if (w !is WorkoutState.Recording && m.ending) ending.value = false + syncSticky(workout) + val confirming = m.confirmEnd > SystemClock.elapsedRealtime() || m.ending val now = SystemClock.elapsedRealtime() val n: Notification if (w is WorkoutState.Recording) { @@ -184,7 +188,49 @@ class StrapService : LifecycleService() { getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, n) } } - return if (recording) START_STICKY else START_NOT_STICKY + return stickiness(workout) + } + + /** "Yes, end": the confirmation stays up until the workout has ended ([ending]), where it used to reset at once. */ + private fun endConfirmed(workout: WorkoutSession) { + ending.value = true + confirmEnd.value = 0 + workout.end() + lifecycleScope.launch { delay(END_WAIT_MS); ending.value = false } + } + + /** + * Saved's Undo: only while the workout is still as that notification left it (ended on its own, at the time it + * named). A trim made by hand since changes both, and is never undone from here. The notification goes either way. + */ + private fun undo(workout: WorkoutSession, dao: HealthDao, start: Long, end: Long, recordedEnd: Long) { + lifecycleScope.launch { + val w = catching { dao.appWorkoutOnce(start) }.getOrNull() + if (w != null && WorkoutNotifier.undoApplies(w, end, recordedEnd)) workout.undoTrim(start) + WorkoutNotifier.cancelSaved(this@StrapService) + } + } + + /** + * Sticky while a workout is in progress, or before the session has checked for one: a restart after the process + * died comes before [WorkoutSession.restore] finishes, and answering on that instant would drop the workout. + */ + private fun stickiness(workout: WorkoutSession): Int { + val s = workout.state.value + sticky = !workout.restored.value || s is WorkoutState.Recording || s is WorkoutState.Ended + return if (sticky) START_STICKY else START_NOT_STICKY + } + + /** + * A start command's answer holds until the next one, so once the session has checked and nothing is in progress, + * the service starts itself again to answer not sticky. + */ + private fun syncSticky(workout: WorkoutSession) { + val s = workout.state.value + if (sticky && workout.restored.value && s !is WorkoutState.Recording && s !is WorkoutState.Ended) { + sticky = false + catching { start(this) } + } } /** @@ -212,9 +258,6 @@ class StrapService : LifecycleService() { ) // Left by the old Quiet switch: Android raises a foreground service's MIN channel to LOW anyway. nm.deleteNotificationChannel("strap_quiet") - nm.createNotificationChannel( - NotificationChannel(SAVED_CHANNEL, getString(R.string.system_channel_saved), NotificationManager.IMPORTANCE_LOW), - ) WorkoutNotification.createChannel(this) KeepRecordingNotice.createChannel(this) // Left by workout auto-start ("Looks like a workout"), which is gone. @@ -474,59 +517,6 @@ class StrapService : LifecycleService() { WorkoutNotification.actions(paused = false, confirming = true, intent = ::service).forEach(::addAction) } - /** - * Once a workout is saved, a quiet summary with View, and Undo when it ended on its own (the stop or car question) - * and the time after was kept. It goes when the summary in the app is closed. - */ - private suspend fun watchEnded(workoutState: StateFlow, dao: HealthDao) { - val nm = getSystemService(NotificationManager::class.java) - var previous: WorkoutState? = null - workoutState.collect { st -> - val was = previous - previous = st - when { - st is WorkoutState.Ended && was is WorkoutState.Recording -> { - val w = dao.appWorkoutOnce(st.start) ?: return@collect - nm.notify(SUMMARY_ID, savedNotification(w)) - } - st !is WorkoutState.Ended -> nm.cancel(SUMMARY_ID) - } - } - } - - private fun savedNotification(w: org.openstrap.app.data.db.AppWorkout): Notification { - val end = w.end ?: System.currentTimeMillis() / 1000 - val duration = WorkoutRecorder.activeSeconds(w.copy(end = null, pausedAt = null), end) - val facts = listOfNotNull( - Units.workoutClock(duration), - w.distanceMeters?.let { Units.distance(it, Units.Precision.Workout, w.distanceFromSteps) }, - w.averageHeartRate?.let { getString(R.string.system_saved_average_bpm, it) }, - ).joinToString(", ") - val auto = w.endReason == org.openstrap.app.data.db.AppWorkout.END_AUTO || w.endReason == org.openstrap.app.data.db.AppWorkout.END_CAR - val cut = w.recordedEnd?.let { it - end }?.takeIf { auto && it >= 60 } - val time = TimeOfDay.format(end, java.time.ZoneId.systemDefault()) - val text = if (cut != null) getString(R.string.system_saved_cut, facts, time, (cut / 60).toInt()) else facts - val b = NotificationCompat.Builder(this, SAVED_CHANNEL) - .setSmallIcon(R.drawable.ic_stat_unstrap) - .setContentTitle(getString(R.string.system_saved_title, Workouts.sportName(w.sportType))) - .setContentText(facts) - .setStyle(NotificationCompat.BigTextStyle().bigText(text)) - .setCategory(NotificationCompat.CATEGORY_WORKOUT) - .setAutoCancel(true) - .setContentIntent(openApp()) - .addAction(NotificationCompat.Action(0, getString(R.string.system_saved_action_view), openApp())) - if (cut != null) b.addAction( - NotificationCompat.Action( - 0, getString(R.string.system_saved_action_undo), - PendingIntent.getService( - this, REQUEST_UNDO, Intent(this, StrapService::class.java).setAction(ACTION_UNDO).putExtra(EXTRA_START, w.start), - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, - ), - ), - ) - return b.build() - } - /** Strength on the lock screen: the set or the rest counting down, its progress, and the next step. */ private fun strengthNotification(r: WorkoutState.Recording, bpm: Int?, connected: Boolean, confirming: Boolean, zones: HeartZones): Notification { val now = System.currentTimeMillis() @@ -617,7 +607,7 @@ class StrapService : LifecycleService() { PendingIntent.getService(this, action.hashCode(), Intent(this, StrapService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE) private data class Status(val connection: ConnectionState, val heartRate: Int?, val workout: WorkoutState, val restored: Boolean, val more: More) - private data class More(val sync: SyncState, val figures: Figures?, val hidden: Hidden?, val confirmEnd: Long) + private data class More(val sync: SyncState, val figures: Figures?, val hidden: Hidden?, val confirmEnd: Long, val ending: Boolean) private data class Hidden(val problem: String?) private data class Figures( val recovery: Int?, val charge: Int?, val sport: Int, val syncedAt: Long?, @@ -631,14 +621,15 @@ class StrapService : LifecycleService() { internal const val ACTION_END_CANCEL = "org.openstrap.app.workout.END_CANCEL" private const val ACTION_SYNC = "org.openstrap.app.strap.SYNC" private const val ACTION_RETRY = "org.openstrap.app.strap.RETRY" - private const val ACTION_UNDO = "org.openstrap.app.workout.UNDO" + internal const val ACTION_UNDO = "org.openstrap.app.workout.UNDO" private const val ACTION_HIDE = "org.openstrap.app.strap.HIDE" - private const val EXTRA_START = "start" - private const val SUMMARY_ID = 4 - private const val SAVED_CHANNEL = "workout_saved" + internal const val EXTRA_START = "start" + internal const val EXTRA_END = "end" + internal const val EXTRA_RECORDED_END = "recorded_end" private const val REQUEST_START = 5 - private const val REQUEST_UNDO = 6 private const val CONFIRM_MS = 6_000L + /** How long "Yes, end" stays up for an end that hasn't finished; a failed end brings the usual actions back. */ + private const val END_WAIT_MS = 15_000L private const val FIGURES_REFRESH_MS = 30 * 60_000L /** The red dot in the "OS." logo, the app's heart colour: zone 5's red. */ private const val BRAND_DOT = WorkoutColors.ZONE_5 @@ -656,7 +647,7 @@ class StrapService : LifecycleService() { private const val ACTION_EXTEND = "org.openstrap.app.workout.EXTEND" /** Each zone's length on the notification's progress bar. */ private const val ZONE_SPAN = 20 - private const val REQUEST_OPEN = 2 + internal const val REQUEST_OPEN = 2 /** Whether the service is up; a start then needn't (and, once swiped away, mustn't) post its notification. */ @Volatile var running = false diff --git a/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt b/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt new file mode 100644 index 00000000..008028a1 --- /dev/null +++ b/app/src/main/kotlin/org/openstrap/app/device/WorkoutNotifier.kt @@ -0,0 +1,140 @@ +package org.openstrap.app.device + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.core.app.NotificationCompat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import org.openstrap.app.MainActivity +import org.openstrap.app.R +import org.openstrap.app.data.WorkoutRecorder +import org.openstrap.app.data.Workouts +import org.openstrap.app.data.catching +import org.openstrap.app.data.db.AppWorkout +import org.openstrap.app.presentation.TimeOfDay +import org.openstrap.app.presentation.Units + +/** + * Owns the workout notifications that outlive [StrapService]: Saved, and the Keep recording notice. Both follow the + * session's state and live on the app scope, so a service that stops itself, or a fresh one, can't orphan, drop or + * cancel one (audit S10). The ongoing workout notification stays the service's: it is the foreground notification, and + * Android removes it with the service. + */ +class WorkoutNotifier( + context: Context, + private val state: StateFlow, + /** The stored workout by its start. */ + private val workoutOnce: suspend (Long) -> AppWorkout?, + private val scope: CoroutineScope, +) { + private val context = context.applicationContext + private var previous: WorkoutState? = null + + /** Follows the session from now on. */ + fun start() { + scope.launch { state.collect { sync(it) } } + } + + /** + * Posts and cancels from [st]: Saved once a workout is saved, and gone as soon as the summary is closed or another + * workout starts; the Keep recording notice gone as soon as nothing records. + */ + suspend fun sync(st: WorkoutState) { + val was = previous + previous = st + if (st !is WorkoutState.Recording) KeepRecordingNotice.end(context) + when { + st is WorkoutState.Ended && was is WorkoutState.Recording -> { + val w = catching { workoutOnce(st.start) }.getOrNull() ?: return + // The summary may already be closed by the time the read returns. + if (state.value == st) notifySaved(w) + } + st !is WorkoutState.Ended -> cancelSaved(context) + } + } + + private fun notifySaved(w: AppWorkout) { + val nm = context.getSystemService(NotificationManager::class.java) + nm.createNotificationChannel( + NotificationChannel(SAVED_CHANNEL, context.getString(R.string.system_channel_saved), NotificationManager.IMPORTANCE_LOW), + ) + nm.notify(SUMMARY_ID, savedNotification(w)) + } + + private fun openApp(): PendingIntent = PendingIntent.getActivity( + context, StrapService.REQUEST_OPEN, + Intent(context, MainActivity::class.java).putExtra(MainActivity.EXTRA_SHOW_WORKOUT, true).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + + /** + * A quiet summary with View, and Undo when it ended on its own (the stop or car question) and the time after was + * kept. Undo carries the end it was posted for, so it can tell a later trim by hand ([undoApplies]). + */ + private fun savedNotification(w: AppWorkout): Notification { + val end = w.end ?: System.currentTimeMillis() / 1000 + val duration = WorkoutRecorder.activeSeconds(w.copy(end = null, pausedAt = null), end) + val facts = listOfNotNull( + Units.workoutClock(duration), + w.distanceMeters?.let { Units.distance(it, Units.Precision.Workout, w.distanceFromSteps) }, + w.averageHeartRate?.let { context.getString(R.string.system_saved_average_bpm, it) }, + ).joinToString(", ") + val cut = cutSeconds(w) + val time = TimeOfDay.format(end, java.time.ZoneId.systemDefault()) + val text = if (cut != null) context.getString(R.string.system_saved_cut, facts, time, (cut / 60).toInt()) else facts + val b = NotificationCompat.Builder(context, SAVED_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_unstrap) + .setContentTitle(context.getString(R.string.system_saved_title, Workouts.sportName(w.sportType))) + .setContentText(facts) + .setStyle(NotificationCompat.BigTextStyle().bigText(text)) + .setCategory(NotificationCompat.CATEGORY_WORKOUT) + .setAutoCancel(true) + .setContentIntent(openApp()) + .addAction(NotificationCompat.Action(0, context.getString(R.string.system_saved_action_view), openApp())) + if (cut != null) b.addAction( + NotificationCompat.Action( + 0, context.getString(R.string.system_saved_action_undo), + PendingIntent.getService( + context, REQUEST_UNDO, + Intent(context, StrapService::class.java).setAction(StrapService.ACTION_UNDO) + .putExtra(StrapService.EXTRA_START, w.start) + .putExtra(StrapService.EXTRA_END, end) + .putExtra(StrapService.EXTRA_RECORDED_END, w.recordedEnd ?: 0L), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ), + ), + ) + return b.build() + } + + companion object { + internal const val SUMMARY_ID = 4 + internal const val SAVED_CHANNEL = "workout_saved" + private const val REQUEST_UNDO = 6 + private const val MIN_CUT_S = 60 + + /** The time an automatic end left out, in seconds, when it is long enough to offer Undo for. */ + internal fun cutSeconds(w: AppWorkout): Long? { + val end = w.end ?: return null + val auto = w.endReason == AppWorkout.END_AUTO || w.endReason == AppWorkout.END_CAR + return w.recordedEnd?.let { it - end }?.takeIf { auto && it >= MIN_CUT_S } + } + + /** + * Whether Undo, posted for a workout that ended at [end] with [recordedEnd] recorded, may still be applied: only + * while it is as it was left, an automatic end. A trim by hand since is a user end at another time. + */ + internal fun undoApplies(w: AppWorkout, end: Long, recordedEnd: Long): Boolean = + w.end == end && w.recordedEnd == recordedEnd && + (w.endReason == AppWorkout.END_AUTO || w.endReason == AppWorkout.END_CAR) + + fun cancelSaved(context: Context) { + context.getSystemService(NotificationManager::class.java).cancel(SUMMARY_ID) + } + } +} diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt index eb8417b7..a2e88075 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/AppNavState.kt @@ -264,6 +264,14 @@ class AppNavState(initial: Snapshot = Snapshot()) { workout = WorkoutOverlay.None } + /** + * The session left Idle, however it started (the app, the tile, the strap): Ready and Choose close, so neither + * comes back after the summary. Also closes one a request opened while the summary showed. + */ + fun sessionInProgress() { + if (workout != WorkoutOverlay.None) workout = WorkoutOverlay.None + } + /** Your zones, over Ready. */ fun openZones() { (workout as? WorkoutOverlay.Ready)?.let { workout = it.copy(zones = true) } diff --git a/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt b/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt index e108e69a..4cdf3d9e 100644 --- a/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt +++ b/app/src/main/kotlin/org/openstrap/app/ui/root/NavRequestsEffect.kt @@ -2,19 +2,29 @@ package org.openstrap.app.ui.root import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import org.openstrap.app.NavRequest import org.openstrap.app.NavigationRequests +import org.openstrap.app.device.WorkoutState import org.openstrap.app.ui.dashboard.Detail +import kotlinx.coroutines.flow.StateFlow /** * What a notification, a widget, the tile or a shortcut asked for, each once and in the order asked. A request sent * before the first frame waits for it. */ @Composable -internal fun NavRequestsEffect(requests: NavigationRequests, nav: AppNavState, hooks: NavRequestHooks) { +internal fun NavRequestsEffect( + requests: NavigationRequests, nav: AppNavState, hooks: NavRequestHooks, session: StateFlow, +) { val current by rememberUpdatedState(hooks) + // Whatever started the workout, Ready and Choose go with it; re-run if one is opened while it is in progress. + val state by session.collectAsState() + val inProgress = state is WorkoutState.Recording || state is WorkoutState.Ended + val overlay = nav.workout + LaunchedEffect(inProgress, overlay) { if (inProgress) nav.sessionInProgress() } LaunchedEffect(requests, nav) { requests.requests.collect { r -> val h = current diff --git a/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt b/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt index 100dbe54..3c10d7b8 100644 --- a/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/device/KeepRecordingNoticeTest.kt @@ -49,4 +49,25 @@ class KeepRecordingNoticeTest { service.destroy() } } + + @Test + fun aClearThatLandsAfterTheServicesRefusalLeavesTheNoticeUp() { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + // The session's start call returned without throwing, after the service had already been refused. + KeepRecordingNotice.clear(context) + assertNotNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + KeepRecordingNotice.serviceUp(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } + + @Test + fun theNoticeGoesWhenNothingRecordsEvenAfterTheServicesRefusal() { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + KeepRecordingNotice.end(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + // And a plain clear works again afterwards. + KeepRecordingNotice.show(context, sportType = 1) + KeepRecordingNotice.clear(context) + assertNull(shadowOf(manager).getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } } diff --git a/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt b/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt new file mode 100644 index 00000000..15e4090d --- /dev/null +++ b/app/src/test/kotlin/org/openstrap/app/device/WorkoutNotifierTest.kt @@ -0,0 +1,81 @@ +package org.openstrap.app.device + +import android.app.NotificationManager +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.openstrap.app.data.db.AppWorkout + +/** Saved and the Keep recording notice follow the session's state, whatever the service is doing (audit S10). */ +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class WorkoutNotifierTest { + private val context = ApplicationProvider.getApplicationContext() + private val manager = shadowOf(context.getSystemService(NotificationManager::class.java)) + private val start = 1_000_000L + private val state = MutableStateFlow(WorkoutState.Idle) + private val stored = AppWorkout( + start = start, end = start + 1_200, sportType = 1, endReason = AppWorkout.END_AUTO, recordedEnd = start + 1_800, + ) + + private fun notifier(scope: TestScope) = WorkoutNotifier(context, state, { stored }, scope) + + private fun recording() = WorkoutState.Recording(stored.copy(end = null, recordedEnd = null), maxHeartRate = 190) + + private fun saved() = manager.getNotification(WorkoutNotifier.SUMMARY_ID) + + @Test + fun savedPostsWhenARecordingEndsAndGoesWhenTheSummaryCloses() = runTest { + val n = notifier(this) + n.sync(recording()) + assertNull(saved()) + state.value = WorkoutState.Ended(start) + n.sync(state.value) + assertNotNull(saved()) + state.value = WorkoutState.Idle + n.sync(WorkoutState.Idle) + assertNull(saved()) + } + + @Test + fun aFreshNotifierDoesNotPostSavedForAnEndedStateItNeverSawRecording() = runTest { + state.value = WorkoutState.Ended(start) + notifier(this).sync(state.value) + assertNull(saved()) + } + + @Test + fun theKeepRecordingNoticeGoesWhenTheSessionStopsRecording() = runTest { + KeepRecordingNotice.serviceRefused(context, sportType = 1) + val n = notifier(this) + n.sync(recording()) + assertNotNull(manager.getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + n.sync(WorkoutState.Idle) + assertNull(manager.getNotification(KeepRecordingNotice.NOTIFICATION_ID)) + } + + @Test + fun undoOnlyAppliesWhileTheWorkoutIsAsTheNotificationLeftIt() { + assertTrue(WorkoutNotifier.undoApplies(stored, stored.end!!, stored.recordedEnd!!)) + // A trim by hand: a user end at another time. + val trimmed = stored.copy(end = start + 900, endReason = AppWorkout.END_USER) + assertFalse(WorkoutNotifier.undoApplies(trimmed, stored.end!!, stored.recordedEnd!!)) + // Trimmed by hand to the same end, still a user end. + assertFalse(WorkoutNotifier.undoApplies(stored.copy(endReason = AppWorkout.END_USER), stored.end!!, stored.recordedEnd!!)) + assertEquals(600L, WorkoutNotifier.cutSeconds(stored)) + } +} diff --git a/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt b/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt index 869dca45..7020ee95 100644 --- a/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt +++ b/app/src/test/kotlin/org/openstrap/app/ui/root/AppNavStateTest.kt @@ -130,6 +130,19 @@ class AppNavStateTest { assertEquals(WorkoutOverlay.None, nav.workout) } + @Test + fun `a session in progress closes Ready and Choose however it started`() { + val nav = AppNavState() + nav.openChoose() + nav.openReady(5) + nav.sessionInProgress() + assertEquals(WorkoutOverlay.None, nav.workout) + // A request opening Ready during the summary is closed again by the same effect. + nav.apply(NavRequest.OpenReady(4), recording = false, firmwareInstalling = false) + nav.sessionInProgress() + assertEquals(WorkoutOverlay.None, nav.workout) + } + @Test fun `an update installing keeps its pages open`() { val nav = AppNavState(AppNavState.Snapshot(pages = listOf(Page.Strap, Page.Firmware))) From fb2ff1f9282159074d2fe9e43bd1a35c4b4e24dc Mon Sep 17 00:00:00 2001 From: Sayed Ameer Date: Tue, 10 Nov 2026 11:00:58 +0400 Subject: [PATCH 17/27] Sync status kept once and read by the app and widgets, Bluetooth off as a state, companion prompt cancel only hides the offer S5: SyncCoordinator persists the last full sync and the failing-since time. The header, the Strap page and the widgets read that one status. A push sync no longer moves the Synced time, and busy now covers the work after a sync. S12: ConnectionState.BluetoothOff with a Turn on action on the Strap page, the notification and widgets. Companion: Back on Android's prompt hides the offer for now, a real failure falls back to the battery setting. Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/openstrap/app/OpenStrapApp.kt | 1 + .../app/data/settings/SettingsStore.kt | 33 +++++++++-- .../org/openstrap/app/device/CompanionLink.kt | 23 ++++++-- .../openstrap/app/device/ConnectionManager.kt | 30 ++++++++-- .../openstrap/app/device/StrapController.kt | 18 +++++- .../org/openstrap/app/device/StrapService.kt | 12 +++- .../openstrap/app/device/SyncCoordinator.kt | 58 +++++++++++++++---- .../openstrap/app/ui/device/DeviceScreen.kt | 54 +++++++++++++---- .../app/ui/device/DeviceViewModel.kt | 10 +++- .../org/openstrap/app/ui/glow/ReadyScreen.kt | 3 +- .../org/openstrap/app/ui/root/StrapHeader.kt | 4 +- .../org/openstrap/app/ui/workout/ReadyHero.kt | 2 +- .../org/openstrap/app/ui/workout/StartCopy.kt | 3 +- .../org/openstrap/app/widget/StrapStatus.kt | 38 +++++++++--- .../org/openstrap/app/widget/WidgetParts.kt | 14 +++-- .../org/openstrap/app/widget/WidgetRefresh.kt | 4 +- .../openstrap/app/widget/WidgetSnapshot.kt | 5 ++ .../openstrap/app/widget/WidgetStatusLine.kt | 3 +- .../openstrap/app/widget/WidgetTriggers.kt | 19 ++++-- .../org/openstrap/app/widget/WidgetUpdater.kt | 3 + .../strings_system_notifications.xml | 2 + .../values-zh-rCN/strings_system_widgets.xml | 3 + .../res/values-zh-rCN/strings_you_strap.xml | 2 + .../values/strings_system_notifications.xml | 2 + .../res/values/strings_system_widgets.xml | 3 + app/src/main/res/values/strings_you_strap.xml | 2 + .../app/data/settings/ForgetDeviceTest.kt | 11 +++- .../openstrap/app/device/StrapConnectTest.kt | 11 ++++ .../openstrap/app/device/SyncRecordTest.kt | 11 ++++ .../openstrap/app/ui/device/StrapPageTest.kt | 11 ++++ .../openstrap/app/widget/StrapStatusTest.kt | 16 +++++ .../app/widget/WidgetTriggersTest.kt | 35 +++++++++++ 32 files changed, 380 insertions(+), 66 deletions(-) diff --git a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt index a5b1cfd0..d84037ec 100644 --- a/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt +++ b/app/src/main/kotlin/org/openstrap/app/OpenStrapApp.kt @@ -81,6 +81,7 @@ class AppContainer(val app: Application) { workoutState = { workout.state.value }, location = { org.openstrap.app.device.locationAvailable(app) }, placed = { org.openstrap.app.widget.placedWidgets(app) }, + bluetoothOff = { strap.connection.value == org.openstrap.app.device.ConnectionState.BluetoothOff }, ) /** The moment as the Moment widget reads it, for the strap's notification: its name, lead and Today's sentence. */ diff --git a/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt b/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt index a95b01aa..bae210ac 100644 --- a/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt +++ b/app/src/main/kotlin/org/openstrap/app/data/settings/SettingsStore.kt @@ -102,7 +102,14 @@ data class BackupState( val on get() = folder != null } -data class StrapSnapshot(val paired: Boolean, val battery: Int?, val charging: Boolean, val lastSyncDone: Long?) +data class StrapSnapshot( + val paired: Boolean, + val battery: Int?, + val charging: Boolean, + val lastSyncDone: Long?, + /** When the syncs began to fail since [lastSyncDone] (epoch seconds), null while they work. */ + val failingSince: Long? = null, +) /** * Auto sync to Health Connect: [on] or off (off by default), when OpenStrap last wrote there ([lastSynced], epoch @@ -621,13 +628,17 @@ class SettingsStore private constructor(private val store: DataStore = read { prefs -> - StrapSnapshot(prefs[address] != null && prefs[authKey] != null, prefs[strapBattery], prefs[strapCharging] == true, prefs[syncDone]) + StrapSnapshot( + prefs[address] != null && prefs[authKey] != null, prefs[strapBattery], prefs[strapCharging] == true, prefs[syncDone], + prefs[syncFailingSince], + ) } /** The connected strap's battery and charging, written when either changes. */ @@ -638,9 +649,20 @@ class SettingsStore private constructor(private val store: DataStore