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: route settings changes through four tiers with open_setting
Durganshu Mishra8d8d7a7134b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 757665d..ea9e1bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,70 @@ All notable changes to Gotcha are documented here.## [Unreleased]+### Added — tiered settings control (`open_setting`)++Settings were previously reached one of two ways: silently through an Android API,+or by asking the App Navigator to open the Settings app and search for the control.+The second path is the least reliable thing the agent does, and it was being used+even for settings with a documented direct intent. Two mechanisms Android does+provide — `Settings.Panel.*` sheets and `ACTION_*_SETTINGS` deep links — went+unused. Settings are now routed through four tiers, with the tier decided by what+the platform actually permits rather than by preference.++- **tools/SettingsRouter.kt** (new): the tier-2/3 routing table. 21 entries mapping+ a setting name to a panel or deep-link intent, an SDK floor with a fallback+ action, and a hint describing where the control sits on the screen that opens.+ The routing decision (`decide` / `resolveAction`) is a `Context`-free companion+ function so it is unit-testable on the JVM; only firing the intent needs a device.+ An unknown key returns an error naming `navigate_app`, so a miss degrades to the+ previous behaviour instead of dead-ending.+- **tools/ToolDefinitions.kt**: added the `open_setting` schema (`setting`,+ optional `confirmed`) and registered it in `all`. Corrected `toggle_wifi`'s+ description, which claimed direct toggling worked "on Android 13+" — the reverse+ is true: `WifiManager.setWifiEnabled` has been a no-op since API 29, so the+ panel fallback is what runs on every current device.+- **tools/ToolExecutor.kt**, **ToolCategories.kt**, **ToolRegistry.kt**: dispatch,+ `FOREGROUND` narration category, and Operator + App Navigator availability+ (including a trimmed navigator schema, without which `toolsForNavigator()` would+ silently drop it).+- **tools/SystemTool.kt**: the Wi-Fi fallback now goes through `SettingsRouter`+ rather than a private duplicate of the same intent.+- **Security-relevant screens require confirmation.** `developer_options`,+ `lock_screen`, `vpn` and `device_admin` refuse until `confirmed=true`, directing+ the agent to the existing `question` tool. This guards against accidental and+ prompt-injected changes; it is not a security boundary, since `run_root_command`,+ `write_secure_settings` and `navigate_app` reach the same screens.++### Changed — silent settings changes now report what they overwrote++A background change the user cannot observe was also one they were never told+about. `set_volume` already reported its previous value; the rest now match.++- **tools/SystemTool.kt**: `set_brightness` reports `Brightness 30% → 60%`, and+ reports `auto` when adaptive brightness was on rather than quoting the+ system-chosen value as if it were the user's setting.+- **tools/DeviceTool.kt**: `set_dnd` and `set_ringer_mode` report their previous+ state. `toggle_torch` deliberately does not — `CameraManager` has no synchronous+ torch getter, and a flashlight is visible to the user anyway.+- No undo tool: the model reverts by calling the setter again with the value it was+ told, which avoids a stored revert overwriting something the user changed by hand+ in the meantime.++### Fixed — duplicate Settings skills++`assets/skills/settings.json` and `assets/skills/settings/settings_search.json`+both targeted `com.android.settings`. The asset walk is recursive and+`SkillPromptBuilder` concatenates every match, so both were injected on every+Settings turn with overlapping, partly contradictory advice ("ALWAYS look for a+search bar" vs "start searching manually by swiping").++- Deleted `settings/settings_search.json`; `settings.json` is now the single+ Settings skill and teaches the tier order, with searching demoted to step 4.+- Gated on `requiresTools: ["open_setting"]`.+- **SkillRegistryTest**: the shadowing test asserted on a phrase from the shipped+ skill's text; it now asserts against the community text, so rewording the skill+ cannot fail a test about id collisions.+### Added — Samosa AI provider (Google authentication)Adds "Samosa AI" as an additional LLM provider alongside the existingdiff --git a/app/src/main/assets/skills/settings.json b/app/src/main/assets/skills/settings.jsonindex 9780b1c..51ef3a0 100644--- a/app/src/main/assets/skills/settings.json+++ b/app/src/main/assets/skills/settings.json@@ -1,7 +1,8 @@{"id": "settings_operations","targetPackageNames": ["com.android.settings"],- "name": "Android Settings Skills",- "description": "Optimal instructions for navigating Android system settings.",- "instructions": "When interacting with Android Settings, do NOT scroll manually to find a setting. This takes too long and fails frequently.\n1. Find the search bar or search icon at the top/bottom of the main Settings page.\n2. Tap it and type the exact setting you are looking for (e.g. 'Wi-Fi', 'Bluetooth', 'Display').\n3. Wait for the search results to load and tap the corresponding result.\n4. If a setting requires a toggle, look for a switch element and tap it to enable/disable. \n5. If you can't find settings by searching, cancel the search and start searching manually by swiping.."+ "title": "Android Settings Skills",+ "description": "How to reach and change Android system settings reliably.",+ "requiresTools": ["open_setting"],+ "instructions": "Work down this list and stop at the first step that applies. Opening the Settings app and searching is the LAST resort, not the first move.\n\n1. CHANGE IT DIRECTLY. Some settings never need the Settings app at all: set_volume, set_brightness, set_dnd, set_ringer_mode, toggle_torch and vibrate take effect immediately. Prefer these — they are instant and cannot fail on navigation. Most of them report the previous value; pass that on if it is relevant, and reuse it if you are later asked to change the setting back.\n\n2. JUMP STRAIGHT TO THE SCREEN. For settings you cannot change directly, call open_setting with the matching name (wifi, internet, mobile_data, nfc, bluetooth, location, airplane_mode, battery_saver, display, sound, date_time, language, input_method, storage, accessibility, default_apps, cast). It lands on the exact screen and tells you where the control is — then read_screen and tap it. Do not search for these; you are already there.\n\n3. ASK FIRST FOR RISKY ONES. developer_options, lock_screen, vpn and device_admin change device security or how the phone can be controlled. Use the question tool to get the user's explicit agreement, then call open_setting again with confirmed=true. Never do these silently, even if the request seems to imply it.\n\n4. ONLY THEN SEARCH. If open_setting has no entry for what you need (OEM-specific screens, gesture settings, per-manufacturer battery managers), open the Settings app and use its search: find the search bar or magnifying glass at the top, tap it, then use input_text — do NOT tap the on-screen keyboard key by key. After typing, tap the result with tap or tap_index rather than pressing enter. If the keyboard hides the results, use swipe to reveal what is behind it. Only scroll the Settings home page manually if search itself fails.\n\nWhen you report back, say what actually happened. If you only opened a screen for the user to finish, say that — do not claim you changed a setting you merely navigated to."}diff --git a/app/src/main/assets/skills/settings/settings_search.json b/app/src/main/assets/skills/settings/settings_search.jsondeleted file mode 100644index 8ac125d..0000000--- a/app/src/main/assets/skills/settings/settings_search.json+++ /dev/null@@ -1,6 +0,0 @@-{- "id": "settings_search",- "targetPackageNames": ["com.android.settings"],- "description": "Helps navigate Android Settings efficiently using search.",- "instructions": "In the Settings app, ALWAYS look for a search bar or search icon (magnifying glass) at the top/bottom of the screen. Tap it and use 'input_text' to search for the specific setting instead of scrolling manually in the home setting page. When you tap on it, you will see a keyboard appearing on the screen. Do not start typing on the keyboard. Use the tool 'input_text' and then use 'tap' tool to select the appropriate settings. Use the tool 'swipe' in order to see the hidden settings that are behind the keyboard."-}diff --git a/app/src/main/java/com/gotcha/tools/DeviceTool.kt b/app/src/main/java/com/gotcha/tools/DeviceTool.ktindex 058dc3a..a43e75f 100644--- a/app/src/main/java/com/gotcha/tools/DeviceTool.kt+++ b/app/src/main/java/com/gotcha/tools/DeviceTool.kt@@ -14,7 +14,15 @@ import android.os.VibratorManagerclass DeviceTool(private val context: Context) {- /** Turn the camera flash on or off. No permission needed for CameraManager.setTorchMode. */+ /**+ * Turn the camera flash on or off. No permission needed for CameraManager.setTorchMode.+ *+ * Unlike the other device tools this does *not* report a previous state.+ * `CameraManager` has no synchronous torch getter — the only way to read it is+ * `registerTorchCallback`, which delivers asynchronously on a handler thread.+ * The point of prior-state reporting is to surface changes the user cannot+ * observe, and a flashlight is the one change here they always can.+ */fun toggleTorch(on: Boolean, durationSeconds: Int?): ToolResult {return try {val cm = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager@@ -121,8 +129,9 @@ class DeviceTool(private val context: Context) {}return try {val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager+ val previous = ringerLabel(am.ringerMode)am.ringerMode = ringerMode- ToolResult.ok("Ringer set to ${mode.lowercase().trim()}.")+ ToolResult.ok("Ringer $previous → ${mode.lowercase().trim()}.")} catch (_: SecurityException) {ToolResult.permissionNeeded(ToolResult.DND_ACCESS,@@ -196,6 +205,7 @@ class DeviceTool(private val context: Context) {}return try {val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ val wasOn = nm.currentInterruptionFilter != NotificationManager.INTERRUPTION_FILTER_ALLnm.setInterruptionFilter(if (enabled) {NotificationManager.INTERRUPTION_FILTER_PRIORITY@@ -203,12 +213,21 @@ class DeviceTool(private val context: Context) {NotificationManager.INTERRUPTION_FILTER_ALL})- ToolResult.ok("Do Not Disturb turned ${if (enabled) "on" else "off"}.")+ ToolResult.ok(+ "Do Not Disturb ${if (wasOn) "on" else "off"} → ${if (enabled) "on" else "off"}."+ )} catch (e: Exception) {ToolResult.error("Could not change Do Not Disturb: ${e.message}")}}+ private fun ringerLabel(mode: Int): String = when (mode) {+ AudioManager.RINGER_MODE_NORMAL -> "normal"+ AudioManager.RINGER_MODE_VIBRATE -> "vibrate"+ AudioManager.RINGER_MODE_SILENT -> "silent"+ else -> "unknown"+ }+private fun hasDndAccess(): Boolean {val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManagerreturn nm.isNotificationPolicyAccessGranteddiff --git a/app/src/main/java/com/gotcha/tools/SettingsRouter.kt b/app/src/main/java/com/gotcha/tools/SettingsRouter.ktnew file mode 100644index 0000000..6ec4f1e--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/SettingsRouter.kt@@ -0,0 +1,297 @@+package com.gotcha.tools++import android.content.Context+import android.content.Intent+import android.os.Build+import android.provider.Settings++/**+ * How a settings destination is reached. The tier is dictated by what Android+ * permits a non-privileged app to do, not by preference — see the tier model in+ * `AGENTS.md`.+ *+ * Tier 1 (change it silently through an API) is not represented here: those are+ * ordinary tools on [DeviceTool] / [SystemTool]. This router owns tiers 2 and 3,+ * and hands anything it does not know back to tier 4 (`navigate_app`).+ */+enum class Route {+ /** A `Settings.Panel.*` sheet: slides up over the caller, one tap, no navigation. */+ PANEL,++ /** An `ACTION_*_SETTINGS` deep link: lands on the exact screen, then 1-2 taps. */+ DEEPLINK,++ /**+ * A deep link the agent must not follow without asking first.+ *+ * This is a guard against *accidental* silent changes and against injected+ * ones — the app reads screen text, notifications and email into the model's+ * context, all of which an attacker can influence. It is deliberately **not**+ * a security boundary: `run_root_command`, `write_secure_settings` and+ * `navigate_app` all reach the same screens by other routes.+ */+ CONFIRM_FIRST+}++/**+ * One row of the routing table.+ *+ * @param action the intent action to fire on a device new enough for it.+ * @param minSdk the API level [action] was introduced at; below this,+ * [fallbackAction] is used instead.+ * @param hint where the control lives on the screen that opens. Returned to the+ * agent so the navigator starts from a known position rather than re-deriving+ * it from a screen read.+ */+data class SettingRoute(+ val key: String,+ val route: Route,+ val action: String,+ val label: String,+ val hint: String,+ val minSdk: Int = 0,+ val fallbackAction: String? = null+)++/**+ * Opens Android settings screens the app is not allowed to change silently.+ *+ * The table is a closed list on purpose: an unknown key returns an error naming+ * `navigate_app`, so a miss degrades to the old search-and-scroll behaviour+ * rather than dead-ending. Expect to add entries over time — that maintenance+ * cost was accepted when this replaced blind navigation as the default path.+ */+class SettingsRouter(private val context: Context) {++ fun open(key: String, confirmed: Boolean): ToolResult {+ val entry = when (val decision = decide(key, confirmed)) {+ is Decision.Refused -> return ToolResult.error(decision.message)+ is Decision.Proceed -> decision.entry+ }++ val action = resolveAction(entry, Build.VERSION.SDK_INT)+ return try {+ context.startActivity(+ Intent(action).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }+ )+ ToolResult.ok("Opened ${entry.label}. ${entry.hint}")+ } catch (e: Exception) {+ // Not every OEM ships an activity for every documented action.+ ToolResult.error(+ "Could not open ${entry.label} directly (${e.message}). Fall back to navigate_app: " ++ "open the Settings app and search for it there."+ )+ }+ }++ /** Whether a request may proceed, and why not when it may not. */+ sealed interface Decision {+ data class Proceed(val entry: SettingRoute) : Decision+ data class Refused(val message: String) : Decision+ }++ companion object {++ fun knownKeys(): List<String> = ROUTES.keys.sorted()++ /** Exposed for tests; the router itself goes through [ROUTES]. */+ internal fun routeFor(key: String): SettingRoute? = ROUTES[key]++ /**+ * The whole routing decision, with no [Context] involved — everything up+ * to the point where an intent is actually fired. Kept separate so it is+ * testable on the JVM: the table, the confirmation gate and the+ * unknown-key fallback are where the bugs would be, not `startActivity`.+ */+ internal fun decide(key: String, confirmed: Boolean): Decision {+ val normalized = key.lowercase().trim().replace(' ', '_').replace('-', '_')+ val entry = ROUTES[normalized] ?: return Decision.Refused(+ "No direct route for '$key'. Known settings: ${knownKeys().joinToString(", ")}. " ++ "For anything else, use navigate_app to open the Settings app and search for it."+ )+ if (entry.route == Route.CONFIRM_FIRST && !confirmed) {+ return Decision.Refused(+ "${entry.label} affects device security or how the phone is controlled, so it " ++ "needs the user's explicit go-ahead. Ask them with the 'question' tool, " ++ "then call open_setting again with confirmed=true if they agree."+ )+ }+ return Decision.Proceed(entry)+ }++ /** The action to fire at [sdkInt], honouring [SettingRoute.minSdk]. */+ internal fun resolveAction(entry: SettingRoute, sdkInt: Int): String =+ if (sdkInt < entry.minSdk && entry.fallbackAction != null) {+ entry.fallbackAction+ } else {+ entry.action+ }++ internal val ROUTES: Map<String, SettingRoute> = listOf(+ // ---- Tier 2: Settings Panels (slide-up sheet, no navigation) ----+ SettingRoute(+ key = "wifi",+ route = Route.PANEL,+ action = Settings.Panel.ACTION_WIFI,+ label = "the Wi-Fi panel",+ hint = "It lists nearby networks with a Wi-Fi toggle at the top."+ ),+ SettingRoute(+ key = "internet",+ route = Route.PANEL,+ action = Settings.Panel.ACTION_INTERNET_CONNECTIVITY,+ label = "the internet connectivity panel",+ hint = "It has both the Wi-Fi and mobile-data toggles.",+ minSdk = Build.VERSION_CODES.Q,+ fallbackAction = Settings.Panel.ACTION_WIFI+ ),+ SettingRoute(+ key = "mobile_data",+ route = Route.PANEL,+ action = Settings.Panel.ACTION_INTERNET_CONNECTIVITY,+ label = "the internet connectivity panel",+ hint = "Mobile data is the second toggle, under Wi-Fi.",+ minSdk = Build.VERSION_CODES.Q,+ fallbackAction = Settings.ACTION_DATA_ROAMING_SETTINGS+ ),+ SettingRoute(+ key = "nfc",+ route = Route.PANEL,+ action = Settings.Panel.ACTION_NFC,+ label = "the NFC panel",+ hint = "A single NFC toggle."+ ),++ // ---- Tier 3: deep links (exact screen, then 1-2 taps) ----+ SettingRoute(+ key = "bluetooth",+ route = Route.DEEPLINK,+ action = Settings.ACTION_BLUETOOTH_SETTINGS,+ label = "Bluetooth settings",+ hint = "The master toggle is at the top; paired devices are listed below it."+ ),+ SettingRoute(+ key = "location",+ route = Route.DEEPLINK,+ action = Settings.ACTION_LOCATION_SOURCE_SETTINGS,+ label = "Location settings",+ hint = "The master 'Use location' toggle is at the top."+ ),+ SettingRoute(+ key = "airplane_mode",+ route = Route.DEEPLINK,+ action = Settings.ACTION_AIRPLANE_MODE_SETTINGS,+ label = "Airplane mode settings",+ hint = "The airplane-mode toggle is in the network list on this screen."+ ),+ SettingRoute(+ key = "battery_saver",+ route = Route.DEEPLINK,+ action = Settings.ACTION_BATTERY_SAVER_SETTINGS,+ label = "Battery saver settings",+ hint = "'Use Battery Saver' is the main toggle."+ ),+ SettingRoute(+ key = "display",+ route = Route.DEEPLINK,+ action = Settings.ACTION_DISPLAY_SETTINGS,+ label = "Display settings",+ hint = "Brightness, dark theme, font size and screen timeout live here."+ ),+ SettingRoute(+ key = "sound",+ route = Route.DEEPLINK,+ action = Settings.ACTION_SOUND_SETTINGS,+ label = "Sound settings",+ hint = "Volume sliders, ringtone and Do Not Disturb live here."+ ),+ // No "notifications" entry on purpose: ACTION_NOTIFICATION_SETTINGS is+ // @hide in AOSP, and the public ACTION_APP_NOTIFICATION_SETTINGS needs+ // an EXTRA_APP_PACKAGE, so it cannot open the device-wide screen. That+ // makes notifications a genuine tier-4 case — navigate_app handles it.+ SettingRoute(+ key = "date_time",+ route = Route.DEEPLINK,+ action = Settings.ACTION_DATE_SETTINGS,+ label = "Date & time settings",+ hint = "Turn off 'Set time automatically' before the manual fields become editable."+ ),+ SettingRoute(+ key = "language",+ route = Route.DEEPLINK,+ action = Settings.ACTION_LOCALE_SETTINGS,+ label = "Language settings",+ hint = "'Add a language' is at the bottom; drag a language to the top to make it primary."+ ),+ SettingRoute(+ key = "input_method",+ route = Route.DEEPLINK,+ action = Settings.ACTION_INPUT_METHOD_SETTINGS,+ label = "Keyboard settings",+ hint = "Installed keyboards are listed with per-keyboard toggles."+ ),+ SettingRoute(+ key = "storage",+ route = Route.DEEPLINK,+ action = Settings.ACTION_INTERNAL_STORAGE_SETTINGS,+ label = "Storage settings",+ hint = "Usage by category, with a 'Free up space' action."+ ),+ SettingRoute(+ key = "accessibility",+ route = Route.DEEPLINK,+ action = Settings.ACTION_ACCESSIBILITY_SETTINGS,+ label = "Accessibility settings",+ hint = "Installed services are under 'Downloaded apps' or 'Installed services'."+ ),+ SettingRoute(+ key = "default_apps",+ route = Route.DEEPLINK,+ action = Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS,+ label = "Default apps settings",+ hint = "One row per role (browser, phone, SMS, assistant).",+ minSdk = Build.VERSION_CODES.N,+ fallbackAction = Settings.ACTION_SETTINGS+ ),+ SettingRoute(+ key = "cast",+ route = Route.DEEPLINK,+ action = Settings.ACTION_CAST_SETTINGS,+ label = "Cast settings",+ hint = "Nearby cast targets are listed; tap one to connect."+ ),++ // ---- Security-relevant: always confirm with the user first ----+ SettingRoute(+ key = "developer_options",+ route = Route.CONFIRM_FIRST,+ action = Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS,+ label = "Developer options",+ hint = "The master toggle is at the top. Many switches here weaken device safety."+ ),+ SettingRoute(+ key = "lock_screen",+ route = Route.CONFIRM_FIRST,+ action = Settings.ACTION_SECURITY_SETTINGS,+ label = "Security & lock screen settings",+ hint = "'Screen lock' is near the top. Changing it may require the current PIN."+ ),+ SettingRoute(+ key = "vpn",+ route = Route.CONFIRM_FIRST,+ action = Settings.ACTION_VPN_SETTINGS,+ label = "VPN settings",+ hint = "Configured VPNs are listed; a VPN can see all network traffic.",+ minSdk = Build.VERSION_CODES.N,+ fallbackAction = Settings.ACTION_SETTINGS+ ),+ SettingRoute(+ key = "device_admin",+ route = Route.CONFIRM_FIRST,+ action = Settings.ACTION_SECURITY_SETTINGS,+ label = "Device admin settings",+ hint = "'Device admin apps' is under the advanced section. These apps can wipe the device."+ )+ ).associateBy { it.key }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.ktindex 4b35207..7fd1cbb 100644--- a/app/src/main/java/com/gotcha/tools/SystemTool.kt+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt@@ -22,6 +22,10 @@ class SystemTool(private val context: Context) {}return try {val resolver = context.contentResolver+ // Read before writing so the reply can say what was overwritten — the+ // user never sees this change happen, and it is the only way the model+ // can put the old value back if asked.+ val previous = previousBrightnessLabel(resolver)Settings.System.putInt(resolver,Settings.System.SCREEN_BRIGHTNESS_MODE,@@ -32,12 +36,35 @@ class SystemTool(private val context: Context) {Settings.System.SCREEN_BRIGHTNESS,(percent * 255) / 100)- ToolResult.ok("Screen brightness set to $percent%.")+ ToolResult.ok("Brightness $previous → $percent%.")} catch (e: Exception) {ToolResult.error("Could not set brightness: ${e.message}")}}+ /**+ * The brightness the user had, as text. Reports "auto" when adaptive+ * brightness was on: the stored [Settings.System.SCREEN_BRIGHTNESS] is+ * whatever the system last picked, so quoting it as the user's setting would+ * be misleading, and telling the model to restore it would silently leave+ * adaptive brightness off.+ */+ private fun previousBrightnessLabel(resolver: android.content.ContentResolver): String = try {+ val auto = Settings.System.getInt(+ resolver,+ Settings.System.SCREEN_BRIGHTNESS_MODE,+ Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL+ ) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC+ if (auto) {+ "auto"+ } else {+ val raw = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS, -1)+ if (raw < 0) "unknown" else "${(raw * 100) / 255}%"+ }+ } catch (_: Exception) {+ "unknown"+ }+fun getBatteryInfo(): ToolResult {return try {val bm = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager@@ -107,16 +134,13 @@ class SystemTool(private val context: Context) {}}- private fun openWifiSettings(): ToolResult {- return try {- val intent = Intent(Settings.Panel.ACTION_WIFI)- .apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }- context.startActivity(intent)- ToolResult.ok("Opened the Wi-Fi settings panel so the user can toggle Wi-Fi.")- } catch (e: Exception) {- ToolResult.error("Could not open Wi-Fi settings: ${e.message}")- }- }+ /**+ * The path every device from Android 10 on actually takes: `setWifiEnabled`+ * has been a no-op since API 29, so the panel is the only way. Routed through+ * [SettingsRouter] so there is one place that knows how Wi-Fi is reached.+ */+ private fun openWifiSettings(): ToolResult =+ SettingsRouter(context).open("wifi", confirmed = false)fun openApp(packageName: String): ToolResult {return try {diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex 646dcc4..b833ad6 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -11,7 +11,7 @@ object ToolCategories {private val foregroundTools = setOf("tap", "tap_index", "long_press", "long_press_index","swipe", "input_text", "press_key",- "global_action", "open_app",+ "global_action", "open_app", "open_setting","read_screen", "read_screen_raw","navigate_app", "task","dial_number", "compose_email", "show_alarms"diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 9e3b884..912a7b9 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -177,8 +177,9 @@ object ToolDefinitions {val toggleWifi = tool("toggle_wifi",- "Turn Wi-Fi on or off directly (on Android 13+) or open the Wi-Fi settings panel for the " +- "user to toggle it (older Android). Reports whether Wi-Fi is currently enabled.",+ "Turn Wi-Fi on or off. Android 10 and newer forbid apps from toggling the radio, so on " ++ "any current device this opens the Wi-Fi panel for the user to flip instead — say so " ++ "rather than claiming the radio changed. Direct toggling only works below Android 10.",schema {putJsonObject("properties") {putJsonObject("enabled") {@@ -190,6 +191,38 @@ object ToolDefinitions {})+ val openSetting = tool(+ "open_setting",+ "Open an Android settings screen directly, for settings this app is not allowed to " ++ "change on its own. Much more reliable than opening the Settings app and searching. " ++ "Use it before navigate_app for anything it covers, then tap the control it " ++ "describes. Valid values for 'setting': " ++ "wifi, internet, mobile_data, nfc, bluetooth, location, airplane_mode, " ++ "battery_saver, display, sound, date_time, language, input_method, " ++ "storage, accessibility, default_apps, cast, developer_options, lock_screen, vpn, " ++ "device_admin. For anything not listed, use navigate_app instead. " ++ "Prefer the direct tools where they exist — set_volume, set_brightness, set_dnd, " ++ "set_ringer_mode and toggle_torch change those without leaving the app.",+ schema {+ putJsonObject("properties") {+ putJsonObject("setting") {+ put("type", "string")+ put("description", "Which settings screen to open, e.g. 'location' or 'bluetooth'.")+ }+ putJsonObject("confirmed") {+ put("type", "boolean")+ put(+ "description",+ "Set true only after the user has explicitly agreed. Required for the " ++ "security-relevant screens (developer_options, lock_screen, vpn, " ++ "device_admin), which otherwise refuse to open."+ )+ }+ }+ putJsonArray("required") { add("setting") }+ }+ )+val setWallpaper = tool("set_wallpaper","Set the home-screen wallpaper from an image URL, or a random image if no URL is given.",@@ -1821,7 +1854,7 @@ object ToolDefinitions {put("type", "string")put("description",- "The package name, app name, or operation to search for (e.g. 'com.whatsapp', 'whatsapp', 'settings_search')."+ "The package name, app name, or operation to search for (e.g. 'com.whatsapp', 'whatsapp', 'settings_operations').")}}@@ -2152,7 +2185,7 @@ object ToolDefinitions {val all: List<ToolDefinition> = listOf(dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,- openApp, setBrightness, toggleWifi,+ openApp, setBrightness, toggleWifi, openSetting,setWallpaper, runCommand,// Tier 0–2 additionscallNumber, readCallLog, findContact, addContact, sendSms, readRecentSms,diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 5bc06e1..48f7592 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -33,6 +33,7 @@ class ToolExecutor(private val appContext = context.applicationContextprivate val phoneTool = PhoneTool(appContext)private val systemTool = SystemTool(appContext)+ private val settingsRouter = SettingsRouter(appContext)private val storageTool = StorageTool()private val fileTool = FileTool(appContext)private val terminalTool = TerminalTool()@@ -198,6 +199,10 @@ class ToolExecutor("toggle_wifi" -> systemTool.toggleWifi(args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled"))+ "open_setting" -> settingsRouter.open(+ key = args.requireString("setting") ?: return missing("setting"),+ confirmed = args["confirmed"]?.jsonPrimitive?.booleanOrNull ?: false+ )"set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))"run_command" -> terminalTool.runCommand(command = args.requireString("command") ?: return missing("command"),diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex c9844cc..62dc0f5 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -66,7 +66,7 @@ object ToolRegistry {/** Tools available to the App Navigator sub-agent. */val navigatorTools: Set<String> = setOf("tap", "tap_index", "long_press", "long_press_index", "swipe", "input_text", "press_key",- "global_action", "open_app", "list_installed_apps", "search_skills",+ "global_action", "open_app", "open_setting", "list_installed_apps", "search_skills","sleep", "ask_final_answer")@@ -281,6 +281,25 @@ object ToolRegistry {})),+ "open_setting" to ToolDefinition(+ function = FunctionDefinition(+ "open_setting",+ "Jump straight to an Android settings screen instead of searching in Settings. " ++ "One of: wifi, internet, mobile_data, nfc, bluetooth, location, airplane_mode, " ++ "battery_saver, display, sound, date_time, language, " ++ "input_method, storage, accessibility, default_apps, cast.",+ buildJsonObject {+ put("type", "object")+ putJsonObject("properties") {+ putJsonObject("setting") {+ put("type", "string")+ put("description", "Which settings screen to open")+ }+ }+ putJsonArray("required") { add("setting") }+ }+ )+ ),"global_action" to ToolDefinition(function = FunctionDefinition("global_action",diff --git a/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt b/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.ktindex d4803aa..4958a6e 100644--- a/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt+++ b/app/src/test/java/com/gotcha/agent/skills/SkillRegistryTest.kt@@ -4,6 +4,7 @@ import androidx.test.core.app.ApplicationProviderimport kotlinx.coroutines.runBlockingimport org.junit.Afterimport org.junit.Assert.assertEquals+import org.junit.Assert.assertNotEqualsimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertTrueimport org.junit.Before@@ -115,8 +116,10 @@ class SkillRegistryTest {SkillRegistry.importCommunity(json)val resolved = SkillRegistry.getSkillById("settings_operations")assertNotNull(resolved)- // Bundled wins — its instructions never get replaced.- assertTrue(resolved!!.instructions.contains("do NOT scroll"))+ // Bundled wins — its instructions never get replaced. Asserted against the+ // community text rather than a phrase from the bundled skill, so rewording+ // the shipped skill cannot fail a test about shadowing.+ assertNotEquals("shadowed", resolved!!.instructions)}@Testdiff --git a/app/src/test/java/com/gotcha/tools/SettingsRouterTest.kt b/app/src/test/java/com/gotcha/tools/SettingsRouterTest.ktnew file mode 100644index 0000000..4734f97--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/SettingsRouterTest.kt@@ -0,0 +1,132 @@+package com.gotcha.tools++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * Guards the routing table itself — the half of `open_setting` that decides+ * *where* to go. Firing the intent needs a device; picking the right one does+ * not, which is the point of keeping the table as data.+ */+class SettingsRouterTest {++ private val routes = SettingsRouter.ROUTES.values++ @Test+ fun everyEntryIsUsable() {+ routes.forEach { entry ->+ assertTrue("${entry.key}: blank action", entry.action.isNotBlank())+ assertTrue("${entry.key}: blank label", entry.label.isNotBlank())+ // The hint is the whole reason a deep link beats a blind search — it+ // tells the navigator where the control is on the screen that opens.+ assertTrue("${entry.key}: blank hint", entry.hint.isNotBlank())+ }+ }++ @Test+ fun keysAreNormalisedLowerSnakeCase() {+ routes.forEach { entry ->+ assertEquals(+ "${entry.key}: keys must be lower_snake_case so open() can normalise input to them",+ entry.key.lowercase().replace(' ', '_').replace('-', '_'),+ entry.key+ )+ }+ }++ @Test+ fun sdkGatedEntriesDeclareAFallback() {+ routes.filter { it.minSdk > 0 }.forEach { entry ->+ assertNotNull(+ "${entry.key}: declares minSdk ${entry.minSdk} but no fallbackAction, so it " ++ "would fire an action the device does not have",+ entry.fallbackAction+ )+ }+ // …and nothing declares a fallback it can never use.+ routes.filter { it.fallbackAction != null }.forEach { entry ->+ assertTrue("${entry.key}: fallbackAction with no minSdk is dead code", entry.minSdk > 0)+ }+ }++ @Test+ fun securityRelevantScreensAreConfirmFirst() {+ setOf("developer_options", "lock_screen", "vpn", "device_admin").forEach { key ->+ val entry = SettingsRouter.routeFor(key)+ assertNotNull("$key missing from the routing table", entry)+ assertEquals(+ "$key must not be reachable without the user agreeing first",+ Route.CONFIRM_FIRST,+ entry!!.route+ )+ }+ }++ @Test+ fun knownKeysListsEveryEntry() {+ assertEquals(SettingsRouter.ROUTES.size, SettingsRouter.knownKeys().size)+ assertTrue("location" in SettingsRouter.knownKeys())+ }++ @Test+ fun unknownKeyPointsAtNavigateApp() {+ val decision = SettingsRouter.decide("font_size", confirmed = false)+ assertTrue(decision is SettingsRouter.Decision.Refused)+ val message = (decision as SettingsRouter.Decision.Refused).message+ assertTrue(+ "an unlisted setting must degrade to navigate_app, not dead-end: $message",+ message.contains("navigate_app")+ )+ }++ @Test+ fun keysAreMatchedLeniently() {+ // The model writes what it likes; "Airplane Mode" and "airplane-mode"+ // must reach the same row as "airplane_mode".+ listOf("airplane_mode", "Airplane Mode", "airplane-mode", " AIRPLANE_MODE ").forEach { input ->+ val decision = SettingsRouter.decide(input, confirmed = false)+ assertTrue("'$input' did not resolve", decision is SettingsRouter.Decision.Proceed)+ assertEquals(+ "airplane_mode",+ (decision as SettingsRouter.Decision.Proceed).entry.key+ )+ }+ }++ @Test+ fun confirmFirstRefusesUntilConfirmed() {+ val refused = SettingsRouter.decide("developer_options", confirmed = false)+ assertTrue(refused is SettingsRouter.Decision.Refused)+ val message = (refused as SettingsRouter.Decision.Refused).message+ assertTrue(+ "the refusal must tell the agent how to proceed: $message",+ message.contains("question") && message.contains("confirmed=true")+ )++ val allowed = SettingsRouter.decide("developer_options", confirmed = true)+ assertTrue("confirming must unblock it", allowed is SettingsRouter.Decision.Proceed)+ }++ @Test+ fun ordinaryRoutesDoNotNeedConfirmation() {+ val decision = SettingsRouter.decide("location", confirmed = false)+ assertTrue(decision is SettingsRouter.Decision.Proceed)+ }++ @Test+ fun sdkFallbackIsUsedBelowMinSdk() {+ val gated = routes.first { it.minSdk > 0 && it.fallbackAction != null }+ assertEquals(+ "below minSdk the fallback action must be chosen",+ gated.fallbackAction,+ SettingsRouter.resolveAction(gated, gated.minSdk - 1)+ )+ assertEquals(+ "at or above minSdk the primary action must be chosen",+ gated.action,+ SettingsRouter.resolveAction(gated, gated.minSdk)+ )+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 66baa88..014a5c8 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -69,11 +69,19 @@"tool": "toggle_wifi","tier": "MANUAL_ONLY","reason": "The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier.",- "manualSteps": "Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio.",+ "manualSteps": "Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio. The panel is opened via SettingsRouter, so open_setting('wifi') must behave identically.","tests": ["com.gotcha.tools.SystemToolTest"]},+ {+ "tool": "open_setting",+ "tier": "UNIT",+ "tests": [+ "com.gotcha.tools.SettingsRouterTest"+ ],+ "notes": "routing table integrity, SDK fallback selection, unknown-key fallback to navigate_app, and the confirm-first gate"+ },{"tool": "set_wallpaper","tier": "MANUAL_ONLY",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex e03868a..4a7923c 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -13,13 +13,13 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|-| `UNIT` | 19 | Plain JVM unit test — no Android framework needed. |+| `UNIT` | 20 | Plain JVM unit test — no Android framework needed. || `ROBOLECTRIC` | 17 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **100** | |+| **Total** | **101** | |-**36 of 100** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**37 of 101** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -33,6 +33,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `long_press_index` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `navigate_app` | `MANUAL_ONLY` | Nested navigator agent loop over a live accessibility service and a live LLM connection. || `open_app` | `ROBOLECTRIC` | `SystemToolTest` — launch intent flags and the unknown-package message |+| `open_setting` | `UNIT` | `SettingsRouterTest` — routing table integrity, SDK fallback selection, unknown-key fallback to navigate_app, and the confirm-first gate || `press_key` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `read_screen` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `read_screen_raw` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). |@@ -274,7 +275,7 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Pure UI round-trip: writes the visible todo list in the chat surface.- [ ] **`toggle_torch`** — Ask the agent to turn the torch on, then off; confirm the flash physically lights up.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.-- [ ] **`toggle_wifi`** — Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio.+- [ ] **`toggle_wifi`** — Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio. The panel is opened via SettingsRouter, so open_setting('wifi') must behave identically.<br>_Why not automated:_ The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier.- [ ] **`uninstall_app`** — Install a throwaway app, ask the agent to uninstall it; confirm the confirmation prompt appears, then that the system uninstall dialog opens and the app is removed.<br>_Why not automated:_ AgentLoopTest covers the CONFIRM_UNINSTALL marker and both sides of the confirmation gate, but the actual package removal is a system dialog that cannot be automated.