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 support for targeting UI elements by index in input_text and swipe tools using a screen element cache

Rishabh Bajpai2f8973e8ba4d
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 042daa6..eebdbca 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -1263,6 +1263,12 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
val rebuilt = llmHistory.mapNotNull { msg ->
val text = msg.textContent
when {
+ msg.role == "user" && (text.startsWith("[Screen State]") || text.startsWith("Screen text:")) -> {
+ val saved = if (text.contains("Saved to:")) " → " + text.substringAfter("Saved to:").trim() else ""
+ val msgText = if (text.startsWith("Screen text:")) "[Full-resolution screenshot captured]$saved"
+ else "[Screenshot captured for visual context]"
+ UiMessage(nextId++, MessageKind.ASSISTANT, msgText)
+ }
msg.role == "user" -> UiMessage(nextId++, MessageKind.USER, text.ifEmpty { "(image attached)" })
msg.role == "assistant" && text.isNotBlank() ->
UiMessage(nextId++, MessageKind.ASSISTANT, text)
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index 838f0ee..bd0a9cd 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -134,12 +134,55 @@ class GotchaAccessibilityService : AccessibilityService() {
/** Type [text] into the currently focused editable field. */
fun typeText(text: String): Boolean {
val focused = findFocus(AccessibilityNodeInfo.FOCUS_INPUT) ?: return false
+ val ok = setTextOnNode(focused, text)
+ focused.recycle()
+ return ok
+ }
+
+ /** Type [text] into a specific node matching the given bounds (left, top, right, bottom). */
+ fun typeTextIntoNodeByBounds(boundsStr: String, text: String): Boolean {
+ val targetBounds = android.graphics.Rect()
+ try {
+ val parts = boundsStr.split(",").map { it.trim().toInt() }
+ if (parts.size == 4) {
+ targetBounds.set(parts[0], parts[1], parts[2], parts[3])
+ } else return false
+ } catch (e: Exception) {
+ return false
+ }
+
+ val root = rootInActiveWindow ?: return false
+ var match: AccessibilityNodeInfo? = null
+
+ fun search(node: AccessibilityNodeInfo?) {
+ if (node == null || match != null) return
+ if (node.isVisibleToUser) {
+ val bounds = android.graphics.Rect()
+ node.getBoundsInScreen(bounds)
+ if (bounds == targetBounds) {
+ match = AccessibilityNodeInfo.obtain(node)
+ return
+ }
+ }
+ for (i in 0 until node.childCount) {
+ search(node.getChild(i))
+ }
+ }
+
+ search(root)
+ root.recycle()
+
+ val nodeToEdit = match ?: return false
+ val ok = setTextOnNode(nodeToEdit, text)
+ nodeToEdit.recycle()
+ return ok
+ }
+
+ private fun setTextOnNode(node: AccessibilityNodeInfo, text: String): Boolean {
val args = android.os.Bundle().apply {
putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text)
}
- val ok = focused.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)
- focused.recycle()
- return ok
+ return node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)
}
/** Dispatch a tap gesture at absolute screen coordinates (API 24+). */
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 70993e6..16185c5 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -52,8 +52,31 @@ class AccessibilityTool(private val context: Context) {
}
/** 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): ToolResult {
+ 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()
+ if (index != null) {
+ 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.none { it == null }) {
+ val cx = (parts[0]!! + parts[2]!!) / 2f
+ val top = parts[1]!!.toFloat()
+ val bottom = parts[3]!!.toFloat()
+ val left = parts[0]!!.toFloat()
+ val right = parts[2]!!.toFloat()
+ val h = bottom - top
+ val w = right - left
+ val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
+ "up" -> listOf(cx, top + h * 0.8f, cx, top + h * 0.2f)
+ "down" -> listOf(cx, top + h * 0.2f, cx, top + h * 0.8f)
+ "left" -> listOf(left + w * 0.8f, (top + bottom) / 2f, left + w * 0.2f, (top + bottom) / 2f)
+ "right" -> listOf(left + w * 0.2f, (top + bottom) / 2f, left + w * 0.8f, (top + bottom) / 2f)
+ else -> return ToolResult.error("Provide a direction (up/down/left/right) when using index.")
+ }
+ return if (service.swipe(sx, sy, ex, ey, 500)) ToolResult.ok("Swiped $direction on element $index.")
+ else ToolResult.error("Could not dispatch the swipe gesture on element $index.")
+ }
+ }
if (x1 != null && y1 != null && x2 != null && y2 != null) {
val (sx, sy, ex, ey) = if (normalized) {
val (w, h) = ScreenPerception.getScreenDimensions()
@@ -72,10 +95,10 @@ class AccessibilityTool(private val context: Context) {
val h = metrics.heightPixels.toFloat()
val scrollPx = distance?.toFloat()?.takeIf { it > 0f } ?: (h * 0.6f)
val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
- "up" -> listOf(w / 2, h * 0.2f, w / 2, h * 0.2f + scrollPx)
- "down" -> listOf(w / 2, h * 0.8f, w / 2, h * 0.8f - scrollPx)
- "left" -> listOf(w * 0.2f, h / 2, w * 0.2f + scrollPx, h / 2)
- "right" -> listOf(w * 0.8f, h / 2, w * 0.8f - scrollPx, h / 2)
+ "up" -> listOf(w / 2, h * 0.8f, w / 2, h * 0.8f - scrollPx)
+ "down" -> listOf(w / 2, h * 0.2f, w / 2, h * 0.2f + scrollPx)
+ "left" -> listOf(w * 0.8f, h / 2, w * 0.8f - scrollPx, h / 2)
+ "right" -> listOf(w * 0.2f, h / 2, w * 0.2f + scrollPx, h / 2)
else -> return ToolResult.error(
"Provide a direction (up/down/left/right) or explicit x1,y1,x2,y2 coordinates."
)
@@ -84,11 +107,19 @@ class AccessibilityTool(private val context: Context) {
else ToolResult.error("Could not dispatch the swipe gesture.")
}
- /** Type text into the currently focused input field. */
- fun inputText(text: String): ToolResult {
+ /** Type text into the currently focused input field or target an element directly by index. */
+ fun inputText(text: String, index: Int? = null): ToolResult {
val service = GotchaAccessibilityService.instance ?: return if (isEnabled()) serviceNotRunning() else notEnabled()
+ if (index != null) {
+ val element = ScreenPerception.resolveElementByIndex(index)
+ ?: return ToolResult.error("No UI element with index $index found on screen.")
+ if (service.typeTextIntoNodeByBounds(element.bounds, text)) {
+ return ToolResult.ok("Typed \"$text\" into element $index.")
+ }
+ // Fall through if direct setting fails, maybe it wasn't editable via ACTION_SET_TEXT
+ }
return if (service.typeText(text)) ToolResult.ok("Typed \"$text\" into the focused field.")
- else ToolResult.error("No editable field is focused. Tap a text field first, then input text.")
+ else ToolResult.error("No editable field is focused. Try passing the index of the text field.")
}
/** Perform a device-wide navigation gesture via the accessibility service (back/home/recents/...). */
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
index f0f0e16..2f3fe3f 100644
--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -23,6 +23,9 @@ object ScreenPerception {
@Volatile
var mediaProjectionResultData: android.content.Intent? = null
+ @Volatile
+ private var lastElementsCache: List<UiElement>? = null
+
/** Application context — set by ChatViewModel.init(). Used by captureRawBytes. */
@Volatile
var appContext: android.content.Context? = null
@@ -96,6 +99,7 @@ object ScreenPerception {
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 ->
@@ -128,13 +132,7 @@ object ScreenPerception {
}
fun resolveElementByIndex(targetIndex: Int): UiElement? {
- val service = GotchaAccessibilityService.instance ?: return null
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) return null
- val root = service.rootInActiveWindow ?: return null
- val container = mutableListOf<UiElement>()
- collectElements(root, container, 1000)
- root.recycle()
- return container.firstOrNull { it.index == targetIndex }
+ return lastElementsCache?.firstOrNull { it.index == targetIndex }
}
fun normalizeToPixel(modelX: Int, modelY: Int, displayW: Int, displayH: Int): Pair<Int, Int> {
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index f5de64b..6342e84 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1269,15 +1269,20 @@ object ToolDefinitions {
val swipe = tool(
"swipe",
- "Swipe the screen via the accessibility service — a named direction (up/down/left/right) " +
- "or explicit start/end coordinates. Use for scrolling and navigation. Needs the " +
- "accessibility service enabled.",
+ "Swipe the screen via the accessibility service — a named direction (up/down/left/right), " +
+ "explicit start/end coordinates, or by UI element index. Use for scrolling and navigation. " +
+ "If using a direction, 'down' means scroll the content down to see lower items (which performs an upward swipe). " +
+ "Needs the accessibility service enabled.",
schema {
putJsonObject("properties") {
putJsonObject("direction") {
put("type", "string")
put("description", "One of: up, down, left, right.")
}
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Optional index of the UI element to swipe on.")
+ }
putJsonObject("x1") { put("type", "integer"); put("description", "Start X (with y1,x2,y2).") }
putJsonObject("y1") { put("type", "integer"); put("description", "Start Y.") }
putJsonObject("x2") { put("type", "integer"); put("description", "End X.") }
@@ -1344,14 +1349,19 @@ object ToolDefinitions {
val inputText = tool(
"input_text",
- "Type text into the currently focused input field via the accessibility service. Tap a " +
- "text field first so it is focused. Needs the accessibility service enabled.",
+ "Type text into a text field via the accessibility service. You can optionally target an " +
+ "element directly by providing its index. If no index is provided, it types into the currently " +
+ "focused field. Needs the accessibility service enabled.",
schema {
putJsonObject("properties") {
putJsonObject("text") {
put("type", "string")
put("description", "Text to type into the focused field.")
}
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Optional index of the text field to type into.")
+ }
}
putJsonArray("required") { add("text") }
}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 112ccac..2e8925f 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -360,7 +360,8 @@ class ToolExecutor(
direction = args.requireString("direction"),
x1 = args.requireInt("x1"), y1 = args.requireInt("y1"),
x2 = args.requireInt("x2"), y2 = args.requireInt("y2"),
- normalized = args.requireBoolean("normalized") ?: false
+ normalized = args.requireBoolean("normalized") ?: false,
+ index = args.requireInt("index")
)
"tap_index" -> {
val index = args.requireInt("index") ?: return missing("index")
@@ -379,7 +380,10 @@ class ToolExecutor(
handler(task)
}
}
- "input_text" -> accessibilityTool.inputText(args.requireString("text") ?: return missing("text"))
+ "input_text" -> accessibilityTool.inputText(
+ text = args.requireString("text") ?: return missing("text"),
+ index = args.requireInt("index")
+ )
"global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))
"read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)
"dismiss_notifications" -> notificationTool.dismissNotifications(args.requireString("key"))
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index 733dfa4..dabf8bc 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -80,21 +80,23 @@ object ToolRegistry {
}
)),
"swipe" to ToolDefinition(function = FunctionDefinition("swipe",
- "Scroll the screen in a direction. Each swipe scrolls about half the screen.",
+ "Scroll the screen in a direction. 'down' scrolls to see lower content (upward swipe).",
buildJsonObject {
put("type", "object")
putJsonObject("properties") {
putJsonObject("direction") { put("type", "string"); put("description", "up, down, left, or right") }
+ putJsonObject("index") { put("type", "integer"); put("description", "Optional element index to scroll") }
}
putJsonArray("required") { add("direction") }
}
)),
"input_text" to ToolDefinition(function = FunctionDefinition("input_text",
- "Type text into the focused field.",
+ "Type text into a field. Provide 'index' to target it directly.",
buildJsonObject {
put("type", "object")
putJsonObject("properties") {
putJsonObject("text") { put("type", "string"); put("description", "Text to type") }
+ putJsonObject("index") { put("type", "integer"); put("description", "Element index") }
}
putJsonArray("required") { add("text") }
}