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.
fix: make the Health Connect settings toggle work and reflect real grants
Rishabh Bajpaib9d4ba7c966a
diff --git a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt b/app/src/main/java/com/gotcha/ui/PermissionsSection.ktindex aafb57f..46dfe7a 100644--- a/app/src/main/java/com/gotcha/ui/PermissionsSection.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionsSection.kt@@ -20,6 +20,7 @@ import androidx.compose.material3.Switchimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember@@ -30,9 +31,13 @@ import androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalLifecycleOwnerimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dp+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.PermissionControllerimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleEventObserverimport com.gotcha.service.GotchaDeviceAdminReceiver+import com.gotcha.tools.HealthPermissionState+import com.gotcha.tools.HealthToolimport com.gotcha.tools.ToolResultimport android.provider.Settings as AndroidSettings@@ -57,6 +62,15 @@ fun PermissionsSection(packageName: String) {ActivityResultContracts.RequestMultiplePermissions()) { /* permission state is re-read on next ON_RESUME via resumeSignal */ }+ // Health Connect only reports granted permissions through a suspend call, so its row+ // cannot re-read live state like the others — it reads this value instead, refreshed+ // whenever the screen resumes (covers grants made in Health Connect's own screen or+ // manually in system settings).+ var healthConnectGranted by remember { mutableStateOf(HealthPermissionState.isGranted()) }+ LaunchedEffect(resumeSignal) {+ healthConnectGranted = HealthPermissionState.refresh(context)+ }+// No "Permissions" heading: PermissionsScreen's top bar already says it.Text("Configure permissions that the assistant needs. Runtime permissions show a system dialog " +@@ -93,8 +107,17 @@ fun PermissionsSection(packageName: String) {AnimatedVisibility(visible = expanded) {Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {for (item in items) {- // Read live permission state from Android, re-checked on every resume- val granted = remember(resumeSignal) { item.isGranted(context) }+ // Read live permission state from Android, re-checked on every resume.+ // Health Connect is the exception: its grants come from a suspend call, so+ // its row is driven by healthConnectGranted (refreshed above). Read directly+ // rather than via remember — the refresh lands asynchronously after the+ // resume-triggered recomposition, and reading the state subscribes the row+ // to it.+ val granted = if (item.specialMarker == ToolResult.HEALTH_CONNECT) {+ healthConnectGranted+ } else {+ remember(resumeSignal) { item.isGranted(context) }+ }PermissionRow(item = item,granted = granted,@@ -159,8 +182,15 @@ private fun PermissionRow(* whose permission steps offer the same journey from their coach card — two* copies of this intent table would be two places for an OEM quirk to be fixed* in only one.+ *+ * Returns the intent that was fired (or null when [marker] has nothing to open),+ * so tests can assert on the routing table itself; callers ignore the return.*/-internal fun openSpecialAccess(context: android.content.Context, marker: String, packageName: String) {+internal fun openSpecialAccess(+ context: android.content.Context,+ marker: String,+ packageName: String+): Intent? {val intent: Intent? = when (marker) {ToolResult.WRITE_SETTINGS -> Intent(AndroidSettings.ACTION_MANAGE_WRITE_SETTINGS,@@ -189,6 +219,20 @@ internal fun openSpecialAccess(context: android.content.Context, marker: String,`package` = it.`package`}}+ ToolResult.HEALTH_CONNECT -> {+ if (HealthConnectClient.getSdkStatus(context) == HealthConnectClient.SDK_AVAILABLE) {+ PermissionController.createRequestPermissionResultContract()+ .createIntent(context, HealthTool.PERMISSIONS)+ } else {+ // No provider (or one that is out of date): steer to the Play listing instead of+ // crash-launching a screen nothing can handle — same journey as the agent path in+ // MainActivity.requestHealthConnect.+ Intent(+ Intent.ACTION_VIEW,+ Uri.parse("market://details?id=com.google.android.apps.healthdata")+ )+ }+ }// Only the Termux half of the journey: this path has no Activity to request the runtime// permission from, and the allow-external-apps property can only be set inside Termux.// MainActivity.requestTermuxAccess handles both halves when the agent asks.@@ -199,4 +243,5 @@ internal fun openSpecialAccess(context: android.content.Context, marker: String,intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)context.startActivity(intent)}+ return intent}diff --git a/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.ktnew file mode 100644index 0000000..5795ab1--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt@@ -0,0 +1,85 @@+package com.gotcha.ui++import android.content.Context+import androidx.health.connect.client.PermissionController+import androidx.test.core.app.ApplicationProvider+import com.gotcha.tools.HealthPermissionState+import com.gotcha.tools.HealthTool+import com.gotcha.tools.ToolResult+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Guards the permission routing table (`openSpecialAccess`) against the exact+ * regression it has already had once: a permission row whose toggle has no+ * route and therefore silently does nothing — the Health Connect row before+ * `ToolResult.HEALTH_CONNECT` was routed.+ *+ * Firing an intent needs a device; picking *which* intent to fire does not,+ * which is the point of keeping the table as a `when` that maps markers to+ * intents.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30])+class PermissionsRoutingTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val packageName = context.packageName++ @Test+ fun everySpecialMarkerInTheCatalogHasARoute() {+ val markers = allPermissionGroups()+ .flatMap { it.items }+ .mapNotNull { it.specialMarker }+ .toSet()+ assertTrue("catalog must declare at least one special-access marker", markers.isNotEmpty())++ markers.forEach { marker ->+ // A missing case falls through to `else -> null` and the toggle does nothing —+ // exactly the bug this test exists for.+ val intent = openSpecialAccess(context, marker, packageName)+ when (marker) {+ // Env-dependent no-ops: nothing in the test environment can be launched,+ // but the route must still degrade cleanly instead of throwing.+ ToolResult.VPN_CONSENT,+ ToolResult.TERMUX_ACCESS -> Unit+ ToolResult.HEALTH_CONNECT -> assertEquals(+ "with no provider installed the toggle must steer to the Play listing",+ "market://details?id=com.google.android.apps.healthdata",+ intent?.getData()?.toString()+ )+ else -> assertNotNull("marker '$marker' must have a route", intent)+ }+ }+ }++ @Test+ fun healthConnectPermissionScreenIsTheProviderTargetedIntent() {+ // The exact intent the HEALTH_CONNECT route fires when the provider is available:+ // PermissionController.createRequestPermissionResultContract().createIntent(...). The+ // route itself can't be driven to this branch on the JVM (getSdkStatus needs a real+ // Health Connect provider), so pin down the intent it would fire.+ val intent = PermissionController.createRequestPermissionResultContract()+ .createIntent(context, HealthTool.PERMISSIONS)++ assertEquals(+ "the permission request must target the Health Connect provider",+ "com.google.android.apps.healthdata",+ intent.getPackage()+ )+ }++ @Test+ fun refreshIsASafeNoOpWhenHealthConnectIsAbsent() = runTest {+ // Health Connect is not installed under Robolectric; the resume-refresh+ // path added to PermissionsSection must not throw on such devices.+ assertFalse(HealthPermissionState.refresh(context))+ }+}diff --git a/docs/health-connect.md b/docs/health-connect.mdindex 3919449..8a5112f 100644--- a/docs/health-connect.md+++ b/docs/health-connect.md@@ -31,7 +31,8 @@ tool and letting it open the screen. Users can grant any subset — metrics withThe Settings row reflects the **last known** grant state. Health Connect only reports grantsfrom a suspend call, which the synchronous permission list cannot make, so the row is-refreshed whenever a health tool runs or the permission screen returns.+re-read whenever the Permissions screen resumes (covering grants made in Health Connect's+own screen and grants made manually in system settings) and whenever a health tool runs.## Tools@@ -53,10 +54,17 @@ prerequisite — worth knowing before planning a Play listing.1. On a device **without** Health Connect: run `get_health_summary` and confirm it steers toinstalling it rather than crashing.-2. Grant permissions, then `get_health_summary` → figures match what the Health Connect app+2. On a device **without** Health Connect: Settings → Permissions → Health → toggle Health+ Connect on → the Play listing opens instead of the toggle silently doing nothing.+3. On a device **with** Health Connect: Settings → Permissions → Health → toggle Health+ Connect on → Health Connect's permission screen opens; grant a few data types → the+ Settings toggle is on after returning.+4. Grant/revoke a data type manually in system Settings (Health Connect → App permissions →+ Gotcha) → the Settings toggle reflects it on the next resume, without running a health tool.+5. Grant permissions, then `get_health_summary` → figures match what the Health Connect appitself reports for the same window.-3. Revoke one data type in Health Connect → that metric disappears from the summary instead+6. Revoke one data type in Health Connect → that metric disappears from the summary insteadof showing zero.-4. Revoke everything → the tool reports that permissions are needed and reopens the screen.-5. `get_health_records("sleep", 7)` → individual sessions with start, end and duration.-6. `get_health_records("nonsense")` → a clear error listing the valid types.+7. Revoke everything → the tool reports that permissions are needed and reopens the screen.+8. `get_health_records("sleep", 7)` → individual sessions with start, end and duration.+9. `get_health_records("nonsense")` → a clear error listing the valid types.