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: implement ScreenPerception utility for automated screenshot compression and UI hierarchy parsing.

Rishabh Bajpai8bfea7747f24
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index f824483..b2e3e73 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -22,6 +22,7 @@ import com.gotcha.llm.visionUserMessage
import com.gotcha.tools.AgentMode
import com.gotcha.tools.FileResolver
import com.gotcha.tools.SubAgentSession
+import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
import com.gotcha.tools.ToolResult
@@ -42,9 +43,12 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put
import java.io.ByteArrayOutputStream
@@ -562,6 +566,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
addAll(trimmedHistory())
addAll(agentInstructionMessages(agent))
}
+ cullOldImages()
val response = try {
llm.chat(messages, ToolRegistry.toolsForAgent(agent), sessionId = sessionId)
} catch (e: CancellationException) {
@@ -650,19 +655,31 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
)
}
// 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.
+ // capture a compressed JPEG screenshot + UI hierarchy + coordinate
+ // contract and inject them as a vision user message so the LLM
+ // can "see" the screen alongside structured element data.
if (result.success && call.function.name == "read_screen") {
- val screenshotBase64 = captureScreenshotBase64()
- if (screenshotBase64 != null) {
- val screenText = result.message.take(500)
+ val screenshot = captureCompressedScreenshot()
+ if (screenshot != null) {
+ val uiTree = ScreenPerception.buildUiHierarchyText()
+ val observationText = ScreenPerception.buildObservationText(screenshot, uiTree)
+ val visionMsg = visionUserMessage(observationText, screenshot.base64, "jpeg")
+ llmHistory.add(visionMsg)
+ appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")
+ }
+ }
+ // read_screen_raw: full-resolution PNG screenshot for visual detail.
+ if (result.success && call.function.name == "read_screen_raw") {
+ val screenshot = captureFullResScreenshot()
+ if (screenshot != null) {
+ val screenText = result.message.removePrefix("read_screen_raw:").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"
+ "Screen text:\n$screenText\n\nThe assistant captured a " +
+ "full-resolution screenshot for visual detail.",
+ screenshot.base64, screenshot.format
)
llmHistory.add(visionMsg)
- appendUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")
+ appendUi(MessageKind.ASSISTANT, "[Full-resolution screenshot captured]")
}
}
// Special-access markers: emit and continue (no wait needed since they open Settings)
@@ -1189,33 +1206,49 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
/**
- * Capture a screenshot via the `screencap -p` shell command.
- * Returns the image as a base64-encoded PNG string, or null on failure.
- * The app runs as an unprivileged uid; on many devices `screencap` requires
- * the `DUMP` permission or root. This is best-effort.
+ * Capture a screenshot via the `screencap -p` shell command, compressed as JPEG.
+ * Returns a [ScreenPerception.CompressedScreenshot] with base64 data, or null on failure.
*/
- private suspend fun captureScreenshotBase64(): String? {
- return try {
- val bytes = withContext(kotlinx.coroutines.Dispatchers.IO) {
- val process = java.lang.Runtime.getRuntime().exec("screencap -p")
- val b = process.inputStream.use { it.readBytes() }
- process.waitFor()
- b
+ private suspend fun captureCompressedScreenshot(): ScreenPerception.CompressedScreenshot? {
+ return ScreenPerception.compressScreenshot()
+ }
+
+ /**
+ * Capture a full-resolution screenshot (uncompressed PNG).
+ * Used by read_screen_raw for maximum visual detail.
+ */
+ private suspend fun captureFullResScreenshot(): ScreenPerception.CompressedScreenshot? {
+ return ScreenPerception.compressScreenshot(
+ maxDimension = 0,
+ format = android.graphics.Bitmap.CompressFormat.PNG,
+ quality = 100
+ )
+ }
+
+ /**
+ * Scans [llmHistory] for vision messages containing embedded images.
+ * Strips the image data from all but the 2 most recent such messages,
+ * keeping their text portions intact. This prevents accumulated
+ * screenshots from exhausting the LLM context window.
+ */
+ private fun cullOldImages() {
+ val imageMsgIndices = llmHistory.indices.filter { i ->
+ val content = llmHistory[i].content
+ content is JsonArray && content.any { part ->
+ part.jsonObject["type"]?.jsonPrimitive?.content == "image_url"
}
- if (bytes.isEmpty()) return null
- val bitmap = android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
- val maxDim = 1024
- val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {
- val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)
- (bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()
- } else bitmap.width to bitmap.height
- val scaled = android.graphics.Bitmap.createScaledBitmap(bitmap, w, h, true)
- if (scaled != bitmap) bitmap.recycle()
- val output = java.io.ByteArrayOutputStream()
- scaled.compress(android.graphics.Bitmap.CompressFormat.PNG, 90, output)
- scaled.recycle()
- android.util.Base64.encodeToString(output.toByteArray(), android.util.Base64.NO_WRAP)
- } catch (_: Exception) { null }
+ }
+ val toCull = imageMsgIndices.dropLast(2)
+ for (idx in toCull) {
+ val msg = llmHistory[idx]
+ val text = msg.textContent
+ llmHistory[idx] = msg.copy(
+ content = JsonPrimitive(
+ text + "\n\n[Previous screenshot removed to save context. " +
+ "Only the 2 most recent screenshots are retained.]"
+ )
+ )
+ }
}
private companion object {
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 43c328c..0c37afd 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -25,6 +25,15 @@ class AccessibilityTool(private val context: Context) {
}
}
+ /** Read screen text AND flag for full-resolution screenshot capture. */
+ fun readScreenRaw(): ToolResult {
+ val service = requireService() ?: return notEnabled()
+ val lines = service.dumpScreenText()
+ val text = if (lines.isEmpty()) "No readable text is on screen right now."
+ else lines.joinToString("\n") { "- $it" }
+ return ToolResult.ok("read_screen_raw:$text")
+ }
+
/** Tap either an on-screen element matching [text], or absolute coordinates. */
fun tap(text: String?, x: Int?, y: Int?): ToolResult {
val service = requireService() ?: return notEnabled()
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
new file mode 100644
index 0000000..973484a
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -0,0 +1,148 @@
+package com.gotcha.tools
+
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Rect
+import android.os.Build
+import android.util.Base64
+import android.view.accessibility.AccessibilityNodeInfo
+import com.gotcha.service.GotchaAccessibilityService
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.ByteArrayOutputStream
+
+object ScreenPerception {
+
+ data class CompressedScreenshot(
+ val base64: String,
+ val width: Int,
+ val height: Int,
+ val format: String,
+ val originalSizeBytes: Long
+ )
+
+ data class UiElement(
+ val index: Int,
+ val className: String,
+ val text: String,
+ val bounds: String,
+ val clickable: Boolean,
+ val scrollable: Boolean,
+ val checked: Boolean?,
+ val enabled: Boolean
+ )
+
+ suspend fun compressScreenshot(
+ maxDimension: Int = 2000,
+ format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,
+ quality: Int = 50
+ ): CompressedScreenshot? {
+ val bytes = captureRawBytes() ?: return null
+ val originalSize = bytes.size.toLong()
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) ?: return null
+ val scaled = if (maxDimension > 0) downscale(bitmap, maxDimension) else bitmap
+ if (scaled != bitmap) bitmap.recycle()
+ val output = ByteArrayOutputStream()
+ scaled.compress(format, quality, output)
+ scaled.recycle()
+ val base64 = Base64.encodeToString(output.toByteArray(), Base64.NO_WRAP)
+ val fmtName = when (format) {
+ Bitmap.CompressFormat.JPEG -> "jpeg"
+ Bitmap.CompressFormat.PNG -> "png"
+ Bitmap.CompressFormat.WEBP_LOSSY -> "webp"
+ Bitmap.CompressFormat.WEBP_LOSSLESS -> "webp"
+ else -> "jpeg"
+ }
+ return CompressedScreenshot(base64, scaled.width, scaled.height, fmtName, originalSize)
+ }
+
+ fun buildUiHierarchyText(maxElements: Int = 100): String {
+ val service = GotchaAccessibilityService.instance ?: return "(accessibility service not available)"
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) return "(requires API 18+)"
+ val root = service.rootInActiveWindow ?: return "(no active window)"
+ val elements = mutableListOf<UiElement>()
+ collectElements(root, elements, maxElements)
+ root.recycle()
+ if (elements.isEmpty()) return "(no UI elements found)"
+ return elements.joinToString("\n") { el ->
+ val props = buildString {
+ if (el.clickable) append(" clickable")
+ if (el.scrollable) append(" scrollable")
+ el.checked?.let { if (it) append(" checked") }
+ if (!el.enabled) append(" disabled")
+ }
+ val text = if (el.text.isNotBlank()) "\"${el.text}\"" else ""
+ "${el.index}. ${el.className} $text (${el.bounds})$props"
+ }
+ }
+
+ fun buildObservationText(screenshot: CompressedScreenshot, uiTree: String): String {
+ return buildString {
+ appendLine("[Screen State]")
+ appendLine("── Screenshot ──")
+ appendLine("(image attached, ${screenshot.width} x ${screenshot.height} px, ${screenshot.format})")
+ appendLine("── UI Elements ──")
+ appendLine(uiTree)
+ appendLine("── Coordinate Contract ──")
+ appendLine("Screenshot is ${screenshot.width} x ${screenshot.height} pixels.")
+ appendLine("UI element bounds below are in native pixel coordinates.")
+ appendLine("For coordinate-based actions, use [0, 1000] normalized space:")
+ appendLine(" actual_x = (model_x / 1000) * ${screenshot.width}")
+ appendLine(" actual_y = (model_y / 1000) * ${screenshot.height}")
+ }
+ }
+
+ private suspend fun captureRawBytes(): ByteArray? {
+ return try {
+ withContext(Dispatchers.IO) {
+ val process = Runtime.getRuntime().exec("screencap -p")
+ val bytes = process.inputStream.use { it.readBytes() }
+ process.waitFor()
+ if (bytes.isEmpty()) null else bytes
+ }
+ } catch (_: Exception) { null }
+ }
+
+ private fun downscale(bitmap: Bitmap, maxDim: Int): Bitmap {
+ val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {
+ val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)
+ (bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()
+ } else bitmap.width to bitmap.height
+ return Bitmap.createScaledBitmap(bitmap, w, h, true)
+ }
+
+ private fun collectElements(
+ node: AccessibilityNodeInfo?,
+ out: MutableList<UiElement>,
+ max: Int,
+ index: IntArray = intArrayOf(0)
+ ) {
+ if (node == null || index[0] >= max) return
+ if (!node.isVisibleToUser) return
+ val bounds = Rect()
+ node.getBoundsInScreen(bounds)
+ if (bounds.width() < 5 && bounds.height() < 5) return
+
+ val text = node.text?.toString()?.trim() ?: ""
+ val desc = node.contentDescription?.toString()?.trim() ?: ""
+ val label = text.ifBlank { desc }
+
+ index[0]++
+ out.add(
+ UiElement(
+ index = index[0],
+ className = node.className?.toString()?.substringAfterLast('.') ?: "Unknown",
+ text = label,
+ bounds = "${bounds.left}, ${bounds.top}, ${bounds.right}, ${bounds.bottom}",
+ clickable = node.isClickable,
+ scrollable = node.isScrollable,
+ checked = if (node.isCheckable) node.isChecked else null,
+ enabled = node.isEnabled
+ )
+ )
+
+ for (i in 0 until node.childCount) {
+ collectElements(node.getChild(i), out, max, index)
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index b5e4e08..402eb28 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1231,6 +1231,15 @@ object ToolDefinitions {
schema { putJsonObject("properties") {} }
)
+ val readScreenRaw = tool(
+ "read_screen_raw",
+ "Read the visible text AND capture a full-resolution screenshot of whatever app " +
+ "is currently on screen. Use this instead of read_screen when you need the " +
+ "highest quality visual detail (e.g. for reading small text, icons, or " +
+ "images). Prefer read_screen for most cases to save context.",
+ schema { putJsonObject("properties") {} }
+ )
+
val tap = tool(
"tap",
"Tap the screen via the accessibility service — either an on-screen element matching " +
@@ -1514,7 +1523,7 @@ object ToolDefinitions {
webSearch, webFetch,
// DEPRECATED: readImage excluded from the active catalog — use read_file instead.
// Tier 3 additions
- readScreen, tap, swipe, inputText, globalAction,
+ readScreen, readScreenRaw, tap, swipe, inputText, globalAction,
readNotifications, dismissNotifications, mediaControl,
showOverlay, hideOverlay,
lockScreen, disableCamera, setPasswordPolicy,
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 5a7c4d9..d2a63cc 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -343,6 +343,7 @@ class ToolExecutor(
)
// ---- Tier 3 ----
"read_screen" -> accessibilityTool.readScreen()
+ "read_screen_raw" -> accessibilityTool.readScreenRaw()
"tap" -> accessibilityTool.tap(
text = args.requireString("text"),
x = args.requireInt("x"),