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.

refactor: improve clipboard monitoring and smart action handling with logging, activity focus management, and event-based triggers

Rishabh Bajpai9b55c85fc713
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 88ea58d..831f007 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -94,23 +94,31 @@ class AssistiveBallService : Service() {
overlay.setSmartActionAvailable(label, prompt)
},
onReadClipboardRequest = {
- /* ... */
-
+ android.util.Log.d("AssistiveBallService", "onReadClipboardRequest called")
overlay.readClipboardWithFocus { clip ->
+ android.util.Log.d(
+ "AssistiveBallService",
+ "readClipboardWithFocus: null=${clip == null}, count=${clip?.itemCount ?: 0}"
+ )
com.gotcha.service.GotchaAccessibilityService.lastClipboardData = clip
val clipText = clip?.getItemAt(0)?.text?.toString()
+ android.util.Log.d("AssistiveBallService", "clipText = $clipText")
if (!clipText.isNullOrBlank()) {
if (android.util.Patterns.WEB_URL.matcher(clipText).find()) {
+ android.util.Log.d("AssistiveBallService", "Setting smart action: Link copied. Summarize?")
overlay.setSmartActionAvailable(
"🔗 Link copied. Summarize?",
- "Summarize the content of the copied URL."
+ "Summarize the content of the copied URL: $clipText"
)
} else {
+ android.util.Log.d("AssistiveBallService", "Setting smart action: Text copied. Translate?")
overlay.setSmartActionAvailable(
"📋 Text copied. Translate?",
- "Translate the copied text to English if it is not, otherwise summarize it."
+ "Translate the copied text to English if it is not, otherwise summarize it:\n\n$clipText"
)
}
+ } else {
+ android.util.Log.d("AssistiveBallService", "clipText is null or blank, not setting smart action")
}
}
}
@@ -171,7 +179,9 @@ class AssistiveBallService : Service() {
}
private fun handleSmartActionSelected(prompt: String, history: MutableList<com.gotcha.llm.ChatMessage>) {
- val attachScreenshot = prompt.contains("screenshot", ignoreCase = true)
+ val attachScreenshot = prompt.contains("screenshot", ignoreCase = true) ||
+ prompt.contains("screen", ignoreCase = true) ||
+ prompt.contains("webpage", ignoreCase = true)
screenCompanionPanel.show(prompt)
scope.launch {
try {
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
index d65e803..f76ba4e 100644
--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt
@@ -3,8 +3,6 @@ package com.gotcha.service
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.ClipData
-import android.content.ClipboardManager
-import android.content.Context
import android.graphics.Bitmap
import android.graphics.Path
import android.os.Build
@@ -40,9 +38,99 @@ class GotchaAccessibilityService : AccessibilityService() {
// Passive: we drive the UI on demand from tools rather than reacting to events,
// except for broadcasting window state changes to the ScreenCompanionController.
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
- if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
- val intent = android.content.Intent("com.gotcha.action.APP_CHANGED")
+ if (event == null) return
+
+ if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
+ val intent = android.content.Intent("com.gotcha.action.APP_CHANGED").apply {
+ setPackage(packageName)
+ }
+ sendBroadcast(intent)
+ }
+
+ // Detect copy actions or clipboard toast alerts
+ if (event.eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
+ val source = event.source
+ if (source != null) {
+ val text = source.text?.toString() ?: ""
+ val desc = source.contentDescription?.toString() ?: ""
+ val viewId = source.viewIdResourceName ?: ""
+ if (isCopyString(text) || isCopyString(desc) || viewId.lowercase().contains("copy")) {
+ android.util.Log.d(
+ "GotchaAccessibilityService",
+ "Copy click: text=$text, desc=$desc, id=$viewId"
+ )
+ triggerClipboardBroadcast()
+ }
+ source.recycle()
+ }
+ val eventTexts = event.text ?: emptyList()
+ for (t in eventTexts) {
+ val textStr = t?.toString() ?: ""
+ if (isCopyString(textStr)) {
+ android.util.Log.d("GotchaAccessibilityService", "Copy event text: $textStr")
+ triggerClipboardBroadcast()
+ break
+ }
+ }
+ } else if (event.eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
+ val eventTexts = event.text ?: emptyList()
+ for (t in eventTexts) {
+ val textStr = t?.toString() ?: ""
+ if (isClipboardToast(textStr)) {
+ android.util.Log.d(
+ "GotchaAccessibilityService",
+ "Clipboard toast: $textStr"
+ )
+ triggerClipboardBroadcast()
+ break
+ }
+ }
+ }
+ }
+
+ private fun isCopyString(s: String): Boolean {
+ val lower = s.lowercase().trim()
+ return lower == "copy" ||
+ lower == "复制" ||
+ lower == "剪切" ||
+ lower == "copying" ||
+ lower == "copier" ||
+ lower == "copiar" ||
+ lower == "kopieren" ||
+ lower == "copia" ||
+ lower == "コピー" ||
+ lower == "복사"
+ }
+
+ private fun isClipboardToast(s: String): Boolean {
+ val lower = s.lowercase()
+ return lower.contains("copy") ||
+ lower.contains("copied") ||
+ lower.contains("clipboard") ||
+ lower.contains("复制") ||
+ lower.contains("剪贴") ||
+ lower.contains("剪切板") ||
+ lower.contains("copi") ||
+ lower.contains("kopier") ||
+ lower.contains("clip")
+ }
+
+ private fun triggerClipboardBroadcast() {
+ try {
+ val intent = android.content.Intent("com.gotcha.action.CLIPBOARD_CHANGED").apply {
+ setPackage(packageName)
+ }
sendBroadcast(intent)
+ android.util.Log.d(
+ "GotchaAccessibilityService",
+ "Sent CLIPBOARD_CHANGED broadcast"
+ )
+ } catch (e: Exception) {
+ android.util.Log.e(
+ "GotchaAccessibilityService",
+ "Failed to send broadcast",
+ e
+ )
}
}
@@ -256,12 +344,9 @@ class GotchaAccessibilityService : AccessibilityService() {
/** Register a clipboard listener to cache clipboard content. */
internal fun initClipboardListener() {
- val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
- cm.addPrimaryClipChangedListener {
- try {
- val intent = android.content.Intent("com.gotcha.action.CLIPBOARD_CHANGED")
- sendBroadcast(intent)
- } catch (_: Exception) {}
- }
+ android.util.Log.d(
+ "GotchaAccessibilityService",
+ "initClipboardListener: using event-based detection"
+ )
}
}
diff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
index 5baf015..0eedab2 100644
--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt
@@ -34,6 +34,7 @@ class ScreenCompanionController(
private val appChangeReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
+ android.util.Log.d("ScreenCompanionController", "appChangeReceiver received action: ${intent?.action}")
if (intent?.action == ACTION_APP_CHANGED) {
performLightweightScan(triggerType = "AppChange")
} else if (intent?.action == ACTION_CLIPBOARD_CHANGED) {
@@ -81,6 +82,10 @@ class ScreenCompanionController(
}
if (triggerType == "Clipboard") {
+ android.util.Log.d(
+ "ScreenCompanionController",
+ "Clipboard trigger: request read on Main"
+ )
// We must read clipboard from Main thread via overlay to avoid SecurityException
withContext(Dispatchers.Main) {
onReadClipboardRequest()
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index 312b5e9..76da51c 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -205,6 +205,16 @@ class AssistiveBallOverlay(context: Context) {
fun setSmartActionAvailable(label: String, prompt: String) {
mainHandler.post {
if (isCallActive()) return@post
+
+ val currentLabel = pendingSmartAction?.first ?: ""
+ if (currentLabel.contains("copied", ignoreCase = true) && !label.contains("copied", ignoreCase = true)) {
+ android.util.Log.d(
+ "AssistiveBallOverlay",
+ "Preventing overwrite of active clipboard action '$currentLabel' by passive action '$label'"
+ )
+ return@post
+ }
+
pendingSmartAction = Pair(label, prompt)
showSmartActionRing()
mainHandler.removeCallbacks(smartActionClearRunnable)
@@ -855,13 +865,16 @@ class AssistiveBallOverlay(context: Context) {
const val DOCK_SIDE_END = 1
}
fun readClipboardWithFocus(onResult: (android.content.ClipData?) -> Unit) {
+ android.util.Log.d("AssistiveBallOverlay", "readClipboardWithFocus called. Setting onClipboardRead callback.")
ClipboardReaderActivity.onClipboardRead = onResult
val intent = android.content.Intent(appContext, ClipboardReaderActivity::class.java).apply {
addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION)
}
try {
+ android.util.Log.d("AssistiveBallOverlay", "Starting ClipboardReaderActivity...")
appContext.startActivity(intent)
- } catch (e: SecurityException) {
+ android.util.Log.d("AssistiveBallOverlay", "startActivity called successfully")
+ } catch (e: Exception) {
android.util.Log.e("AssistiveBallOverlay", "Failed to start ClipboardReaderActivity", e)
onResult(null)
}
diff --git a/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt b/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt
index 80698c2..4ae39ae 100644
--- a/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt
+++ b/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt
@@ -10,28 +10,52 @@ class ClipboardReaderActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
+ android.util.Log.d("ClipboardReaderActivity", "onCreate")
+
+ // Create a dummy view and set it to ensure the window has a view that can gain focus
+ val dummyView = android.view.View(this).apply {
+ isFocusable = true
+ isFocusableInTouchMode = true
+ }
+ setContentView(dummyView)
+ dummyView.requestFocus()
+
// Delay a bit in case window focus doesn't fire
window.decorView.postDelayed({
+ android.util.Log.d(
+ "ClipboardReaderActivity",
+ "postDelayed triggered, read=$hasAttemptedRead"
+ )
if (!hasAttemptedRead) {
- readClipboardAndFinish()
+ readClipboardAndFinish("timeout")
}
}, 500)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
+ android.util.Log.d(
+ "ClipboardReaderActivity",
+ "onWindowFocusChanged: $hasFocus, read=$hasAttemptedRead"
+ )
if (hasFocus && !hasAttemptedRead) {
- readClipboardAndFinish()
+ readClipboardAndFinish("focus")
}
}
- private fun readClipboardAndFinish() {
+ private fun readClipboardAndFinish(source: String) {
+ android.util.Log.d("ClipboardReaderActivity", "readClipboardAndFinish: $source")
hasAttemptedRead = true
try {
val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
+ android.util.Log.d("ClipboardReaderActivity", "Retrieving primaryClip")
val clip = cm.primaryClip
+ android.util.Log.d(
+ "ClipboardReaderActivity",
+ "clip retrieved: count=${clip?.itemCount ?: 0}"
+ )
onClipboardRead?.invoke(clip)
- } catch (e: SecurityException) {
+ } catch (e: Exception) {
android.util.Log.e("ClipboardReaderActivity", "Failed to read clipboard", e)
onClipboardRead?.invoke(null)
}
diff --git a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
index 386cc7f..210133a 100644
--- a/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/ScreenCompanionPanelOverlay.kt
@@ -38,7 +38,12 @@ class ScreenCompanionPanelOverlay(private val context: Context) {
@Suppress("LongMethod", "CyclomaticComplexMethod")
@SuppressLint("ClickableViewAccessibility")
fun show(initialPrompt: String, resultText: String? = null) {
- if (panelView != null) return
+ if (panelView != null) {
+ try {
+ windowManager.removeView(panelView)
+ } catch (_: Exception) {}
+ panelView = null
+ }
val container = LinearLayout(appContext).apply {
orientation = LinearLayout.VERTICAL