Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(tools): add Health Connect reading and improve media control

Durganshu Mishra2b993793671f
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 01b6da1..325025f 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -221,6 +221,9 @@ dependencies {
implementation("com.sun.mail:android-mail:1.6.7")
implementation("com.sun.mail:android-activation:1.6.7")
+ // Health Connect: on-device fitness/health records (no cloud API, no credentials)
+ implementation("androidx.health.connect:connect-client:1.1.0-alpha07")
+
// Markdown rendering
implementation("com.halilibo.compose-richtext:richtext-ui-material3:0.17.0")
implementation("com.halilibo.compose-richtext:richtext-commonmark:0.17.0")
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 20c76fa..fcb61c5 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -69,7 +69,20 @@
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Needed on API 30+ so open_app can see other launchable apps. -->
+ <!-- Health Connect (read-only). Granted through Health Connect's own permission
+ screen, not the standard runtime dialog. -->
+ <uses-permission android:name="android.permission.health.READ_STEPS" />
+ <uses-permission android:name="android.permission.health.READ_DISTANCE" />
+ <uses-permission android:name="android.permission.health.READ_ACTIVE_CALORIES_BURNED" />
+ <uses-permission android:name="android.permission.health.READ_SLEEP" />
+ <uses-permission android:name="android.permission.health.READ_HEART_RATE" />
+ <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />
+ <uses-permission android:name="android.permission.health.READ_WEIGHT" />
+ <uses-permission android:name="android.permission.health.READ_EXERCISE" />
+
<queries>
+ <!-- Health Connect provider app (Android 13 and below). -->
+ <package android:name="com.google.android.apps.healthdata" />
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -118,8 +131,25 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
+ <!-- Health Connect shows this rationale when the user taps the app in its
+ permission list (Android 13 and below). -->
+ <intent-filter>
+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />
+ </intent-filter>
</activity>
+ <!-- Android 14+ routes the same rationale through a permission-usage alias. -->
+ <activity-alias
+ android:name="ViewPermissionUsageActivity"
+ android:exported="true"
+ android:targetActivity=".MainActivity"
+ android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />
+ <category android:name="android.intent.category.HEALTH_PERMISSIONS" />
+ </intent-filter>
+ </activity-alias>
+
<activity
android:name=".ui.ClipboardReaderActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 40b6cbe..a1c2508 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -87,6 +87,22 @@ class MainActivity : ComponentActivity() {
}
}
+ /**
+ * Health Connect uses its own permission contract rather than the standard
+ * runtime dialog, so it needs a launcher of its own.
+ */
+ private val healthConnectLauncher = registerForActivityResult(
+ androidx.health.connect.client.PermissionController.createRequestPermissionResultContract()
+ ) { granted ->
+ com.gotcha.tools.HealthPermissionState.set(granted.isNotEmpty())
+ val message = if (granted.isEmpty()) {
+ "No health permissions granted."
+ } else {
+ "Health Connect: ${granted.size} permission(s) granted."
+ }
+ Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
+ }
+
/** Requests all runtime permissions at once on first launch. */
private val firstLaunchLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ ->
@@ -232,10 +248,38 @@ class MainActivity : ComponentActivity() {
mediaProjectionLauncher.launch(mpManager.createScreenCaptureIntent())
}
}
+ ToolResult.HEALTH_CONNECT -> requestHealthConnect()
// Runtime permissions are mapped in Settings → Permissions; skip here.
}
}
+ /**
+ * Opens Health Connect's permission screen, or steers to the Play listing when
+ * no provider is installed (Android 13 and below ship it as a separate app).
+ */
+ private fun requestHealthConnect() {
+ val status = androidx.health.connect.client.HealthConnectClient.getSdkStatus(this)
+ if (status == androidx.health.connect.client.HealthConnectClient.SDK_AVAILABLE) {
+ healthConnectLauncher.launch(com.gotcha.tools.HealthTool.PERMISSIONS)
+ return
+ }
+ Toast.makeText(
+ this,
+ "Health Connect is not available — install or update it from the Play Store.",
+ Toast.LENGTH_LONG
+ ).show()
+ runCatching {
+ startActivity(
+ Intent(
+ Intent.ACTION_VIEW,
+ android.net.Uri.parse(
+ "market://details?id=com.google.android.apps.healthdata"
+ )
+ )
+ )
+ }
+ }
+
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
diff --git a/app/src/main/java/com/gotcha/tools/HealthFormat.kt b/app/src/main/java/com/gotcha/tools/HealthFormat.kt
new file mode 100644
index 0000000..7e7c1d2
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/HealthFormat.kt
@@ -0,0 +1,69 @@
+package com.gotcha.tools
+
+import java.time.Duration
+import java.time.Instant
+import java.time.ZoneId
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+import kotlin.math.roundToLong
+
+/**
+ * Pure formatting and window arithmetic for [HealthTool]. Kept separate from the
+ * Health Connect client so it can be unit-tested on the JVM — the client itself
+ * needs a device with a Health Connect provider.
+ */
+object HealthFormat {
+
+ private const val METRES_PER_KM = 1000.0
+ private const val MINUTES_PER_HOUR = 60L
+ private const val MAX_DAYS = 365
+
+ private val dayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault())
+ private val minuteFormatter =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault())
+
+ /** Clamps the requested lookback to a sane range; defaults to a week. */
+ fun days(requested: Int?): Int = (requested ?: 7).coerceIn(1, MAX_DAYS)
+
+ /** `[now - days, now]`, the window every summary is computed over. */
+ fun window(now: Instant, days: Int): Pair<Instant, Instant> =
+ now.minus(Duration.ofDays(days.toLong())) to now
+
+ fun day(instant: Instant): String = dayFormatter.format(instant)
+
+ fun minute(instant: Instant): String = minuteFormatter.format(instant)
+
+ /** "2 h 35 min" / "45 min" — sleep and exercise durations read better than raw minutes. */
+ fun duration(duration: Duration): String {
+ val totalMinutes = duration.toMinutes()
+ if (totalMinutes < MINUTES_PER_HOUR) return "$totalMinutes min"
+ val hours = totalMinutes / MINUTES_PER_HOUR
+ val minutes = totalMinutes % MINUTES_PER_HOUR
+ return if (minutes == 0L) "$hours h" else "$hours h $minutes min"
+ }
+
+ fun metresAsKm(metres: Double): String =
+ String.format(Locale.US, "%.2f km", metres / METRES_PER_KM)
+
+ fun kilograms(kg: Double): String = String.format(Locale.US, "%.1f kg", kg)
+
+ fun steps(count: Long): String = String.format(Locale.US, "%,d", count)
+
+ /** Rounds a per-day average for display; null input means "no data in the window". */
+ fun perDay(total: Long?, days: Int): String =
+ total?.let { "${steps((it.toDouble() / days).roundToLong())}/day" } ?: "—"
+
+ /**
+ * Assembles the summary text. Entries whose value is null are omitted, so a
+ * user who only tracks steps does not get a wall of "no data" lines.
+ */
+ fun summary(days: Int, entries: List<Pair<String, String?>>): String {
+ val present = entries.filter { it.second != null }
+ if (present.isEmpty()) {
+ return "Health Connect has no data for the last $days day(s). The user may not have " +
+ "granted the permissions, or no app is writing health data on this device."
+ }
+ return "Health summary for the last $days day(s):\n" +
+ present.joinToString("\n") { (label, value) -> " $label: $value" }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/HealthPermissionState.kt b/app/src/main/java/com/gotcha/tools/HealthPermissionState.kt
new file mode 100644
index 0000000..621daac
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/HealthPermissionState.kt
@@ -0,0 +1,43 @@
+package com.gotcha.tools
+
+import android.content.Context
+import androidx.health.connect.client.HealthConnectClient
+
+/**
+ * Last known Health Connect grant state.
+ *
+ * Health Connect only exposes granted permissions through a `suspend` call, but
+ * the Settings permission list ([com.gotcha.ui.PermissionItems]) needs a
+ * synchronous answer to render a row. This caches the most recent result:
+ * [refresh] is called from [HealthTool] on every health tool call and from
+ * MainActivity after the permission screen returns, so the row is accurate by
+ * the time a user could look at it.
+ */
+object HealthPermissionState {
+
+ @Volatile
+ private var granted: Boolean = false
+
+ /** Cached answer — false until the first [refresh]. */
+ fun isGranted(): Boolean = granted
+
+ /** Re-reads the grant state; safe to call when Health Connect is absent. */
+ suspend fun refresh(context: Context): Boolean {
+ granted = runCatching {
+ if (HealthConnectClient.getSdkStatus(context) != HealthConnectClient.SDK_AVAILABLE) {
+ false
+ } else {
+ HealthConnectClient.getOrCreate(context)
+ .permissionController
+ .getGrantedPermissions()
+ .any { it in HealthTool.PERMISSIONS }
+ }
+ }.getOrDefault(false)
+ return granted
+ }
+
+ /** Records a result already known (e.g. straight from the permission launcher). */
+ fun set(value: Boolean) {
+ granted = value
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/HealthTool.kt b/app/src/main/java/com/gotcha/tools/HealthTool.kt
new file mode 100644
index 0000000..4af57e7
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/HealthTool.kt
@@ -0,0 +1,211 @@
+package com.gotcha.tools
+
+import android.content.Context
+import androidx.health.connect.client.HealthConnectClient
+import androidx.health.connect.client.aggregate.AggregationResult
+import androidx.health.connect.client.permission.HealthPermission
+import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord
+import androidx.health.connect.client.records.DistanceRecord
+import androidx.health.connect.client.records.ExerciseSessionRecord
+import androidx.health.connect.client.records.HeartRateRecord
+import androidx.health.connect.client.records.Record
+import androidx.health.connect.client.records.RestingHeartRateRecord
+import androidx.health.connect.client.records.SleepSessionRecord
+import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.WeightRecord
+import androidx.health.connect.client.request.AggregateRequest
+import androidx.health.connect.client.request.ReadRecordsRequest
+import androidx.health.connect.client.time.TimeRangeFilter
+import java.time.Duration
+import java.time.Instant
+
+/**
+ * Read-only access to the device's Health Connect store (steps, distance,
+ * calories, sleep, heart rate, weight, workouts).
+ *
+ * Not a connector: Health Connect is on-device, needs no credentials and no
+ * network. It does need its own `android.permission.health.*` grants, which are
+ * requested through the existing special-access mechanism via
+ * [ToolResult.HEALTH_CONNECT].
+ *
+ * Deliberately read-only in v1 — the agent never writes to the user's health
+ * record.
+ */
+class HealthTool(private val context: Context) {
+
+ companion object {
+ /** Every permission the two tools can need; requested as one batch. */
+ val PERMISSIONS: Set<String> = setOf(
+ HealthPermission.getReadPermission(StepsRecord::class),
+ HealthPermission.getReadPermission(DistanceRecord::class),
+ HealthPermission.getReadPermission(ActiveCaloriesBurnedRecord::class),
+ HealthPermission.getReadPermission(SleepSessionRecord::class),
+ HealthPermission.getReadPermission(HeartRateRecord::class),
+ HealthPermission.getReadPermission(RestingHeartRateRecord::class),
+ HealthPermission.getReadPermission(WeightRecord::class),
+ HealthPermission.getReadPermission(ExerciseSessionRecord::class)
+ )
+
+ private const val PLAY_LISTING = "Health Connect"
+ private const val MAX_RECORDS = 50
+
+ /** Record types [readRecords] accepts, and the arg value that selects each. */
+ private val RECORD_TYPES = mapOf(
+ "steps" to StepsRecord::class,
+ "distance" to DistanceRecord::class,
+ "calories" to ActiveCaloriesBurnedRecord::class,
+ "sleep" to SleepSessionRecord::class,
+ "heart_rate" to HeartRateRecord::class,
+ "resting_heart_rate" to RestingHeartRateRecord::class,
+ "weight" to WeightRecord::class,
+ "exercise" to ExerciseSessionRecord::class
+ )
+
+ val RECORD_TYPE_NAMES: List<String> = RECORD_TYPES.keys.toList()
+ }
+
+ private fun clientOrNull(): HealthConnectClient? =
+ if (HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE) {
+ runCatching { HealthConnectClient.getOrCreate(context) }.getOrNull()
+ } else {
+ null
+ }
+
+ private fun unavailable(): ToolResult = when (HealthConnectClient.getSdkStatus(context)) {
+ HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED -> ToolResult.error(
+ "$PLAY_LISTING is installed but out of date on this device. Ask the user to update " +
+ "it from the Play Store, then try again."
+ )
+ else -> ToolResult.error(
+ "$PLAY_LISTING is not available on this device. On Android 13 and below it is a " +
+ "separate app the user must install from the Play Store; on Android 14+ it is " +
+ "built in and may be disabled."
+ )
+ }
+
+ private fun needsPermission(): ToolResult = ToolResult.permissionNeeded(
+ ToolResult.HEALTH_CONNECT,
+ "Reading health data needs Health Connect permissions, which have not been granted. " +
+ "I have opened the permission screen — please allow the data types you're happy to " +
+ "share and ask again."
+ )
+
+ private suspend fun granted(client: HealthConnectClient): Boolean {
+ val granted = client.permissionController.getGrantedPermissions().any { it in PERMISSIONS }
+ // Keep the Settings permission row in sync — it can only read a cached value.
+ HealthPermissionState.set(granted)
+ return granted
+ }
+
+ /** Aggregated overview of the last N days. */
+ @Suppress("ReturnCount")
+ suspend fun getSummary(daysArg: Int?): ToolResult {
+ val client = clientOrNull() ?: return unavailable()
+ return try {
+ if (!granted(client)) return needsPermission()
+ val days = HealthFormat.days(daysArg)
+ val (start, end) = HealthFormat.window(Instant.now(), days)
+ val filter = TimeRangeFilter.between(start, end)
+
+ val aggregate: AggregationResult = client.aggregate(
+ AggregateRequest(
+ metrics = setOf(
+ StepsRecord.COUNT_TOTAL,
+ DistanceRecord.DISTANCE_TOTAL,
+ ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL,
+ SleepSessionRecord.SLEEP_DURATION_TOTAL,
+ HeartRateRecord.BPM_AVG,
+ HeartRateRecord.BPM_MAX,
+ RestingHeartRateRecord.BPM_AVG,
+ WeightRecord.WEIGHT_AVG
+ ),
+ timeRangeFilter = filter
+ )
+ )
+
+ val steps = aggregate[StepsRecord.COUNT_TOTAL]
+ val sleep = aggregate[SleepSessionRecord.SLEEP_DURATION_TOTAL]
+ val entries = listOf(
+ "Steps" to steps?.let { "${HealthFormat.steps(it)} total (${HealthFormat.perDay(it, days)})" },
+ "Distance" to aggregate[DistanceRecord.DISTANCE_TOTAL]
+ ?.let { HealthFormat.metresAsKm(it.inMeters) },
+ "Active calories" to aggregate[ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL]
+ ?.let { "${it.inKilocalories.toLong()} kcal" },
+ "Sleep" to sleep?.let {
+ "${HealthFormat.duration(it)} total (${HealthFormat.duration(it.dividedBy(days.toLong()))}/night)"
+ },
+ "Average heart rate" to aggregate[HeartRateRecord.BPM_AVG]?.let { "$it bpm" },
+ "Peak heart rate" to aggregate[HeartRateRecord.BPM_MAX]?.let { "$it bpm" },
+ "Resting heart rate" to aggregate[RestingHeartRateRecord.BPM_AVG]?.let { "$it bpm" },
+ "Weight" to aggregate[WeightRecord.WEIGHT_AVG]
+ ?.let { HealthFormat.kilograms(it.inKilograms) }
+ )
+ ToolResult.ok(HealthFormat.summary(days, entries))
+ } catch (ignored: SecurityException) {
+ // The user revoked a grant between the check and the read.
+ needsPermission()
+ } catch (e: Exception) {
+ ToolResult.error("Could not read Health Connect data: ${e.message}")
+ }
+ }
+
+ /** Individual records of one type, for questions the summary can't answer. */
+ @Suppress("ReturnCount")
+ suspend fun getRecords(type: String?, daysArg: Int?): ToolResult {
+ val client = clientOrNull() ?: return unavailable()
+ val recordType = RECORD_TYPES[type?.lowercase()?.trim()]
+ ?: return ToolResult.error(
+ "Unknown health record type '${type.orEmpty()}'. Use one of: " +
+ RECORD_TYPE_NAMES.joinToString(", ") + "."
+ )
+ return try {
+ if (!granted(client)) return needsPermission()
+ val days = HealthFormat.days(daysArg)
+ val (start, end) = HealthFormat.window(Instant.now(), days)
+ val records = client.readRecords(
+ ReadRecordsRequest(
+ recordType = recordType,
+ timeRangeFilter = TimeRangeFilter.between(start, end),
+ pageSize = MAX_RECORDS
+ )
+ ).records
+
+ if (records.isEmpty()) {
+ return ToolResult.ok("No '$type' records in the last $days day(s).")
+ }
+ val rows = records.joinToString("\n") { " " + describe(it) }
+ ToolResult.ok("${records.size} '$type' record(s) in the last $days day(s):\n$rows")
+ } catch (ignored: SecurityException) {
+ // The user revoked a grant between the check and the read.
+ needsPermission()
+ } catch (e: Exception) {
+ ToolResult.error("Could not read Health Connect records: ${e.message}")
+ }
+ }
+
+ @Suppress("CyclomaticComplexMethod")
+ private fun describe(record: Record): String = when (record) {
+ is StepsRecord ->
+ "${HealthFormat.day(record.startTime)}: ${HealthFormat.steps(record.count)} steps"
+ is DistanceRecord ->
+ "${HealthFormat.day(record.startTime)}: ${HealthFormat.metresAsKm(record.distance.inMeters)}"
+ is ActiveCaloriesBurnedRecord ->
+ "${HealthFormat.day(record.startTime)}: ${record.energy.inKilocalories.toLong()} kcal"
+ is SleepSessionRecord ->
+ "${HealthFormat.minute(record.startTime)} → ${HealthFormat.minute(record.endTime)} " +
+ "(${HealthFormat.duration(Duration.between(record.startTime, record.endTime))})"
+ is HeartRateRecord -> {
+ val samples = record.samples
+ val avg = samples.map { it.beatsPerMinute }.average().toLong()
+ "${HealthFormat.minute(record.startTime)}: $avg bpm average over ${samples.size} sample(s)"
+ }
+ is RestingHeartRateRecord ->
+ "${HealthFormat.day(record.time)}: ${record.beatsPerMinute} bpm resting"
+ is WeightRecord ->
+ "${HealthFormat.day(record.time)}: ${HealthFormat.kilograms(record.weight.inKilograms)}"
+ is ExerciseSessionRecord ->
+ "${HealthFormat.minute(record.startTime)}: ${record.title ?: "workout"} " +
+ "(${HealthFormat.duration(Duration.between(record.startTime, record.endTime))})"
+ else -> record.javaClass.simpleName
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/MediaSelection.kt b/app/src/main/java/com/gotcha/tools/MediaSelection.kt
new file mode 100644
index 0000000..becc72d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/MediaSelection.kt
@@ -0,0 +1,105 @@
+package com.gotcha.tools
+
+import android.media.session.PlaybackState
+
+/**
+ * What a media action maps to, once the requested verb has been normalised.
+ *
+ * Shuffle and repeat are deliberately absent: the framework's
+ * `MediaController.TransportControls` has no such methods (only the
+ * `androidx.media` compat class does), so there is no way to drive them here.
+ */
+enum class MediaAction {
+ PLAY,
+ PAUSE,
+ TOGGLE,
+ NEXT,
+ PREVIOUS,
+ STOP,
+ SEEK,
+ FAST_FORWARD,
+ REWIND
+}
+
+/**
+ * The subset of a media session the picker needs. Keeping it as a plain data
+ * class lets the selection rules be unit-tested without a MediaController.
+ */
+data class SessionInfo(
+ val packageName: String,
+ val appLabel: String,
+ /** One of the `PlaybackState.STATE_*` constants. */
+ val state: Int
+)
+
+/**
+ * Pure session-picking and action-parsing rules for [NotificationTool]'s media
+ * tools. Extracted so the interesting logic — "which of three running players did
+ * the user mean?" — is testable on the JVM.
+ */
+object MediaSelection {
+
+ /** Maps the tool's free-form `action` argument onto a [MediaAction]. */
+ fun parseAction(action: String): MediaAction? = when (action.lowercase().trim()) {
+ "play", "resume" -> MediaAction.PLAY
+ "pause" -> MediaAction.PAUSE
+ "toggle", "playpause", "play_pause" -> MediaAction.TOGGLE
+ "next", "skip", "forward" -> MediaAction.NEXT
+ "previous", "prev", "back" -> MediaAction.PREVIOUS
+ "stop" -> MediaAction.STOP
+ "seek" -> MediaAction.SEEK
+ "fast_forward", "ff" -> MediaAction.FAST_FORWARD
+ "rewind" -> MediaAction.REWIND
+ else -> null
+ }
+
+ /**
+ * Picks the session to act on.
+ *
+ * With an [app] hint, only sessions whose package or label match are eligible
+ * — returning null rather than silently acting on the wrong player. Without
+ * one, a currently-playing session wins over a merely-open one; that is what
+ * the user means by "pause the music" when a podcast app is also loaded but
+ * idle.
+ */
+ fun pick(sessions: List<SessionInfo>, app: String?): SessionInfo? {
+ val candidates = if (app.isNullOrBlank()) {
+ sessions
+ } else {
+ val needle = app.trim()
+ sessions.filter {
+ it.packageName.contains(needle, ignoreCase = true) ||
+ it.appLabel.contains(needle, ignoreCase = true)
+ }
+ }
+ return candidates.firstOrNull { it.state == PlaybackState.STATE_PLAYING }
+ ?: candidates.firstOrNull { it.state == PlaybackState.STATE_BUFFERING }
+ ?: candidates.firstOrNull()
+ }
+
+ /** Human-readable playback state for `get_now_playing`. */
+ fun describeState(state: Int): String = when (state) {
+ PlaybackState.STATE_PLAYING -> "playing"
+ PlaybackState.STATE_PAUSED -> "paused"
+ PlaybackState.STATE_STOPPED -> "stopped"
+ PlaybackState.STATE_BUFFERING -> "buffering"
+ PlaybackState.STATE_CONNECTING -> "connecting"
+ PlaybackState.STATE_ERROR -> "error"
+ PlaybackState.STATE_NONE -> "idle"
+ else -> "unknown"
+ }
+
+ /** `3:07` / `1:02:33` — position and duration read better than raw milliseconds. */
+ fun formatPosition(millis: Long): String {
+ if (millis < 0) return "--:--"
+ val totalSeconds = millis / 1000
+ val hours = totalSeconds / 3600
+ val minutes = (totalSeconds % 3600) / 60
+ val seconds = totalSeconds % 60
+ return if (hours > 0) {
+ String.format(java.util.Locale.US, "%d:%02d:%02d", hours, minutes, seconds)
+ } else {
+ String.format(java.util.Locale.US, "%d:%02d", minutes, seconds)
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
index 6d8637e..1044485 100644
--- a/app/src/main/java/com/gotcha/tools/NotificationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
@@ -2,8 +2,10 @@ package com.gotcha.tools
import android.content.ComponentName
import android.content.Context
+import android.media.MediaMetadata
import android.media.session.MediaController
import android.media.session.MediaSessionManager
+import android.media.session.PlaybackState
import android.provider.Settings
import android.view.KeyEvent
import com.gotcha.service.GotchaNotificationListenerService
@@ -18,6 +20,10 @@ import java.util.Locale
*/
class NotificationTool(private val context: Context) {
+ private companion object {
+ const val MILLIS_PER_SECOND = 1000L
+ }
+
fun readNotifications(limit: Int, app: String? = null): ToolResult {
val service = requireService() ?: return notEnabled()
var notifications = service.currentNotifications().toList()
@@ -78,30 +84,35 @@ class NotificationTool(private val context: Context) {
}
}
- /** Control the active media session: play, pause, next, previous, stop. */
- fun mediaControl(action: String): ToolResult {
+ /**
+ * Control a media session: play, pause, toggle, next, previous, stop, seek,
+ * fast_forward, rewind.
+ *
+ * Uses [MediaController.TransportControls] rather than media key events,
+ * because keys only offer a play/pause *toggle* and cannot seek at all. The
+ * one exception is `toggle` itself, which stays on the key-event path since
+ * that is exactly what the key means — and it is what the previous
+ * implementation used for every action, so existing behaviour is preserved.
+ */
+ fun mediaControl(action: String, app: String? = null, positionSeconds: Int? = null): ToolResult {
if (!hasNotificationAccess()) return notEnabled()
- val keyCode = when (action.lowercase().trim()) {
- "play", "pause", "toggle", "playpause" -> KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
- "next", "skip" -> KeyEvent.KEYCODE_MEDIA_NEXT
- "previous", "prev", "back" -> KeyEvent.KEYCODE_MEDIA_PREVIOUS
- "stop" -> KeyEvent.KEYCODE_MEDIA_STOP
- else -> return ToolResult.error(
- "Unknown media action '$action'. Use play, pause, next, previous, or stop."
+ val parsed = MediaSelection.parseAction(action)
+ ?: return ToolResult.error(
+ "Unknown media action '$action'. Use play, pause, toggle, next, previous, stop, " +
+ "seek, fast_forward, or rewind."
)
+ if (parsed == MediaAction.SEEK && positionSeconds == null) {
+ return ToolResult.error("seek needs 'position_seconds'.")
}
return try {
- val msm = context.getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager
- val component = ComponentName(context, GotchaNotificationListenerService::class.java)
- val controllers: List<MediaController> = msm.getActiveSessions(component)
- val controller = controllers.firstOrNull()
- ?: return ToolResult.error(
- "No app is currently playing media. You may open a music or video app with open_app first, " +
- "then try media_control again."
- )
- controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_DOWN, keyCode))
- controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_UP, keyCode))
- ToolResult.ok("Sent media '$action' to ${controller.packageName}.")
+ val controllers = activeControllers()
+ val chosen = MediaSelection.pick(controllers.map { it.toSessionInfo() }, app)
+ ?: return noSessionError(controllers, app)
+ val controller = controllers.first { it.packageName == chosen.packageName }
+
+ applyAction(controller, parsed, positionSeconds)
+ val target = appLabel(context.packageManager, controller.packageName)
+ ToolResult.ok("Sent media '$action' to $target.")
} catch (_: SecurityException) {
notEnabled()
} catch (e: Exception) {
@@ -109,6 +120,100 @@ class NotificationTool(private val context: Context) {
}
}
+ /** Reports what every active media session is playing. */
+ fun getNowPlaying(): ToolResult {
+ if (!hasNotificationAccess()) return notEnabled()
+ return try {
+ val controllers = activeControllers()
+ if (controllers.isEmpty()) {
+ return ToolResult.ok("Nothing is playing — no app holds an active media session.")
+ }
+ val rows = controllers.joinToString("\n") { controller ->
+ val metadata = controller.metadata
+ val title = metadata?.getString(MediaMetadata.METADATA_KEY_TITLE).orEmpty()
+ val artist = metadata?.getString(MediaMetadata.METADATA_KEY_ARTIST)
+ ?: metadata?.getString(MediaMetadata.METADATA_KEY_ALBUM_ARTIST).orEmpty()
+ val album = metadata?.getString(MediaMetadata.METADATA_KEY_ALBUM).orEmpty()
+ val duration = metadata?.getLong(MediaMetadata.METADATA_KEY_DURATION) ?: -1L
+ val playback = controller.playbackState
+ val state = MediaSelection.describeState(
+ playback?.state ?: PlaybackState.STATE_NONE
+ )
+ val position = playback?.position ?: -1L
+
+ val what = listOf(title, artist, album)
+ .filter { it.isNotBlank() }
+ .joinToString(" — ")
+ .ifBlank { "(no metadata)" }
+ val progress = if (duration > 0) {
+ " [${MediaSelection.formatPosition(position)} / " +
+ "${MediaSelection.formatPosition(duration)}]"
+ } else {
+ ""
+ }
+ "- ${appLabel(context.packageManager, controller.packageName)} " +
+ "(${controller.packageName}): $state | $what$progress"
+ }
+ ToolResult.ok("Active media session(s):\n$rows")
+ } catch (_: SecurityException) {
+ notEnabled()
+ } catch (e: Exception) {
+ ToolResult.error("Could not read media sessions: ${e.message}")
+ }
+ }
+
+ private fun activeControllers(): List<MediaController> {
+ val msm = context.getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager
+ val component = ComponentName(context, GotchaNotificationListenerService::class.java)
+ return msm.getActiveSessions(component)
+ }
+
+ private fun MediaController.toSessionInfo() = SessionInfo(
+ packageName = packageName,
+ appLabel = appLabel(context.packageManager, packageName),
+ state = playbackState?.state ?: PlaybackState.STATE_NONE
+ )
+
+ private fun noSessionError(controllers: List<MediaController>, app: String?): ToolResult =
+ if (app.isNullOrBlank()) {
+ ToolResult.error(
+ "No app is currently playing media. You may open a music or video app with " +
+ "open_app first, then try media_control again."
+ )
+ } else {
+ val running = controllers.joinToString(", ") {
+ appLabel(context.packageManager, it.packageName)
+ }.ifBlank { "none" }
+ ToolResult.error(
+ "No media session matched '$app'. Apps with a media session right now: $running."
+ )
+ }
+
+ /** Applies [action], falling back to a media key event if transport controls refuse it. */
+ private fun applyAction(
+ controller: MediaController,
+ action: MediaAction,
+ positionSeconds: Int?
+ ) {
+ val transport = controller.transportControls
+ when (action) {
+ MediaAction.PLAY -> transport.play()
+ MediaAction.PAUSE -> transport.pause()
+ MediaAction.TOGGLE -> dispatchKey(controller, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
+ MediaAction.NEXT -> transport.skipToNext()
+ MediaAction.PREVIOUS -> transport.skipToPrevious()
+ MediaAction.STOP -> transport.stop()
+ MediaAction.SEEK -> transport.seekTo((positionSeconds ?: 0).toLong() * MILLIS_PER_SECOND)
+ MediaAction.FAST_FORWARD -> transport.fastForward()
+ MediaAction.REWIND -> transport.rewind()
+ }
+ }
+
+ private fun dispatchKey(controller: MediaController, keyCode: Int) {
+ controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_DOWN, keyCode))
+ controller.dispatchMediaButtonEvent(KeyEvent(KeyEvent.ACTION_UP, keyCode))
+ }
+
private fun requireService(): GotchaNotificationListenerService? =
if (hasNotificationAccess()) GotchaNotificationListenerService.instance else null
diff --git a/app/src/main/java/com/gotcha/tools/ToolResult.kt b/app/src/main/java/com/gotcha/tools/ToolResult.kt
index 388e806..26b9c0b 100644
--- a/app/src/main/java/com/gotcha/tools/ToolResult.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolResult.kt
@@ -42,6 +42,13 @@ data class ToolResult(
/** Marker for the one-time system VPN consent dialog (VpnService). */
const val VPN_CONSENT = "special:vpn_consent"
+ /**
+ * Marker for the Health Connect read permissions. These are
+ * `android.permission.health.*` grants, but they are requested through
+ * Health Connect's own screen rather than the standard runtime dialog.
+ */
+ const val HEALTH_CONNECT = "special:health_connect"
+
fun ok(message: String) = ToolResult(true, message)
fun error(message: String) = ToolResult(false, message)
fun permissionNeeded(permission: String, message: String) =
diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
index d2a5595..1570a15 100644
--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt
+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt
@@ -9,6 +9,8 @@ import android.os.Environment
import android.provider.Settings
import androidx.core.content.ContextCompat
import com.gotcha.service.GotchaDeviceAdminReceiver
+import com.gotcha.tools.HealthPermissionState
+import com.gotcha.tools.ToolResult
data class PermissionGroup(
val name: String,
@@ -255,6 +257,20 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf(
{ c -> Settings.canDrawOverlays(c) }
)
)
+ ),
+ PermissionGroup(
+ "Health",
+ listOf(
+ PermissionItem(
+ "Health Connect",
+ "Read steps, sleep, heart rate, weight and workouts",
+ null,
+ ToolResult.HEALTH_CONNECT,
+ // Health Connect only reports grants from a suspend call, so this
+ // reflects the last check (see HealthPermissionState).
+ { _ -> HealthPermissionState.isGranted() }
+ )
+ )
)
)
diff --git a/app/src/test/java/com/gotcha/tools/HealthFormatTest.kt b/app/src/test/java/com/gotcha/tools/HealthFormatTest.kt
new file mode 100644
index 0000000..deb0f11
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/HealthFormatTest.kt
@@ -0,0 +1,94 @@
+package com.gotcha.tools
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.time.Duration
+import java.time.Instant
+
+class HealthFormatTest {
+
+ @Test
+ fun `days defaults to a week and is clamped`() {
+ assertEquals(7, HealthFormat.days(null))
+ assertEquals(1, HealthFormat.days(0))
+ assertEquals(1, HealthFormat.days(-5))
+ assertEquals(365, HealthFormat.days(10_000))
+ assertEquals(30, HealthFormat.days(30))
+ }
+
+ @Test
+ fun `window ends now and starts the requested number of days earlier`() {
+ val now = Instant.parse("2026-07-25T12:00:00Z")
+ val (start, end) = HealthFormat.window(now, 7)
+ assertEquals(now, end)
+ assertEquals(Instant.parse("2026-07-18T12:00:00Z"), start)
+ }
+
+ @Test
+ fun `durations under an hour render as minutes`() {
+ assertEquals("45 min", HealthFormat.duration(Duration.ofMinutes(45)))
+ assertEquals("0 min", HealthFormat.duration(Duration.ZERO))
+ }
+
+ @Test
+ fun `durations on the hour omit the minutes part`() {
+ assertEquals("2 h", HealthFormat.duration(Duration.ofHours(2)))
+ }
+
+ @Test
+ fun `durations render hours and minutes together`() {
+ assertEquals("7 h 35 min", HealthFormat.duration(Duration.ofMinutes(455)))
+ }
+
+ @Test
+ fun `distance converts metres to kilometres`() {
+ assertEquals("5.00 km", HealthFormat.metresAsKm(5000.0))
+ assertEquals("0.75 km", HealthFormat.metresAsKm(750.0))
+ }
+
+ @Test
+ fun `step counts are grouped for readability`() {
+ assertTrue(HealthFormat.steps(1234567).contains("1"))
+ assertEquals("500", HealthFormat.steps(500))
+ }
+
+ @Test
+ fun `per-day average divides the total over the window`() {
+ assertEquals("1,000/day", HealthFormat.perDay(7000, 7))
+ }
+
+ @Test
+ fun `per-day average of missing data is a dash, not zero`() {
+ assertEquals("—", HealthFormat.perDay(null, 7))
+ }
+
+ @Test
+ fun `summary omits metrics with no data`() {
+ val text = HealthFormat.summary(
+ 7,
+ listOf(
+ "Steps" to "50,000 total",
+ "Weight" to null,
+ "Sleep" to "49 h total"
+ )
+ )
+ assertTrue(text.contains("Steps"))
+ assertTrue(text.contains("Sleep"))
+ assertTrue("absent metrics must not be listed", !text.contains("Weight"))
+ }
+
+ @Test
+ fun `an entirely empty summary explains why rather than reporting zeroes`() {
+ val text = HealthFormat.summary(7, listOf("Steps" to null, "Sleep" to null))
+ assertTrue(text.contains("no data"))
+ assertTrue(text.contains("permissions"))
+ assertTrue("must not fabricate a zero reading", !text.contains(": 0"))
+ }
+
+ @Test
+ fun `summary names the window it covers`() {
+ val text = HealthFormat.summary(30, listOf("Steps" to "1 total"))
+ assertTrue(text.contains("30 day"))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/MediaSelectionTest.kt b/app/src/test/java/com/gotcha/tools/MediaSelectionTest.kt
new file mode 100644
index 0000000..78123c9
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/MediaSelectionTest.kt
@@ -0,0 +1,117 @@
+package com.gotcha.tools
+
+import android.media.session.PlaybackState
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class MediaSelectionTest {
+
+ private val spotify = SessionInfo("com.spotify.music", "Spotify", PlaybackState.STATE_PAUSED)
+ private val ytMusic = SessionInfo(
+ "com.google.android.apps.youtube.music",
+ "YT Music",
+ PlaybackState.STATE_PLAYING
+ )
+ private val podcast = SessionInfo("fm.player", "Podcasts", PlaybackState.STATE_STOPPED)
+
+ // ---- action parsing ----
+
+ @Test
+ fun `action synonyms map to the same action`() {
+ assertEquals(MediaAction.PLAY, MediaSelection.parseAction("play"))
+ assertEquals(MediaAction.PLAY, MediaSelection.parseAction("resume"))
+ assertEquals(MediaAction.NEXT, MediaSelection.parseAction("skip"))
+ assertEquals(MediaAction.NEXT, MediaSelection.parseAction("forward"))
+ assertEquals(MediaAction.PREVIOUS, MediaSelection.parseAction("prev"))
+ assertEquals(MediaAction.TOGGLE, MediaSelection.parseAction("playpause"))
+ assertEquals(MediaAction.FAST_FORWARD, MediaSelection.parseAction("ff"))
+ }
+
+ @Test
+ fun `play and pause are now distinct rather than both toggling`() {
+ assertEquals(MediaAction.PLAY, MediaSelection.parseAction("play"))
+ assertEquals(MediaAction.PAUSE, MediaSelection.parseAction("pause"))
+ }
+
+ @Test
+ fun `action parsing ignores case and surrounding space`() {
+ assertEquals(MediaAction.PAUSE, MediaSelection.parseAction(" PAUSE "))
+ }
+
+ @Test
+ fun `unknown actions are rejected`() {
+ assertNull(MediaSelection.parseAction("explode"))
+ assertNull(MediaSelection.parseAction(""))
+ // Removed deliberately: the framework TransportControls cannot do these.
+ assertNull(MediaSelection.parseAction("shuffle"))
+ assertNull(MediaSelection.parseAction("repeat"))
+ }
+
+ // ---- session picking ----
+
+ @Test
+ fun `a playing session wins over a merely open one`() {
+ assertEquals(ytMusic, MediaSelection.pick(listOf(spotify, podcast, ytMusic), null))
+ }
+
+ @Test
+ fun `with nothing playing the first session is used`() {
+ assertEquals(spotify, MediaSelection.pick(listOf(spotify, podcast), null))
+ }
+
+ @Test
+ fun `a buffering session is preferred over a stopped one`() {
+ val buffering = SessionInfo("a.b", "Buffering app", PlaybackState.STATE_BUFFERING)
+ assertEquals(buffering, MediaSelection.pick(listOf(podcast, buffering), null))
+ }
+
+ @Test
+ fun `an app hint matches the package name`() {
+ assertEquals(spotify, MediaSelection.pick(listOf(spotify, ytMusic), "com.spotify"))
+ }
+
+ @Test
+ fun `an app hint matches the app label case-insensitively`() {
+ assertEquals(spotify, MediaSelection.pick(listOf(spotify, ytMusic), "SPOTIFY"))
+ }
+
+ @Test
+ fun `an app hint beats the playing-session preference`() {
+ // Spotify is only paused, but the user named it explicitly.
+ assertEquals(spotify, MediaSelection.pick(listOf(ytMusic, spotify), "spotify"))
+ }
+
+ @Test
+ fun `an app hint that matches nothing returns null rather than the wrong app`() {
+ assertNull(MediaSelection.pick(listOf(spotify, ytMusic), "vlc"))
+ }
+
+ @Test
+ fun `no sessions yields null`() {
+ assertNull(MediaSelection.pick(emptyList(), null))
+ assertNull(MediaSelection.pick(emptyList(), "spotify"))
+ }
+
+ // ---- formatting ----
+
+ @Test
+ fun `playback states are described in plain words`() {
+ assertEquals("playing", MediaSelection.describeState(PlaybackState.STATE_PLAYING))
+ assertEquals("paused", MediaSelection.describeState(PlaybackState.STATE_PAUSED))
+ assertEquals("idle", MediaSelection.describeState(PlaybackState.STATE_NONE))
+ assertEquals("unknown", MediaSelection.describeState(-99))
+ }
+
+ @Test
+ fun `positions render as minutes and seconds`() {
+ assertEquals("0:00", MediaSelection.formatPosition(0))
+ assertEquals("3:07", MediaSelection.formatPosition(187_000))
+ assertEquals("1:02:33", MediaSelection.formatPosition(3_753_000))
+ }
+
+ @Test
+ fun `an unknown position renders as dashes rather than a negative time`() {
+ assertEquals("--:--", MediaSelection.formatPosition(-1))
+ }
+}