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 read_image tool to process and inject filesystem images into LLM vision context
Rishabh Bajpaif507e887f623
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex e9c26e0..235ed50 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -380,15 +380,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {"Do not retry automatically; tell the user to ask again when ready.")}- 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}"- )+ if (result.success && result.message.startsWith("IMAGE_DATA:")) {+ handleImageResult(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}"+ )+ }result.needsPermission?.let { _permissionRequests.tryEmit(it) }}saveCurrentSession()@@ -448,6 +452,52 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {}}+ /**+ * Handles a tool result that contains an image (prefixed with IMAGE_DATA:).+ * Injects the image as a vision user message so the LLM can "see" it,+ * and stores a clean text-only tool result in history for display.+ *+ * Format: IMAGE_DATA:<mime>:<width>x<height>:<bytes>:<filename>:<base64>+ */+ private fun handleImageResult(call: ToolCall, result: ToolResult) {+ val parts = result.message.split(":", limit = 6)+ if (parts.size < 6) {+ llmHistory += ChatMessage(+ role = "tool", content = JsonPrimitive("Failed to parse image data."),+ toolCallId = call.id+ )+ appendUi(MessageKind.ERROR, "${call.function.name}: Failed to parse image data.")+ return+ }+ val mime = parts[1]+ val dimensions = parts[2]+ val bytesStr = parts[3]+ val filename = parts[4]+ val base64 = parts[5]+ val fileSize = try { bytesStr.toLong() } catch (_: Exception) { 0L }+ val sizeDisplay = when {+ fileSize >= 1024 * 1024 -> "${fileSize / (1024 * 1024)} MB"+ fileSize >= 1024 -> "${fileSize / 1024} KB"+ else -> "$fileSize B"+ }++ // Inject vision user message so the model "sees" the image+ val format = mime.substringAfter("image/")+ val visionMsg = visionUserMessage(+ "The assistant read an image file: $filename ($dimensions, $sizeDisplay).",+ base64, format+ )+ llmHistory.add(visionMsg)++ // Store a clean text-only tool result for display/conversation context+ llmHistory += ChatMessage(+ role = "tool",+ content = JsonPrimitive("Read image: $filename ($dimensions, $sizeDisplay)"),+ toolCallId = call.id+ )+ appendUi(MessageKind.TOOL, "${call.function.name}: Read image $filename ($dimensions)")+ }+private suspend fun executeCall(call: ToolCall): ToolResult {_uiState.update { it.copy(activity = "Running: ${call.function.name}…") }val args: JsonObject = try {diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 19e1b46..6536baa 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -554,6 +554,26 @@ object ToolDefinitions {schema { putJsonObject("properties") {} })+ val readImage = tool(+ "read_image",+ "Read an image file from an allowed directory and feed its visual content to the " ++ "vision model. The image appears as if you 'see' it — you can describe, analyze, or " ++ "read text from it. Use this for photos, screenshots, diagrams, scanned documents, " ++ "and any image stored on the device. " ++ "Allowed roots are the same as list_files/read_file: 'files', 'cache', 'external', " ++ "'downloads', 'pictures', 'dcim', 'documents', and 'storage' (needs All-files access). " ++ "Supported formats: PNG, JPEG, GIF, WebP, BMP.",+ schema {+ putJsonObject("properties") {+ putJsonObject("path") {+ put("type", "string")+ put("description", "Image file path rooted at an allowed root, e.g. 'downloads/photo.jpg'.")+ }+ }+ putJsonArray("required") { add("path") }+ }+ )+// ---- Tier 3 additions (component-based / device-wide access) ----val readScreen = tool(@@ -828,6 +848,8 @@ object ToolDefinitions {toggleTorch, setVolume, setRingerMode, vibrate, setDnd,getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,+ // Image reading (available to both Monitor and Operator)+ readImage,// Tier 3 additionsreadScreen, tap, swipe, inputText, globalAction,readNotifications, dismissNotifications, mediaControl,diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex ef3084b..7998409 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -32,6 +32,7 @@ class ToolExecutor(context: Context) {private val clipboardTool = ClipboardTool(appContext)private val mediaCaptureTool = MediaCaptureTool(appContext)// Tier 3 tools+ private val visionTool = VisionTool(appContext)private val accessibilityTool = AccessibilityTool(appContext)private val notificationTool = NotificationTool(appContext)private val overlayTool = OverlayTool(appContext)@@ -127,6 +128,7 @@ class ToolExecutor(context: Context) {"take_photo" -> mediaCaptureTool.takePhoto()"start_audio_recording" -> mediaCaptureTool.startAudioRecording()"stop_audio_recording" -> mediaCaptureTool.stopAudioRecording()+ "read_image" -> visionTool.readImage(args.requireString("path") ?: return missing("path"))// ---- Tier 3 ----"read_screen" -> accessibilityTool.readScreen()"tap" -> accessibilityTool.tap(diff --git a/app/src/main/java/com/gotcha/tools/VisionTool.kt b/app/src/main/java/com/gotcha/tools/VisionTool.ktnew file mode 100644index 0000000..5af18a1--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/VisionTool.kt@@ -0,0 +1,183 @@+package com.gotcha.tools++import android.content.Context+import android.graphics.BitmapFactory+import android.os.Build+import android.os.Environment+import android.provider.Settings+import android.util.Base64+import java.io.File++/**+ * Tool for reading image files and making their contents visible to the LLM.+ *+ * Returns a structured result with the [IMAGE_DATA_PREFIX] marker that the tool+ * loop in ChatViewModel detects and injects as vision content (user role with+ * image_url) so the model can "see" the image.+ */+class VisionTool(private val context: Context) {++ companion object {+ const val IMAGE_DATA_PREFIX = "IMAGE_DATA:"+ private const val MAX_IMAGE_BYTES = 20 * 1024 * 1024++ private val SUPPORTED_EXTENSIONS = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp")++ private val MAGIC_PNG = byteArrayOf(-119, 80, 78, 71, 13, 10, 26, 10)+ private val MAGIC_JPEG = byteArrayOf(-1, -40, -1)+ private val MAGIC_GIF = byteArrayOf(71, 73, 70, 56)+ private val MAGIC_WEBP_RIFF = byteArrayOf(82, 73, 70, 70)+ private val MAGIC_WEBP_WEBP = byteArrayOf(87, 69, 66, 80)+ private val MAGIC_BMP = byteArrayOf(66, 77)+ }++ private val sandboxRoots: Map<String, File?> by lazy {+ mapOf(+ "files" to context.filesDir,+ "cache" to context.cacheDir,+ "external" to context.getExternalFilesDir(null)+ )+ }++ private val publicRoots: Map<String, File> by lazy {+ mapOf(+ "downloads" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),+ "pictures" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),+ "dcim" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),+ "documents" to Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ )+ }++ private val manageRoots: Map<String, File> by lazy {+ mapOf("storage" to Environment.getExternalStorageDirectory())+ }++ private val allowedRootNames: String+ get() = (sandboxRoots.keys + publicRoots.keys + manageRoots.keys).joinToString(", ")++ fun readImage(path: String): ToolResult {+ val normalized = path.trim().trimStart('/')+ val rootName = normalized.substringBefore('/').lowercase()+ val rest = normalized.substringAfter('/', "")++ val root: File = when {+ sandboxRoots.containsKey(rootName) -> sandboxRoots[rootName] ?: return badPath(path)+ manageRoots.containsKey(rootName) -> {+ val perm = checkAllFilesAccess()+ if (perm != null) return perm+ manageRoots.getValue(rootName)+ }+ publicRoots.containsKey(rootName) -> {+ val perm = checkMediaPermission()+ if (perm != null) return perm+ publicRoots.getValue(rootName)+ }+ else -> return badPath(path)+ }++ val target = if (rest.isEmpty()) root else File(root, rest)+ val canonicalRoot = root.canonicalPath+ val canonicalTarget = target.canonicalPath+ if (canonicalTarget != canonicalRoot && !canonicalTarget.startsWith("$canonicalRoot/")) {+ return ToolResult.error("Path '$path' is outside its allowed root.")+ }++ if (!target.exists()) return ToolResult.error("File '$path' does not exist.")+ if (!target.isFile) return ToolResult.error("'$path' is not a regular file.")++ val ext = target.extension.lowercase()+ if (ext !in SUPPORTED_EXTENSIONS) {+ return ToolResult.error(+ "Unsupported image format '.$ext'. Supported: ${SUPPORTED_EXTENSIONS.joinToString(", ")}"+ )+ }++ if (target.length() > MAX_IMAGE_BYTES) {+ return ToolResult.error(+ "Image too large (${target.length() / 1024 / 1024} MB). Max: ${MAX_IMAGE_BYTES / 1024 / 1024} MB."+ )+ }++ return try {+ val bytes = target.readBytes()++ val mime = detectMime(bytes)+ if (mime == null) {+ return ToolResult.error("File '$path' is not a recognized image format.")+ }++ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)+ if (opts.outWidth <= 0 || opts.outHeight <= 0) {+ return ToolResult.error("File '$path' could not be decoded as an image.")+ }++ val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)+ val displayName = target.name++ ToolResult.ok(+ "$IMAGE_DATA_PREFIX$mime:${opts.outWidth}x${opts.outHeight}:${bytes.size}:$displayName:$base64"+ )+ } catch (e: Exception) {+ ToolResult.error("Could not read image '$path': ${e.message}")+ }+ }++ private fun detectMime(bytes: ByteArray): String? {+ return when {+ startsWith(bytes, MAGIC_PNG) -> "image/png"+ startsWith(bytes, MAGIC_JPEG) -> "image/jpeg"+ startsWith(bytes, MAGIC_GIF) -> "image/gif"+ startsWith(bytes, MAGIC_BMP) -> "image/bmp"+ startsWith(bytes, MAGIC_WEBP_RIFF) && bytes.size >= 12 &&+ startsWith(bytes.copyOfRange(8, 12), MAGIC_WEBP_WEBP) -> "image/webp"+ else -> null+ }+ }++ private fun startsWith(data: ByteArray, prefix: ByteArray): Boolean {+ if (data.size < prefix.size) return false+ for (i in prefix.indices) {+ if (data[i] != prefix[i]) return false+ }+ return true+ }++ private fun formatSize(bytes: Long): String = when {+ bytes >= 1024 * 1024 -> "${bytes / (1024 * 1024)} MB"+ bytes >= 1024 -> "${bytes / 1024} KB"+ else -> "$bytes B"+ }++ private fun checkMediaPermission(): ToolResult? {+ val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ android.Manifest.permission.READ_MEDIA_IMAGES+ } else {+ android.Manifest.permission.READ_EXTERNAL_STORAGE+ }+ val granted = androidx.core.content.ContextCompat.checkSelfPermission(context, permission) ==+ android.content.pm.PackageManager.PERMISSION_GRANTED+ return if (granted) null else ToolResult.permissionNeeded(+ permission,+ "Reading images from public folders needs a storage permission. I have requested it — " ++ "please grant it and ask again."+ )+ }++ private fun checkAllFilesAccess(): ToolResult? {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ return if (Environment.isExternalStorageManager()) null+ else ToolResult.permissionNeeded(+ ToolResult.ALL_FILES_ACCESS,+ "Reading images from the 'storage' root needs \"All files access\". I have opened " ++ "that settings page — please enable it for Gotcha and ask again."+ )+ }+ return checkMediaPermission()+ }++ private fun badPath(path: String) = ToolResult.error(+ "Path '$path' is not allowed. Use one of the allowed roots ($allowedRootNames), " ++ "optionally followed by a relative sub-path; '..' and absolute paths are rejected."+ )+}