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 long-press tool and improve error handling across tool execution and screen perception services

Rishabh Bajpai0c823a99eef4
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index bd0a9cd..72b6e51 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -116,6 +116,14 @@ class GotchaAccessibilityService : AccessibilityService() {
return performed
}
+ fun longPressByText(query: String): Boolean {
+ val root = rootInActiveWindow ?: return false
+ val match = findClickable(root, query.lowercase())
+ val performed = match?.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK) ?: false
+ root.recycle()
+ return performed
+ }
+
private fun findClickable(node: AccessibilityNodeInfo?, query: String): AccessibilityNodeInfo? {
if (node == null) return null
val hay = ((node.text?.toString() ?: "") + " " + (node.contentDescription?.toString() ?: ""))
@@ -187,6 +195,8 @@ class GotchaAccessibilityService : AccessibilityService() {
/** Dispatch a tap gesture at absolute screen coordinates (API 24+). */
fun tapAt(x: Float, y: Float): Boolean = gesture(x, y, x, y, 50)
+
+ fun longPressAt(x: Float, y: Float): Boolean = gesture(x, y, x, y, 1000)
/** Dispatch a swipe gesture between two points. */
fun swipe(x1: Float, y1: Float, x2: Float, y2: Float, durationMs: Long = 300): Boolean =
diff --git a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
index e6731e2..29ff4b6 100644
--- a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
+++ b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt
@@ -88,7 +88,11 @@ class MediaProjectionService : Service() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
- startForeground(NOTIFICATION_ID, buildNotification())
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ startForeground(NOTIFICATION_ID, buildNotification(), android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
+ } else {
+ startForeground(NOTIFICATION_ID, buildNotification())
+ }
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -187,8 +191,8 @@ class MediaProjectionService : Service() {
bmp.copyPixelsFromBuffer(java.nio.ByteBuffer.wrap(packedBytes))
Log.d("ScreenCapture", "captureScreenshot: bitmap=${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)")
bmp
- } catch (e: Exception) {
- Log.e("ScreenCapture", "captureScreenshot: bitmap creation failed: ${e.message}")
+ } catch (t: Throwable) {
+ Log.e("ScreenCapture", "captureScreenshot: bitmap creation failed: ${t.message}", t)
null
}
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 4313570..a4458b6 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -52,6 +52,20 @@ class AccessibilityTool(private val context: Context) {
}
}
+ /** Long-press either an on-screen element matching [text], or absolute coordinates. */
+ fun longPress(text: String?, x: Int?, y: Int?): ToolResult {
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
+ return when {
+ !text.isNullOrBlank() ->
+ if (service.longPressByText(text)) ToolResult.ok("Long-pressed an element matching \"$text\".")
+ else ToolResult.error("Found no element matching \"$text\" on screen.")
+ x != null && y != null ->
+ if (service.longPressAt(x.toFloat(), y.toFloat())) ToolResult.ok("Long-pressed at ($x, $y).")
+ else ToolResult.error("Could not dispatch the long-press gesture.")
+ else -> ToolResult.error("Provide either 'text' to match, or both 'x' and 'y' coordinates.")
+ }
+ }
+
/** Swipe in a named direction, or between explicit coordinates. */
fun swipe(direction: String?, x1: Int?, y1: Int?, x2: Int?, y2: Int?, normalized: Boolean = false, distance: Int? = null, index: Int? = null): ToolResult {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
@@ -149,6 +163,22 @@ class AccessibilityTool(private val context: Context) {
else ToolResult.error("Could not dispatch the tap gesture for element $index.")
}
+ /** Long-press a UI element by its index from the numbered elements list. */
+ fun longPressByIndex(index: Int): ToolResult {
+ val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
+ val element = ScreenPerception.resolveElementByIndex(index)
+ ?: return ToolResult.error("No UI element with index $index found on screen.")
+ val parts = element.bounds.split(",").map { it.trim().toIntOrNull() }
+ if (parts.size != 4 || parts.any { it == null }) {
+ return ToolResult.error("Invalid bounds for element $index.")
+ }
+ val cx = (parts[0]!! + parts[2]!!) / 2f
+ val cy = (parts[1]!! + parts[3]!!) / 2f
+ return if (service.longPressAt(cx, cy))
+ ToolResult.ok("Long-pressed element $index: \"${element.text.take(50)}\" at (${cx.toInt()}, ${cy.toInt()}).")
+ else ToolResult.error("Could not dispatch the long-press gesture for element $index.")
+ }
+
/**
* Press a system key or perform a common navigation action.
* For "enter", clicks the currently focused input element.
diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
index 19ff36e..d7ba9bf 100644
--- a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
@@ -105,7 +105,7 @@ class AppNavigatorSession(
)
} catch (e: CancellationException) {
throw e
- } catch (e: Exception) {
+ } catch (e: Throwable) {
actionLog.add("Step $step: LLM error — ${e.message}")
break
}
@@ -163,15 +163,15 @@ class AppNavigatorSession(
call.function.name, args,
AgentMode.OPERATOR, isSubAgent = true
)
- java.lang.Thread.sleep(300)
+ kotlinx.coroutines.delay(300)
if (lastResult.success) return lastResult
} catch (e: CancellationException) {
throw e
- } catch (_: Exception) {
- lastResult = ToolResult.error("Attempt $attempt failed")
+ } catch (e: Throwable) {
+ lastResult = ToolResult.error("Attempt $attempt failed: ${e.message}")
}
if (attempt < 3 && !lastResult.success) {
- java.lang.Thread.sleep(500)
+ kotlinx.coroutines.delay(500)
}
}
return lastResult
@@ -204,6 +204,8 @@ You are a mobile app navigation agent. Your job is to operate Android apps step
## Available Actions
- tap_index(index) — tap an element by its number from the UI Elements list
- tap(x, y, normalized=true) — tap at normalized coordinate (0-1000 space)
+- long_press_index(index) — long-press an element by its number
+- long_press(x, y, normalized=true) — long-press at normalized coordinate
- swipe(direction) or swipe(x1,y1,x2,y2, normalized=true) — swipe/scroll
- input_text(text) — type into the focused field
- press_key(key) — back, home, enter
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
index 254c8ac..a313b48 100644
--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -58,88 +58,98 @@ object ScreenPerception {
drawGrid: Boolean = false,
saveDir: File? = null
): CompressedScreenshot? {
- Log.d("ScreenCapture", "compressScreenshot: starting capture...")
- val bytes = captureRawBytes()
- if (bytes == null) {
- Log.e("ScreenCapture", "compressScreenshot: captureRawBytes returned null — all paths failed")
- return null
- }
- Log.d("ScreenCapture", "compressScreenshot: got ${bytes.size} raw bytes")
- val originalSize = bytes.size.toLong()
- val options = BitmapFactory.Options().apply {
- inMutable = true
- inScaled = false
- }
- val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
- if (bitmap == null) {
- Log.e("ScreenCapture", "compressScreenshot: BitmapFactory.decodeByteArray returned null — invalid image data")
- return null
- }
- Log.d("ScreenCapture", "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}")
- val annotated = if (drawGrid) {
- val elements = lastElementsCache ?: emptyList()
- if (elements.isNotEmpty()) {
- drawElementOverlays(bitmap, elements)
+ return try {
+ Log.d("ScreenCapture", "compressScreenshot: starting capture...")
+ val bytes = captureRawBytes()
+ if (bytes == null) {
+ Log.e("ScreenCapture", "compressScreenshot: captureRawBytes returned null — all paths failed")
+ return null
+ }
+ Log.d("ScreenCapture", "compressScreenshot: got ${bytes.size} raw bytes")
+ val originalSize = bytes.size.toLong()
+ val options = BitmapFactory.Options().apply {
+ inMutable = true
+ inScaled = false
+ }
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
+ if (bitmap == null) {
+ Log.e("ScreenCapture", "compressScreenshot: BitmapFactory.decodeByteArray returned null — invalid image data")
+ return null
+ }
+ Log.d("ScreenCapture", "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}")
+ val annotated = if (drawGrid) {
+ val elements = lastElementsCache ?: emptyList()
+ if (elements.isNotEmpty()) {
+ drawElementOverlays(bitmap, elements)
+ } else {
+ drawCoordinateGrid(bitmap)
+ }
} else {
- drawCoordinateGrid(bitmap)
+ bitmap
}
- } else {
- bitmap
- }
-
- val forEncoding = if (maxDimension > 0) downscale(annotated, maxDimension) else annotated
-
- val sw = forEncoding.width
- val sh = forEncoding.height
- val output = ByteArrayOutputStream()
- forEncoding.compress(format, quality, output)
-
- if (saveDir != null) {
- try {
- if (!saveDir.exists()) saveDir.mkdirs()
- val debugFile = File(saveDir, "screenshot_overlay_${System.currentTimeMillis()}.png")
- FileOutputStream(debugFile).use { fos ->
- forEncoding.compress(Bitmap.CompressFormat.PNG, 100, fos)
+
+ val forEncoding = if (maxDimension > 0) downscale(annotated, maxDimension) else annotated
+
+ val sw = forEncoding.width
+ val sh = forEncoding.height
+ val output = ByteArrayOutputStream()
+ forEncoding.compress(format, quality, output)
+
+ if (saveDir != null) {
+ try {
+ if (!saveDir.exists()) saveDir.mkdirs()
+ val debugFile = File(saveDir, "screenshot_overlay_${System.currentTimeMillis()}.png")
+ FileOutputStream(debugFile).use { fos ->
+ forEncoding.compress(Bitmap.CompressFormat.PNG, 100, fos)
+ }
+ } catch (e: Throwable) {
+ Log.e("ScreenCapture", "Failed to save debug screenshot: ${e.message}")
}
- } catch (e: Exception) {
- Log.e("ScreenCapture", "Failed to save debug screenshot: ${e.message}")
}
+
+ if (forEncoding !== annotated) forEncoding.recycle()
+ if (annotated !== bitmap) annotated.recycle()
+ bitmap.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"
+ }
+ CompressedScreenshot(base64, sw, sh, fmtName, originalSize)
+ } catch (e: kotlinx.coroutines.CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ Log.e("ScreenCapture", "compressScreenshot failed with throwable: ${e.message}", e)
+ null
}
-
-
-
- if (forEncoding !== annotated) forEncoding.recycle()
- if (annotated !== bitmap) annotated.recycle()
- bitmap.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, sw, sh, 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)
- lastElementsCache = elements.toList()
- 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")
+ return try {
+ 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)
+ lastElementsCache = elements.toList()
+ root.recycle()
+ if (elements.isEmpty()) return "(no UI elements found)"
+ 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"
}
- val text = if (el.text.isNotBlank()) "\"${el.text}\"" else ""
- "${el.index}. ${el.className} $text (${el.bounds})$props"
+ } catch (e: Throwable) {
+ Log.e("ScreenCapture", "buildUiHierarchyText failed with throwable: ${e.message}", e)
+ "(error reading UI: ${e.message})"
}
}
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index f5719ec..076af73 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -78,8 +78,8 @@ class SubAgentSession(
subLlm.chat(history.toList(), subAgentTools, sessionId = sessionId)
} catch (e: CancellationException) {
throw e
- } catch (e: Exception) {
- Log.e(TAG, "Sub-agent LLM call failed: ${e.message}")
+ } catch (e: Throwable) {
+ Log.e(TAG, "Sub-agent LLM call failed: ${e.message}", e)
onStep("error", "completed", e.message ?: "LLM call failed")
return SubAgentOutput("Task failed: ${e.message}", collectedSteps.toList())
}
@@ -141,7 +141,7 @@ class SubAgentSession(
toolExecutor.execute(call.function.name, args, AgentMode.OPERATOR, isSubAgent = true)
} catch (e: CancellationException) {
throw e
- } catch (e: Exception) {
+ } catch (e: Throwable) {
ToolResult.error("Tool '${call.function.name}' failed: ${e.message}")
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 80bc307..b66ef2c 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1310,6 +1310,41 @@ object ToolDefinitions {
}
)
+ val longPress = tool(
+ "long_press",
+ "Perform a long-press gesture on a specific on-screen UI element or explicit coordinates.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("text") {
+ put("type", "string")
+ put("description", "Visible text/label of the element to long press.")
+ }
+ putJsonObject("x") {
+ put("type", "integer")
+ put("description", "Absolute X coordinate.")
+ }
+ putJsonObject("y") {
+ put("type", "integer")
+ put("description", "Absolute Y coordinate.")
+ }
+ }
+ }
+ )
+
+ val longPressIndex = tool(
+ "long_press_index",
+ "Perform a long-press gesture on a UI element from the numbered elements list shown in the screen observation.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Index of the element to long press (from the ── UI Elements ── list).")
+ }
+ }
+ putJsonArray("required") { add("index") }
+ }
+ )
+
val pressKey = tool(
"press_key",
"Press a system key or perform a navigation action. " +
@@ -1592,7 +1627,7 @@ object ToolDefinitions {
webSearch, webFetch,
// DEPRECATED: readImage excluded from the active catalog — use read_file instead.
// Tier 3 additions
- readScreen, readScreenRaw, tap, swipe, tapIndex, pressKey, inputText, globalAction,
+ readScreen, readScreenRaw, tap, longPress, swipe, tapIndex, longPressIndex, pressKey, inputText, globalAction,
navigateApp,
readNotifications, dismissNotifications, mediaControl,
showOverlay, hideOverlay,
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 2e8925f..e745391 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -367,6 +367,26 @@ class ToolExecutor(
val index = args.requireInt("index") ?: return missing("index")
accessibilityTool.tapByIndex(index)
}
+ "long_press" -> {
+ var x = args.requireInt("x")
+ var y = args.requireInt("y")
+ val normalized = args.requireBoolean("normalized") ?: false
+ if (normalized && x != null && y != null) {
+ val (w, h) = ScreenPerception.getScreenDimensions()
+ val pixelCoords = ScreenPerception.normalizeToPixel(x, y, w, h)
+ x = pixelCoords.first
+ y = pixelCoords.second
+ }
+ accessibilityTool.longPress(
+ text = args.requireString("text"),
+ x = x,
+ y = y
+ )
+ }
+ "long_press_index" -> {
+ val index = args.requireInt("index") ?: return missing("index")
+ accessibilityTool.longPressByIndex(index)
+ }
"press_key" -> {
val key = args.requireString("key") ?: return missing("key")
accessibilityTool.pressKey(key)
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index dabf8bc..30a106b 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -49,7 +49,7 @@ object ToolRegistry {
/** Tools available to the App Navigator sub-agent. */
val navigatorTools: Set<String> = setOf(
- "tap", "tap_index", "swipe", "input_text", "press_key",
+ "tap", "tap_index", "long_press", "long_press_index", "swipe", "input_text", "press_key",
"sleep", "ask_final_answer"
)
@@ -79,6 +79,28 @@ object ToolRegistry {
putJsonArray("required") { add("index") }
}
)),
+ "long_press" to ToolDefinition(function = FunctionDefinition("long_press",
+ "Long press at coordinates. Use normalized=true and x,y in [0,1000] space.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("x") { put("type", "integer"); put("description", "X in [0,1000]") }
+ putJsonObject("y") { put("type", "integer"); put("description", "Y in [0,1000]") }
+ putJsonObject("normalized") { put("type", "boolean"); put("description", "Default true") }
+ putJsonObject("text") { put("type", "string"); put("description", "Element text to match") }
+ }
+ }
+ )),
+ "long_press_index" to ToolDefinition(function = FunctionDefinition("long_press_index",
+ "Long press a UI element by its index from the UI Elements list.",
+ buildJsonObject {
+ put("type", "object")
+ putJsonObject("properties") {
+ putJsonObject("index") { put("type", "integer"); put("description", "Element index") }
+ }
+ putJsonArray("required") { add("index") }
+ }
+ )),
"swipe" to ToolDefinition(function = FunctionDefinition("swipe",
"Scroll the screen in a direction. 'down' scrolls to see lower content (upward swipe).",
buildJsonObject {