Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1142,6 +1142,9 @@ because breaking it fails silently:
`AccuracyScorer.SCORING_VERSION`: finished checks otherwise keep their stored result forever,
and an outdated one is re-scored once by itself (app launch, or opening the accuracy screen).
Corrections already accepted are not touched by a re-score.
- **Reaching back over past days moves grading, never the pause** (`historyFrom`, v39). Grading
starts at `gradeFrom`; `startedAt`, the day count and every `pausedFrom` stay at the real start.
Never before the ring was paired, for the same no-device-id reason as the next rule.
- **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started
from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split
the two rings' data.
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@
"Allow camera access in Settings to scan barcodes, or enter the food manually instead.": "Permita o acesso à câmera em Configurações para ler códigos de barras, ou insira o alimento manualmente.",
"Allow installs from this app, then tap Update again.": "Permita instalações deste app e toque em Atualizar de novo.",
"Allow more": "Permitir mais",
"Also grading the days since {0}.": "Avaliando também os dias desde {0}.",
"Always": "Sempre",
"Always on: paired AI tools on this network can read your health data. Tap to stop.": "Sempre ligado: ferramentas de IA pareadas nesta rede podem ler seus dados de saúde. Toque para parar.",
"An LLM-native health app that turns a cheap Bluetooth smart ring into a real, conversational health tracker. It talks to the ring directly over Bluetooth — no vendor cloud, no account — and layers an AI coach on top of your own data.": "Um app de saúde nativo de LLM que transforma um anel inteligente Bluetooth barato em um monitor de saúde de verdade, com conversa. Ele se comunica com o anel diretamente via Bluetooth — sem nuvem do fabricante, sem conta — e adiciona um coach de IA sobre os seus próprios dados.",
Expand Down Expand Up @@ -916,6 +917,8 @@
"In sync": "Em sincronia",
"In the Oura app: Settings → Health Connect, and turn on sharing. Then come back and look again.": "No app Oura: Configurações → Health Connect, e ative o compartilhamento. Depois volte e verifique novamente.",
"Inactivity": "Inatividade",
"Include": "Incluir",
"Include past days": "Incluir dias passados",
"Includes {0} added by you, not staged or scored": "Inclui {0} adicionados por você, sem fase nem pontuação",
"Increase duration by 5 minutes": "Aumentar a duração em 5 minutos",
"Increase {0}": "Aumentar {0}",
Expand Down Expand Up @@ -1303,6 +1306,7 @@
"On. PulseLoop syncs your ring about every 30 minutes, even while the phone is idle.": "Ativado. O PulseLoop sincroniza seu anel a cada 30 minutos, mesmo com o celular ocioso.",
"Once per dose, at its time, for what you add with + Log → Medication or supplement.": "Uma vez por dose, no horário, para o que você adicionar em + Registrar → Medicamento ou suplemento.",
"One tap for the usual ones": "Um toque para as de sempre",
"Only days since this ring was paired. The Health Connect export isn't affected: those days were exported already.": "Só os dias desde que este anel foi pareado. A exportação para o Health Connect não muda: esses dias já foram exportados.",
"Only needed if you started the server with --api-key. Leave blank otherwise.": "Só é necessário se você iniciou o servidor com --api-key. Caso contrário, deixe em branco.",
"Only new data from now on": "Apenas dados novos daqui em diante",
"Only providers that don't retain data": "Apenas provedores que não retêm dados",
Expand Down Expand Up @@ -2147,6 +2151,7 @@
"Your preference: ": "Sua preferência: ",
"Your resting heart rate is up on last week. Prioritise recovery and sleep.": "Sua frequência cardíaca em repouso subiu em relação à semana passada. Priorize recuperação e sono.",
"Your ring and phone agree within 5% ({0} days).": "Seu anel e seu celular concordam dentro de 5% ({0} dias).",
"Your ring and the reference already hold past days. Grading them too gives an answer sooner.": "Seu anel e a referência já guardam dias passados. Avaliá-los também dá uma resposta mais cedo.",
"Your ring counts about {0}% fewer steps than your phone ({1} days).": "Seu anel conta cerca de {0}% menos passos que seu celular ({1} dias).",
"Your ring counts about {0}% more steps than your phone ({1} days).": "Seu anel conta cerca de {0}% mais passos que seu celular ({1} dias).",
"Your ring logs heart rate every few minutes, so short sessions may show none.": "Seu anel registra a frequência cardíaca a cada poucos minutos, então sessões curtas podem não mostrar nenhuma.",
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/com/pulseloop/data/DataArchive.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ data class PulseArchive(
val state: String, val endReason: String? = null, val resumeChoice: String? = null,
val bandsRaw: String? = null, val pauseRefreshedAt: Long? = null, val scoredAt: Long? = null,
val firmware: String? = null,
val historyFrom: Long? = null,
)

@Serializable data class AccuracyPausedUnitDTO(val checkId: String, val unit: String, val pausedFrom: Long)
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/com/pulseloop/data/DataArchiveService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,7 @@ object DataArchiveService {
state = c.str("state"), endReason = c.strOrNull("endReason"), resumeChoice = c.strOrNull("resumeChoice"),
bandsRaw = c.strOrNull("bandsRaw"), pauseRefreshedAt = c.longOrNull("pauseRefreshedAt"),
scoredAt = c.longOrNull("scoredAt"), firmware = c.strOrNull("firmware"),
historyFrom = c.longOrNull("historyFrom"),
)
},
accuracyPausedUnits = collect("accuracy_paused_units") { c ->
Expand Down Expand Up @@ -506,6 +507,7 @@ object DataArchiveService {
referenceLabel = a.referenceLabel, startedAt = a.startedAt, plannedEndAt = a.plannedEndAt,
endedAt = a.endedAt, state = a.state, endReason = a.endReason, resumeChoice = a.resumeChoice,
bandsRaw = a.bandsRaw, pauseRefreshedAt = a.pauseRefreshedAt, scoredAt = a.scoredAt, firmware = a.firmware,
historyFrom = a.historyFrom,
))
}
if (archive.accuracyPausedUnits.isNotEmpty()) {
Expand Down
10 changes: 9 additions & 1 deletion app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ import com.pulseloop.data.entity.*
LabResultEntity::class,
ComparisonReadingEntity::class,
],
version = 38,
version = 39,
exportSchema = false,
)
abstract class PulseLoopDatabase : RoomDatabase() {
Expand Down Expand Up @@ -730,6 +730,13 @@ abstract class PulseLoopDatabase : RoomDatabase() {
}
}

/** v39: an accuracy check can grade past days (`historyFrom`). */
private val MIGRATION_38_39 = object : Migration(38, 39) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE `accuracy_checks` ADD COLUMN `historyFrom` INTEGER")
}
}

private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) {
db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`")
db.execSQL(
Expand Down Expand Up @@ -834,6 +841,7 @@ abstract class PulseLoopDatabase : RoomDatabase() {
MIGRATION_35_36,
MIGRATION_36_37,
MIGRATION_37_38,
MIGRATION_38_39,
)
// Downgrades only (sideloading an older APK). A blanket destructive
// fallback would silently wipe every measurement, sleep session, and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,15 @@ data class AccuracyCheckEntity(
val scoredAt: Long? = null,
/** The ring's firmware when the check started, so a correction can tell it went stale. */
val firmware: String? = null,
/**
* Where grading starts when the check also covers past days ([startedAt] is still when the
* check, and the export pause, began). Null = from [startedAt].
*/
val historyFrom: Long? = null,
) {
/** The first moment the check grades: [historyFrom] when it reaches back, else [startedAt]. */
val gradeFrom: Long get() = historyFrom?.coerceAtMost(startedAt) ?: startedAt

val isOpen: Boolean get() = state == STATE_RUNNING || state == STATE_AWAITING_RESUME

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import com.pulseloop.health.HealthConnectPrefsStore
import com.pulseloop.health.HealthConnectSdk
import kotlinx.coroutines.sync.withLock
import java.time.Instant
import java.time.ZoneId
import kotlin.reflect.KClass

/** Which ring a check or a correction belongs to. */
Expand Down Expand Up @@ -45,6 +46,9 @@ object AccuracyCheckController {
private const val TAG = "AccuracyCheck"
val DURATIONS_DAYS = listOf(3, 5, 7, 14)
const val DEFAULT_DAYS = 7
/** Past days a check can also grade, from what the app and Health Connect already hold. */
val LOOK_BACK_DAYS = listOf(0, 7, 14, 30)
const val DEFAULT_LOOK_BACK_DAYS = 14
private const val DAY_MS = 86_400_000L

sealed interface StartResult {
Expand All @@ -59,6 +63,7 @@ object AccuracyCheckController {
source: ReferenceSourceSurvey,
referenceLabel: String,
days: Int,
lookBackDays: Int = 0,
now: Long = System.currentTimeMillis(),
): StartResult {
val db = PulseLoopDatabase.getInstance(context)
Expand All @@ -76,6 +81,7 @@ object AccuracyCheckController {
plannedEndAt = now + days.coerceAtLeast(DURATIONS_DAYS.first()) * DAY_MS,
pauseRefreshedAt = now,
firmware = ring.firmwareVersion,
historyFrom = historyStart(now, lookBackDays, ring.createdAt),
)
dao.upsert(check)
dao.insertPausedUnits(units.map { AccuracyPausedUnitEntity(check.id, it.name, pausedFrom = now) })
Expand All @@ -84,6 +90,38 @@ object AccuracyCheckController {
return StartResult.Started(check)
}

/**
* Where grading starts for a check that also covers [lookBackDays] past days: local midnight
* that many days ago, but never before this ring was paired ([ringPairedAt]), because ring
* rows carry no device id and an earlier ring's days would be graded as this one's. Null when
* there is nothing to reach back over. The export pause is unaffected: past days were
* exported long ago, and the reference reads filter on `DataOrigin`, so those exports can't
* come back as the reference.
*/
fun historyStart(now: Long, lookBackDays: Int, ringPairedAt: Long, zone: ZoneId = ZoneId.systemDefault()): Long? {
if (lookBackDays <= 0) return null
val midnight = Instant.ofEpochMilli(now).atZone(zone).toLocalDate().minusDays(lookBackDays.toLong())
.atStartOfDay(zone).toInstant().toEpochMilli()
return maxOf(midnight, ringPairedAt).takeIf { it < now }
}

/**
* Widens a running check to also grade [lookBackDays] past days. Only ever moves grading
* earlier; the end and the export pause stay as they are. Returns the widened check.
*/
suspend fun includePastDays(context: Context, lookBackDays: Int, now: Long = System.currentTimeMillis()): AccuracyCheckEntity? {
val db = PulseLoopDatabase.getInstance(context)
val dao = db.accuracyDao()
val check = dao.open()?.takeIf { it.state == AccuracyCheckEntity.STATE_RUNNING } ?: return null
val ring = db.deviceDao().currentReal() ?: return null
val start = historyStart(now, lookBackDays, ring.createdAt) ?: return check
if (start >= check.gradeFrom) return check
val widened = check.copy(historyFrom = start, scoredAt = null)
dao.upsert(widened)
Log.i(TAG, "${check.id} now grades from ${Instant.ofEpochMilli(start)}")
return widened
}

/** RUNNING → AWAITING_RESUME. Export stays paused until [resolve]. */
suspend fun end(context: Context, reason: String, at: Long = System.currentTimeMillis()): AccuracyCheckEntity? {
val dao = PulseLoopDatabase.getInstance(context).accuracyDao()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ object AccuracyScorer {
val dao = db.accuracyDao()
val client = HealthConnectClient.getOrCreate(context)
val zone = ZoneId.systemDefault()
val from = check.startedAt
val from = check.gradeFrom
val to = check.endedAt ?: minOf(now, check.plannedEndAt)
val readable = AccuracyCheckPermissions.readable(ReferenceSourceScanner.grantedPermissions(context))
val compared = dao.pausedUnits(check.id).mapNotNull { ExportUnit.byName(it.unit)?.metric }.toSet() intersect readable
Expand All @@ -125,7 +125,7 @@ object AccuracyScorer {
out += r.records
token = r.pageToken
pages++
} while (token != null && pages < 40)
} while (token != null && pages < 150) // a check reaching 30 days back reads a month of samples
return out
}

Expand Down
55 changes: 50 additions & 5 deletions app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,9 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) {
context = context,
source = src,
onDismiss = { starting = null },
onStart = { label, days ->
onStart = { label, days, lookBack ->
scope.launch {
note = when (AccuracyCheckController.start(context, src, label, days)) {
note = when (AccuracyCheckController.start(context, src, label, days, lookBack)) {
is AccuracyCheckController.StartResult.Started -> null
AccuracyCheckController.StartResult.AlreadyOpen -> tr("A check is already open.")
AccuracyCheckController.StartResult.NoRing -> tr("Pair your ring first.")
Expand All @@ -267,7 +267,8 @@ internal object AccuracyUiText {
/** "Oct 21" / "21 de out.": the locale's own order and month names, never a forced "d MMM". */
fun date(ms: Long): String = com.pulseloop.ui.components.PhoneFormat.date("MMMd", ms)

fun span(c: AccuracyCheckEntity): String = "${date(c.startedAt)} – ${date(c.endedAt ?: c.plannedEndAt)}"
/** What the check grades: from its earliest past day when it reaches back. */
fun span(c: AccuracyCheckEntity): String = "${date(c.gradeFrom)} – ${date(c.endedAt ?: c.plannedEndAt)}"

fun dayOf(c: AccuracyCheckEntity, now: Long = System.currentTimeMillis()): Pair<Int, Int> {
val total = ((c.plannedEndAt - c.startedAt + 43_200_000L) / 86_400_000L).toInt().coerceAtLeast(1)
Expand All @@ -285,20 +286,61 @@ internal object AccuracyUiText {
ExportUnit.entries.filter { it in units }.joinToString(", ") { it.metric.label.lowercase() }.replaceFirstChar { it.uppercase() }
}

/** Past-days choice: none (from today), or 7 / 14 / 30 days back. Wraps, like "How long". */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun LookBackChips(selected: Int, includeNone: Boolean = true, onPick: (Int) -> Unit) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
AccuracyCheckController.LOOK_BACK_DAYS.filter { includeNone || it > 0 }.forEach { d ->
FilterChip(
selected = selected == d, onClick = { onPick(d) },
label = { Text(if (d == 0) tr("None") else trf("{0} days", d)) },
)
}
}
}

@Composable
private fun RunningCard(check: AccuracyCheckEntity, scope: kotlinx.coroutines.CoroutineScope) {
val context = LocalContext.current
val db = remember { PulseLoopDatabase.getInstance(context) }
val paused by remember(db) { db.accuracyDao().allPausedUnitsFlow() }.collectAsState(initial = emptyList())
val units = paused.filter { it.checkId == check.id }.mapNotNull { ExportUnit.byName(it.unit) }
var confirmEnd by remember { mutableStateOf(false) }
var pickPast by remember { mutableStateOf(false) }
val (day, total) = AccuracyUiText.dayOf(check)
AccuracyCard {
Text(trf("Accuracy check · day {0} of {1}", day, total), fontSize = 16.sp, fontWeight = FontWeight.Bold, color = com.pulseloop.ui.calm.Look.text)
Text(trf("{0} vs {1}, until {2}.", check.deviceLabel, check.referenceLabel, AccuracyUiText.date(check.plannedEndAt)), fontSize = 14.sp, color = com.pulseloop.ui.calm.Look.textSecondary)
Text(trf("Wear both as usual. Health Connect export paused for: {0}.", AccuracyUiText.units(units)), fontSize = 12.sp, color = PulseColors.warning)
if (check.historyFrom == null) {
Text(tr("Your ring and the reference already hold past days. Grading them too gives an answer sooner."), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary)
PulseButton(PulseButtonStyle.Tonal, onClick = { pickPast = true }) { Text(tr("Include past days")) }
} else {
Text(trf("Also grading the days since {0}.", AccuracyUiText.date(check.gradeFrom)), fontSize = 12.sp, color = com.pulseloop.ui.calm.Look.textSecondary)
}
PulseButton(PulseButtonStyle.Outlined, onClick = { confirmEnd = true }) { Text(tr("End now")) }
}
if (pickPast) {
var lookBack by remember { mutableStateOf(AccuracyCheckController.DEFAULT_LOOK_BACK_DAYS) }
AlertDialog(
onDismissRequest = { pickPast = false },
title = { Text(tr("Include past days")) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
LookBackChips(lookBack, includeNone = false) { lookBack = it }
Text(tr("Only days since this ring was paired. The Health Connect export isn't affected: those days were exported already."), fontSize = 12.sp)
}
},
confirmButton = {
PulseButton(PulseButtonStyle.Text, onClick = {
pickPast = false
scope.launch { AccuracyCheckController.includePastDays(context, lookBack) }
}) { Text(tr("Include")) }
},
dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = { pickPast = false }) { Text(tr("Cancel")) } },
)
}
if (confirmEnd) {
AlertDialog(
onDismissRequest = { confirmEnd = false },
Expand Down Expand Up @@ -347,7 +389,7 @@ private fun StartDialog(
context: Context,
source: ReferenceSourceSurvey,
onDismiss: () -> Unit,
onStart: (label: String, days: Int) -> Unit,
onStart: (label: String, days: Int, lookBackDays: Int) -> Unit,
) {
val defaultLabel = remember(source) {
val app = ReferenceAppLabels.label(context, source.packageName)
Expand All @@ -356,6 +398,7 @@ private fun StartDialog(
}
var label by remember { mutableStateOf(defaultLabel) }
var days by remember { mutableStateOf(AccuracyCheckController.DEFAULT_DAYS) }
var lookBack by remember { mutableStateOf(AccuracyCheckController.DEFAULT_LOOK_BACK_DAYS) }
val units = source.metrics.map { ExportUnit.of(it.metric) }
AlertDialog(
onDismissRequest = onDismiss,
Expand All @@ -376,14 +419,16 @@ private fun StartDialog(
FilterChip(selected = days == d, onClick = { days = d }, label = { Text(trf("{0} days", d)) })
}
}
Text(tr("Include past days"), fontSize = 14.sp, fontWeight = FontWeight.SemiBold)
LookBackChips(lookBack) { lookBack = it }
Text(
trf("Compared: {0}. These stop exporting to Health Connect until the check ends and you choose what to do with those days.", AccuracyUiText.units(units)),
fontSize = 12.sp,
)
Text(tr("Wear both devices as you normally would, including at night."), fontSize = 12.sp)
}
},
confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { onStart(label.trim(), days) }) { Text(tr("Start")) } },
confirmButton = { PulseButton(PulseButtonStyle.Text, onClick = { onStart(label.trim(), days, lookBack) }) { Text(tr("Start")) } },
dismissButton = { PulseButton(PulseButtonStyle.Text, onClick = onDismiss) { Text(tr("Cancel")) } },
)
}
Expand Down
Loading
Loading