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
18 changes: 18 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1243,6 +1243,24 @@ clutter came from ignoring one of them:
- **A goal saved anywhere goes through `GoalSync.afterManualSave`** — it is what stops the field
following the coach, sends the step goal to the ring and republishes the widget.

## Detected workouts: guess the type, ask, learn (docs/activity-recognition-plan.md)

The rings give no raw accelerometer, so `ActivityClassifier` guesses from step cadence and
burstiness and from heart-rate level and unevenness. Every type is ranked; the user always picks.
Rules a change must keep:

- **Nothing is logged without a tap.** A wrong workout reaches Health Connect and Strava.
- **The user's answers win.** A confirmed suggestion stores its features with the chosen type
(`activity_detection` → `learned`, newest 200, in the backup). Close earlier answers outweigh
the rules, so don't tune the rules to override them.
- **"Not this" holds by overlap, not by key** (`ActivityDetection.open`): a re-detection with
shifted bounds or a changed guess must not resurface a dismissed stretch.
- **Steps and heart stretches merge into one window** (`mergeActive`), so a run is never also
offered as cardio.
- **Notify once, recent only** (`ActivityDetectionNotifier`): after a sync's `done`, for
activity ending in the last 12 h, never twice for the same stretch, behind its own switch and
channel. Today shows the newest as one line; the Activity tab's card is where it is answered.

## Logging a food again: suggestions come from the user's own history

Typing a meal's name in the Log Meal form offers foods logged before (`service/FoodHistory.kt`,
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/assets/i18n/pt-BR.json
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@
"After 3 or more": "Depois de 3 ou mais",
"After 3 or more drinks, your HRV runs {0}% {1} than on dry nights.": "Depois de 3 ou mais bebidas, sua HRV fica {0}% {1} do que nas noites sem álcool.",
"After a session": "Depois de uma sessão",
"After a sync, what your ring saw you doing (a walk, a ride, strength training), to add with a tap. Nothing is logged without you.": "Depois de uma sincronização, o que seu anel viu você fazendo (uma caminhada, um pedal, musculação), para adicionar com um toque. Nada é registrado sem você.",
"After birth, sleep is broken rather than short. The longest unbroken stretch is the number to watch; it usually grows over the first months.": "Depois do parto, o sono fica fragmentado, mais do que curto. O maior trecho sem interrupção é o número a acompanhar; ele costuma crescer nos primeiros meses.",
"After the period, until about two weeks before the next one.": "Depois da menstruação, até cerca de duas semanas antes da próxima.",
"Against your {0} dry nights since you started. A pattern in your data, not proof of cause.": "Comparado com suas {0} noites sem álcool desde que começou. Um padrão nos seus dados, não prova de causa.",
Expand Down Expand Up @@ -476,6 +477,8 @@
"Details": "Detalhes",
"Detect server & configure": "Detectar servidor e configurar",
"Detected by PulseLoop and confirmed": "Detectado pelo PulseLoop e confirmado",
"Detected workout notifications": "Notificações de treinos detectados",
"Detected workouts": "Treinos detectados",
"Detecting…": "Detectando…",
"Developer": "Desenvolvedor",
"Developer options are already enabled.": "As opções de desenvolvedor já estão ativadas.",
Expand Down Expand Up @@ -878,7 +881,13 @@
"Long-term insights appear as more nights are tracked.": "Insights de longo prazo aparecem conforme mais noites são registradas.",
"Look again": "Verificar novamente",
"Looking for apps writing to Health Connect…": "Procurando apps que gravam no Health Connect…",
"Looks like a hike": "Parece uma trilha",
"Looks like a ride": "Parece um pedal",
"Looks like a run": "Parece uma corrida",
"Looks like a strong night after a more active day. Your duration was solid and deep sleep made up a healthy part of the night, which kept the score high.": "Parece uma noite forte depois de um dia mais ativo. A duração foi boa e o sono profundo ocupou uma parte saudável da noite, o que manteve a pontuação alta.",
"Looks like a walk": "Parece uma caminhada",
"Looks like a workout": "Parece um treino",
"Looks like strength training": "Parece musculação",
"Low": "Baixo",
"Low (medication)": "Baixa (medicação)",
"Low Battery Notifications": "Notificações de bateria fraca",
Expand Down Expand Up @@ -1292,6 +1301,7 @@
"Resume": "Retomar",
"Retake (every 3 months)": "Refazer (a cada 3 meses)",
"Retry": "Tentar novamente",
"Review": "Revisar",
"Review & adjust": "Revisar e ajustar",
"Ride it out": "Aguentar firme",
"Right at your limit": "Exatamente no seu limite",
Expand Down Expand Up @@ -1730,6 +1740,7 @@
"What affects you": "O que afeta você",
"What changed": "O que mudou",
"What did you do?": "O que você fez?",
"What your ring saw you doing, to add with a tap": "O que seu anel viu você fazendo, para adicionar com um toque",
"What's your goal?": "Qual é a sua meta?",
"When": "Quando",
"When did it end?": "Quando terminou?",
Expand Down Expand Up @@ -1921,6 +1932,7 @@
"{0} markers outside the lab's range in your latest report. Talk them over with your doctor.": "{0} marcadores fora da faixa do laboratório no seu último laudo. Converse sobre eles com seu médico.",
"{0} min a night less than your usual over the last 7 nights.": "{0} min por noite a menos que o seu habitual nas últimas 7 noites.",
"{0} min a night more than your usual over the last 7 nights.": "{0} min por noite a mais que o seu habitual nas últimas 7 noites.",
"{0} min at {1}. Tap to add it, or say it wasn't.": "{0} min às {1}. Toque para adicionar, ou diga que não foi.",
"{0} min {1} sleep": "{0} min de sono {1}",
"{0} ml at {1}% · about {2} kcal": "{0} ml a {1}% · cerca de {2} kcal",
"{0} more dry day{1} to reach {2}": "Mais {0} dia{1} sem álcool para chegar a {2}",
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/com/pulseloop/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@ class MainActivity : ComponentActivity() {
} else if (intent?.action == ACTION_OPEN_ACCURACY_CHECK) {
com.pulseloop.ui.LaunchRequests.route.value = "settings/accuracy-check"
intent.action = null
} else if (intent?.action == ACTION_OPEN_ACTIVITY) {
// A detected-workout notification: the suggestion waits on the Activity tab.
com.pulseloop.ui.LaunchRequests.route.value = "activity"
intent.action = null
}
}

Expand All @@ -180,6 +184,8 @@ class MainActivity : ComponentActivity() {
const val ACTION_LOG_MEAL = "com.pulseloop.action.LOG_MEAL"
/** The accuracy-report-ready notification. */
const val ACTION_OPEN_ACCURACY_CHECK = "com.pulseloop.action.OPEN_ACCURACY_CHECK"
/** A detected-workout notification (ActivityDetectionNotifier). */
const val ACTION_OPEN_ACTIVITY = "com.pulseloop.action.OPEN_ACTIVITY"
}

private fun handleStravaRedirect(intent: Intent) {
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ class PulseLoopApplication : Application() {
// Accuracy check: a different ring ends a running check at once (it can't be told apart later).
com.pulseloop.health.accuracy.AccuracyRingWatcher.start(this, appScope)
com.pulseloop.health.accuracy.AccuracyNotifications.createChannel(this)
// What the ring saw the user doing, said after each sync (docs/activity-recognition-plan.md).
com.pulseloop.notifications.ActivityDetectionNotifier.createChannel(this)
com.pulseloop.notifications.ActivityDetectionNotifier.start(this, appScope)
// One-time cleanup of activity totals corrupted by the old bucket handling; runs off the
// main thread and is prefs-gated so it executes once. Safe to race the first sync — the
// ring can't connect before this completes a couple of DELETE statements.
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/com/pulseloop/data/ArchivedSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ object ArchivedSettings {
"mindful_sessions" to emptySet(),
// The phone-step calibration and its daily counts. The raw step counter is this phone's.
"step_calibration" to setOf("lastCounter"),
// Detected workouts and naps already answered, so they aren't asked again.
"activity_detection" to emptySet(),
// Detected workouts: what was answered (not asked again), the types the user taught the
// classifier ("learned"), and the notification switch. Which ones notified stays here.
"activity_detection" to setOf("notified"),
// Rest Mode, while it lasts.
"rest_mode" to emptySet(),
// Whether the coach may use the lab results.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.pulseloop.notifications

import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.pulseloop.MainActivity
import com.pulseloop.data.PulseLoopDatabase
import com.pulseloop.ring.PulseEvent
import com.pulseloop.ring.PulseEventBus
import com.pulseloop.service.ActivityDetection
import com.pulseloop.ui.i18n.tr
import com.pulseloop.ui.i18n.trf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

/**
* After each completed sync, says what the ring saw the user doing ("Looks like strength
* training · 45 min at 18:10"). One notification per new suggestion, only for activity that ended
* in the last 12 hours, never twice for the same stretch. Tapping opens the Activity tab, where
* the user confirms, changes the type or dismisses it. See docs/activity-recognition-plan.md.
*/
object ActivityDetectionNotifier {
private const val CHANNEL_ID = "detected_workouts"
private const val RECENT_MS = 12 * 60 * 60_000L

fun createChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, tr("Detected workouts"), NotificationManager.IMPORTANCE_DEFAULT)
.apply { description = tr("What your ring saw you doing, to add with a tap") }
(context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)
}
}

/** Application-scoped, like the accuracy watcher: runs whether or not a screen is open. */
fun start(context: Context, scope: CoroutineScope) {
val app = context.applicationContext
scope.launch {
PulseEventBus.events
.filter { it is PulseEvent.SyncProgress && it.stage == CoachNotificationDataTrigger.DONE_STAGE }
.collectLatest {
// Let the sync's last rows land and back-to-back completions coalesce.
delay(5_000L)
runCatching { kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) { check(app) } }
}
}
}

suspend fun check(context: Context, now: Long = System.currentTimeMillis()) {
if (!ActivityDetection.notifyEnabled(context)) return
val db = PulseLoopDatabase.getInstance(context)
val already = ActivityDetection.notified(context)
val fresh = ActivityDetection.load(context, db, days = 1, now = now)
.filter { it.kind != ActivityDetection.Proposal.Kind.NAP && it.endAt >= now - RECENT_MS && it.key !in already }
if (fresh.isEmpty()) return
// Marked before delivery: a missing permission must not make every later sync retry it.
ActivityDetection.markNotified(context, fresh.map { it.key })
fresh.take(2).forEach { deliver(context, it) }
}

/** "a ride", "strength training": how the notification names a guessed type. */
fun phrase(type: String): String = when (type) {
"walk" -> tr("Looks like a walk")
"run" -> tr("Looks like a run")
"cycle" -> tr("Looks like a ride")
"gym" -> tr("Looks like strength training")
"hike" -> tr("Looks like a hike")
else -> tr("Looks like a workout")
}

private fun deliver(context: Context, p: ActivityDetection.Proposal) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) return
val time = Instant.ofEpochMilli(p.startAt).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("HH:mm"))
val intent = Intent(context, MainActivity::class.java)
.setAction(MainActivity.ACTION_OPEN_ACTIVITY)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pending = PendingIntent.getActivity(context, p.key.hashCode(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val n = NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(phrase(p.bestType))
.setContentText(trf("{0} min at {1}. Tap to add it, or say it wasn't.", p.minutes, time))
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
.setContentIntent(pending)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
NotificationManagerCompat.from(context).notify(p.key.hashCode(), n)
}
}
112 changes: 112 additions & 0 deletions app/src/main/java/com/pulseloop/service/ActivityClassifier.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.pulseloop.service

import kotlin.math.sqrt

/**
* What a stretch of movement probably was, from what every ring syncs: step cadence and how
* bursty it is, and how high and how uneven heart rate ran. See docs/activity-recognition-plan.md.
*
* Rules give the first guess; the user's own earlier answers win once there are some close to
* this stretch. Every type is returned, best first, because the user always picks: this only
* decides which one is selected and what order the rest come in.
*/
object ActivityClassifier {

data class Features(
val minutes: Double,
/** Steps per minute over the whole stretch. */
val cadence: Double,
/** Coefficient of variation of the per-bucket cadence: sets with steps between them read high. */
val stepBurst: Double,
/** Mean heart rate as a share of heart-rate reserve (0 = quiet level, 1 = HRmax). */
val hrMeanPct: Double,
/** 90th-percentile heart rate as a share of heart-rate reserve. */
val hrPeakPct: Double,
/** Coefficient of variation of the heart-rate readings: intervals and sets read high. */
val hrCv: Double,
)

/** A stretch the user labelled, kept to steer later guesses. */
data class Example(val features: Features, val type: String)

/** The types a guess can name, in ActivityMeta's own order for the ones rules can't tell apart. */
val TYPES = listOf("walk", "run", "cycle", "gym", "sport", "hike", "dance", "yoga", "squash", "other")

fun features(
startAt: Long,
endAt: Long,
steps: List<Pair<Long, Int>>,
hr: List<Pair<Long, Double>>,
quiet: Double,
hrMax: Double,
): Features {
val minutes = ((endAt - startAt) / 60_000.0).coerceAtLeast(1.0)
val inSteps = steps.filter { it.first in startAt until endAt }.sortedBy { it.first }
val cadence = inSteps.sumOf { it.second } / minutes
// Bucket length from the data itself: families sync 1- to 15-minute buckets.
val bucketMin = inSteps.zipWithNext { a, b -> (b.first - a.first) / 60_000.0 }.filter { it > 0 }.minOrNull() ?: 15.0
val perBucket = inSteps.map { it.second / bucketMin }
val stepBurst = cv(perBucket).takeIf { perBucket.size >= 3 } ?: 0.0
val bpm = hr.filter { it.first in startAt..endAt }.map { it.second }
val reserve = (hrMax - quiet).coerceAtLeast(20.0)
fun pct(v: Double) = ((v - quiet) / reserve).coerceIn(-0.5, 1.2)
val mean = if (bpm.isEmpty()) 0.0 else pct(bpm.average())
val peak = if (bpm.isEmpty()) 0.0 else pct(bpm.sorted()[((bpm.size - 1) * 0.9).toInt()])
val hrCv = cv(bpm).takeIf { bpm.size >= 3 } ?: 0.0
return Features(minutes, cadence, stepBurst, mean, peak, hrCv)
}

/** Every type, most likely first. */
fun rank(f: Features, learned: List<Example> = emptyList()): List<String> {
val rules = ruleScores(f)
val personal = personalScores(f, learned)
val weight = personal.second
val blended = TYPES.associateWith { t -> (1 - weight) * (rules[t] ?: 0.0) + weight * (personal.first[t] ?: 0.0) }
return TYPES.sortedWith(compareByDescending<String> { blended[it] ?: 0.0 }.thenBy { TYPES.indexOf(it) })
}

internal fun ruleScores(f: Features): Map<String, Double> {
fun ramp(x: Double, from: Double, to: Double) = ((x - from) / (to - from)).coerceIn(0.0, 1.0)
val low = ramp(f.cadence, 60.0, 20.0) // few steps for the time spent
val long = ramp(f.minutes, 15.0, 40.0)
val scores = mapOf(
"run" to ramp(f.cadence, 110.0, 145.0),
"walk" to (ramp(f.cadence, 55.0, 85.0) * ramp(f.cadence, 140.0, 115.0)),
// A ride: heart rate held up and steady, for a while, with few steps.
"cycle" to low * ramp(f.hrMeanPct, 0.25, 0.5) * ramp(f.hrCv, 0.15, 0.07) * long,
// Strength: heart rate up but uneven (sets and rests), often with bursts of steps between sets.
"gym" to low * ramp(f.hrMeanPct, 0.12, 0.35) * (0.7 * ramp(f.hrCv, 0.07, 0.15) + 0.3 * ramp(f.stepBurst, 0.4, 1.2)),
// Intervals or a game: high peaks with deep drops.
"sport" to ramp(f.cadence, 100.0, 60.0) * ramp(f.hrPeakPct, 0.6, 0.85) * ramp(f.hrCv, 0.1, 0.2),
"other" to 0.12,
)
val sum = scores.values.sum().takeIf { it > 0 } ?: 1.0
return scores.mapValues { it.value / sum }
}

/** Votes from the nearest earlier answers, and how much they should count (0..0.8). */
internal fun personalScores(f: Features, learned: List<Example>): Pair<Map<String, Double>, Double> {
if (learned.isEmpty()) return emptyMap<String, Double>() to 0.0
val near = learned.map { it to distance(f, it.features) }.filter { it.second < 1.5 }.sortedBy { it.second }.take(5)
if (near.isEmpty()) return emptyMap<String, Double>() to 0.0
val votes = near.groupBy { it.first.type }.mapValues { (_, v) -> v.sumOf { 1.0 / (it.second + 0.25) } }
val sum = votes.values.sum()
return votes.mapValues { it.value / sum } to (0.25 * near.size).coerceAtMost(0.8)
}

internal fun distance(a: Features, b: Features): Double {
fun d(x: Double, y: Double, scale: Double) = (x - y) / scale
val parts = listOf(
d(a.minutes, b.minutes, 45.0), d(a.cadence, b.cadence, 30.0), d(a.stepBurst, b.stepBurst, 0.8),
d(a.hrMeanPct, b.hrMeanPct, 0.2), d(a.hrPeakPct, b.hrPeakPct, 0.2), d(a.hrCv, b.hrCv, 0.08),
)
return sqrt(parts.sumOf { it * it })
}

private fun cv(v: List<Double>): Double {
if (v.isEmpty()) return 0.0
val m = v.average()
if (m <= 0) return 0.0
return sqrt(v.sumOf { (it - m) * (it - m) } / v.size) / m
}
}
Loading
Loading