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(health): add summary metrics handling and permissions validation in HealthTool

Durganshu Mishrad0b3413a6b83
diff --git a/app/src/main/java/com/gotcha/tools/HealthTool.kt b/app/src/main/java/com/gotcha/tools/HealthTool.kt
index 4af57e7..5effaf5 100644
--- a/app/src/main/java/com/gotcha/tools/HealthTool.kt
+++ b/app/src/main/java/com/gotcha/tools/HealthTool.kt
@@ -2,6 +2,7 @@ package com.gotcha.tools
import android.content.Context
import androidx.health.connect.client.HealthConnectClient
+import androidx.health.connect.client.aggregate.AggregateMetric
import androidx.health.connect.client.aggregate.AggregationResult
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.ActiveCaloriesBurnedRecord
@@ -46,6 +47,33 @@ class HealthTool(private val context: Context) {
HealthPermission.getReadPermission(ExerciseSessionRecord::class)
)
+ /**
+ * The summary metrics each read permission unlocks. Health Connect
+ * throws a SecurityException if an [AggregateRequest] names a metric
+ * whose permission is missing, so the request has to be assembled from
+ * the grants the user actually gave rather than from the full set.
+ */
+ private val SUMMARY_METRICS: Map<String, Set<AggregateMetric<*>>> = mapOf(
+ HealthPermission.getReadPermission(StepsRecord::class) to
+ setOf(StepsRecord.COUNT_TOTAL),
+ HealthPermission.getReadPermission(DistanceRecord::class) to
+ setOf(DistanceRecord.DISTANCE_TOTAL),
+ HealthPermission.getReadPermission(ActiveCaloriesBurnedRecord::class) to
+ setOf(ActiveCaloriesBurnedRecord.ACTIVE_CALORIES_TOTAL),
+ HealthPermission.getReadPermission(SleepSessionRecord::class) to
+ setOf(SleepSessionRecord.SLEEP_DURATION_TOTAL),
+ HealthPermission.getReadPermission(HeartRateRecord::class) to
+ setOf(HeartRateRecord.BPM_AVG, HeartRateRecord.BPM_MAX),
+ HealthPermission.getReadPermission(RestingHeartRateRecord::class) to
+ setOf(RestingHeartRateRecord.BPM_AVG),
+ HealthPermission.getReadPermission(WeightRecord::class) to
+ setOf(WeightRecord.WEIGHT_AVG)
+ )
+
+ /** Metrics safe to aggregate given [granted]; empty if none of them are. */
+ fun summaryMetricsFor(granted: Set<String>): Set<AggregateMetric<*>> =
+ SUMMARY_METRICS.filterKeys { it in granted }.values.flatten().toSet()
+
private const val PLAY_LISTING = "Health Connect"
private const val MAX_RECORDS = 50
@@ -83,17 +111,26 @@ class HealthTool(private val context: Context) {
)
}
- private fun needsPermission(): ToolResult = ToolResult.permissionNeeded(
+ /** [type] names the specific data type that was missing, when one is known. */
+ private fun needsPermission(type: String? = null): 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."
+ if (type.isNullOrBlank()) {
+ "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."
+ } else {
+ "Reading '$type' needs its own Health Connect permission, which has not been " +
+ "granted. I have opened the permission screen — please allow '$type' there and " +
+ "ask again, or ask about a data type you have already shared."
+ }
)
- private suspend fun granted(client: HealthConnectClient): Boolean {
- val granted = client.permissionController.getGrantedPermissions().any { it in PERMISSIONS }
+ /** The subset of [PERMISSIONS] the user has actually granted; empty means none. */
+ private suspend fun grantedPermissions(client: HealthConnectClient): Set<String> {
+ val granted = client.permissionController.getGrantedPermissions()
+ .filterTo(mutableSetOf()) { it in PERMISSIONS }
// Keep the Settings permission row in sync — it can only read a cached value.
- HealthPermissionState.set(granted)
+ HealthPermissionState.set(granted.isNotEmpty())
return granted
}
@@ -102,25 +139,17 @@ class HealthTool(private val context: Context) {
suspend fun getSummary(daysArg: Int?): ToolResult {
val client = clientOrNull() ?: return unavailable()
return try {
- if (!granted(client)) return needsPermission()
+ val granted = grantedPermissions(client)
+ // Workouts have no summary metric, so a grant covering only those
+ // leaves nothing to aggregate — treat that like no grant at all.
+ val metrics = summaryMetricsFor(granted)
+ if (metrics.isEmpty()) 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
- )
+ AggregateRequest(metrics = metrics, timeRangeFilter = filter)
)
val steps = aggregate[StepsRecord.COUNT_TOTAL]
@@ -159,7 +188,11 @@ class HealthTool(private val context: Context) {
RECORD_TYPE_NAMES.joinToString(", ") + "."
)
return try {
- if (!granted(client)) return needsPermission()
+ // Only this record type's own grant matters — asking about steps
+ // must not require the user to have shared their weight.
+ if (HealthPermission.getReadPermission(recordType) !in grantedPermissions(client)) {
+ return needsPermission(type)
+ }
val days = HealthFormat.days(daysArg)
val (start, end) = HealthFormat.window(Instant.now(), days)
val records = client.readRecords(
diff --git a/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt b/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt
index bbfae4f..f15236f 100644
--- a/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt
+++ b/app/src/main/java/com/gotcha/tools/MimeMessageBuilder.kt
@@ -21,10 +21,10 @@ object MimeMessageBuilder {
): String {
require(to.isNotEmpty()) { "At least one recipient required" }
val headers = buildList {
- add("From: ${from.trim()}")
- add("To: ${to.joinToString(", ") { it.trim() }}")
- if (cc.isNotEmpty()) add("Cc: ${cc.joinToString(", ") { it.trim() }}")
- if (bcc.isNotEmpty()) add("Bcc: ${bcc.joinToString(", ") { it.trim() }}")
+ add("From: ${address(from)}")
+ add("To: ${addresses(to)}")
+ if (cc.isNotEmpty()) add("Cc: ${addresses(cc)}")
+ if (bcc.isNotEmpty()) add("Bcc: ${addresses(bcc)}")
add("Subject: ${encodeHeader(subject)}")
add("MIME-Version: 1.0")
add("Content-Type: text/plain; charset=\"UTF-8\"")
@@ -39,7 +39,24 @@ object MimeMessageBuilder {
java.util.Base64.getUrlEncoder().withoutPadding()
.encodeToString(rawMessage.toByteArray(Charsets.UTF_8))
- /** RFC 2047 encoded-word for non-ASCII header values; plain values pass through. */
+ private fun addresses(values: List<String>): String =
+ values.joinToString(", ") { address(it) }
+
+ /**
+ * A single address header value. Addresses reach here from model-generated
+ * tool arguments, which in turn derive from content the agent read (emails,
+ * web pages), so a CR/LF inside one would let that content inject its own
+ * headers — `"[email protected]\r\nBcc: [email protected]"` becoming a real Bcc.
+ * No legitimate address contains a control character, so strip them all.
+ */
+ private fun address(value: String): String =
+ value.filterNot { it.code < 32 || it.code == 127 }.trim()
+
+ /**
+ * RFC 2047 encoded-word for non-ASCII header values; plain values pass
+ * through. Control characters fail the printable-ASCII test and so take the
+ * base64 branch, which neutralises any CR/LF a subject might carry.
+ */
private fun encodeHeader(value: String): String {
if (value.all { it.code in 32..126 }) return value
val encoded = java.util.Base64.getEncoder()
diff --git a/app/src/main/java/com/gotcha/tools/NotificationTool.kt b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
index 1044485..fdbe6d1 100644
--- a/app/src/main/java/com/gotcha/tools/NotificationTool.kt
+++ b/app/src/main/java/com/gotcha/tools/NotificationTool.kt
@@ -189,7 +189,12 @@ class NotificationTool(private val context: Context) {
)
}
- /** Applies [action], falling back to a media key event if transport controls refuse it. */
+ /**
+ * Applies [action] through the session's transport controls, which — unlike
+ * media key events — keep play and pause distinct and make seek possible.
+ * TOGGLE is the exception: TransportControls has no toggle, so it goes out
+ * as a PLAY_PAUSE key event.
+ */
private fun applyAction(
controller: MediaController,
action: MediaAction,
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index e442643..7b708e6 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -15,7 +15,10 @@ object ToolRegistry {
private val definitions: Map<String, ToolDefinition> =
ToolDefinitions.all.associateBy { it.function.name }
- val sensitiveTools: Set<String> = setOf("send_email")
+ // Empty by design: AgentEngine.requestConfirmation() auto-approves, so an
+ // entry here would imply a gate that does not exist. send_email has its own
+ // confirmation via the CONFIRM_SEND_EMAIL flow in EmailTools.
+ val sensitiveTools: Set<String> = emptySet()
val destructiveTools: Set<String> = setOf(
"uninstall_app",
diff --git a/app/src/test/java/com/gotcha/tools/HealthPermissionScopeTest.kt b/app/src/test/java/com/gotcha/tools/HealthPermissionScopeTest.kt
new file mode 100644
index 0000000..b121fa8
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/HealthPermissionScopeTest.kt
@@ -0,0 +1,58 @@
+package com.gotcha.tools
+
+import androidx.health.connect.client.permission.HealthPermission
+import androidx.health.connect.client.records.ExerciseSessionRecord
+import androidx.health.connect.client.records.HeartRateRecord
+import androidx.health.connect.client.records.StepsRecord
+import androidx.health.connect.client.records.WeightRecord
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Health Connect throws a SecurityException when an aggregate names a metric
+ * the user has not granted, so the summary request must be built from the
+ * grants actually held — a partial grant has to still produce a summary.
+ */
+class HealthPermissionScopeTest {
+
+ private fun read(type: kotlin.reflect.KClass<out androidx.health.connect.client.records.Record>) =
+ HealthPermission.getReadPermission(type)
+
+ @Test
+ fun `no grants means no metrics`() {
+ assertTrue(HealthTool.summaryMetricsFor(emptySet()).isEmpty())
+ }
+
+ @Test
+ fun `a steps-only grant asks only for the steps metric`() {
+ val metrics = HealthTool.summaryMetricsFor(setOf(read(StepsRecord::class)))
+ assertEquals(setOf(StepsRecord.COUNT_TOTAL), metrics)
+ }
+
+ @Test
+ fun `heart rate contributes both its average and peak`() {
+ val metrics = HealthTool.summaryMetricsFor(setOf(read(HeartRateRecord::class)))
+ assertEquals(setOf(HeartRateRecord.BPM_AVG, HeartRateRecord.BPM_MAX), metrics)
+ }
+
+ @Test
+ fun `a partial grant mixes only the granted types`() {
+ val metrics = HealthTool.summaryMetricsFor(
+ setOf(read(StepsRecord::class), read(WeightRecord::class))
+ )
+ assertEquals(setOf(StepsRecord.COUNT_TOTAL, WeightRecord.WEIGHT_AVG), metrics)
+ }
+
+ @Test
+ fun `workouts alone yield nothing to aggregate`() {
+ // ExerciseSessionRecord has no summary metric; getSummary treats this as
+ // "nothing to show" rather than issuing an empty aggregate request.
+ assertTrue(HealthTool.summaryMetricsFor(setOf(read(ExerciseSessionRecord::class))).isEmpty())
+ }
+
+ @Test
+ fun `granting everything covers every summary metric`() {
+ assertEquals(8, HealthTool.summaryMetricsFor(HealthTool.PERMISSIONS).size)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt b/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt
index 3cc46cc..8a3e6c3 100644
--- a/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt
+++ b/app/src/test/java/com/gotcha/tools/MimeMessageBuilderTest.kt
@@ -57,6 +57,47 @@ class MimeMessageBuilderTest {
assertTrue(raw.contains("Subject: Plain subject\r\n"))
}
+ @Test
+ fun `CRLF in a recipient cannot inject a header`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ to = listOf("[email protected]\r\nBcc: [email protected]"),
+ subject = "Subj",
+ body = "Body"
+ )
+ // The text survives as inert content of the To header, not as a header
+ // of its own — which is what a leading CRLF would have made it.
+ assertEquals(false, raw.contains("\r\nBcc:"))
+ assertTrue(raw.contains("To: [email protected]: [email protected]\r\n"))
+ // Exactly one blank line, i.e. one header block: nothing escaped into it.
+ assertEquals(1, Regex("\r\n\r\n").findAll(raw).count())
+ }
+
+ @Test
+ fun `CRLF in from and cc is stripped too`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]\nX-Spoof: yes",
+ to = listOf("[email protected]"),
+ cc = listOf("[email protected]\r\nX-Also: no"),
+ subject = "Subj",
+ body = "Body"
+ )
+ assertEquals(false, raw.contains("\r\nX-Spoof:"))
+ assertEquals(false, raw.contains("\r\nX-Also:"))
+ }
+
+ @Test
+ fun `CRLF in the subject is neutralised by encoding`() {
+ val raw = MimeMessageBuilder.build(
+ from = "[email protected]",
+ to = listOf("[email protected]"),
+ subject = "Hi\r\nBcc: [email protected]",
+ body = "Body"
+ )
+ assertTrue(raw.contains("Subject: =?UTF-8?B?"))
+ assertEquals(false, raw.contains("Bcc:"))
+ }
+
@Test(expected = IllegalArgumentException::class)
fun `requires at least one recipient`() {
MimeMessageBuilder.build(from = "[email protected]", to = emptyList(), subject = "s", body = "b")
diff --git a/docs/clock-tools.md b/docs/clock-tools.md
new file mode 100644
index 0000000..4f4adc4
--- /dev/null
+++ b/docs/clock-tools.md
@@ -0,0 +1,20 @@
+# Clock tools
+
+`set_alarm`, `set_timer`, `list_alarms`, `list_timers`, `show_alarms`,
+`snooze_alarm`, `dismiss_timer`, `delete_alarm`, and `delete_timer` drive the
+device's clock app through `AlarmClock` intents. There is no API to read or
+modify another app's alarms, so behaviour depends entirely on which clock app
+is installed and how it handles the standard extras.
+
+## Manual clock intent checklist
+
+`set_timer(system=true)`, `show_alarms`, `snooze_alarm`, and `dismiss_timer`
+send intents to whatever clock app is installed; behavior (especially
+`EXTRA_SKIP_UI` and dismiss/snooze support) varies by OEM. Verify manually on
+Google Clock at minimum:
+
+- [ ] `set_alarm` / `set_timer` land in Google Clock's lists.
+- [ ] `show_alarms` opens the alarms tab.
+- [ ] While an alarm is ringing, `snooze_alarm` snoozes it.
+- [ ] While a system timer (`set_timer(system=true)`) is ringing, `dismiss_timer`
+ stops it.
diff --git a/docs/gmail-byo-oauth-setup.md b/docs/gmail-byo-oauth-setup.md
index 188bad3..1887d9b 100644
--- a/docs/gmail-byo-oauth-setup.md
+++ b/docs/gmail-byo-oauth-setup.md
@@ -89,16 +89,3 @@ Gmail's IMAP/SMTP hosts, or fill in another provider's host/port. This gets
full read/write email access with no OAuth setup, at the
cost of scoping to "everything IMAP/SMTP can do" rather than Gmail's more
granular `gmail.modify` scope.
-
-## Manual clock intent checklist
-
-`set_timer(system=true)`, `show_alarms`, `snooze_alarm`, and `dismiss_timer`
-send intents to whatever clock app is installed; behavior (especially
-`EXTRA_SKIP_UI` and dismiss/snooze support) varies by OEM. Verify manually on
-Google Clock at minimum:
-
-- [ ] `set_alarm` / `set_timer` land in Google Clock's lists.
-- [ ] `show_alarms` opens the alarms tab.
-- [ ] While an alarm is ringing, `snooze_alarm` snoozes it.
-- [ ] While a system timer (`set_timer(system=true)`) is ringing, `dismiss_timer`
- stops it.