Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(tools): set_screen_timeout, and open_setting stops describing a screen it can't see
Durganshu1b7c0ab69f80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1df5954..87f420e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -234,6 +234,14 @@ All notable changes to Gotcha are documented here.A chat started with an image and no text is called "Image chat" instead ofhaving a blank name, and gets a proper title from the first message you writein it (#95).+- **Gotcha can change the screen timeout itself.** Asked to keep the screen on+ longer, it used to try a shell command, then open a settings page and describe+ it as if it could see it — on a Redmi, the wrong page. It now sets the timeout+ directly (15 seconds to 30 minutes) with the same "Modify system settings"+ access it uses for brightness, asks for that access the first time, and says+ what the timeout was before. When it opens a settings page, it now names the+ screen your phone actually opened and says what to look for, instead of+ claiming a control is in front of you.- **A task keeps running when you swipe Gotcha away** (#111). Swiping Gotcha outof your recent apps while it worked on a task, or pressing Back on its homescreen mid-task on Android 11, used to stop the task as if you had presseddiff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.mdindex 6cc7d61..59f213f 100644--- a/app/src/main/assets/app/about-gotcha.md+++ b/app/src/main/assets/app/about-gotcha.md@@ -42,7 +42,7 @@ mid-conversation.- **Notifications** — read them, dismiss them, control media playback, reportwhat is now playing.- **Device control** — Wi-Fi, torch, volume, ringer mode, Do Not Disturb,- brightness, wallpaper, vibration, clipboard, app launch and uninstall, app and+ brightness, screen timeout, wallpaper, vibration, clipboard, app launch and uninstall, app anddata usage, location.- **System access** — shell commands, root commands and secure-settings writeson a rooted device, and full Linux user-space through Termux.diff --git a/app/src/main/assets/skills/settings.json b/app/src/main/assets/skills/settings.jsonindex 51ef3a0..b9744c2 100644--- a/app/src/main/assets/skills/settings.json+++ b/app/src/main/assets/skills/settings.json@@ -4,5 +4,5 @@"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."+ "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_screen_timeout, 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/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 3709d0f..69e33f2 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -1408,7 +1408,7 @@ class AgentEngine("and dismiss them, manage the task list.\n" +"- Files & media: write and edit files, read images, take photos, record and " +"pause/stop audio, edit or convert media and PDFs, set the wallpaper.\n" +- "- Device settings: volume, brightness, ringer, Do Not Disturb, Wi-Fi, torch, " ++ "- Device settings: volume, brightness, screen timeout, ringer, Do Not Disturb, Wi-Fi, torch, " +"vibrate, clipboard, lock the screen, open any Settings page, write secure " +"settings, uninstall apps, disable the camera and set password policy.\n" +"- Notifications: dismiss them.\n" +diff --git a/app/src/main/java/com/gotcha/tools/SettingsRouter.kt b/app/src/main/java/com/gotcha/tools/SettingsRouter.ktindex de5f3bb..0f7d4cb 100644--- a/app/src/main/java/com/gotcha/tools/SettingsRouter.kt+++ b/app/src/main/java/com/gotcha/tools/SettingsRouter.kt@@ -42,6 +42,27 @@ enum class Route {* agent so the navigator starts from a known position rather than re-deriving* it from a screen read.*/+/**+ * What open_setting reports. The screen is launched, not seen: nothing here+ * knows what is on it, and phone makers move controls between screens, so+ * [SettingRoute.hint] is offered as where the control is on stock Android, and+ * the model is told to check the screen, or say what to look for, before telling+ * the user where to tap.+ */+internal fun openedMessage(entry: SettingRoute, screenTitle: String?): String = buildString {+ append("Opened ${entry.label}")+ if (screenTitle != null && !screenTitle.equals(entry.label, ignoreCase = true)) {+ append(" (this phone titles the screen \"$screenTitle\")")+ }+ append(". On stock Android: ${entry.hint} ")+ append(+ "Phone makers move settings between screens, so this is not a description of what the " ++ "user sees. Use read_screen before saying where a control is; if the screen can't be " ++ "read, tell the user which screen you opened and what to look for there, not that " ++ "the control is in front of them."+ )+}+data class SettingRoute(val key: String,val route: Route,@@ -69,11 +90,11 @@ class SettingsRouter(private val context: Context) {}val action = resolveAction(entry, Build.VERSION.SDK_INT)+ val intent = Intent(action).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }return try {- context.startActivity(- Intent(action).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }- )- ToolResult.ok("Opened ${entry.label}. ${entry.hint}")+ val title = screenTitle(intent)+ context.startActivity(intent)+ ToolResult.ok(openedMessage(entry, title))} catch (e: Exception) {// Not every OEM ships an activity for every documented action.ToolResult.error(@@ -83,6 +104,19 @@ class SettingsRouter(private val context: Context) {}}+ /**+ * The title of the screen [intent] opens on this phone, when it has one of+ * its own: MIUI answers SECURITY_SETTINGS with "Passwords & security", for+ * instance, not a lock-screen page. Null when it can't be read or is only the+ * Settings app's name.+ */+ private fun screenTitle(intent: Intent): String? = runCatching {+ val pm = context.packageManager+ val info = pm.resolveActivity(intent, 0)?.activityInfo ?: return null+ val title = info.loadLabel(pm).toString()+ title.takeIf { it.isNotBlank() && it != info.applicationInfo.loadLabel(pm).toString() }+ }.getOrNull()+/** Whether a request may proceed, and why not when it may not. */sealed interface Decision {data class Proceed(val entry: SettingRoute) : Decision@@ -195,7 +229,8 @@ class SettingsRouter(private val context: Context) {route = Route.DEEPLINK,action = Settings.ACTION_DISPLAY_SETTINGS,label = "Display settings",- hint = "Brightness, dark theme, font size and screen timeout live here."+ hint = "Brightness, dark theme, font size and screen timeout live here " ++ "(set_screen_timeout changes the timeout directly)."),SettingRoute(key = "sound",diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.ktindex 6dedaf1..7772e2e 100644--- a/app/src/main/java/com/gotcha/tools/SystemTool.kt+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt@@ -68,6 +68,38 @@ class SystemTool("unknown"}+ /**+ * Sets how long the screen stays on without a touch. A plain system setting,+ * so the "Modify system settings" access that [setBrightness] uses is enough:+ * no Accessibility, and no hunting for the page, which OEMs move around (MIUI+ * keeps it under Lock screen as "Sleep", not under Display).+ */+ fun setScreenTimeout(seconds: Int): ToolResult {+ if (seconds !in MIN_SCREEN_TIMEOUT_S..MAX_SCREEN_TIMEOUT_S) {+ return ToolResult.error(+ "Screen timeout must be between $MIN_SCREEN_TIMEOUT_S seconds and " ++ "${MAX_SCREEN_TIMEOUT_S / 60} minutes (got $seconds seconds)."+ )+ }+ if (!Settings.System.canWrite(context)) {+ return ToolResult.permissionNeeded(+ ToolResult.WRITE_SETTINGS,+ "Missing the 'Modify system settings' special access. " ++ "I have opened the settings page — please enable it for Gotcha and ask again."+ )+ }+ return try {+ val resolver = context.contentResolver+ // Read first, as set_brightness does, so the reply can say what was+ // replaced and the model can put it back if asked.+ val previous = Settings.System.getInt(resolver, Settings.System.SCREEN_OFF_TIMEOUT, -1)+ Settings.System.putInt(resolver, Settings.System.SCREEN_OFF_TIMEOUT, seconds * 1000)+ ToolResult.ok("Screen timeout ${timeoutLabel(previous)} → ${timeoutLabel(seconds * 1000)}.")+ } catch (e: Exception) {+ ToolResult.error("Could not set the screen timeout: ${e.message}")+ }+ }+fun getBatteryInfo(): ToolResult {return try {val bm = context.getSystemService(Context.BATTERY_SERVICE) as BatteryManager@@ -180,4 +212,21 @@ class SystemTool(ToolResult.error("Could not open app: ${e.message}")}}++ companion object {+ /** The shortest timeout Android's own settings offer. */+ const val MIN_SCREEN_TIMEOUT_S = 15++ /** The longest Android's own settings offer; anything longer is "never" in practice. */+ const val MAX_SCREEN_TIMEOUT_S = 30 * 60++ /** A screen timeout in milliseconds, as the Settings app would name it. */+ internal fun timeoutLabel(millis: Int): String = when {+ millis < 0 -> "unknown"+ // OEM "Never" options store the largest int rather than a real duration.+ millis >= Int.MAX_VALUE / 2 -> "never"+ millis % 60_000 == 0 -> "${millis / 60_000} min"+ else -> "${millis / 1000} s"+ }+ }}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex 3fac4b2..1d66faa 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -23,7 +23,7 @@ object ToolCategories {"uninstall_app", "delete_calendar_event", "delete_alarm","delete_timer", "edit_alarm","toggle_wifi", "toggle_torch",- "set_volume", "set_ringer_mode", "set_dnd", "set_brightness",+ "set_volume", "set_ringer_mode", "set_dnd", "set_brightness", "set_screen_timeout","set_wallpaper", "set_clipboard","call_number", "send_sms", "add_contact","create_calendar_event", "edit_calendar_event",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 16e69dc..f390d05 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -265,6 +265,27 @@ object ToolDefinitions {})+ val setScreenTimeout = tool(+ "set_screen_timeout",+ "Set how long the screen stays on without a touch (the \"Screen timeout\" or, on some " ++ "phones, \"Sleep\" setting). Changes it directly: no Settings page to find and no " ++ "Accessibility needed. Requires the 'Modify system settings' special access, which the " ++ "tool asks for when it is missing. Reports the previous value.",+ schema {+ putJsonObject("properties") {+ putJsonObject("seconds") {+ put("type", "integer")+ put(+ "description",+ "Timeout in seconds, ${SystemTool.MIN_SCREEN_TIMEOUT_S} to " ++ "${SystemTool.MAX_SCREEN_TIMEOUT_S} (30 minutes)."+ )+ }+ }+ putJsonArray("required") { add("seconds") }+ }+ )+val toggleWifi = tool("toggle_wifi","Turn Wi-Fi on or off. Android 10 and newer forbid apps from toggling the radio, so on " +@@ -291,8 +312,9 @@ object ToolDefinitions {"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.",+ "Prefer the direct tools where they exist — set_volume, set_brightness, " ++ "set_screen_timeout, set_dnd, set_ringer_mode and toggle_torch change those without " ++ "leaving the app.",schema {putJsonObject("properties") {putJsonObject("setting") {@@ -2993,7 +3015,7 @@ object ToolDefinitions {updateUserProfile,updateGotchaSettings,dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,- openApp, setBrightness, toggleWifi, openSetting,+ openApp, setBrightness, setScreenTimeout, 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 ac1a94d..cbb9f16 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -325,6 +325,9 @@ class ToolExecutor("set_brightness" -> systemTool.setBrightness(args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent"))+ "set_screen_timeout" -> systemTool.setScreenTimeout(+ args["seconds"]?.jsonPrimitive?.intOrNull ?: return missing("seconds")+ )"toggle_wifi" -> systemTool.toggleWifi(args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled"))diff --git a/app/src/test/java/com/gotcha/tools/SettingsRouterTest.kt b/app/src/test/java/com/gotcha/tools/SettingsRouterTest.ktindex 4734f97..374c36b 100644--- a/app/src/test/java/com/gotcha/tools/SettingsRouterTest.kt+++ b/app/src/test/java/com/gotcha/tools/SettingsRouterTest.kt@@ -129,4 +129,29 @@ class SettingsRouterTest {SettingsRouter.resolveAction(gated, gated.minSdk))}++ // ---- what open_setting says it did ----++ private val lockScreen get() = SettingsRouter.ROUTES.getValue("lock_screen")++ /**+ * On a Redmi, SECURITY_SETTINGS opens "Passwords & security", which has no+ * screen-timeout control, and the reply used to hand the model the stock hint+ * as if it described the screen. The phone's own title now comes first, and+ * the hint is labelled as stock Android.+ */+ @Test+ fun openedMessageNamesTheScreenThePhoneOpened() {+ val message = openedMessage(lockScreen, "Passwords & security")++ assertTrue(message, message.contains("\"Passwords & security\""))+ assertTrue(message, message.contains("On stock Android: ${lockScreen.hint}"))+ assertTrue(message, message.contains("read_screen"))+ }++ @Test+ fun openedMessageLeavesOutATitleThatAddsNothing() {+ assertTrue(!openedMessage(lockScreen, null).contains("titles the screen"))+ assertTrue(!openedMessage(lockScreen, lockScreen.label).contains("titles the screen"))+ }}diff --git a/app/src/test/java/com/gotcha/tools/SystemToolTest.kt b/app/src/test/java/com/gotcha/tools/SystemToolTest.ktindex 4771139..ca58c3e 100644--- a/app/src/test/java/com/gotcha/tools/SystemToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/SystemToolTest.kt@@ -66,6 +66,46 @@ class SystemToolTest {assertEquals(127, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))}+ // ---- set_screen_timeout ----++ @Test+ fun `set_screen_timeout rejects values outside Android's own range before touching settings`() {+ assertFalse(tool.setScreenTimeout(SystemTool.MIN_SCREEN_TIMEOUT_S - 1).success)+ assertFalse(tool.setScreenTimeout(SystemTool.MAX_SCREEN_TIMEOUT_S + 1).success)+ }++ @Test+ fun `set_screen_timeout asks for WRITE_SETTINGS when it is not granted`() {+ if (Settings.System.canWrite(context)) return++ val result = tool.setScreenTimeout(1800)++ assertFalse(result.message, result.success)+ assertEquals(ToolResult.WRITE_SETTINGS, result.needsPermission)+ }++ @Test+ fun `set_screen_timeout writes milliseconds and reports what it replaced`() {+ if (!Settings.System.canWrite(context)) return+ Settings.System.putInt(context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, 60_000)++ val result = tool.setScreenTimeout(1800)++ assertTrue(result.message, result.success)+ assertEquals("Screen timeout 1 min → 30 min.", result.message)+ assertEquals(+ 1_800_000,+ Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_OFF_TIMEOUT)+ )+ }++ @Test+ fun `timeout labels read like the Settings app, including an OEM never`() {+ assertEquals("30 s", SystemTool.timeoutLabel(30_000))+ assertEquals("2 min", SystemTool.timeoutLabel(120_000))+ assertEquals("never", SystemTool.timeoutLabel(Int.MAX_VALUE))+ }+// ---- get_battery_info ----@Testdiff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex b5ad206..2e79c15 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -98,6 +98,14 @@],"notes": "range validation, value scaling, WRITE_SETTINGS gate"},+ {+ "tool": "set_screen_timeout",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.SystemToolTest"+ ],+ "notes": "range validation, seconds to milliseconds, previous value reported, WRITE_SETTINGS gate"+ },{"tool": "toggle_wifi","tier": "MANUAL_ONLY",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 507d876..f2b4009 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 29 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 30 | 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** | **117** | |+| **Total** | **118** | |-**53 of 117** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**54 of 118** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -85,6 +85,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `set_dnd` | `MANUAL_ONLY` | Needs NotificationPolicyManager access and a real notification shade to verify the DND icon; Robolectric's shadow does not faithfully reproduce the policy enforcement side-effects. || `set_password_policy` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `set_ringer_mode` | `ROBOLECTRIC` | `DeviceToolTest` — normal/vibrate/silent plus the Do-Not-Disturb access gate |+| `set_screen_timeout` | `ROBOLECTRIC` | `SystemToolTest` — range validation, seconds to milliseconds, previous value reported, WRITE_SETTINGS gate || `set_timer` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `set_volume` | `ROBOLECTRIC` | `DeviceToolTest` — percentage-to-stream scaling, aliases, range and stream validation || `set_wallpaper` | `MANUAL_ONLY` | Needs an Android Context and WallpaperManager; the platform wallpaper API has no usable emulator fake for the set-call callback. |