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: implement runtime permission gating and support for uninstallation workflows in tool execution
Rishabh Bajpai29be3f2594ea
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 219d303..886f786 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -115,6 +115,13 @@ dependencies {implementation("com.halilibo.compose-richtext:richtext-ui-material3:0.17.0")implementation("com.halilibo.compose-richtext:richtext-commonmark:0.17.0")+ // CameraX for automated photo capture+ val cameraxVersion = "1.4.0"+ implementation("androidx.camera:camera-core:$cameraxVersion")+ implementation("androidx.camera:camera-camera2:$cameraxVersion")+ implementation("androidx.camera:camera-lifecycle:$cameraxVersion")+ implementation("androidx.camera:camera-view:$cameraxVersion")+// DebugdebugImplementation("androidx.compose.ui:ui-tooling")debugImplementation("androidx.compose.ui:ui-test-manifest")diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex e8303f8..ca96a3f 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -22,6 +22,7 @@<uses-permission android:name="android.permission.WRITE_CALENDAR" /><!-- Tier 0–2: sensors & capture -->+ <uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.RECORD_AUDIO" />diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex bbc4f1f..ef34858 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -57,9 +57,10 @@ class MainActivity : ComponentActivity() {private val permissionLauncher =registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ chatViewModel.onPermissionResult(granted)Toast.makeText(this,- if (granted) "Permission granted — ask the assistant again."+ if (granted) "Permission granted — the assistant will retry the operation."else "Permission denied. The assistant cannot perform that action.",Toast.LENGTH_SHORT).show()@@ -67,6 +68,7 @@ class MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)+ lifecycleOwner = thissettingsRepository = SettingsRepository(this)openChatRequested = intent?.getBooleanExtra(EXTRA_OPEN_CHAT, false) == true@@ -330,5 +332,10 @@ class MainActivity : ComponentActivity() {companion object {/** Intent extra: when true, launch straight into the chat screen. */const val EXTRA_OPEN_CHAT = "com.gotcha.OPEN_CHAT"++ /** Lifecycle owner for CameraX binding. Set in onCreate, valid while activity lives. */+ @Volatile+ var lifecycleOwner: androidx.lifecycle.LifecycleOwner? = null+ private set}}diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex becdf69..2a4e96d 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -4,6 +4,7 @@ import android.app.Applicationimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.net.Uri+import android.util.Logimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport com.gotcha.audio.AudioProvider@@ -41,6 +42,8 @@ import kotlinx.coroutines.launchimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.putimport java.io.ByteArrayOutputStreamenum class MessageKind { USER, ASSISTANT, TOOL, ERROR }@@ -87,6 +90,7 @@ data class ChatUiState(class ChatViewModel(application: Application) : AndroidViewModel(application) {+ private val TAG = "Gotcha"private val settingsRepository = SettingsRepository(application)private val historyRepository = ChatHistoryRepository(application)private val toolExecutor = ToolExecutor(application)@@ -116,6 +120,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {private var nextId = 0Lprivate var confirmationGate: CompletableDeferred<Boolean>? = nullprivate var questionGate: CompletableDeferred<String>? = null+ private var permissionGate: CompletableDeferred<Boolean>? = nullprivate var agentJob: Job? = nullprivate val _uiState = MutableStateFlow(ChatUiState())@@ -244,6 +249,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {questionGate = null}+ /** Called from MainActivity after the user grants or denies a runtime permission. */+ fun onPermissionResult(granted: Boolean) {+ permissionGate?.complete(granted)+ permissionGate = null+ }+/** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */fun setForeground(foreground: Boolean) {appInForeground = foreground@@ -528,49 +539,76 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}val decision = requestConfirmation(toolCalls)- for (call in toolCalls) {- val result = when (decision) {- ConfirmDecision.APPROVED -> executeCall(call)- ConfirmDecision.DENIED ->- ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")- ConfirmDecision.TIMED_OUT -> ToolResult.error(- "Confirmation for '${call.function.name}' timed out with no response. " +- "Do not retry automatically; tell the user to ask again when ready."- )- }- if (result.success && result.message.startsWith("IMAGE_DATA:")) {- handleImageResult(call, result)- } else if (result.success && result.message.startsWith("QUESTION:")) {- handleQuestionResult(call, result)- } else {- llmHistory += ChatMessage(- role = "tool",- content = JsonPrimitive(result.message),- toolCallId = call.id- )- appendUi(- if (result.success) MessageKind.TOOL else MessageKind.ERROR,- "${call.function.name}: ${result.message}"- )- }- // Automatic screenshot injection: when read_screen succeeds,- // capture a screenshot and inject it as vision context so the LLM- // can "see" the screen alongside the accessibility text dump.- if (result.success && call.function.name == "read_screen") {- val screenshotBase64 = captureScreenshotBase64()- if (screenshotBase64 != null) {- val screenText = result.message.take(500)- val visionMsg = visionUserMessage(- "Screen text:\n$screenText\n\nThe assistant also captured a screenshot. " +- "Use it together with the screen text to understand the current screen.",- screenshotBase64, "png"+ suspend fun executeToolCalls() {+ for (call in toolCalls) {+ var result = when (decision) {+ ConfirmDecision.APPROVED -> executeCall(call)+ ConfirmDecision.DENIED ->+ ToolResult.error("The user declined to run '${call.function.name}'. Do not retry.")+ ConfirmDecision.TIMED_OUT -> ToolResult.error(+ "Confirmation for '${call.function.name}' timed out with no response. " ++ "Do not retry automatically; tell the user to ask again when ready.")- llmHistory.add(visionMsg)- appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")+ }++ // Permission gate: if the tool needs a runtime permission (not a special marker),+ // emit the request, suspend until the user responds, and retry if granted.+ val perm = result.needsPermission+ if (perm != null && !perm.startsWith("special:")) {+ Log.d(TAG, "Permission needed: $perm, waiting for user…")+ _permissionRequests.tryEmit(perm)+ val gate = CompletableDeferred<Boolean>()+ permissionGate = gate+ val granted = withTimeoutOrNull(120_000L) { gate.await() } ?: false+ permissionGate = null+ Log.d(TAG, "Permission $perm -> granted=$granted")+ if (granted) {+ result = executeCall(call)+ } else {+ result = ToolResult(false, "${result.message} Permission was not granted.")+ }+ }++ if (result.success && result.message.startsWith("IMAGE_DATA:")) {+ handleImageResult(call, result)+ } else if (result.success && result.message.startsWith("QUESTION:")) {+ handleQuestionResult(call, result)+ } else if (result.success && result.message.startsWith("CONFIRM_UNINSTALL:")) {+ handleUninstallConfirm(call, result)+ } else {+ llmHistory += ChatMessage(+ role = "tool",+ content = JsonPrimitive(result.message),+ toolCallId = call.id+ )+ appendUi(+ if (result.success) MessageKind.TOOL else MessageKind.ERROR,+ "${call.function.name}: ${result.message}"+ )+ }+ // Automatic screenshot injection: when read_screen succeeds,+ // capture a screenshot and inject it as vision context so the LLM+ // can "see" the screen alongside the accessibility text dump.+ if (result.success && call.function.name == "read_screen") {+ val screenshotBase64 = captureScreenshotBase64()+ if (screenshotBase64 != null) {+ val screenText = result.message.take(500)+ val visionMsg = visionUserMessage(+ "Screen text:\n$screenText\n\nThe assistant also captured a screenshot. " ++ "Use it together with the screen text to understand the current screen.",+ screenshotBase64, "png"+ )+ llmHistory.add(visionMsg)+ appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")+ }+ }+ // Special-access markers: emit and continue (no wait needed since they open Settings)+ if (perm != null && perm.startsWith("special:")) {+ _permissionRequests.tryEmit(perm)}}- result.needsPermission?.let { _permissionRequests.tryEmit(it) }}+ executeToolCalls()saveCurrentSession()}appendUi(@@ -727,6 +765,56 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {)}+ /**+ * Handles a tool result prefixed with CONFIRM_UNINSTALL:label:package.+ * Shows a confirmation dialog, and if approved, executes the actual uninstall.+ */+ private suspend fun handleUninstallConfirm(call: ToolCall, result: ToolResult) {+ val body = result.message.removePrefix("CONFIRM_UNINSTALL:")+ val parts = body.split(":", limit = 2)+ if (parts.size < 2) {+ llmHistory += ChatMessage(+ role = "tool", content = JsonPrimitive("Failed to parse uninstall confirmation."),+ toolCallId = call.id+ )+ appendUi(MessageKind.ERROR, "${call.function.name}: Failed to parse uninstall confirmation.")+ return+ }+ val label = parts[0]+ val pkg = parts[1]+ Log.d(TAG, "handleUninstallConfirm: label=$label pkg=$pkg")+ val description = "Request to uninstall \"$label\". After you approve, a system dialog will open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."+ val gate = CompletableDeferred<Boolean>()+ confirmationGate = gate+ _uiState.update { it.copy(activity = null, pendingConfirmation = PendingConfirmation(listOf("uninstall_app"), description)) }++ val approved = withTimeoutOrNull(120_000L) { gate.await() } ?: false+ confirmationOverlay.dismiss()+ _uiState.update { it.copy(pendingConfirmation = null) }+ confirmationGate = null++ if (approved) {+ val actualResult = toolExecutor.executeUninstall(pkg)+ llmHistory += ChatMessage(+ role = "tool",+ content = JsonPrimitive(actualResult.message),+ toolCallId = call.id+ )+ appendUi(+ if (actualResult.success) MessageKind.TOOL else MessageKind.ERROR,+ "Uninstalling $label: ${actualResult.message}"+ )+ } else {+ val msg = "User declined to uninstall $label."+ llmHistory += ChatMessage(+ role = "tool",+ content = JsonPrimitive(msg),+ toolCallId = call.id+ )+ appendUi(MessageKind.TOOL, "${call.function.name}: $msg")+ }+ }+private suspend fun executeCall(call: ToolCall): ToolResult {_uiState.update { it.copy(activity = "Running: ${call.function.name}…") }val args: JsonObject = try {@@ -757,7 +845,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {"You control the device only through the provided tools; never invent tool " +"names or capabilities. If a tool reports a missing permission, explain what " +"to grant and ask again. After changing device state, confirm what was done. " +- "Keep replies short and conversational. Be careful with destructive actions."+ "Keep replies short and conversational. Be careful with destructive actions.\n" ++ "When using uninstall_app: after calling it, the system will open a dialog. " ++ "Tell the user to tap OK in the system dialog to finish the uninstall. " ++ "Do NOT attempt to uninstall via shell commands (run_command, run_root_command) — " ++ "use uninstall_app only."}val reminder = when (agent) {AgentMode.MONITOR ->diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex 47701d3..838f0ee 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -2,6 +2,9 @@ package com.gotcha.serviceimport android.accessibilityservice.AccessibilityServiceimport android.accessibilityservice.GestureDescription+import android.content.ClipData+import android.content.ClipboardManager+import android.content.Contextimport android.graphics.Bitmapimport android.graphics.Pathimport android.os.Build@@ -29,6 +32,7 @@ class GotchaAccessibilityService : AccessibilityService() {override fun onServiceConnected() {super.onServiceConnected()instance = this+ initClipboardListener()}// Passive: we drive the UI on demand from tools rather than reacting to events.@@ -176,5 +180,18 @@ class GotchaAccessibilityService : AccessibilityService() {@Volatilevar instance: GotchaAccessibilityService? = nullprivate set++ /** Last clipboard content, used as fallback when direct read is blocked (API 34+). */+ @Volatile+ var lastClipboardData: ClipData? = null+ internal set+ }++ /** Register a clipboard listener to cache clipboard content. */+ internal fun initClipboardListener() {+ val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ cm.addPrimaryClipChangedListener {+ try { lastClipboardData = cm.primaryClip } catch (_: Exception) {}+ }}}diff --git a/app/src/main/java/com/gotcha/tools/AppsTool.kt b/app/src/main/java/com/gotcha/tools/AppsTool.ktindex fa42c68..fbbd602 100644--- a/app/src/main/java/com/gotcha/tools/AppsTool.kt+++ b/app/src/main/java/com/gotcha/tools/AppsTool.kt@@ -5,6 +5,9 @@ import android.app.usage.NetworkStatsManagerimport android.app.usage.UsageStatsManagerimport android.content.Contextimport android.content.Intent+import android.content.pm.ApplicationInfo+import android.content.pm.PackageManager+import android.util.Logimport android.net.ConnectivityManagerimport android.net.Uriimport android.os.Build@@ -12,39 +15,130 @@ import android.os.Processclass AppsTool(private val context: Context) {- /** List launchable installed apps (name + package). Uses the manifest <queries> visibility. */- fun listInstalledApps(): ToolResult {+ private val TAG = "Gotcha"+ private data class AppEntry(val label: String, val packageName: String, val isSystemApp: Boolean)++ /** List installed apps with optional search filter. */+ fun listInstalledApps(search: String?): ToolResult {return try {val pm = context.packageManagerval intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)- val apps = pm.queryIntentActivities(intent, 0)- .map { "${it.loadLabel(pm)} (${it.activityInfo.packageName})" }- .distinct()- .sorted()- if (apps.isEmpty()) return ToolResult.ok("No launchable apps are visible.")- ToolResult.ok("Installed apps (${apps.size}):\n" + apps.joinToString("\n") { "- $it" })+ val allApps = pm.queryIntentActivities(intent, 0).map {+ val isSystem = (it.activityInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0+ AppEntry(+ label = it.loadLabel(pm).toString(),+ packageName = it.activityInfo.packageName,+ isSystemApp = isSystem+ )+ }.distinctBy { it.packageName }.sortedBy { it.label.lowercase() }++ val userApps = allApps.count { !it.isSystemApp }+ val systemApps = allApps.count { it.isSystemApp }+ val total = allApps.size++ val query = search?.trim()?.lowercase()++ if (query.isNullOrBlank()) {+ // Full listing+ val listing = allApps.take(200).joinToString("\n") {+ "- ${it.label} (${it.packageName})${if (it.isSystemApp) " [system]" else ""}"+ }+ val truncated = if (allApps.size > 200) "\n…(${allApps.size - 200} more apps — use search to find specific ones)" else ""+ ToolResult.ok("Total: $total apps installed ($userApps user, $systemApps system).\n$listing$truncated")+ } else {+ // Filtered listing+ val matches = allApps.filter {+ it.label.lowercase().contains(query) || it.packageName.lowercase().contains(query)+ }+ if (matches.isEmpty()) {+ return ToolResult.ok(+ "No apps matching '$search' ($total apps installed total). Try a different search term."+ )+ }+ val matchCount = matches.size+ val listing = matches.take(30).joinToString("\n") {+ "- ${it.label} (${it.packageName})${if (it.isSystemApp) " [system]" else ""}"+ }+ val truncated = if (matchCount > 30) " (showing 30 of $matchCount)" else ""+ ToolResult.ok("Found $matchCount app(s) matching '$search'$truncated ($total total, $userApps user, $systemApps system).\n$listing")+ }} catch (e: Exception) {ToolResult.error("Could not list apps: ${e.message}")}}- /** Open the system uninstall dialog for a package (user confirms). */+ /**+ * Uninstall an app. First call resolves the app name/package and returns+ * a confirmation request. The ChatViewModel catches that marker, shows a+ * dialog, and if confirmed calls [doUninstall] to actually execute.+ */fun uninstallApp(packageName: String): ToolResult {val pkg = packageName.trim()- if (pkg.isEmpty()) return ToolResult.error("Please provide the package name to uninstall.")+ if (pkg.isEmpty()) return ToolResult.error("Please provide the app name or package name.")+ val pm = context.packageManager++ // Try exact package match first+ val info = try {+ pm.getApplicationInfo(pkg, 0).let { it to pm.getApplicationLabel(it).toString() }+ } catch (_: Exception) {+ null+ }++ if (info != null) {+ val label = info.second+ return ToolResult.ok("CONFIRM_UNINSTALL:$label:$pkg")+ }++ // Fuzzy match by app label+ val query = pkg.lowercase()+ val match = try {+ pm.getInstalledApplications(0).firstOrNull { app ->+ val label = try { pm.getApplicationLabel(app).toString().lowercase() } catch (_: Exception) { "" }+ label.contains(query) || app.packageName.lowercase().contains(query)+ }+ } catch (_: Exception) { null }++ if (match != null) {+ val label = try { pm.getApplicationLabel(match).toString() } catch (_: Exception) { match.packageName }+ return ToolResult.ok("CONFIRM_UNINSTALL:$label:${match.packageName}")+ }++ return ToolResult.error(+ "No app found matching '$packageName'. Use list_installed_apps to find the correct package name."+ )+ }++ /**+ * Fires the uninstall intent after the user has confirmed the destructive+ * action. The system uninstall dialog opens and the user must tap OK.+ * Detection of completion is unreliable on some OEMs (Xiaomi MIUI);+ * the tool returns immediately and the LLM asks the user to verify+ * the app is gone via list_installed_apps after tapping OK.+ */+ fun doUninstall(packageName: String): ToolResult {+ Log.d(TAG, "doUninstall: $packageName")return try {+ val pm = context.packageManagerval installed = try {- context.packageManager.getPackageInfo(pkg, 0); true+ pm.getPackageInfo(packageName, 0); true} catch (_: Exception) {false}- if (!installed) return ToolResult.error("No app with package '$pkg' is installed.")+ if (!installed) return ToolResult.error("No app with package '$packageName' is installed.")++ val label = try {+ pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()+ } catch (_: Exception) { packageName }+@Suppress("DEPRECATION")- val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$pkg"))+ val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:$packageName")).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)context.startActivity(intent)- ToolResult.ok("Opened the uninstall dialog for $pkg. The user must confirm removal.")++ Log.d(TAG, "doUninstall: dialog opened for $label")+ ToolResult.ok("System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone.")} catch (e: Exception) {+ Log.e(TAG, "doUninstall failed: ${e.message}")ToolResult.error("Could not start uninstall: ${e.message}")}}diff --git a/app/src/main/java/com/gotcha/tools/ClipboardTool.kt b/app/src/main/java/com/gotcha/tools/ClipboardTool.ktindex fde740c..787488a 100644--- a/app/src/main/java/com/gotcha/tools/ClipboardTool.kt+++ b/app/src/main/java/com/gotcha/tools/ClipboardTool.kt@@ -3,22 +3,51 @@ package com.gotcha.toolsimport android.content.ClipDataimport android.content.ClipboardManagerimport android.content.Context+import android.os.Build+import com.gotcha.service.GotchaAccessibilityServiceclass ClipboardTool(private val context: Context) {private val clipboard: ClipboardManagerget() = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager- /** Read the current clipboard text (works while the app is foreground). */+ /** Read the current clipboard text. */fun getClipboard(): ToolResult {return try {- val clip = clipboard.primaryClip- if (clip == null || clip.itemCount == 0) {- return ToolResult.ok("The clipboard is empty.")+ // On API 34+ the platform blocks clipboard reads by non-IME apps.+ // Try the direct API first, then fall back to the accessibility service cache.+ val directClip = if (Build.VERSION.SDK_INT < 34) {+ clipboard.primaryClip+ } else {+ try { clipboard.primaryClip } catch (_: SecurityException) { null }+ }++ if (directClip != null && directClip.itemCount > 0) {+ val text = directClip.getItemAt(0).coerceToText(context).toString()+ if (text.isNotEmpty()) return ToolResult.ok("Clipboard: ${text.take(2000)}")+ }++ // Fall back to accessibility clipboard cache+ val a11yClip = GotchaAccessibilityService.lastClipboardData+ if (a11yClip != null && a11yClip.itemCount > 0) {+ val text = a11yClip.getItemAt(0).coerceToText(context).toString()+ if (text.isNotEmpty()) return ToolResult.ok("Clipboard (from accessibility service): ${text.take(2000)}")+ }++ if (Build.VERSION.SDK_INT >= 34) {+ val hasA11y = GotchaAccessibilityService.instance != null+ if (hasA11y) {+ ToolResult.ok("The clipboard is empty. Ask the user to copy something first.")+ } else {+ ToolResult.ok(+ "Clipboard reading is restricted on Android 14+. Enable the Gotcha " ++ "accessibility service for clipboard access, or ask the user to copy " ++ "the text again while Gotcha is open."+ )+ }+ } else {+ ToolResult.ok("The clipboard is empty.")}- val text = clip.getItemAt(0).coerceToText(context).toString()- if (text.isEmpty()) ToolResult.ok("The clipboard holds no text.")- else ToolResult.ok("Clipboard: ${text.take(2000)}")} catch (e: Exception) {ToolResult.error("Could not read the clipboard: ${e.message}")}@@ -28,6 +57,11 @@ class ClipboardTool(private val context: Context) {fun setClipboard(text: String): ToolResult {return try {clipboard.setPrimaryClip(ClipData.newPlainText("Gotcha", text))+ // Also update the accessibility cache so subsequent reads work+ if (GotchaAccessibilityService.instance != null) {+ GotchaAccessibilityService.lastClipboardData =+ ClipData.newPlainText("Gotcha", text)+ }ToolResult.ok("Copied to the clipboard.")} catch (e: Exception) {ToolResult.error("Could not set the clipboard: ${e.message}")diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktindex eb351d5..d24c7dc 100644--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -2,48 +2,96 @@ package com.gotcha.toolsimport android.Manifestimport android.content.Context-import android.content.Intentimport android.content.pm.PackageManagerimport android.media.MediaRecorderimport android.os.Build-import android.provider.MediaStore+import android.util.Log+import androidx.camera.core.CameraSelector+import androidx.camera.core.ImageCapture+import androidx.camera.core.ImageCaptureException+import androidx.camera.lifecycle.ProcessCameraProviderimport androidx.core.content.ContextCompat-import androidx.core.content.FileProvider+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.withContextimport java.io.Fileimport java.text.SimpleDateFormatimport java.util.Locale+import java.util.concurrent.TimeUnit+import kotlin.coroutines.resumeclass MediaCaptureTool(private val context: Context) {+ private val TAG = "Gotcha"private var recorder: MediaRecorder? = nullprivate var recordingFile: File? = null/**- * Launch the camera app to capture a photo into the app's external Pictures dir.- * No CAMERA permission is declared, so the intent runs as a plain hand-off; the user- * snaps the photo and it is saved to the returned path.+ * Capture a photo automatically using CameraX. No camera app is opened.+ * Takes a photo from the selected camera in the background.*/- fun takePhoto(): ToolResult {+ suspend fun takePhoto(camera: String?): ToolResult {+ Log.d(TAG, "takePhoto: camera=$camera")+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)+ != PackageManager.PERMISSION_GRANTED+ ) {+ return ToolResult.permissionNeeded(+ Manifest.permission.CAMERA,+ "Taking photos needs the Camera permission. I have requested it — " ++ "please grant it and ask again."+ )+ }+ val lifecycleOwner = com.gotcha.MainActivity.lifecycleOwner+ ?: return ToolResult.error("Camera system is not ready yet. Try again in a moment.")+return try {val dir = context.getExternalFilesDir("Pictures")?: return ToolResult.error("No external storage is available for photos.")dir.mkdirs()val file = File(dir, "photo_${timestamp()}.jpg")- val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)- val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply {- putExtra(MediaStore.EXTRA_OUTPUT, uri)- addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)++ val cameraSelector = if (camera?.trim()?.lowercase() == "front") {+ CameraSelector.DEFAULT_FRONT_CAMERA+ } else {+ CameraSelector.DEFAULT_BACK_CAMERA}- if (intent.resolveActivity(context.packageManager) == null) {- return ToolResult.error("No camera app is available on this device.")++ val imageCapture = ImageCapture.Builder()+ .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)+ .build()++ val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build()++ val result = withContext(Dispatchers.Main) {+ Log.d(TAG, "takePhoto: on main thread, acquiring provider…")+ val cameraProvider = ProcessCameraProvider.getInstance(context).get(5, TimeUnit.SECONDS)+ Log.d(TAG, "takePhoto: provider acquired, binding…")+ cameraProvider.unbindAll()+ cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, imageCapture)++ val res = suspendCancellableCoroutine<ToolResult> { cont ->+ Log.d(TAG, "takePhoto: calling takePicture…")+ imageCapture.takePicture(+ outputOptions,+ ContextCompat.getMainExecutor(context),+ object : ImageCapture.OnImageSavedCallback {+ override fun onImageSaved(output: ImageCapture.OutputFileResults) {+ Log.d(TAG, "takePhoto: image saved to ${file.absolutePath}")+ cont.resume(ToolResult.ok("Photo saved to ${file.absolutePath}."))+ }+ override fun onError(exception: ImageCaptureException) {+ Log.e(TAG, "takePhoto: error: ${exception.message}")+ cont.resume(ToolResult.error("Camera error: ${exception.message}"))+ }+ }+ )+ }+ cameraProvider.unbindAll()+ res}- context.startActivity(intent)- ToolResult.ok(- "Opened the camera. Once the user takes the photo it is saved to ${file.absolutePath}."- )+ result} catch (e: Exception) {- ToolResult.error("Could not open the camera: ${e.message}")+ ToolResult.error("Could not take photo: ${e.message}")}}diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex dfbfdce..832fd37 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -492,18 +492,30 @@ object ToolDefinitions {val listInstalledApps = tool("list_installed_apps",- "List the launchable apps installed on the device with their package names.",- schema { putJsonObject("properties") {} }+ "List installed apps optionally filtered by name or package. Returns a summary of " ++ "how many apps are installed and, when a search is provided, the matching apps. " ++ "Use this before uninstall_app to find the exact package name.",+ schema {+ putJsonObject("properties") {+ putJsonObject("search") {+ put("type", "string")+ put("description", "Optional: filter to apps whose name or package contains this text.")+ }+ }+ })val uninstallApp = tool("uninstall_app",- "Open the system uninstall dialog for an app package. The user confirms removal.",+ "Uninstall an app by its name or package name. Accepts both exact package names " ++ "(e.g. com.example.app) and human-readable app names (e.g. YouTube). " ++ "When a name is given, the tool resolves it to the matching package automatically. " ++ "The user will be asked to confirm before the uninstall proceeds.",schema {putJsonObject("properties") {putJsonObject("package_name") {put("type", "string")- put("description", "Package name to uninstall, e.g. com.example.app")+ put("description", "App name or package name to uninstall, e.g. com.example.app or YouTube.")}}putJsonArray("required") { add("package_name") }@@ -558,9 +570,17 @@ object ToolDefinitions {val takePhoto = tool("take_photo",- "Open the camera app to capture a photo; the image is saved into the app's storage. " +- "Returns the file path where the photo will be saved.",- schema { putJsonObject("properties") {} }+ "Capture a photo automatically using the device camera. No camera app is opened — " ++ "the photo is taken in the background and saved to the app's storage. " ++ "Needs the Camera permission. Returns the file path of the captured photo.",+ schema {+ putJsonObject("properties") {+ putJsonObject("camera") {+ put("type", "string")+ put("description", "Which camera to use: 'back' (default) or 'front'.")+ }+ }+ })val startAudioRecording = tool(diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex e99a128..834c721 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -1,6 +1,7 @@package com.gotcha.toolsimport android.content.Context+import android.util.Logimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.JsonArray@@ -18,6 +19,7 @@ import kotlinx.serialization.json.jsonPrimitive*/class ToolExecutor(context: Context) {+ private val TAG = "Gotcha"private val appContext = context.applicationContextprivate val phoneTool = PhoneTool(appContext)private val systemTool = SystemTool(appContext)@@ -71,10 +73,22 @@ class ToolExecutor(context: Context) {} catch (e: Exception) {ToolResult.error("Tool '$name' failed: ${e.message}")}+ Log.d(TAG, "execute: $name -> success=${result.success}, msg=${result.message.take(80)}, perm=${result.needsPermission}")actionLog.record(name, args.toString(), result)return result}+ /**+ * Execute an uninstall that was already confirmed by the user.+ * Bypasses the destructive-action confirmation flow.+ */+ suspend fun executeUninstall(packageName: String): ToolResult {+ Log.d(TAG, "executeUninstall: $packageName")+ val result = withContext(Dispatchers.IO) { appsTool.doUninstall(packageName) }+ actionLog.record("uninstall_app", packageName, result)+ return result+ }+private suspend fun dispatch(name: String, args: JsonObject): ToolResult {return when (name) {"dial_number" -> phoneTool.dialNumber(args.requireString("number") ?: return missing("number"))@@ -150,13 +164,13 @@ class ToolExecutor(context: Context) {args["enabled"]?.jsonPrimitive?.booleanOrNull ?: return missing("enabled"))"get_location" -> locationTool.getLocation()- "list_installed_apps" -> appsTool.listInstalledApps()+ "list_installed_apps" -> appsTool.listInstalledApps(args.requireString("search"))"uninstall_app" -> appsTool.uninstallApp(args.requireString("package_name") ?: return missing("package_name"))"get_app_usage" -> appsTool.getAppUsage(args.requireInt("days") ?: 7)"get_data_usage" -> appsTool.getDataUsage(args.requireInt("days") ?: 30)"get_clipboard" -> clipboardTool.getClipboard()"set_clipboard" -> clipboardTool.setClipboard(args.requireString("text") ?: return missing("text"))- "take_photo" -> mediaCaptureTool.takePhoto()+ "take_photo" -> mediaCaptureTool.takePhoto(args.requireString("camera"))"start_audio_recording" -> mediaCaptureTool.startAudioRecording()"stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()"question" -> questionTool.ask(diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 438f91e..c557486 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -27,7 +27,7 @@ object ToolRegistry {// Tier 0–2 additions: outbound actions, personal-data reads, and captures."call_number", "read_call_log", "find_contact", "add_contact","send_sms", "read_recent_sms", "create_calendar_event", "list_calendar_events",- "get_location", "uninstall_app",+ "get_location","take_photo", "start_audio_recording", "stop_audio_recording",// Tier 3: device-wide / other-app control is always sensitive."read_screen", "tap", "swipe", "input_text", "global_action",@@ -40,6 +40,15 @@ object ToolRegistry {"run_root_command", "write_secure_settings")+ /**+ * Destructive tools that require explicit, separate user confirmation even when+ * sensitive-action confirmation is enabled. Each call presents a dedicated dialog+ * to the user before the tool is actually executed.+ */+ val destructiveTools: Set<String> = setOf(+ "uninstall_app"+ )+/*** Tools available to Monitor mode — read-only / informational only.* The Monitor can inspect, list, read, and query, but cannot create,@@ -85,6 +94,8 @@ object ToolRegistry {fun isSensitive(name: String): Boolean = name in sensitiveTools+ fun isDestructive(name: String): Boolean = name in destructiveTools+/** Whether [name] is callable by the given [agent] mode. */fun isAllowedForAgent(name: String, agent: AgentMode): Boolean = when (agent) {AgentMode.MONITOR -> name in monitorTools