Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add toggle_wifi and get_volume tools, remove toggle_dark_mode, and update manifest permissions

Rishabh Bajpai3a997e7717f5
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 1e7856e..e8303f8 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -30,6 +30,7 @@
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions" />
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 79f5931..becdf69 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -71,7 +71,7 @@ data class PendingQuestion(
data class ChatUiState(
val messages: List<UiMessage> = emptyList(),
val isBusy: Boolean = false,
- val activity: String? = null, // e.g. "Running: toggle_dark_mode…"
+ val activity: String? = null, // e.g. "Running: set_brightness…"
val pendingConfirmation: PendingConfirmation? = null,
val pendingQuestion: PendingQuestion? = null,
val isConfigured: Boolean = false,
diff --git a/app/src/main/java/com/gotcha/tools/DeviceTool.kt b/app/src/main/java/com/gotcha/tools/DeviceTool.kt
index 258afb0..da460ed 100644
--- a/app/src/main/java/com/gotcha/tools/DeviceTool.kt
+++ b/app/src/main/java/com/gotcha/tools/DeviceTool.kt
@@ -6,29 +6,45 @@ import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.media.AudioManager
import android.os.Build
+import android.os.Handler
+import android.os.Looper
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
class DeviceTool(private val context: Context) {
- /** Turn the camera flash on or off (no permission needed for CameraManager.setTorchMode). */
- fun toggleTorch(on: Boolean): ToolResult {
+ /** Turn the camera flash on or off. No permission needed for CameraManager.setTorchMode. */
+ fun toggleTorch(on: Boolean, durationSeconds: Int?): ToolResult {
return try {
val cm = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val cameraId = cm.cameraIdList.firstOrNull { id ->
cm.getCameraCharacteristics(id)
.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
} ?: return ToolResult.error("This device has no controllable flashlight.")
+
cm.setTorchMode(cameraId, on)
- ToolResult.ok("Flashlight turned ${if (on) "on" else "off"}.")
+ if (on && durationSeconds != null && durationSeconds > 0) {
+ val ms = durationSeconds.coerceIn(1, 300) * 1000L
+ Handler(Looper.getMainLooper()).postDelayed({
+ try { cm.setTorchMode(cameraId, false) } catch (_: Exception) {}
+ }, ms)
+ ToolResult.ok("Flashlight turned on for ${durationSeconds}s.")
+ } else {
+ ToolResult.ok("Flashlight turned ${if (on) "on" else "off"}.")
+ }
} catch (e: Exception) {
- ToolResult.error("Could not toggle the flashlight: ${e.message}")
+ val msg = e.message?.lowercase() ?: ""
+ if ("in use" in msg || "already" in msg) {
+ ToolResult.error("Another app may be using the camera. Close other camera apps and try again.")
+ } else {
+ ToolResult.error("Could not toggle the flashlight: ${e.message}")
+ }
}
}
- /** Set a volume stream to a percentage (no permission, though muting ring may need DND access). */
- fun setVolume(stream: String, percent: Int): ToolResult {
+ /** Set a volume stream to a percentage. Reports previous level. */
+ fun setVolume(stream: String, percent: Int, showUi: Boolean): ToolResult {
if (percent !in 0..100) return ToolResult.error("Volume must be between 0 and 100 (got $percent).")
val streamType = when (stream.lowercase().trim()) {
"media", "music" -> AudioManager.STREAM_MUSIC
@@ -43,9 +59,11 @@ class DeviceTool(private val context: Context) {
return try {
val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val max = am.getStreamMaxVolume(streamType)
+ val previousPct = (am.getStreamVolume(streamType) * 100) / max
val target = (percent * max) / 100
- am.setStreamVolume(streamType, target, 0)
- ToolResult.ok("Set $stream volume to $percent%.")
+ val flags = if (showUi) AudioManager.FLAG_SHOW_UI else 0
+ am.setStreamVolume(streamType, target, flags)
+ ToolResult.ok("Set $stream volume from ${previousPct}% to ${percent}%.")
} catch (e: SecurityException) {
ToolResult.permissionNeeded(
ToolResult.DND_ACCESS,
@@ -56,6 +74,32 @@ class DeviceTool(private val context: Context) {
}
}
+ /** Read current volume level(s). */
+ fun getVolume(stream: String?): ToolResult {
+ return try {
+ val am = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
+ val streams = if (stream != null) listOf(stream.lowercase().trim()) else
+ listOf("media", "ring", "alarm", "notification", "call")
+ val results = streams.map { name ->
+ val type = when (name) {
+ "media", "music" -> AudioManager.STREAM_MUSIC
+ "ring", "ringer" -> AudioManager.STREAM_RING
+ "alarm" -> AudioManager.STREAM_ALARM
+ "notification" -> AudioManager.STREAM_NOTIFICATION
+ "call", "voice" -> AudioManager.STREAM_VOICE_CALL
+ else -> return ToolResult.error("Unknown stream '$name'. Use media, ring, alarm, notification, or call.")
+ }
+ val max = am.getStreamMaxVolume(type)
+ val current = am.getStreamVolume(type)
+ val pct = (current * 100) / max
+ "$name: ${pct}%"
+ }
+ ToolResult.ok(results.joinToString("\n"))
+ } catch (e: Exception) {
+ ToolResult.error("Could not read volume: ${e.message}")
+ }
+ }
+
/** Set the ringer mode: normal / vibrate / silent. Silent & vibrate need DND access on N+. */
fun setRingerMode(mode: String): ToolResult {
val ringerMode = when (mode.lowercase().trim()) {
@@ -84,23 +128,53 @@ class DeviceTool(private val context: Context) {
}
}
- /** Vibrate for a number of milliseconds (needs VIBRATE, an install-time permission). */
- fun vibrate(durationMs: Int): ToolResult {
- val ms = durationMs.coerceIn(1, 5000).toLong()
+ /** Vibrate with optional intensity and pattern (needs VIBRATE, an install-time permission). */
+ fun vibrate(durationMs: Int, intensity: Int, pattern: String?): ToolResult {
+ val vibrator = getVibrator() ?: return ToolResult.error("This device has no vibrator.")
+ val amplitude = (intensity.coerceIn(0, 100) * 255) / 100
+ val effect = if (pattern != null) {
+ patternEffect(pattern.lowercase().trim(), amplitude)
+ } else {
+ val ms = durationMs.coerceIn(1, 5000).toLong()
+ if (amplitude == 0) VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE)
+ else VibrationEffect.createOneShot(ms, amplitude)
+ }
+ return try {
+ vibrator.vibrate(effect)
+ val desc = if (pattern != null) " (pattern: $pattern)" else " for ${durationMs.coerceIn(1, 5000)}ms"
+ ToolResult.ok("Vibrated$desc.")
+ } catch (e: Exception) {
+ ToolResult.error("Could not vibrate: ${e.message}")
+ }
+ }
+
+ private fun patternEffect(pattern: String, amplitude: Int): VibrationEffect {
+ val timings = when (pattern) {
+ "short" -> longArrayOf(0, 100)
+ "long" -> longArrayOf(0, 1000)
+ "double" -> longArrayOf(0, 200, 800, 200)
+ "sos" -> longArrayOf(0, 200, 200, 200, 200, 200, 600, 600, 600, 200, 600, 200, 600, 600, 200, 200, 200, 200, 200)
+ else -> longArrayOf(0, 500)
+ }
+ val amps = if (amplitude == 0) null else IntArray(timings.size) { amplitude }
+ return if (amps != null) {
+ VibrationEffect.createWaveform(timings, amps, -1)
+ } else {
+ @Suppress("DEPRECATION")
+ VibrationEffect.createWaveform(timings, -1)
+ }
+ }
+
+ private fun getVibrator(): Vibrator? {
return try {
- val vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val vm = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
vm.defaultVibrator
} else {
@Suppress("DEPRECATION")
context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}
- if (!vibrator.hasVibrator()) return ToolResult.error("This device has no vibrator.")
- vibrator.vibrate(VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE))
- ToolResult.ok("Vibrated for ${ms}ms.")
- } catch (e: Exception) {
- ToolResult.error("Could not vibrate: ${e.message}")
- }
+ } catch (_: Exception) { null }
}
/** Turn Do Not Disturb on or off (needs DND / notification-policy access). */
diff --git a/app/src/main/java/com/gotcha/tools/SystemTool.kt b/app/src/main/java/com/gotcha/tools/SystemTool.kt
index 3acc5be..23ce2aa 100644
--- a/app/src/main/java/com/gotcha/tools/SystemTool.kt
+++ b/app/src/main/java/com/gotcha/tools/SystemTool.kt
@@ -1,36 +1,15 @@
package com.gotcha.tools
-import android.app.UiModeManager
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
+import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.os.Build
import android.provider.Settings
class SystemTool(private val context: Context) {
- fun toggleDarkMode(enabled: Boolean): ToolResult {
- return try {
- val uiModeManager = context.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
- uiModeManager.setApplicationNightMode(
- if (enabled) UiModeManager.MODE_NIGHT_YES else UiModeManager.MODE_NIGHT_NO
- )
- ToolResult.ok("${if (enabled) "Dark" else "Light"} mode enabled for the app.")
- } else {
- // System-wide night mode below Android 12 needs privileged access;
- // fall back to reporting the limitation honestly.
- ToolResult.error(
- "Changing the theme programmatically requires Android 12+. " +
- "On this device the user can toggle dark mode in Settings > Display."
- )
- }
- } catch (e: Exception) {
- ToolResult.error("Could not change theme: ${e.message}")
- }
- }
-
fun setBrightness(percent: Int): ToolResult {
if (percent !in 0..100) {
return ToolResult.error("Brightness must be between 0 and 100 (got $percent).")
@@ -108,7 +87,26 @@ class SystemTool(private val context: Context) {
}
}
- fun toggleWifi(): ToolResult {
+ fun toggleWifi(enabled: Boolean): ToolResult {
+ val wifi = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager
+ val wasEnabled = wifi?.isWifiEnabled
+ return try {
+ if (wifi != null && wifi.setWifiEnabled(enabled)) {
+ val now = wifi.isWifiEnabled
+ return ToolResult.ok(
+ "Wi-Fi turned ${if (enabled) "on" else "off"}" +
+ if (wasEnabled != null) " (was ${if (wasEnabled) "on" else "off"}, now ${if (now) "on" else "off"})." else "."
+ )
+ }
+ openWifiSettings()
+ } catch (e: SecurityException) {
+ openWifiSettings()
+ } catch (e: Exception) {
+ ToolResult.error("Could not toggle Wi-Fi: ${e.message}")
+ }
+ }
+
+ private fun openWifiSettings(): ToolResult {
return try {
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Intent(Settings.Panel.ACTION_WIFI)
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 425dcba..dfbfdce 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -129,20 +129,6 @@ object ToolDefinitions {
}
)
- val toggleDarkMode = tool(
- "toggle_dark_mode",
- "Enable or disable dark theme for this app (and the system where supported).",
- schema {
- putJsonObject("properties") {
- putJsonObject("enabled") {
- put("type", "boolean")
- put("description", "true for dark, false for light")
- }
- }
- putJsonArray("required") { add("enabled") }
- }
- )
-
val setBrightness = tool(
"set_brightness",
"Set the screen brightness to a percentage between 0 and 100. Requires the 'Modify system settings' special access.",
@@ -159,8 +145,17 @@ object ToolDefinitions {
val toggleWifi = tool(
"toggle_wifi",
- "Open the system Wi-Fi settings panel so the user can toggle Wi-Fi (apps cannot toggle it directly on modern Android).",
- schema { putJsonObject("properties") {} }
+ "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.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("enabled") {
+ put("type", "boolean")
+ put("description", "true to turn Wi-Fi on, false to turn it off")
+ }
+ }
+ putJsonArray("required") { add("enabled") }
+ }
)
val setWallpaper = tool(
@@ -381,13 +376,18 @@ object ToolDefinitions {
val toggleTorch = tool(
"toggle_torch",
- "Turn the camera flashlight (torch) on or off.",
+ "Turn the camera flashlight (torch) on or off. If the flashlight is already in the " +
+ "requested state, reports that without error.",
schema {
putJsonObject("properties") {
putJsonObject("on") {
put("type", "boolean")
put("description", "true to turn the flashlight on, false to turn it off.")
}
+ putJsonObject("duration_seconds") {
+ put("type", "integer")
+ put("description", "Optional: auto-turn off after this many seconds (1-300). Only applies when turning on.")
+ }
}
putJsonArray("required") { add("on") }
}
@@ -395,7 +395,8 @@ object ToolDefinitions {
val setVolume = tool(
"set_volume",
- "Set a volume stream to a percentage. Streams: media, ring, alarm, notification, call.",
+ "Set a volume stream to a percentage (0-100). Use 0 to mute or 100 for max volume. " +
+ "Streams: media, ring, alarm, notification, call. Reports the previous and new volume levels.",
schema {
putJsonObject("properties") {
putJsonObject("stream") {
@@ -404,7 +405,11 @@ object ToolDefinitions {
}
putJsonObject("percent") {
put("type", "integer")
- put("description", "Target volume 0-100.")
+ put("description", "Target volume 0-100 (0 = mute, 100 = max).")
+ }
+ putJsonObject("show_ui") {
+ put("type", "boolean")
+ put("description", "Show the volume slider briefly. Default false.")
}
}
putJsonArray("required") {
@@ -414,6 +419,20 @@ object ToolDefinitions {
}
)
+ val getVolume = tool(
+ "get_volume",
+ "Read the current volume level (0-100) of a stream, or all streams if none is specified. " +
+ "Streams: media, ring, alarm, notification, call. Reports each stream's current percentage.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("stream") {
+ put("type", "string")
+ put("description", "Which stream to read: media, ring, alarm, notification, call. If omitted, all streams are reported.")
+ }
+ }
+ }
+ )
+
val setRingerMode = tool(
"set_ringer_mode",
"Set the ringer mode: normal, vibrate, or silent. Silent/vibrate need Do Not Disturb access.",
@@ -430,12 +449,21 @@ object ToolDefinitions {
val vibrate = tool(
"vibrate",
- "Vibrate the device for a short duration.",
+ "Vibrate the device. Supports custom intensity and predefined patterns. " +
+ "Use for haptic feedback, notifications, alerts, or attention-getting.",
schema {
putJsonObject("properties") {
putJsonObject("duration_ms") {
put("type", "integer")
- put("description", "Vibration length in milliseconds (1-5000). Default 500.")
+ put("description", "Vibration length in milliseconds (1-5000). Default 500. Ignored when pattern is set.")
+ }
+ putJsonObject("intensity") {
+ put("type", "integer")
+ put("description", "Vibration strength 0-100 (0 = none, 100 = max). Default 100.")
+ }
+ putJsonObject("pattern") {
+ put("type", "string")
+ put("description", "Predefined pattern: short (100ms), long (1s), double (two quick buzzes), sos (...---...). Overrides duration_ms.")
}
}
}
@@ -1003,12 +1031,12 @@ object ToolDefinitions {
val all: List<ToolDefinition> = listOf(
dialNumber, getStorageInfo, getBatteryInfo, listFiles, readFile, writeFile,
- openApp, toggleDarkMode, setBrightness, toggleWifi,
+ openApp, setBrightness, toggleWifi,
setWallpaper, runCommand,
// Tier 0–2 additions
callNumber, readCallLog, findContact, addContact, sendSms, readRecentSms,
listCalendarEvents, createCalendarEvent, setAlarm, setTimer,
- toggleTorch, setVolume, setRingerMode, vibrate, setDnd,
+ toggleTorch, setVolume, getVolume, setRingerMode, vibrate, setDnd,
getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,
getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,
// User interaction
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index f4d65c2..e99a128 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -94,13 +94,12 @@ class ToolExecutor(context: Context) {
append = args["append"]?.jsonPrimitive?.booleanOrNull ?: false
)
"open_app" -> systemTool.openApp(args.requireString("package_name") ?: return missing("package_name"))
- "toggle_dark_mode" -> systemTool.toggleDarkMode(
- args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
- )
"set_brightness" -> systemTool.setBrightness(
args["percent"]?.jsonPrimitive?.intOrNull ?: return missing("percent")
)
- "toggle_wifi" -> systemTool.toggleWifi()
+ "toggle_wifi" -> systemTool.toggleWifi(
+ args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
+ )
"set_wallpaper" -> wallpaperTool.setWallpaper(args.requireString("url"))
"run_command" -> terminalTool.runCommand(args.requireString("command") ?: return missing("command"))
"call_number" -> phoneTool.callNumber(args.requireString("number") ?: return missing("number"))
@@ -132,14 +131,21 @@ class ToolExecutor(context: Context) {
message = args.requireString("message")
)
"toggle_torch" -> deviceTool.toggleTorch(
- args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on")
+ on = args["on"]?.jsonPrimitive?.booleanOrNull ?: return missing("on"),
+ durationSeconds = args.requireInt("duration_seconds")
)
"set_volume" -> deviceTool.setVolume(
stream = args.requireString("stream") ?: return missing("stream"),
- percent = args.requireInt("percent") ?: return missing("percent")
+ percent = args.requireInt("percent") ?: return missing("percent"),
+ showUi = args["show_ui"]?.jsonPrimitive?.booleanOrNull ?: false
)
+ "get_volume" -> deviceTool.getVolume(args.requireString("stream"))
"set_ringer_mode" -> deviceTool.setRingerMode(args.requireString("mode") ?: return missing("mode"))
- "vibrate" -> deviceTool.vibrate(args.requireInt("duration_ms") ?: 500)
+ "vibrate" -> deviceTool.vibrate(
+ durationMs = args.requireInt("duration_ms") ?: 500,
+ intensity = args.requireInt("intensity") ?: 100,
+ pattern = args.requireString("pattern")
+ )
"set_dnd" -> deviceTool.setDnd(
args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled")
)
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 0028b66..438f91e 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -52,7 +52,7 @@ object ToolRegistry {
// Calendar (read-only)
"list_calendar_events",
// Info & sensors
- "get_storage_info", "get_battery_info", "get_location",
+ "get_storage_info", "get_battery_info", "get_location", "get_volume",
"get_app_usage", "get_data_usage",
// Apps (read-only + intent)
"open_app", "list_installed_apps",