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(accessibility): enhance permission handling and user feedback for accessibility tools
Durganshu47ac7cd10c92
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 1070b03..31c9139 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -15,6 +15,7 @@ import com.gotcha.llm.LLMClientimport com.gotcha.llm.ToolCallimport com.gotcha.llm.visionUserMessageimport com.gotcha.llm.withValidToolCallArguments+import com.gotcha.tools.AccessibilityStateimport com.gotcha.tools.AgentModeimport com.gotcha.tools.AppNavigatorSessionimport com.gotcha.tools.DeviceCapabilities@@ -203,10 +204,16 @@ class AgentEngine(appContext.startActivity(launchIntent)}} catch (_: Exception) { }- if (!output.success) {- ToolResult.error(output.finalAnswer)- } else {- ToolResult.ok("TASK_RESULT:App Navigation:$stepsEncoded\n|||\n${output.finalAnswer}")+ when {+ // Carry the marker out so the host opens the settings screen.+ // Dropping it here left the user with prose about a failed+ // navigation and no way to act on it (issue #76).+ output.needsPermission != null ->+ ToolResult.permissionNeeded(output.needsPermission, output.finalAnswer)+ !output.success -> ToolResult.error(output.finalAnswer)+ else -> ToolResult.ok(+ "TASK_RESULT:App Navigation:$stepsEncoded\n|||\n${output.finalAnswer}"+ )}})@@ -1264,7 +1271,7 @@ class AgentEngine(// Same probes that decide tool exposure, so the status the model reads can// never disagree with the tools it was offered.- val accEnabled = DeviceCapabilities.accessibilityEnabled(app)+ val accState = DeviceCapabilities.accessibilityState(app)val notifEnabled = DeviceCapabilities.notificationListenerEnabled(app)val deviceAdmin = DeviceCapabilities.deviceAdminActive(app)val termux = com.gotcha.tools.TermuxTool(app).status()@@ -1286,7 +1293,22 @@ class AgentEngine(" Android version: ${android.os.Build.VERSION.RELEASE} (API ${android.os.Build.VERSION.SDK_INT})")appendLine(" Active agent: ${agent.name}")- appendLine(" Accessibility service enabled: ${if (accEnabled) "yes" else "no"}")+ // Three states, not two: "switched on but not bound" needs different+ // advice from "switched off", and telling a user to enable something+ // already enabled is the wrong-error half of issue #76.+ appendLine(+ when (accState) {+ AccessibilityState.AVAILABLE -> " Accessibility service: enabled and running"+ AccessibilityState.ENABLED_BUT_NOT_BOUND ->+ " Accessibility service: switched on but NOT running, so every tool that " ++ "needs it is withheld. Tell the user to toggle Gotcha off and on in " ++ "Settings ▸ Accessibility; do not tell them to enable it, it is already on."+ AccessibilityState.OFF ->+ " Accessibility service: off (so screen reading, tapping, typing and " ++ "navigate_app are all unavailable — tell the user to enable Gotcha in " ++ "Settings ▸ Accessibility)"+ }+ )appendLine(" Notification listener enabled: ${if (notifEnabled) "yes" else "no"}")appendLine(" Device admin active: ${if (deviceAdmin) "yes" else "no"}")// run_termux_command is withheld unless Termux is installed, and refuses until itsdiff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.ktindex c774f46..a37fb70 100644--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt@@ -2,8 +2,6 @@ package com.gotcha.toolsimport android.content.Contextimport android.os.Build-import android.provider.Settings-import android.text.TextUtilsimport android.view.accessibility.AccessibilityNodeInfoimport com.gotcha.service.GotchaAccessibilityService@@ -19,7 +17,7 @@ class AccessibilityTool(private val context: Context) {/** Read the visible on-screen text of whatever app is in the foreground. */fun readScreen(): ToolResult {val service = GotchaAccessibilityService.instance- if (service == null) return if (isEnabled()) serviceNotRunning() else notEnabled()+ if (service == null) return unavailable()val lines = service.dumpScreenText()return if (lines.isEmpty()) {ToolResult.ok("No readable text is on screen right now.")@@ -31,7 +29,7 @@ class AccessibilityTool(private val context: Context) {/** Read screen text AND flag for full-resolution screenshot capture. */fun readScreenRaw(): ToolResult {val service = GotchaAccessibilityService.instance- if (service == null) return if (isEnabled()) serviceNotRunning() else notEnabled()+ if (service == null) return unavailable()val lines = service.dumpScreenText()val text = if (lines.isEmpty()) {"No readable text is on screen right now."@@ -43,7 +41,7 @@ class AccessibilityTool(private val context: Context) {/** Tap either an on-screen element matching [text], or absolute coordinates. */fun tap(text: String?, x: Int?, y: Int?): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()return when {!text.isNullOrBlank() ->if (service.tapByText(text)) {@@ -72,7 +70,7 @@ class AccessibilityTool(private val context: Context) {/** Long-press either an on-screen element matching [text], or absolute coordinates. */fun longPress(text: String?, x: Int?, y: Int?): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()return when {!text.isNullOrBlank() ->if (service.longPressByText(text)) {@@ -110,7 +108,7 @@ class AccessibilityTool(private val context: Context) {distance: Int? = null,index: Int? = null): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()if (index != null) {val result = swipeOnElement(service, direction, index)if (result != null) return result@@ -206,7 +204,7 @@ class AccessibilityTool(private val context: Context) {/** Type text into the currently focused input field or target an element directly by index. */fun inputText(text: String, index: Int? = null): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()if (index != null) {val element = ScreenPerception.resolveElementByIndex(index)?: return ToolResult.error(@@ -227,7 +225,7 @@ class AccessibilityTool(private val context: Context) {/** Perform a device-wide navigation gesture via the accessibility service (back/home/recents/...). */fun globalAction(action: String): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()return if (service.performGlobal(action)) {ToolResult.ok("Performed global action: $action.")} else {@@ -240,7 +238,7 @@ class AccessibilityTool(private val context: Context) {/** Tap a UI element by its index from the numbered elements list. */fun tapByIndex(index: Int): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()val element = ScreenPerception.resolveElementByIndex(index)?: return ToolResult.error("No UI element with index $index found on screen. The screen may have changed — use read_screen " +@@ -264,7 +262,7 @@ class AccessibilityTool(private val context: Context) {/** Long-press a UI element by its index from the numbered elements list. */fun longPressByIndex(index: Int): ToolResult {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()val element = ScreenPerception.resolveElementByIndex(index)?: return ToolResult.error("No UI element with index $index found on screen. The screen may have changed — use read_screen " +@@ -297,7 +295,7 @@ class AccessibilityTool(private val context: Context) {val globalKeys = setOf("back", "home", "recents", "notifications", "quick_settings", "lock_screen")if (k in globalKeys) return globalAction(k)if (k == "enter") {- val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()+ val service = GotchaAccessibilityService.instance ?: return unavailable()try {val root = service.rootInActiveWindowval result = try {@@ -324,35 +322,27 @@ class AccessibilityTool(private val context: Context) {)}- private fun notEnabled() = ToolResult.permissionNeeded(- ToolResult.ACCESSIBILITY_ACCESS,- "This action needs the Gotcha accessibility service. I have opened Accessibility " +- "settings — please enable Gotcha there and ask again."- )-- private fun serviceNotRunning() = ToolResult.error(- "The Gotcha accessibility service is enabled but not running. " +- "This can happen after an app restart. Please toggle it off and on in " +- "Settings → Accessibility, or force-stop and reopen the app."- )-- /** True when this app's service is listed in the system's enabled-accessibility-services setting. */- private fun isEnabled(): Boolean {- val enabled = Settings.Secure.getString(- context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES- ) ?: return false- val pkg = context.packageName- val cls = GotchaAccessibilityService::class.java.name- val splitter = TextUtils.SimpleStringSplitter(':')- splitter.setString(enabled)- while (splitter.hasNext()) {- val entry = splitter.next()- // Check long form (com.gotcha/com.gotcha.service.GotchaAccessibilityService)- if (entry.equals("$pkg/$cls", ignoreCase = true)) return true- // Check short form (com.gotcha/.service.GotchaAccessibilityService)- if (entry.equals("$pkg/.${cls.substringAfter(pkg)}", ignoreCase = true)) return true- if (entry.startsWith("$pkg/", ignoreCase = true) && entry.endsWith(cls.substringAfterLast('.'), ignoreCase = true)) return true- }- return false+ /**+ * Why the service could not be reached, as something the user can act on.+ *+ * Both branches carry [ToolResult.ACCESSIBILITY_ACCESS] so the host opens+ * Settings ▸ Accessibility either way — the screen is the same, only the+ * instruction on it differs.+ */+ private fun unavailable(): ToolResult = when (DeviceCapabilities.accessibilityState(context)) {+ AccessibilityState.ENABLED_BUT_NOT_BOUND -> ToolResult.permissionNeeded(+ ToolResult.ACCESSIBILITY_ACCESS,+ "The Gotcha accessibility service is switched on but is not running — Android " ++ "stops it after an app update or under memory pressure. I have opened " ++ "Accessibility settings; please toggle Gotcha off and on there, then ask again."+ )+ // OFF, and the AVAILABLE branch: reaching here with a bound service means+ // it was unbound between the state read and the call, which is the same+ // problem from the user's side.+ else -> ToolResult.permissionNeeded(+ ToolResult.ACCESSIBILITY_ACCESS,+ "This action needs the Gotcha accessibility service, which is switched off. " ++ "I have opened Accessibility settings — please enable Gotcha there and ask again."+ )}}diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.ktindex 5b4390c..0f693eb 100644--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt@@ -22,7 +22,16 @@ import kotlinx.serialization.json.putJsonObjectdata class AppNavigatorOutput(val finalAnswer: String,val steps: List<String>,- val success: Boolean = true+ val success: Boolean = true,+ /**+ * A [ToolResult] special-access marker when the run ended because something+ * needs granting, so the host can open that screen.+ *+ * Without it the marker raised inside the session died here and the caller+ * saw only prose — which is how a disabled accessibility service surfaced as+ * "reached N steps without completing the task" (issue #76).+ */+ val needsPermission: String? = null)class AppNavigatorSession(@@ -40,6 +49,7 @@ class AppNavigatorSession(private val actionLog = mutableListOf<String>()suspend fun run(): AppNavigatorOutput {+ blockedOnAccessibility()?.let { return it }val model = settings.navigatorModel.ifEmpty { settings.model }val llmClient = LLMClient(apiKey = settings.effectiveApiKey,@@ -233,6 +243,44 @@ class AppNavigatorSession(}}+ /**+ * The refusal to run at all when the accessibility service cannot serve a+ * call, or null to proceed.+ *+ * Every step of the loop reads the screen and taps through that service.+ * Without it each observation comes back as "(accessibility service not+ * available)" and each action fails, yet the session still burns maxSteps+ * LLM round-trips before reporting that it ran out of steps — the unrelated+ * error of issue #76, arrived at slowly and expensively.+ */+ private fun blockedOnAccessibility(): AppNavigatorOutput? {+ val state = DeviceCapabilities.accessibilityState(appContext)+ if (state == AccessibilityState.AVAILABLE) return null+ val reason = if (state == AccessibilityState.ENABLED_BUT_NOT_BOUND) {+ "the Gotcha accessibility service is switched on but is not running"+ } else {+ "the Gotcha accessibility service is switched off"+ }+ return AppNavigatorOutput(+ finalAnswer = "Task failed: app navigation needs the accessibility service, and " ++ "$reason. I have opened Accessibility settings — tell the user to enable Gotcha " ++ "there (toggling it off and on if it is already listed), then ask again. " ++ "Do not retry.",+ steps = emptyList(),+ success = false,+ needsPermission = ToolResult.ACCESSIBILITY_ACCESS+ )+ }++ /**+ * Tools withheld from the navigator this turn. Mirrors [SubAgentSession] —+ * without it a tool whose capability went away mid-run reaches a router that+ * cannot serve it and fails with something that does not name the cause.+ */+ private fun hiddenTools(): Set<String> =+ com.gotcha.connectors.ConnectorRegistry.hiddenToolNames(settings.disabledConnectors) ++ DeviceCapabilities.hiddenToolNames(appContext)+private suspend fun executeWithRetry(call: ToolCall): ToolResult {var lastResult: ToolResult = ToolResult.error("Exhausted retries")val args: JsonObject = try {@@ -245,10 +293,15 @@ class AppNavigatorSession(try {lastResult = toolExecutor.execute(call.function.name, args,- AgentMode.OPERATOR, isSubAgent = true+ AgentMode.OPERATOR, isSubAgent = true,+ hiddenTools = hiddenTools())kotlinx.coroutines.delay(300)if (lastResult.success) return lastResult+ // A missing grant is not a transient failure: retrying spends two+ // more rounds to produce the identical message and buries the+ // marker the user needs under a retry log.+ if (lastResult.needsPermission != null) return lastResult} catch (e: CancellationException) {throw e} catch (e: Throwable) {diff --git a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.ktindex cd5b6b6..fb778fa 100644--- a/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt+++ b/app/src/main/java/com/gotcha/tools/CapabilityCatalog.kt@@ -16,7 +16,18 @@ enum class Capability(/** Human name used in the tool-unavailable message. */val label: String,/** Tools that cannot function without it. */- val tools: Set<String>+ val tools: Set<String>,+ /**+ * The [ToolResult] special-access marker that opens the screen where this+ * capability is granted, or null when there is no screen to open (root and+ * Health Connect availability are properties of the device, not grants).+ *+ * This is what makes a *hidden* tool still actionable. The tool itself is+ * withheld from the model, so its own `permissionNeeded` result can never+ * run; carrying the marker on the capability lets [ToolExecutor] emit the+ * same deep-link when the model reaches for a tool that is not there.+ */+ val permissionMarker: String? = null) {ACCESSIBILITY("the accessibility service",@@ -25,19 +36,22 @@ enum class Capability("input_text", "press_key", "global_action","read_screen", "read_screen_raw","navigate_app"- )+ ),+ ToolResult.ACCESSIBILITY_ACCESS),NOTIFICATION_LISTENER("notification access",// media_control and get_now_playing read MediaSessions, which Android// only hands out to an enabled notification listener.- setOf("read_notifications", "dismiss_notifications", "media_control", "get_now_playing")+ setOf("read_notifications", "dismiss_notifications", "media_control", "get_now_playing"),+ ToolResult.NOTIFICATION_LISTENER_ACCESS),DEVICE_ADMIN("device admin",- setOf("lock_screen", "disable_camera", "set_password_policy")+ setOf("lock_screen", "disable_camera", "set_password_policy"),+ ToolResult.DEVICE_ADMIN),ROOT(@@ -57,7 +71,10 @@ enum class Capability(// run_termux_command. Hiding it without Termux is the point: it is the only route to// MP3, and a model that could see it on a device that cannot run it would promise a// conversion it has no way to perform.- setOf("run_termux_command", "media_convert", "pull_from_termux")+ setOf("run_termux_command", "media_convert", "pull_from_termux"),+ // Installing Termux is not a grant, so there is no settings screen to+ // open; the <env> block tells the model to say "install it from F-Droid".+ null),HEALTH_CONNECT(@@ -67,7 +84,8 @@ enum class Capability(OVERLAY("the display-over-other-apps permission",- setOf("show_overlay", "hide_overlay")+ setOf("show_overlay", "hide_overlay"),+ ToolResult.OVERLAY_ACCESS)}diff --git a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.ktindex bd547c5..77bb892 100644--- a/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt+++ b/app/src/main/java/com/gotcha/tools/DeviceCapabilities.kt@@ -1,8 +1,31 @@package com.gotcha.toolsimport android.content.Context+import android.text.TextUtils+import com.gotcha.service.GotchaAccessibilityServiceimport java.io.File+/**+ * What the accessibility service can actually do right now.+ *+ * Two states would not be enough. "Listed in the settings" and "bound and+ * usable" come apart routinely — the OS unbinds the service under memory+ * pressure, across an app update, and when the master switch goes off while the+ * component stays listed — and the advice differs: [OFF] means enable it,+ * [ENABLED_BUT_NOT_BOUND] means toggle it off and on. Collapsing them is what+ * made a disabled setting surface as an unrelated failure (issue #76).+ */+enum class AccessibilityState {+ /** Bound and serving calls. */+ AVAILABLE,++ /** The user switched it on, but no live service is bound to talk to. */+ ENABLED_BUT_NOT_BOUND,++ /** Not switched on. */+ OFF+}+/*** Runtime probes for the [Capability] set. Cheap enough to call once per LLM* round: everything here is a settings string read or a service lookup, except@@ -30,7 +53,11 @@ object DeviceCapabilities {private var cachedRoot: Boolean? = nullfun available(context: Context): Set<Capability> = buildSet {- if (accessibilityEnabled(context)) add(Capability.ACCESSIBILITY)+ // Gated on the service being *bound*, not on the setting listing it.+ // A listed-but-unbound service cannot serve a single call, and offering+ // the tools anyway is what produced the "reached N steps without+ // completing the task" dead end in AppNavigatorSession.+ if (accessibilityState(context) == AccessibilityState.AVAILABLE) add(Capability.ACCESSIBILITY)if (notificationListenerEnabled(context)) add(Capability.NOTIFICATION_LISTENER)if (deviceAdminActive(context)) add(Capability.DEVICE_ADMIN)if (rootAvailable()) add(Capability.ROOT)@@ -43,11 +70,63 @@ object DeviceCapabilities {fun hiddenToolNames(context: Context): Set<String> =CapabilityCatalog.hiddenTools(available(context))- fun accessibilityEnabled(context: Context): Boolean = secureListContains(- context,- android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,- "${context.packageName}/com.gotcha.service.GotchaAccessibilityService"- )+ /**+ * The one probe for accessibility. Everything else — tool gating, the `<env>`+ * line, the permissions screen, the feature tour — routes here, because three+ * copies of this string comparison drifted into three different answers.+ *+ * A bound service is authoritative: if calls are being served, no reading of+ * the settings string can make that false.+ */+ fun accessibilityState(context: Context): AccessibilityState = when {+ GotchaAccessibilityService.instance != null -> AccessibilityState.AVAILABLE+ accessibilityEnabled(context) -> AccessibilityState.ENABLED_BUT_NOT_BOUND+ else -> AccessibilityState.OFF+ }++ /**+ * Whether the user has switched the service on — which is not the same as it+ * being usable; see [accessibilityState].+ *+ * Both halves matter. `ENABLED_ACCESSIBILITY_SERVICES` keeps listing the+ * component after the master switch goes off, so reading only the list+ * reports a service that the framework has already stopped.+ */+ fun accessibilityEnabled(context: Context): Boolean =+ accessibilityMasterSwitchOn(context) && accessibilityServiceListed(context)++ private fun accessibilityMasterSwitchOn(context: Context): Boolean = runCatching {+ android.provider.Settings.Secure.getInt(+ context.contentResolver,+ android.provider.Settings.Secure.ACCESSIBILITY_ENABLED,+ 0+ ) == 1+ }.getOrDefault(false)++ /**+ * Whether our component appears in the enabled-services list.+ *+ * Parsed rather than substring-matched, and tolerant of both spellings: the+ * Settings UI writes the flattened long form, but a backup restore, an `adb+ * settings put`, and some OEM ROMs write the short form+ * (`com.gotcha/.service.GotchaAccessibilityService`). Matching only the long+ * form reported "off" on a device where the service was bound and working.+ */+ private fun accessibilityServiceListed(context: Context): Boolean = runCatching {+ val listed = android.provider.Settings.Secure.getString(+ context.contentResolver,+ android.provider.Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES+ ) ?: return false+ val pkg = context.packageName+ val cls = GotchaAccessibilityService::class.java.name+ val splitter = TextUtils.SimpleStringSplitter(':')+ splitter.setString(listed)+ splitter.any { entry ->+ val trimmed = entry.trim()+ trimmed.equals("$pkg/$cls", ignoreCase = true) ||+ trimmed.equals("$pkg/.${cls.substringAfter("$pkg.")}", ignoreCase = true)+ }+ }.getOrDefault(false)fun notificationListenerEnabled(context: Context): Boolean =secureListContains(context, "enabled_notification_listeners", context.packageName)diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 516a71c..41e79f4 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -120,7 +120,7 @@ class ToolExecutor(return ToolResult.error("Unknown tool '$name'. Only the fixed tool catalog is available.")}if (name in hiddenTools) {- return ToolResult.error(unavailableMessage(name))+ return unavailableResult(name)}if (!isSubAgent && !ToolRegistry.isAllowedForAgent(name, agent)) {return ToolResult.error(@@ -655,12 +655,31 @@ class ToolExecutor(}}- /** Names what would make [name] work, so the model can steer the user there. */- private fun unavailableMessage(name: String): String {+ /**+ * What to hand back for a tool that was withheld this turn: a message naming+ * what would make it work, plus — for a capability the user can actually+ * grant — the special-access marker that opens the right settings screen.+ *+ * The marker is the point. A gated tool is hidden from the model, so its own+ * `permissionNeeded` result never runs, and before this the user's only hope+ * was that the model would read the `<env>` block and explain the gap in+ * prose. It usually did; when it did not, the failure surfaced as whatever+ * unrelated thing it tried instead (issue #76). Emitting the marker here+ * makes the deep-link fire whether or not the model words it well.+ */+ private fun unavailableResult(name: String): ToolResult {CapabilityCatalog.ownerOf(name)?.let { capability ->- return "Tool '$name' is unavailable: it needs ${capability.label}, which is not " ++ val message = "Tool '$name' is unavailable: it needs ${capability.label}, which is not " +"available on this device right now. Tell the user what to enable; do not retry."+ return capability.permissionMarker+ ?.let { ToolResult.permissionNeeded(it, message) }+ ?: ToolResult.error(message)}+ return ToolResult.error(connectorUnavailableMessage(name))+ }++ /** The connector half of [unavailableResult] — no device grant to deep-link to. */+ private fun connectorUnavailableMessage(name: String): String {// Dynamic tools (e.g. Home Assistant MCP) are registered at runtime, so the// compile-time catalog cannot know them; name the owning connector explicitly.if (name in ToolRegistry.dynamicTools) {diff --git a/app/src/main/java/com/gotcha/ui/PermissionItems.kt b/app/src/main/java/com/gotcha/ui/PermissionItems.ktindex 47fca3e..015839e 100644--- a/app/src/main/java/com/gotcha/ui/PermissionItems.kt+++ b/app/src/main/java/com/gotcha/ui/PermissionItems.kt@@ -295,16 +295,16 @@ fun allPermissionGroups(): List<PermissionGroup> = listOf(* Whether Gotcha's accessibility service is switched on.** Named rather than inlined into the catalog above because the feature tour asks- * the same question to decide when its "grant Accessibility" step is finished,- * and two copies of this string comparison would be two chances to drift.+ * the same question to decide when its "grant Accessibility" step is finished.+ * It delegates rather than comparing the settings string itself: three copies of+ * that comparison had already drifted into three different answers, which is how+ * a disabled setting came to surface as an unrelated error (issue #76). This is+ * the "has the user granted it" question, so it reads the setting rather than+ * [com.gotcha.tools.DeviceCapabilities.accessibilityState] — a granted service+ * that Android has unbound should still show as granted here.*/-fun isAccessibilityGranted(context: Context): Boolean {- val expected = "${context.packageName}/com.gotcha.service.GotchaAccessibilityService"- val enabled = Settings.Secure.getString(- context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES- ) ?: ""- return enabled.contains(expected, ignoreCase = true)-}+fun isAccessibilityGranted(context: Context): Boolean =+ com.gotcha.tools.DeviceCapabilities.accessibilityEnabled(context)/** Whether "Display over other apps" is allowed — the assistive ball and Lens need it. */fun isOverlayGranted(context: Context): Boolean = Settings.canDrawOverlays(context)diff --git a/app/src/test/java/com/gotcha/tools/AccessibilityCapabilityTest.kt b/app/src/test/java/com/gotcha/tools/AccessibilityCapabilityTest.ktnew file mode 100644index 0000000..d07f77e--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/AccessibilityCapabilityTest.kt@@ -0,0 +1,135 @@+package com.gotcha.tools++import android.content.Context+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import com.gotcha.service.GotchaAccessibilityService+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * The accessibility probe, which used to exist in three drifting copies —+ * [DeviceCapabilities], `AccessibilityTool` and `PermissionItems` each read the+ * settings string their own way and each got a different answer. When they+ * disagreed, the tools were gated on one answer while the `<env>` block reported+ * another, and a disabled setting surfaced as an unrelated failure (issue #76).+ *+ * No service can be bound under Robolectric, so `instance` stays null throughout+ * and these tests pin the settings-reading half: exactly the half that was wrong.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30])+class AccessibilityCapabilityTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private val longForm get() = "${context.packageName}/com.gotcha.service.GotchaAccessibilityService"+ private val shortForm get() = "${context.packageName}/.service.GotchaAccessibilityService"++ @Before+ fun clearSetting() {+ write(services = "", masterSwitch = 0)+ }++ private fun write(services: String, masterSwitch: Int) {+ Settings.Secure.putString(+ context.contentResolver,+ Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,+ services+ )+ Settings.Secure.putInt(+ context.contentResolver,+ Settings.Secure.ACCESSIBILITY_ENABLED,+ masterSwitch+ )+ }++ @Test+ fun `the flattened long form counts as enabled`() {+ write(services = longForm, masterSwitch = 1)+ assertTrue(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `the short form counts as enabled`() {+ // Written by a backup restore, by `adb settings put`, and by some OEM+ // ROMs. Matching only the long form reported "off" on a device where the+ // service was bound and working — the model then told the user to enable+ // something that was already on.+ write(services = shortForm, masterSwitch = 1)+ assertTrue(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `our entry is found among other enabled services`() {+ write(services = "com.other/.A11yService:$longForm:com.third/.Svc", masterSwitch = 1)+ assertTrue(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `the master switch being off means disabled even while we are listed`() {+ // The framework leaves ENABLED_ACCESSIBILITY_SERVICES populated when the+ // master switch goes off, so reading only the list reports a service+ // Android has already stopped — tools exposed, every call failing.+ write(services = longForm, masterSwitch = 0)+ assertFalse(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `another app's service does not count as ours`() {+ write(services = "com.other/.GotchaAccessibilityService", masterSwitch = 1)+ assertFalse(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `an empty setting is disabled, not a crash`() {+ write(services = "", masterSwitch = 1)+ assertFalse(DeviceCapabilities.accessibilityEnabled(context))+ }++ @Test+ fun `switched on but unbound is its own state`() {+ // The state that produced the wrong advice: "enabled" by the setting, but+ // with no service to serve a single call. It must not read as OFF (which+ // would tell the user to enable an already-enabled service) and must not+ // read as AVAILABLE (which would expose tools that cannot work).+ write(services = longForm, masterSwitch = 1)+ assertEquals(null, GotchaAccessibilityService.instance)+ assertEquals(+ AccessibilityState.ENABLED_BUT_NOT_BOUND,+ DeviceCapabilities.accessibilityState(context)+ )+ }++ @Test+ fun `switched off reads as off`() {+ write(services = "", masterSwitch = 0)+ assertEquals(AccessibilityState.OFF, DeviceCapabilities.accessibilityState(context))+ }++ @Test+ fun `an unbound service withholds the accessibility tools`() {+ // The gate is binding, not the setting. Offering tap/read_screen against+ // an unbound service is what let AppNavigatorSession grind through every+ // step and report "reached N steps without completing the task".+ write(services = longForm, masterSwitch = 1)+ val hidden = DeviceCapabilities.hiddenToolNames(context)+ assertTrue("read_screen" in hidden)+ assertTrue("tap" in hidden)+ assertTrue("navigate_app" in hidden)+ }++ @Test+ fun `the permissions screen still shows a granted-but-unbound service as granted`() {+ // "Has the user granted it" is a different question from "can it serve a+ // call": an Android-unbound service must not make the toggle read as off.+ write(services = longForm, masterSwitch = 1)+ assertTrue(com.gotcha.ui.isAccessibilityGranted(context))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.kt b/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.ktindex 5ca8a06..1678243 100644--- a/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.kt+++ b/app/src/test/java/com/gotcha/tools/CapabilityGatingTest.kt@@ -87,6 +87,30 @@ class CapabilityGatingTest {}}+ @Test+ fun `every capability the user can grant carries its settings marker`() {+ // Without a marker a hidden tool can only produce prose, and whether the+ // user learns which setting to enable comes down to how the model words+ // it that turn — the intermittency behind issue #76.+ assertEquals(ToolResult.ACCESSIBILITY_ACCESS, Capability.ACCESSIBILITY.permissionMarker)+ assertEquals(+ ToolResult.NOTIFICATION_LISTENER_ACCESS,+ Capability.NOTIFICATION_LISTENER.permissionMarker+ )+ assertEquals(ToolResult.DEVICE_ADMIN, Capability.DEVICE_ADMIN.permissionMarker)+ assertEquals(ToolResult.OVERLAY_ACCESS, Capability.OVERLAY.permissionMarker)+ }++ @Test+ fun `capabilities with nothing to grant carry no marker`() {+ // Root and Health Connect are properties of the device, and Termux is an+ // app to install: there is no settings screen a deep-link could open, so+ // a marker would send the user somewhere that cannot help.+ assertNull(Capability.ROOT.permissionMarker)+ assertNull(Capability.TERMUX.permissionMarker)+ assertNull(Capability.HEALTH_CONNECT.permissionMarker)+ }+@Testfun `hidden capability tools drop out of the operator schema list`() {val hidden = CapabilityCatalog.hiddenTools(emptySet())diff --git a/app/src/test/java/com/gotcha/tools/HiddenToolPermissionTest.kt b/app/src/test/java/com/gotcha/tools/HiddenToolPermissionTest.ktnew file mode 100644index 0000000..7ec982a--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/HiddenToolPermissionTest.kt@@ -0,0 +1,124 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.JsonObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * What a tool withheld by a missing device capability hands back.+ *+ * The message alone is not enough. A hidden tool never reaches its own+ * `permissionNeeded` result, so before this the only thing standing between the+ * user and a bare "something went wrong" was the model choosing to read the+ * `<env>` block and explain — which it did most of the time, and that+ * "most of the time" is what made issue #76 look unreproducible. The marker+ * makes the deep-link fire regardless of how the model words its reply.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30])+class HiddenToolPermissionTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private lateinit var executor: ToolExecutor++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ executor = ToolExecutor(context)+ }++ private suspend fun runHidden(tool: String): ToolResult =+ executor.execute(tool, JsonObject(emptyMap()), hiddenTools = setOf(tool))++ @Test+ fun `a withheld accessibility tool asks for accessibility, not something else`() = runTest {+ val result = runHidden("read_screen")+ assertFalse(result.success)+ assertEquals(ToolResult.ACCESSIBILITY_ACCESS, result.needsPermission)+ assertTrue(+ "the message must name the accessibility service: ${result.message}",+ result.message.contains("accessibility service")+ )+ }++ @Test+ fun `every grantable capability's tools carry that capability's marker`() {+ // Not just accessibility: the same gap existed for the overlay,+ // notification-listener and device-admin tools, and the issue asks for+ // the pattern, not a one-off fix.+ Capability.entries.forEach { capability ->+ val marker = capability.permissionMarker ?: return@forEach+ capability.tools.forEach { tool ->+ val result = kotlinx.coroutines.runBlocking { runHidden(tool) }+ assertEquals(+ "hidden '$tool' must deep-link to ${capability.name}",+ marker,+ result.needsPermission+ )+ }+ }+ }++ @Test+ fun `capabilities with no settings screen produce a message and no deep-link`() = runTest {+ // run_root_command cannot be granted anywhere; sending the user to a+ // settings screen would be worse than the plain explanation.+ val result = runHidden("run_root_command")+ assertFalse(result.success)+ assertNull(result.needsPermission)+ assertTrue(result.message.contains("root"))+ }++ @Test+ fun `a withheld connector tool still steers to Connectors`() = runTest {+ // Connector gating is a different owner with no device grant behind it;+ // the capability change must not have swallowed its message.+ val result = runHidden("list_emails")+ assertFalse(result.success)+ assertNull(result.needsPermission)+ assertTrue(result.message.contains("Connectors"))+ }++ @Test+ fun `the navigator refuses up front instead of burning every step`() = runTest {+ // No service can bind under Robolectric, so this is the blocked state.+ // The old path ran maxSteps LLM round-trips against "(accessibility+ // service not available)" observations and ended on "Reached N steps+ // without completing the task" — the unrelated error users reported.+ // Returning before the first round also means no LLM call is attempted,+ // which is what keeps this test off the network.+ val output = AppNavigatorSession(+ appContext = context,+ toolExecutor = executor,+ settings = com.gotcha.data.Settings(),+ task = "open the settings screen"+ ).run()++ assertFalse(output.success)+ assertTrue("the run must not have stepped", output.steps.isEmpty())+ assertEquals(ToolResult.ACCESSIBILITY_ACCESS, output.needsPermission)+ assertTrue(+ "the answer must name accessibility, not step exhaustion: ${output.finalAnswer}",+ output.finalAnswer.contains("accessibility service")+ )+ assertFalse(output.finalAnswer.contains("Reached"))+ }++ @Test+ fun `the marker is one the host knows how to open`() = runTest {+ // AgentEngine only forwards markers prefixed "special:" to the host.+ val marker = runHidden("tap").needsPermission+ assertTrue("marker '$marker' would never reach the host", marker!!.startsWith("special:"))+ }+}diff --git a/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.ktindex 5776e67..d018195 100644--- a/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt+++ b/app/src/test/java/com/gotcha/ui/PermissionsRoutingTest.kt@@ -63,6 +63,22 @@ class PermissionsRoutingTest {}}+ @Test+ fun everyGrantableCapabilityHasARoute() {+ // A capability's marker is what makes a *hidden* tool actionable: the+ // tool never runs, so ToolExecutor emits the capability's marker instead.+ // A marker with no route here means the deep-link silently does nothing+ // and the user is back to guessing which setting to enable (issue #76).+ val markers = com.gotcha.tools.Capability.entries.mapNotNull { it.permissionMarker }+ assertTrue("at least one capability must be grantable", markers.isNotEmpty())+ markers.forEach { marker ->+ assertNotNull(+ "capability marker '$marker' must have a route",+ openSpecialAccess(context, marker, packageName)+ )+ }+ }+@Testfun healthConnectPermissionScreenIsTheProviderTargetedIntent() {// The exact intent the HEALTH_CONNECT route fires when the provider is available: