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: enhance tool execution with coordinate normalization, grid visualization, and expanded accessibility actions like indexing and key events.

Rishabh Bajpai055ceaf6ca02
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index e832a16..1e369b3 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -139,6 +139,18 @@ class MainActivity : ComponentActivity() {
}
}
+ // Collect exported chat content and launch a share sheet
+ lifecycleScope.launch {
+ chatViewModel.exportContent.collect { markdown ->
+ val shareIntent = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, markdown)
+ putExtra(Intent.EXTRA_SUBJECT, "Gotcha Chat Export")
+ }
+ startActivity(Intent.createChooser(shareIntent, "Share Chat Export"))
+ }
+ }
+
// Auto-request runtime permissions on first launch
lifecycleScope.launch {
val prefs = settingsRepository.prefs
@@ -336,7 +348,8 @@ class MainActivity : ComponentActivity() {
onSwitchAgent = chatViewModel::switchAgent,
onSpeak = chatViewModel::speak,
onStartListening = chatViewModel::startListening,
- onStopRecording = chatViewModel::stopRecording
+ onStopRecording = chatViewModel::stopRecording,
+ onExportChat = chatViewModel::exportChat
)
}
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index b2e3e73..ff2eb2c 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.AppNavigatorSession
import com.gotcha.tools.ScreenPerception
import com.gotcha.tools.ToolExecutor
import com.gotcha.tools.ToolRegistry
@@ -147,39 +148,89 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
private val _permissionRequests = MutableSharedFlow<String>(extraBufferCapacity = 4)
val permissionRequests: SharedFlow<String> = _permissionRequests.asSharedFlow()
+ /** Exported chat markdown content the Activity should share. */
+ private val _exportContent = MutableSharedFlow<String>(extraBufferCapacity = 2)
+ val exportContent: SharedFlow<String> = _exportContent.asSharedFlow()
+
init {
- toolExecutor = ToolExecutor(application) { description, prompt ->
- _uiState.update { it.copy(subAgentRunning = description, subAgentCurrentAction = "starting…") }
- val steps = mutableListOf<SubAgentStepUi>()
- val subSession = SubAgentSession(
- appContext = getApplication(),
- toolExecutor = toolExecutor,
- settings = settings,
- description = description,
- prompt = prompt,
- onStep = { action, status, detail ->
- steps.add(SubAgentStepUi(action, status, detail))
- _uiState.update {
- it.copy(
- subAgentCurrentAction = when (status) {
- "running" -> "→ $action"
- "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
- else "✓ $action"
- else -> "$action: ${detail.take(60)}"
- }
- )
+ toolExecutor = ToolExecutor(
+ application,
+ onTask = { description, prompt ->
+ _uiState.update { it.copy(subAgentRunning = description, subAgentCurrentAction = "starting…") }
+ val steps = mutableListOf<SubAgentStepUi>()
+ val subSession = SubAgentSession(
+ appContext = getApplication(),
+ toolExecutor = toolExecutor,
+ settings = settings,
+ description = description,
+ prompt = prompt,
+ onStep = { action, status, detail ->
+ steps.add(SubAgentStepUi(action, status, detail))
+ _uiState.update {
+ it.copy(
+ subAgentCurrentAction = when (status) {
+ "running" -> "→ $action"
+ "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
+ else "✓ $action"
+ else -> "$action: ${detail.take(60)}"
+ }
+ )
+ }
+ },
+ sessionId = activeSessionId?.let { "${it}_task" }
+ )
+ val output = subSession.run()
+ val stepsEncoded = output.steps.joinToString("\n")
+ _uiState.update { it.copy(subAgentRunning = null, subAgentCurrentAction = null) }
+ if (output.finalAnswer.startsWith("Task failed") || output.finalAnswer.startsWith("Task exceeded")) {
+ ToolResult.error(output.finalAnswer)
+ } else {
+ ToolResult.ok("TASK_RESULT:$description:$stepsEncoded\n|||\n${output.finalAnswer}")
+ }
+ },
+ onNavigateApp = { task ->
+ _uiState.update { it.copy(subAgentRunning = "App Navigation", subAgentCurrentAction = "starting…") }
+ val steps = mutableListOf<SubAgentStepUi>()
+ val session = AppNavigatorSession(
+ appContext = getApplication(),
+ toolExecutor = toolExecutor,
+ settings = settings,
+ task = task,
+ onStep = { action, status, detail ->
+ steps.add(SubAgentStepUi(action, status, detail))
+ _uiState.update {
+ it.copy(
+ subAgentCurrentAction = when (status) {
+ "running" -> "→ $action"
+ "completed" -> if (detail.isNotBlank()) "✓ $action → ${detail.take(60)}"
+ else "✓ $action"
+ else -> "$action: ${detail.take(60)}"
+ }
+ )
+ }
+ },
+ sessionId = activeSessionId?.let { "${it}_nav" }
+ )
+ val output = session.run()
+ val stepsEncoded = output.steps.joinToString("\n")
+ _uiState.update { it.copy(subAgentRunning = null, subAgentCurrentAction = null) }
+ // Auto-return to our app after navigation completes
+ try {
+ val pkg = getApplication<android.app.Application>().packageName
+ val launchIntent = getApplication<android.app.Application>()
+ .packageManager.getLaunchIntentForPackage(pkg)
+ if (launchIntent != null) {
+ launchIntent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP)
+ getApplication<android.app.Application>().startActivity(launchIntent)
}
+ } catch (_: Exception) { }
+ if (!output.success) {
+ ToolResult.error(output.finalAnswer)
+ } else {
+ ToolResult.ok("TASK_RESULT:App Navigation:$stepsEncoded\n|||\n${output.finalAnswer}")
}
- )
- val output = subSession.run()
- val stepsEncoded = output.steps.joinToString("\n")
- _uiState.update { it.copy(subAgentRunning = null, subAgentCurrentAction = null) }
- if (output.finalAnswer.startsWith("Task failed") || output.finalAnswer.startsWith("Task exceeded")) {
- ToolResult.error(output.finalAnswer)
- } else {
- ToolResult.ok("TASK_RESULT:$description:$stepsEncoded\n|||\n${output.finalAnswer}")
}
- }
+ )
refreshSettings()
viewModelScope.launch {
val sessions = historyRepository.listSessions()
@@ -1024,6 +1075,11 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
"For example: organizing files, gathering information from multiple sources, " +
"or performing a series of device checks. The sub-agent runs in the foreground; " +
"you will receive its complete report when done. " +
+ "Use the navigate_app tool to delegate app interaction tasks to the App " +
+ "Navigator sub-agent. For example: opening an app, searching for something, " +
+ "scrolling through results, or reading on-screen information. The navigator " +
+ "will look at the screen, tap, swipe, and type step by step. " +
+ "You will receive its complete report when done. " +
"Keep replies short and conversational. Be careful with destructive actions.\n" +
"If the accessibility service is enabled, you have the ability to control any app on the device.\n" +
"When using uninstall_app: after calling it, the system will open a dialog. " +
@@ -1251,6 +1307,86 @@ class ChatViewModel(application: Application) : AndroidViewModel(application) {
}
}
+ fun exportChat() {
+ val sessionId = activeSessionId ?: "unknown"
+ val sb = StringBuilder()
+ sb.appendLine("# Gotcha Chat Export")
+ sb.appendLine("**Session:** $sessionId")
+ sb.appendLine("**Date:** ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US).format(java.util.Date())}")
+ sb.appendLine("**Messages:** ${llmHistory.size}")
+ sb.appendLine()
+ sb.appendLine("---")
+ sb.appendLine()
+
+ for (msg in llmHistory) {
+ val role = msg.role
+ val text = msg.textContent
+
+ when (role) {
+ "user" -> {
+ val isVision = msg.content is JsonArray
+ sb.appendLine("### User")
+ if (text.isNotBlank()) sb.appendLine(text)
+ if (isVision) sb.appendLine("*(Image attached)*")
+ sb.appendLine()
+ }
+ "assistant" -> {
+ sb.appendLine("### Assistant")
+ if (text.isNotBlank()) sb.appendLine(text)
+ val calls = msg.toolCalls
+ if (!calls.isNullOrEmpty()) {
+ sb.appendLine()
+ sb.appendLine("**Called tools:**")
+ for (call in calls) {
+ sb.appendLine("- `${call.function.name}(${call.function.arguments.take(200)})`")
+ }
+ }
+ sb.appendLine()
+ }
+ "tool" -> {
+ if (text.startsWith("SUBAGENT_STEPS:")) {
+ val descEnd = text.indexOf('\n', "SUBAGENT_STEPS:".length)
+ val desc = if (descEnd > 0) text.substring("SUBAGENT_STEPS:".length, descEnd)
+ else text.substring("SUBAGENT_STEPS:".length)
+ sb.appendLine("### Sub-Agent: $desc")
+ val rest = if (descEnd > 0) text.substring(descEnd + 1) else ""
+ val stepsMarker = "── Steps ──\n"
+ val resultMarker = "\n── Result ──\n"
+ if (rest.startsWith(stepsMarker)) {
+ val afterSteps = rest.removePrefix(stepsMarker)
+ val resIdx = afterSteps.indexOf(resultMarker)
+ if (resIdx >= 0) {
+ val steps = afterSteps.substring(0, resIdx).split("\n").filter { it.isNotBlank() }
+ val answer = afterSteps.substring(resIdx + resultMarker.length)
+ sb.appendLine()
+ sb.appendLine("**Steps:**")
+ for (s in steps) sb.appendLine("- $s")
+ sb.appendLine()
+ sb.appendLine("**Result:**")
+ sb.appendLine(answer)
+ } else {
+ sb.appendLine(afterSteps)
+ }
+ } else {
+ sb.appendLine(rest)
+ }
+ } else {
+ sb.appendLine("### Tool Result")
+ sb.appendLine(text.ifEmpty { "(no result)" })
+ }
+ sb.appendLine()
+ }
+ "system" -> {
+ sb.appendLine("### System")
+ sb.appendLine(text.ifEmpty { "(system message)" })
+ sb.appendLine()
+ }
+ }
+ }
+
+ _exportContent.tryEmit(sb.toString())
+ }
+
private companion object {
const val INTER_CALL_DELAY_MS = 400L
const val CONFIRM_TIMEOUT_MS = 60_000L
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 13df17f..fff9aa7 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -11,6 +11,7 @@ data class Settings(
val baseUrl: String = DEFAULT_BASE_URL,
val model: String = DEFAULT_MODEL,
val subAgentModel: String = "", // empty = same as main agent
+ val navigatorModel: String = "", // empty = same as main model
val maxToolRounds: Int = 30,
val maxContextTokens: Int = 40000,
val apiTimeoutSeconds: Long = 0L,
@@ -54,6 +55,7 @@ class SettingsRepository(context: Context) {
?: Settings.DEFAULT_BASE_URL,
model = prefs.getString(KEY_MODEL, Settings.DEFAULT_MODEL) ?: Settings.DEFAULT_MODEL,
subAgentModel = prefs.getString(KEY_SUB_AGENT_MODEL, "") ?: "",
+ navigatorModel = prefs.getString(KEY_NAVIGATOR_MODEL, "") ?: "",
maxToolRounds = prefs.getInt(KEY_MAX_TOOL_ROUNDS, 30),
maxContextTokens = prefs.getInt(KEY_MAX_CONTEXT_TOKENS, 40000),
apiTimeoutSeconds = prefs.getLong(KEY_API_TIMEOUT, 0L),
@@ -73,6 +75,7 @@ class SettingsRepository(context: Context) {
.putString(KEY_BASE_URL, settings.baseUrl)
.putString(KEY_MODEL, settings.model)
.putString(KEY_SUB_AGENT_MODEL, settings.subAgentModel)
+ .putString(KEY_NAVIGATOR_MODEL, settings.navigatorModel)
.putInt(KEY_MAX_TOOL_ROUNDS, settings.maxToolRounds)
.putInt(KEY_MAX_CONTEXT_TOKENS, settings.maxContextTokens)
.putLong(KEY_API_TIMEOUT, settings.apiTimeoutSeconds)
@@ -92,6 +95,7 @@ class SettingsRepository(context: Context) {
const val KEY_BASE_URL = "base_url"
const val KEY_MODEL = "model"
const val KEY_SUB_AGENT_MODEL = "sub_agent_model"
+ const val KEY_NAVIGATOR_MODEL = "navigator_model"
const val KEY_MAX_TOOL_ROUNDS = "max_tool_rounds"
const val KEY_MAX_CONTEXT_TOKENS = "max_context_tokens"
const val KEY_API_TIMEOUT = "api_timeout"
diff --git a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
index 0c37afd..238b316 100644
--- a/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
+++ b/app/src/main/java/com/gotcha/tools/AccessibilityTool.kt
@@ -3,6 +3,7 @@ package com.gotcha.tools
import android.content.Context
import android.provider.Settings
import android.text.TextUtils
+import android.view.accessibility.AccessibilityNodeInfo
import com.gotcha.service.GotchaAccessibilityService
/**
@@ -49,21 +50,30 @@ 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?): ToolResult {
+ fun swipe(direction: String?, x1: Int?, y1: Int?, x2: Int?, y2: Int?, normalized: Boolean = false, distance: Int? = null): ToolResult {
val service = requireService() ?: return notEnabled()
if (x1 != null && y1 != null && x2 != null && y2 != null) {
- return if (service.swipe(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat()))
- ToolResult.ok("Swiped from ($x1, $y1) to ($x2, $y2).")
+ val (sx, sy, ex, ey) = if (normalized) {
+ val (w, h) = ScreenPerception.getScreenDimensions()
+ val s = ScreenPerception.normalizeToPixel(x1, y1, w, h)
+ val e = ScreenPerception.normalizeToPixel(x2, y2, w, h)
+ listOf(s.first.toFloat(), s.second.toFloat(), e.first.toFloat(), e.second.toFloat())
+ } else {
+ listOf(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat())
+ }
+ return if (service.swipe(sx, sy, ex, ey))
+ ToolResult.ok("Swiped from (${sx.toInt()}, ${sy.toInt()}) to (${ex.toInt()}, ${ey.toInt()}).")
else ToolResult.error("Could not dispatch the swipe gesture.")
}
val metrics = context.resources.displayMetrics
val w = metrics.widthPixels.toFloat()
val h = metrics.heightPixels.toFloat()
+ val scrollPx = distance?.toFloat()?.takeIf { it > 0f } ?: (h * 0.4f)
val (sx, sy, ex, ey) = when (direction?.lowercase()?.trim()) {
- "up" -> listOf(w / 2, h * 0.7f, w / 2, h * 0.3f)
- "down" -> listOf(w / 2, h * 0.3f, w / 2, h * 0.7f)
- "left" -> listOf(w * 0.7f, h / 2, w * 0.3f, h / 2)
- "right" -> listOf(w * 0.3f, h / 2, w * 0.7f, h / 2)
+ "up" -> listOf(w / 2, h * 0.6f, w / 2, h * 0.6f - scrollPx)
+ "down" -> listOf(w / 2, h * 0.4f, w / 2, h * 0.4f + scrollPx)
+ "left" -> listOf(w * 0.6f, h / 2, w * 0.6f - scrollPx, h / 2)
+ "right" -> listOf(w * 0.4f, h / 2, w * 0.4f + scrollPx, h / 2)
else -> return ToolResult.error(
"Provide a direction (up/down/left/right) or explicit x1,y1,x2,y2 coordinates."
)
@@ -79,7 +89,7 @@ class AccessibilityTool(private val context: Context) {
else ToolResult.error("No editable field is focused. Tap a text field first, then input text.")
}
- /** Perform a device-wide navigation gesture (back/home/recents/notifications/quick_settings/lock_screen). */
+ /** Perform a device-wide navigation gesture via the accessibility service (back/home/recents/...). */
fun globalAction(action: String): ToolResult {
val service = requireService() ?: return notEnabled()
return if (service.performGlobal(action)) ToolResult.ok("Performed global action: $action.")
@@ -89,6 +99,49 @@ class AccessibilityTool(private val context: Context) {
)
}
+ /** Tap a UI element by its index from the numbered elements list. */
+ fun tapByIndex(index: Int): ToolResult {
+ val service = requireService() ?: return 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.tapAt(cx, cy))
+ ToolResult.ok("Tapped element $index: \"${element.text.take(50)}\" at (${cx.toInt()}, ${cy.toInt()}).")
+ else ToolResult.error("Could not dispatch the tap gesture for element $index.")
+ }
+
+ /**
+ * Press a system key or perform a common navigation action.
+ * For "enter", clicks the currently focused input element.
+ */
+ fun pressKey(key: String): ToolResult {
+ val k = key.lowercase().trim()
+ val globalKeys = setOf("back", "home", "recents", "notifications", "quick_settings", "lock_screen")
+ if (k in globalKeys) return globalAction(k)
+ if (k == "enter") {
+ val service = requireService() ?: return notEnabled()
+ try {
+ val root = service.rootInActiveWindow
+ val result = try {
+ val focused = root?.findFocus(AccessibilityNodeInfo.FOCUS_INPUT)
+ if (focused != null) {
+ focused.performAction(AccessibilityNodeInfo.ACTION_CLICK)
+ } else false
+ } finally { try { root?.recycle() } catch (_: Exception) { } }
+ if (result) return ToolResult.ok("Pressed Enter.")
+ } catch (_: Exception) { }
+ return ToolResult.error("Could not press Enter. No focused element found.")
+ }
+ return ToolResult.error(
+ "Unknown key '$key'. Valid: ${(globalKeys + "enter").joinToString(", ")}."
+ )
+ }
+
private fun requireService(): GotchaAccessibilityService? =
if (isEnabled()) GotchaAccessibilityService.instance else null
diff --git a/app/src/main/java/com/gotcha/tools/AgentDefinition.kt b/app/src/main/java/com/gotcha/tools/AgentDefinition.kt
index 46ccdf6..d05a570 100644
--- a/app/src/main/java/com/gotcha/tools/AgentDefinition.kt
+++ b/app/src/main/java/com/gotcha/tools/AgentDefinition.kt
@@ -13,5 +13,13 @@ data class AgentDefinition(
"Runs all Operator tools and returns a final summary.",
isSubagent = true
)
+
+ val APP_NAVIGATOR = AgentDefinition(
+ name = "APP_NAVIGATOR",
+ description = "App navigation agent that opens apps and operates " +
+ "them step by step: tap, swipe, type, scroll. " +
+ "Returns a detailed action log and final summary.",
+ isSubagent = true
+ )
}
}
diff --git a/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
new file mode 100644
index 0000000..28916ff
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/AppNavigatorSession.kt
@@ -0,0 +1,183 @@
+package com.gotcha.tools
+
+import android.content.Context
+import android.graphics.Bitmap
+import com.gotcha.data.Settings
+import com.gotcha.llm.ChatMessage
+import com.gotcha.llm.ChatResponse
+import com.gotcha.llm.LLMClient
+import com.gotcha.llm.ToolCall
+import kotlinx.coroutines.CancellationException
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.jsonPrimitive
+
+data class AppNavigatorOutput(
+ val finalAnswer: String,
+ val steps: List<String>,
+ val success: Boolean = true
+)
+
+class AppNavigatorSession(
+ private val appContext: Context,
+ private val toolExecutor: ToolExecutor,
+ private val settings: Settings,
+ private val task: String,
+ private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> },
+ private val sessionId: String? = null
+) {
+ private val json = Json { ignoreUnknownKeys = true }
+ private val maxSteps = 30
+ private val actionLog = mutableListOf<String>()
+
+ suspend fun run(): AppNavigatorOutput {
+ val model = settings.navigatorModel.ifEmpty { settings.model }
+ val llmClient = LLMClient(
+ apiKey = settings.apiKey,
+ baseUrl = settings.baseUrl,
+ model = model,
+ context = appContext,
+ apiTimeoutSeconds = settings.apiTimeoutSeconds
+ )
+ val navTools = ToolRegistry.toolsForNavigator()
+
+ for (step in 1..maxSteps) {
+ onStep("Analyzing screen", "running", "")
+
+ // 1. Capture fresh perception with grid overlay
+ val screenshot = ScreenPerception.compressScreenshot(drawGrid = true)
+ val uiTree = ScreenPerception.buildUiHierarchyText()
+
+ // 2. Build single-turn prompt
+ val actionLogText = actionLog.joinToString("\n") { " $it" }.ifEmpty { " (none yet)" }
+ val obsText = if (screenshot != null) {
+ ScreenPerception.buildObservationText(screenshot, uiTree)
+ } else {
+ "── UI Elements ──\n$uiTree\n── Screenshot ──\n(failed to capture)"
+ }
+ val userMsg = buildString {
+ appendLine("## Task")
+ appendLine(task)
+ appendLine()
+ appendLine("## Previous Actions")
+ appendLine(actionLogText)
+ appendLine()
+ appendLine("## Current Screen")
+ appendLine(obsText)
+ }
+
+ // 3. Single-turn LLM call with navigation tools
+ val response: ChatResponse = try {
+ llmClient.chat(
+ messages = listOf(
+ ChatMessage(role = "system", content = JsonPrimitive(NAVIGATOR_SYSTEM_PROMPT)),
+ ChatMessage(role = "user", content = JsonPrimitive(userMsg))
+ ),
+ tools = navTools,
+ sessionId = sessionId
+ )
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ actionLog.add("Step $step: LLM error — ${e.message}")
+ break
+ }
+
+ val msg = response.choices.firstOrNull()?.message ?: break
+ val toolCalls = msg.toolCalls.orEmpty()
+
+ // 4. Check for completion
+ if (toolCalls.isEmpty()) {
+ val content = msg.textContent.ifBlank { "(no reply)" }
+ actionLog.add("Step $step: ✓ $content")
+ return AppNavigatorOutput(finalAnswer = content, steps = actionLog.toList())
+ }
+
+ val completeCall = toolCalls.firstOrNull { it.function.name == "ask_final_answer" }
+ if (completeCall != null) {
+ val answer = parseAnswerArg(completeCall.function.arguments)
+ actionLog.add("Step $step: ✓ Task complete")
+ return AppNavigatorOutput(finalAnswer = answer, steps = actionLog.toList())
+ }
+
+ // 5. Execute each tool call with error recovery
+ for (call in toolCalls) {
+ val result = executeWithRetry(call)
+ val summary = if (result.success) result.message.take(100)
+ else "⚠ ${result.message.take(100)}"
+ actionLog.add("Step $step: ${call.function.name} → $summary")
+ onStep(call.function.name, "completed", summary)
+ }
+ }
+
+ return AppNavigatorOutput(
+ finalAnswer = "Reached $maxSteps steps without completing the task.",
+ steps = actionLog.toList(),
+ success = false
+ )
+ }
+
+ private suspend fun executeWithRetry(call: ToolCall): ToolResult {
+ var lastResult: ToolResult = ToolResult.error("Exhausted retries")
+ val args: JsonObject = try {
+ json.decodeFromString(JsonObject.serializer(), call.function.arguments.ifBlank { "{}" })
+ } catch (_: Exception) {
+ return ToolResult.error("Malformed arguments: ${call.function.arguments.take(100)}")
+ }
+
+ for (attempt in 1..3) {
+ try {
+ lastResult = toolExecutor.execute(
+ call.function.name, args,
+ AgentMode.OPERATOR, isSubAgent = true
+ )
+ java.lang.Thread.sleep(300)
+ if (lastResult.success) return lastResult
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ lastResult = ToolResult.error("Attempt $attempt failed")
+ }
+ if (attempt < 3 && !lastResult.success) {
+ java.lang.Thread.sleep(500)
+ }
+ }
+ return lastResult
+ }
+
+ companion object {
+ private val JSON = Json { ignoreUnknownKeys = true }
+
+ private fun parseAnswerArg(arguments: String): String {
+ return try {
+ val obj = JSON.decodeFromString<JsonObject>(arguments)
+ obj["answer"]?.jsonPrimitive?.content ?: "(completed)"
+ } catch (_: Exception) {
+ "(completed)"
+ }
+ }
+
+ private const val NAVIGATOR_SYSTEM_PROMPT = """
+You are a mobile app navigation agent. Your job is to operate Android apps step by step.
+
+## Rules
+- Take ONE action per turn. After acting, a fresh screenshot will show you the result.
+- The UI Elements list gives you precise positions. The screenshot gives visual context.
+- A coordinate grid is overlaid on the screenshot to help ground coordinates.
+- Prefer tap_index over raw coordinates (it's more precise).
+- When using coordinates, values are in [0, 1000] normalized space.
+- Never repeat an action that already failed.
+- Call ask_final_answer when the task is complete — include a clear summary.
+
+## 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)
+- 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
+- sleep(ms) — wait briefly (max 3000ms)
+- ask_final_answer(answer) — done! Provide the final summary.
+"""
+ }
+}
diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
index 973484a..d3d82cb 100644
--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt
@@ -2,6 +2,9 @@ package com.gotcha.tools
import android.graphics.Bitmap
import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
import android.graphics.Rect
import android.os.Build
import android.util.Base64
@@ -35,16 +38,23 @@ object ScreenPerception {
suspend fun compressScreenshot(
maxDimension: Int = 2000,
format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG,
- quality: Int = 50
+ quality: Int = 50,
+ drawGrid: Boolean = false
): 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 (forEncoding, recycleForEncoding) = if (drawGrid) {
+ drawCoordinateGrid(scaled) to true
+ } else {
+ scaled to false
+ }
+ if (drawGrid) scaled.recycle()
val output = ByteArrayOutputStream()
- scaled.compress(format, quality, output)
- scaled.recycle()
+ forEncoding.compress(format, quality, output)
+ if (recycleForEncoding) forEncoding.recycle()
val base64 = Base64.encodeToString(output.toByteArray(), Base64.NO_WRAP)
val fmtName = when (format) {
Bitmap.CompressFormat.JPEG -> "jpeg"
@@ -85,6 +95,7 @@ object ScreenPerception {
appendLine(uiTree)
appendLine("── Coordinate Contract ──")
appendLine("Screenshot is ${screenshot.width} x ${screenshot.height} pixels.")
+ appendLine("A coordinate grid is overlaid on the screenshot (10x10 divisions).")
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}")
@@ -92,6 +103,89 @@ 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 }
+ }
+
+ fun normalizeToPixel(modelX: Int, modelY: Int, displayW: Int, displayH: Int): Pair<Int, Int> {
+ val actualX = (modelX.toFloat() / 1000f * displayW).toInt().coerceIn(0, displayW)
+ val actualY = (modelY.toFloat() / 1000f * displayH).toInt().coerceIn(0, displayH)
+ return Pair(actualX, actualY)
+ }
+
+ fun denormalizeToModel(pixelX: Int, pixelY: Int, displayW: Int, displayH: Int): Pair<Int, Int> {
+ val modelX = (pixelX.toFloat() / displayW * 1000f).toInt().coerceIn(0, 1000)
+ val modelY = (pixelY.toFloat() / displayH * 1000f).toInt().coerceIn(0, 1000)
+ return Pair(modelX, modelY)
+ }
+
+ fun getScreenDimensions(): Pair<Int, Int> {
+ val service = GotchaAccessibilityService.instance
+ if (service != null) {
+ val root = service.rootInActiveWindow ?: return Pair(1080, 2340)
+ val bounds = Rect()
+ root.getBoundsInScreen(bounds)
+ root.recycle()
+ val w = bounds.right
+ val h = bounds.bottom
+ if (w > 0 && h > 0) return Pair(w, h)
+ }
+ return Pair(1080, 2340)
+ }
+
+ private fun drawCoordinateGrid(bitmap: Bitmap): Bitmap {
+ val result = bitmap.copy(Bitmap.Config.ARGB_8888, true) ?: return bitmap
+ val canvas = Canvas(result)
+ val w = bitmap.width.toFloat()
+ val h = bitmap.height.toFloat()
+ val divisions = 10
+
+ val linePaint = Paint().apply {
+ color = Color.argb(60, 180, 180, 200)
+ strokeWidth = 1.5f
+ isAntiAlias = true
+ }
+ val labelPaint = Paint().apply {
+ color = Color.argb(160, 255, 255, 255)
+ textSize = 20f
+ isAntiAlias = true
+ setShadowLayer(2f, 1f, 1f, Color.argb(128, 0, 0, 0))
+ }
+
+ for (i in 0..divisions) {
+ val x = w * i / divisions
+ val y = h * i / divisions
+ canvas.drawLine(x, 0f, x, h, linePaint)
+ canvas.drawLine(0f, y, w, y, linePaint)
+
+ val labelX = (i * 100).toString()
+ val labelY = (i * 100).toString()
+ if (i > 0 && i < divisions) {
+ canvas.drawText(labelX, x - 10f, h - 6f, labelPaint)
+ canvas.drawText(labelY, 4f, y - 6f, labelPaint)
+ }
+ canvas.drawText("0", 4f, h - 6f, labelPaint)
+ canvas.drawText("1000", w - 42f, h - 6f, labelPaint)
+ canvas.drawText("1000", 4f, 16f, labelPaint)
+ }
+
+ val centerPaint = Paint().apply {
+ color = Color.argb(100, 255, 200, 50)
+ strokeWidth = 2f
+ }
+ val cx = w / 2
+ val cy = h / 2
+ canvas.drawCircle(cx, cy, 8f, centerPaint)
+
+ return result
+ }
+
private suspend fun captureRawBytes(): ByteArray? {
return try {
withContext(Dispatchers.IO) {
diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
index b2764ad..8c7ea2a 100644
--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt
@@ -27,7 +27,8 @@ class SubAgentSession(
private val settings: Settings,
private val description: String,
private val prompt: String,
- private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> }
+ private val onStep: (action: String, status: String, detail: String) -> Unit = { _, _, _ -> },
+ private val sessionId: String? = null
) {
private val TAG = "SubAgentSession"
private val json = Json { ignoreUnknownKeys = true }
@@ -74,7 +75,7 @@ class SubAgentSession(
Log.d(TAG, "Sub-agent round ${round + 1}/$maxRounds")
val response = try {
- subLlm.chat(history.toList(), subAgentTools)
+ subLlm.chat(history.toList(), subAgentTools, sessionId = sessionId)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index 402eb28..e9f0e88 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -1253,11 +1253,15 @@ object ToolDefinitions {
}
putJsonObject("x") {
put("type", "integer")
- put("description", "Absolute X pixel coordinate (use with y instead of text).")
+ put("description", "X coordinate. If normalized=true, use [0,1000] space; else absolute pixels.")
}
putJsonObject("y") {
put("type", "integer")
- put("description", "Absolute Y pixel coordinate (use with x instead of text).")
+ put("description", "Y coordinate. If normalized=true, use [0,1000] space; else absolute pixels.")
+ }
+ putJsonObject("normalized") {
+ put("type", "boolean")
+ put("description", "If true, x and y are in [0, 1000] normalized space. Default false.")
}
}
}
@@ -1278,7 +1282,67 @@ object ToolDefinitions {
putJsonObject("y1") { put("type", "integer"); put("description", "Start Y.") }
putJsonObject("x2") { put("type", "integer"); put("description", "End X.") }
putJsonObject("y2") { put("type", "integer"); put("description", "End Y.") }
+ putJsonObject("normalized") {
+ put("type", "boolean")
+ put("description", "If true, coordinate params are in [0, 1000] normalized space. Default false.")
+ }
+ putJsonObject("distance") {
+ put("type", "integer")
+ put("description", "Scroll distance in pixels. Default 0 = full screen (70% of dimension). Ignored when using explicit coordinates.")
+ }
+ }
+ }
+ )
+
+ val tapIndex = tool(
+ "tap_index",
+ "Tap a UI element from the numbered elements list shown in the screen observation. " +
+ "The index corresponds to the number shown before each element. " +
+ "Prefer this over raw coordinate tap when possible for precision.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("index") {
+ put("type", "integer")
+ put("description", "Index of the element to tap (from the ── UI Elements ── list).")
+ }
+ }
+ putJsonArray("required") { add("index") }
+ }
+ )
+
+ val pressKey = tool(
+ "press_key",
+ "Press a system key or perform a navigation action. " +
+ "For entering text, use input_text instead.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("key") {
+ put("type", "string")
+ put("description", "One of: enter, back, home, recents, notifications, quick_settings, lock_screen, delete, tab, escape.")
+ }
+ }
+ putJsonArray("required") { add("key") }
+ }
+ )
+
+ val navigateApp = tool(
+ "navigate_app",
+ "Open apps and navigate them step by step. Provide a detailed description of " +
+ "what to do — the App Navigator will look at the screen, tap, swipe, type, " +
+ "and scroll until the task is done. " +
+ "Only available to Operator mode. Cannot be called from within a sub-agent.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("task") {
+ put("type", "string")
+ put("description", "Detailed step-by-step instructions of what to do in the app. " +
+ "Include the app name, search terms, what to look for, and what the final " +
+ "summary should contain. " +
+ "Example: 'Open Google Maps, search for restaurants near me, scroll through " +
+ "results, and tell me the top 5 with ratings and distances.'")
+ }
}
+ putJsonArray("required") { add("task") }
}
)
@@ -1523,7 +1587,8 @@ object ToolDefinitions {
webSearch, webFetch,
// DEPRECATED: readImage excluded from the active catalog — use read_file instead.
// Tier 3 additions
- readScreen, readScreenRaw, tap, swipe, inputText, globalAction,
+ readScreen, readScreenRaw, tap, swipe, tapIndex, pressKey, inputText, globalAction,
+ navigateApp,
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 d2a63cc..067cdbd 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -21,7 +21,8 @@ import kotlinx.serialization.json.jsonPrimitive
*/
class ToolExecutor(
context: Context,
- val onTask: (suspend (description: String, prompt: String) -> ToolResult)? = null
+ val onTask: (suspend (description: String, prompt: String) -> ToolResult)? = null,
+ val onNavigateApp: (suspend (task: String) -> ToolResult)? = null
) {
private val TAG = "Gotcha"
@@ -344,16 +345,41 @@ class ToolExecutor(
// ---- Tier 3 ----
"read_screen" -> accessibilityTool.readScreen()
"read_screen_raw" -> accessibilityTool.readScreenRaw()
- "tap" -> accessibilityTool.tap(
- text = args.requireString("text"),
- x = args.requireInt("x"),
- y = args.requireInt("y")
- )
+ "tap" -> {
+ 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 (nx, ny) = ScreenPerception.normalizeToPixel(x, y, w, h)
+ x = nx; y = ny
+ }
+ accessibilityTool.tap(text = args.requireString("text"), x = x, y = y)
+ }
"swipe" -> accessibilityTool.swipe(
direction = args.requireString("direction"),
x1 = args.requireInt("x1"), y1 = args.requireInt("y1"),
- x2 = args.requireInt("x2"), y2 = args.requireInt("y2")
+ x2 = args.requireInt("x2"), y2 = args.requireInt("y2"),
+ normalized = args.requireBoolean("normalized") ?: false,
+ distance = args.requireInt("distance")
)
+ "tap_index" -> {
+ val index = args.requireInt("index") ?: return missing("index")
+ accessibilityTool.tapByIndex(index)
+ }
+ "press_key" -> {
+ val key = args.requireString("key") ?: return missing("key")
+ accessibilityTool.pressKey(key)
+ }
+ "navigate_app" -> {
+ val handler = onNavigateApp
+ if (handler == null) {
+ ToolResult.error("App navigation is not configured.")
+ } else {
+ val task = args.requireString("task") ?: return missing("task")
+ handler(task)
+ }
+ }
"input_text" -> accessibilityTool.inputText(args.requireString("text") ?: return missing("text"))
"global_action" -> accessibilityTool.globalAction(args.requireString("action") ?: return missing("action"))
"read_notifications" -> notificationTool.readNotifications(args.requireInt("limit") ?: 15)
@@ -394,6 +420,9 @@ class ToolExecutor(
private fun JsonObject.requireInt(key: String): Int? =
this[key]?.jsonPrimitive?.let { it.intOrNull ?: it.content.trim().toIntOrNull() }
+ private fun JsonObject.requireBoolean(key: String): Boolean? =
+ this[key]?.jsonPrimitive?.booleanOrNull
+
private fun missing(param: String) =
ToolResult.error("Missing or invalid required parameter '$param'.")
diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
index f95283d..641b356 100644
--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt
@@ -36,8 +36,14 @@ object ToolRegistry {
"check_root"
)
- /** Full Operator tool set minus task (sub-agents cannot delegate further). */
- val subAgentTools: Set<String> = definitions.keys - "task"
+ /** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate further). */
+ val subAgentTools: Set<String> = definitions.keys - setOf("task", "navigate_app")
+
+ /** Tools available to the App Navigator sub-agent. */
+ val navigatorTools: Set<String> = setOf(
+ "tap", "tap_index", "swipe", "input_text", "press_key",
+ "sleep", "ask_final_answer"
+ )
private val operatorTools: Set<String> = definitions.keys
@@ -65,4 +71,7 @@ object ToolRegistry {
fun toolsForSubAgent(): List<ToolDefinition> =
definitions.filterKeys { it in subAgentTools }.values.toList()
+
+ fun toolsForNavigator(): List<ToolDefinition> =
+ definitions.filterKeys { it in navigatorTools }.values.toList()
}
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 1146744..4a811a8 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -26,6 +26,7 @@ import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Send
+import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
@@ -77,7 +78,8 @@ fun ChatScreen(
onSwitchAgent: () -> Unit,
onSpeak: (String) -> Unit = {},
onStartListening: () -> Unit = {},
- onStopRecording: () -> Unit = {}
+ onStopRecording: () -> Unit = {},
+ onExportChat: () -> Unit = {}
) {
var input by rememberSaveable { mutableStateOf("") }
var pendingImageUri by rememberSaveable { mutableStateOf<Uri?>(null) }
@@ -120,6 +122,9 @@ fun ChatScreen(
label = { Text(state.activeAgent.name) },
enabled = !state.isBusy
)
+ IconButton(onClick = onExportChat, enabled = !state.isBusy) {
+ Icon(Icons.Default.Share, contentDescription = "Export chat")
+ }
TextButton(onClick = onOpenSettings) { Text("Settings") }
}
)
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index 768f69f..33a333a 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -59,6 +59,7 @@ fun SettingsScreen(
var baseUrl by remember { mutableStateOf(initial.baseUrl) }
var model by remember { mutableStateOf(initial.model) }
var subAgentModel by remember { mutableStateOf(initial.subAgentModel) }
+ var navigatorModel by remember { mutableStateOf(initial.navigatorModel) }
var maxToolRounds by remember { mutableStateOf(initial.maxToolRounds.toString()) }
var maxContextTokens by remember { mutableStateOf(initial.maxContextTokens.toString()) }
var apiTimeoutSeconds by remember { mutableStateOf(initial.apiTimeoutSeconds.toString()) }
@@ -91,12 +92,14 @@ fun SettingsScreen(
var sttModelExpanded by remember { mutableStateOf(false) }
var modelExpanded by remember { mutableStateOf(false) }
var subAgentModelExpanded by remember { mutableStateOf(false) }
+ var navigatorModelExpanded by remember { mutableStateOf(false) }
fun currentSettings() = Settings(
apiKey = apiKey.trim(),
baseUrl = baseUrl.trim(),
model = model.trim(),
subAgentModel = subAgentModel.trim(),
+ navigatorModel = navigatorModel.trim(),
maxToolRounds = maxToolRounds.toIntOrNull()?.takeIf { it > 0 } ?: 30,
maxContextTokens = maxContextTokens.toIntOrNull()?.takeIf { it > 0 } ?: 40000,
apiTimeoutSeconds = apiTimeoutSeconds.toLongOrNull()?.takeIf { it >= 0 } ?: 0L,
@@ -233,6 +236,43 @@ fun SettingsScreen(
}
}
}
+ ExposedDropdownMenuBox(
+ expanded = navigatorModelExpanded,
+ onExpandedChange = { navigatorModelExpanded = it }
+ ) {
+ val navLabel = if (navigatorModel.isBlank()) "Same as main model" else navigatorModel
+ OutlinedTextField(
+ value = navLabel,
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("Navigator model") },
+ trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = navigatorModelExpanded) },
+ modifier = Modifier.fillMaxWidth().menuAnchor()
+ )
+ ExposedDropdownMenu(
+ expanded = navigatorModelExpanded,
+ onDismissRequest = { navigatorModelExpanded = false }
+ ) {
+ DropdownMenuItem(
+ text = { Text("Same as main model") },
+ onClick = {
+ navigatorModel = ""
+ navigatorModelExpanded = false
+ }
+ )
+ if (availableChatModels.isNotEmpty()) {
+ availableChatModels.forEach { m ->
+ DropdownMenuItem(
+ text = { Text(m) },
+ onClick = {
+ navigatorModel = m
+ navigatorModelExpanded = false
+ }
+ )
+ }
+ }
+ }
+ }
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)