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: implement modular smart action detection and update Lens and proactive scan workflows
Rishabh Bajpaie2010f0a0ce5
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex f99d6b6..8a775f9 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -26,6 +26,7 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextimport java.io.File/**@@ -48,12 +49,19 @@ class AssistiveBallService : Service() {private lateinit var ttsEngine: TtsEngineprivate lateinit var sttEngine: SttEngineprivate var activeCompanionHistory = mutableListOf<com.gotcha.llm.ChatMessage>()++ /**+ * A Lens crop (base64 JPEG) waiting to be attached to the user's next panel+ * message. Set when the user picks "Ask about this"; cleared once consumed.+ */+ private var pendingCropImage: String? = nullprivate lateinit var overlay: com.gotcha.ui.AssistiveBallOverlayprivate lateinit var chatWindow: CallChatWindowprivate lateinit var callController: CallSessionControllerprivate lateinit var screenCompanionController: ScreenCompanionControllerprivate lateinit var screenCompanionPanel: com.gotcha.ui.ScreenCompanionPanelOverlayprivate lateinit var screenLensController: ScreenLensController+ private val webFetchTool by lazy { com.gotcha.tools.WebFetchTool() }private val llmClient by lazy {val s = settingsRepository.load()com.gotcha.llm.LLMClient(@@ -150,16 +158,26 @@ class AssistiveBallService : Service() {}private fun handleSmartActionSelected(prompt: String, history: MutableList<com.gotcha.llm.ChatMessage>) {- // Native structured actions (dial / navigate / schedule) fire an Android- // intent instead of querying the LLM.+ // Native structured actions are handled without an LLM round-trip.if (SmartActionDetector.isNativeAction(prompt)) {- handleNativeAction(prompt)+ val decoded = SmartActionDetector.decode(prompt)+ if (decoded?.first == SmartActionDetector.TYPE_FETCH) {+ // "Summarize link": fetch the page text, then summarize it.+ handleFetchAndSummarize(decoded.second, history)+ } else {+ // dial / navigate / schedule → fire an Android intent.+ handleNativeAction(prompt)+ }return}+ // Only these explicitly-visual actions attach a screenshot. (A generic+ // prompt that merely mentions "screen" must NOT pull in an image.)val attachScreenshot = prompt.contains("screenshot", ignoreCase = true) ||- prompt.contains("screen", ignoreCase = true) ||- prompt.contains("webpage", ignoreCase = true)+ prompt.contains("webpage shown", ignoreCase = true) ||+ prompt.contains("shown on screen", ignoreCase = true) ||+ prompt.contains("shown on the screen", ignoreCase = true)screenCompanionPanel.show(prompt)+ overlay.isPanelOpen = truescope.launch {try {var base64: String? = null@@ -219,12 +237,62 @@ class AssistiveBallService : Service() {}}+ /**+ * Fetch [url]'s content with [webFetchTool] and ask the LLM to summarize the+ * page *text* (never a screenshot). This is the correct behaviour for the+ * "Summarize link?" action — the earlier version wrongly attached a screenshot.+ */+ private fun handleFetchAndSummarize(url: String, history: MutableList<com.gotcha.llm.ChatMessage>) {+ screenCompanionPanel.show("Summarize link:\n$url")+ overlay.isPanelOpen = true+ screenCompanionPanel.updateResponse("Fetching $url …")+ scope.launch {+ val fetched = withContext(Dispatchers.IO) { webFetchTool.fetch(url, "text") }+ if (!fetched.success) {+ screenCompanionPanel.updateResponse("Couldn't fetch the link: ${fetched.message}")+ return@launch+ }+ screenCompanionPanel.updateResponse("Summarizing …")+ try {+ history.clear()+ history.add(+ com.gotcha.llm.ChatMessage(+ "system",+ kotlinx.serialization.json.JsonPrimitive(+ "You are Screen Companion. Summarize the provided web page content " ++ "concisely: a one-line gist, then 3-5 key bullet points."+ )+ )+ )+ history.add(+ com.gotcha.llm.ChatMessage(+ "user",+ kotlinx.serialization.json.JsonPrimitive(+ "Summarize this page ($url):\n\n${fetched.message.take(MAX_FETCH_CHARS)}"+ )+ )+ )+ val response = llmClient.chat(history.toList())+ val replyText = response.choices.firstOrNull()?.message?.textContent ?: "No response"+ history.add(+ com.gotcha.llm.ChatMessage("assistant", kotlinx.serialization.json.JsonPrimitive(replyText))+ )+ screenCompanionPanel.updateResponse(replyText)+ } catch (e: Exception) {+ screenCompanionPanel.updateResponse("Error: ${e.message}")+ }+ }+ }+private fun setupScreenLensController() {screenLensController = ScreenLensController(context = this,scope = scope,- onAskAboutCrop = { prompt, base64 ->- handleCropQuery(prompt, base64)+ onAskAboutCrop = { base64 ->+ openCompanionWithImage(base64)+ },+ onContextualAction = { prompt ->+ handleSmartActionSelected(prompt, activeCompanionHistory)},onError = { overlay.showError(it) })@@ -259,12 +327,11 @@ class AssistiveBallService : Service() {android.util.Log.d("AssistiveBallService", "clipText is null or blank, not setting smart action")return@readClipboardWithFocus}- 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: $clipText"- )+ val url = SmartActionDetector.extractUrl(clipText)+ if (url != null) {+ android.util.Log.d("AssistiveBallService", "Setting smart action: Summarize link ($url)")+ val fetch = SmartActionDetector.fetchAction(url)+ overlay.setSmartActionAvailable(fetch.label, fetch.prompt)return@readClipboardWithFocus}// Prefer a structured action (dial / navigate / convert / schedule / reply)@@ -313,38 +380,25 @@ class AssistiveBallService : Service() {}/**- * Send a Lens-cropped image (base64 JPEG) to the LLM with [prompt] and stream- * the answer into the Screen Companion panel.+ * Open the Screen Companion panel with a Lens crop attached, but do NOT query+ * the LLM yet — the user types their own question, and the image rides along+ * with that first message (see [pendingCropImage] handling in [setupScreenCompanionPanel]).*/- private fun handleCropQuery(prompt: String, base64Jpeg: String) {- val history = activeCompanionHistory- screenCompanionPanel.show(prompt)- overlay.isPanelOpen = true- scope.launch {- try {- history.clear()- history.add(- com.gotcha.llm.ChatMessage(- "system",- kotlinx.serialization.json.JsonPrimitive(- "You are Screen Companion. Provide a short, precise answer."- )- )- )- history.add(com.gotcha.llm.visionUserMessage(prompt, base64Jpeg, "jpeg"))- val response = llmClient.chat(history.toList())- val replyText = response.choices.firstOrNull()?.message?.textContent ?: "No response"- history.add(- com.gotcha.llm.ChatMessage(- "assistant",- kotlinx.serialization.json.JsonPrimitive(replyText)- )+ private fun openCompanionWithImage(base64Jpeg: String) {+ activeCompanionHistory.clear()+ activeCompanionHistory.add(+ com.gotcha.llm.ChatMessage(+ "system",+ kotlinx.serialization.json.JsonPrimitive(+ "You are Screen Companion. The user has attached a captured screen region. " ++ "Answer their question about it precisely.")- screenCompanionPanel.updateResponse(replyText)- } catch (e: Exception) {- screenCompanionPanel.updateResponse("Error: ${e.message}")- }- }+ )+ )+ pendingCropImage = base64Jpeg+ overlay.isPanelOpen = true+ screenCompanionPanel.show("📸 Region attached — ask a question about it below.")+ screenCompanionPanel.updateResponse("Ask me anything about the selected region.")}private fun setupScreenCompanionPanel() {@@ -352,6 +406,7 @@ class AssistiveBallService : Service() {onDismiss = {overlay.isPanelOpen = falseactiveCompanionHistory.clear()+ pendingCropImage = null// Stop any in-flight voice I/O so nothing keeps the mic/TTS alive.stopPanelVoiceInput()ttsEngine.stop()@@ -361,7 +416,15 @@ class AssistiveBallService : Service() {onReadAloud = { text -> readPanelResponseAloud(text) }onStopReadAloud = { ttsEngine.stop() }onSendInput = { input ->- activeCompanionHistory.add(com.gotcha.llm.ChatMessage("user", kotlinx.serialization.json.JsonPrimitive(input)))+ // If a Lens crop is pending, attach it to this first message.+ val pending = pendingCropImage+ val userMsg = if (pending != null) {+ pendingCropImage = null+ com.gotcha.llm.visionUserMessage(input, pending, "jpeg")+ } else {+ com.gotcha.llm.ChatMessage("user", kotlinx.serialization.json.JsonPrimitive(input))+ }+ activeCompanionHistory.add(userMsg)val currentHistory = activeCompanionHistory.toList()updateResponse("Thinking...")scope.launch {@@ -638,6 +701,9 @@ class AssistiveBallService : Service() {private const val CHANNEL_ID = "assistive_ball"private const val NOTIFICATION_ID = 4711+ /** Cap on fetched page text handed to the LLM for link summarization. */+ private const val MAX_FETCH_CHARS = 12000+fun startIntent(context: Context): Intent =Intent(context, AssistiveBallService::class.java).setAction(ACTION_START)diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex f76ba4e..3e9cf01 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -207,6 +207,40 @@ class GotchaAccessibilityService : AccessibilityService() {}}+ /**+ * Collect visible text from nodes that intersect [regionInScreen] (screen+ * pixels). Used by Lens mode to detect structured data (currency, dates, etc.)+ * inside the user's selection without OCR. Returns joined text or null.+ */+ fun dumpTextInRegion(regionInScreen: android.graphics.Rect, limit: Int = 60): String? {+ val root = rootInActiveWindow ?: return null+ val out = ArrayList<String>()+ collectTextInRegion(root, regionInScreen, out, limit)+ root.recycle()+ return if (out.isEmpty()) null else out.joinToString(" ")+ }++ private fun collectTextInRegion(+ node: AccessibilityNodeInfo?,+ region: android.graphics.Rect,+ out: MutableList<String>,+ limit: Int+ ) {+ if (node == null || out.size >= limit) return+ val bounds = android.graphics.Rect()+ node.getBoundsInScreen(bounds)+ if (android.graphics.Rect.intersects(bounds, region)) {+ val text = node.text?.toString()?.trim()+ val desc = node.contentDescription?.toString()?.trim()+ if (!text.isNullOrEmpty()) {+ out.add(text)+ } else if (!desc.isNullOrEmpty()) out.add(desc)+ }+ for (i in 0 until node.childCount) {+ collectTextInRegion(node.getChild(i), region, out, limit)+ }+ }+/** Tap the first clickable node whose text/description contains [query] (case-insensitive). */fun tapByText(query: String): Boolean {val root = rootInActiveWindow ?: return falsediff --git a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt b/app/src/main/java/com/gotcha/service/ScreenCompanionController.ktindex 7808f56..2dc09ff 100644--- a/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenCompanionController.kt@@ -9,7 +9,6 @@ import android.net.Uriimport android.os.Handlerimport android.os.Looperimport android.provider.MediaStore-import android.util.Patternsimport com.gotcha.agent.ScreenSnapshotimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -119,14 +118,12 @@ class ScreenCompanionController(pkg.contains("com.gotcha")val screenText = ScreenSnapshot.captureScreenText(limit = 40) ?: return@withContext- val hasLink = Patterns.WEB_URL.matcher(screenText).find() || screenText.contains("http", ignoreCase = true)+ val url = SmartActionDetector.extractUrl(screenText)- if (hasLink && !isIgnoredForLinks) {+ if (url != null && !isIgnoredForLinks) {withContext(Dispatchers.Main) {- onSmartActionReady(- "🔗 Link detected. Summarize?",- "Summarize the content of the webpage shown on screen."- )+ val fetch = SmartActionDetector.fetchAction(url)+ onSmartActionReady(fetch.label, fetch.prompt)}} else if (screenText.contains("Exception") || screenText.contains("Error", ignoreCase = true)) {withContext(Dispatchers.Main) {diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex f05d149..1a1fbdf 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -24,19 +24,30 @@ import java.io.Fileimport java.io.FileOutputStream/**- * Drives "Lens" mode: the user drags a bounding box over the screen, and the- * selected region is cropped from a fresh accessibility screenshot. The crop can- * then be sent to the LLM (explain / translate), copied to the clipboard, or- * saved to the public Downloads folder.+ * Drives "Lens" mode: the user draws a free-form shape over the screen; its+ * bounding rectangle is cropped from a fresh accessibility screenshot. The crop+ * can then be:+ * - opened in the Screen Companion panel as an attached image, so the user can+ * ask their own question about it (NOT auto-explained),+ * - copied to the clipboard,+ * - saved to the public Downloads folder, or+ * - acted on contextually (convert currency / add to calendar / dial / navigate)+ * when structured data is detected inside the selection.*- * All window mutations are posted to the main thread. The controller owns exactly- * one crop overlay and one action menu at a time.+ * Bitmap lifecycle: the controller owns exactly one [pendingCrop] at a time and is+ * the ONLY place that recycles it. Menu actions read it, then recycle happens once+ * the action's (possibly async) work has finished — this avoids the earlier+ * "can't compress a recycled bitmap" race.+ *+ * All window mutations are posted to the main thread.*/class ScreenLensController(private val context: Context,private val scope: CoroutineScope,- /** Show the companion panel with a prompt and stream the LLM reply into it. */- private val onAskAboutCrop: (prompt: String, base64Jpeg: String) -> Unit,+ /** Open the companion panel with the crop attached; the user asks their own question. */+ private val onAskAboutCrop: (base64Jpeg: String) -> Unit,+ /** Route a detected structured action (native intent or LLM prompt) to the host. */+ private val onContextualAction: (prompt: String) -> Unit,private val onError: (String) -> Unit) {private val appContext = context.applicationContext@@ -46,6 +57,9 @@ class ScreenLensController(private var cropOverlay: View? = nullprivate var actionMenu: View? = null+ /** The current cropped bitmap; owned and recycled only by this controller. */+ private var pendingCrop: Bitmap? = null+/** Begin a Lens capture: add the full-screen crop overlay. */fun start() {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {@@ -55,6 +69,7 @@ class ScreenLensController(mainHandler.post {removeActionMenu()removeCropOverlay()+ recyclePendingCrop()val overlay = ScreenCropOverlayView(appContext,onSelection = { rect -> onRegionSelected(rect) },@@ -84,6 +99,7 @@ class ScreenLensController(mainHandler.post {removeCropOverlay()removeActionMenu()+ recyclePendingCrop()}}@@ -99,6 +115,11 @@ class ScreenLensController(withContext(Dispatchers.Main) { onError("Accessibility service not available") }return@launch}+ // Detect structured data inside the selection via accessibility text+ // (full-screen overlay ⇒ view coords are screen coords).+ val regionText = service.dumpTextInRegion(rectInView)+ val contextualActions = regionText?.let { SmartActionDetector.detectContextual(it) } ?: emptyList()+// Small delay so the removed overlay is gone from the real display.kotlinx.coroutines.delay(120)var full = service.takeScreenshotBitmap()@@ -116,7 +137,10 @@ class ScreenLensController(withContext(Dispatchers.Main) { onError("Selection was empty") }return@launch}- withContext(Dispatchers.Main) { showActionMenu(cropped) }+ withContext(Dispatchers.Main) {+ pendingCrop = cropped+ showActionMenu(contextualActions)+ }}}@@ -141,7 +165,7 @@ class ScreenLensController(}}- private fun showActionMenu(cropped: Bitmap) {+ private fun showActionMenu(contextualActions: List<SmartAction>) {removeActionMenu()val container = LinearLayout(appContext).apply {orientation = LinearLayout.VERTICAL@@ -149,21 +173,27 @@ class ScreenLensController(background = GradientDrawable().apply {cornerRadius = dp(20).toFloat()setColor(Color.parseColor("#F21E1E1E"))- setStroke(dp(1), Color.parseColor("#66FFFFFF"))+ setStroke(dp(1), Color.parseColor("#66E081C0"))}}container.addView(menuTitle("Lens selection"))++ // Contextual actions detected inside the selection come first.+ contextualActions.forEach { action ->+ container.addView(+ menuButton(action.label, highlight = true) {+ finishMenu(recycle = true)+ onContextualAction(action.prompt)+ }+ )+ }+container.addView(- menuButton("🔍 Ask / Explain") {- removeActionMenu()- val base64 = encodeJpeg(cropped)- cropped.recycle()+ menuButton("🔍 Ask about this") {+ val base64 = pendingCrop?.let { encodeJpeg(it) }+ finishMenu(recycle = true)if (base64 != null) {- onAskAboutCrop(- "Explain what is shown in this cropped screen region. If it " +- "contains text in another language, translate it to English.",- base64- )+ onAskAboutCrop(base64)} else {onError("Couldn't encode selection")}@@ -171,27 +201,27 @@ class ScreenLensController()container.addView(menuButton("📋 Copy Image") {- removeActionMenu()- copyImageToClipboard(cropped)- cropped.recycle()+ pendingCrop?.let { copyImageToClipboard(it) }+ finishMenu(recycle = true)})container.addView(menuButton("💾 Save to Downloads") {+ val bmp = pendingCrop+ // Hand ownership to the async saver, which recycles when done.+ pendingCrop = nullremoveActionMenu()- saveToDownloads(cropped)- cropped.recycle()+ if (bmp != null) saveToDownloads(bmp) else onError("Nothing to save")})container.addView(menuButton("✕ Cancel") {- removeActionMenu()- cropped.recycle()+ finishMenu(recycle = true)})val params = WindowManager.LayoutParams(- dp(260),+ dp(280),WindowManager.LayoutParams.WRAP_CONTENT,overlayType(),WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,@@ -207,6 +237,12 @@ class ScreenLensController(}}+ /** Dismiss the menu and optionally recycle the crop the menu was acting on. */+ private fun finishMenu(recycle: Boolean) {+ removeActionMenu()+ if (recycle) recyclePendingCrop()+ }+private fun copyImageToClipboard(bitmap: Bitmap) {try {val uri = writeToCache(bitmap) ?: run {@@ -243,6 +279,7 @@ class ScreenLensController(}}+ /** Saves [bitmap] on IO, then recycles it — takes ownership from the caller. */private fun saveToDownloads(bitmap: Bitmap) {scope.launch(Dispatchers.IO) {try {@@ -283,6 +320,8 @@ class ScreenLensController(}} catch (e: Exception) {withContext(Dispatchers.Main) { onError("Save failed: ${e.message}") }+ } finally {+ bitmap.recycle()}}}@@ -306,33 +345,40 @@ class ScreenLensController(}}+ private fun recyclePendingCrop() {+ pendingCrop?.let { if (!it.isRecycled) it.recycle() }+ pendingCrop = null+ }+private fun toast(msg: String) {android.widget.Toast.makeText(appContext, msg, android.widget.Toast.LENGTH_SHORT).show()}private fun menuTitle(text: String): TextView = TextView(appContext).apply {this.text = text- setTextColor(Color.CYAN)+ setTextColor(Color.parseColor("#E081C0"))textSize = 13fsetPadding(dp(12), dp(6), dp(12), dp(10))}- private fun menuButton(label: String, onClick: () -> Unit): TextView = TextView(appContext).apply {- text = label- setTextColor(Color.WHITE)- textSize = 15f- gravity = Gravity.CENTER_VERTICAL- setPadding(dp(16), dp(12), dp(16), dp(12))- background = GradientDrawable().apply {- cornerRadius = dp(12).toFloat()- setColor(Color.parseColor("#33FFFFFF"))+ private fun menuButton(label: String, highlight: Boolean = false, onClick: () -> Unit): TextView =+ TextView(appContext).apply {+ text = label+ setTextColor(if (highlight) Color.parseColor("#E081C0") else Color.WHITE)+ textSize = 15f+ gravity = Gravity.CENTER_VERTICAL+ setPadding(dp(16), dp(12), dp(16), dp(12))+ background = GradientDrawable().apply {+ cornerRadius = dp(12).toFloat()+ setColor(Color.parseColor(if (highlight) "#332C6BE0" else "#33FFFFFF"))+ if (highlight) setStroke(dp(1), Color.parseColor("#66E081C0"))+ }+ layoutParams = LinearLayout.LayoutParams(+ LinearLayout.LayoutParams.MATCH_PARENT,+ LinearLayout.LayoutParams.WRAP_CONTENT+ ).apply { setMargins(dp(4), dp(4), dp(4), dp(4)) }+ setOnClickListener { onClick() }}- layoutParams = LinearLayout.LayoutParams(- LinearLayout.LayoutParams.MATCH_PARENT,- LinearLayout.LayoutParams.WRAP_CONTENT- ).apply { setMargins(dp(4), dp(4), dp(4), dp(4)) }- setOnClickListener { onClick() }- }private fun removeCropOverlay() {cropOverlay?.let { safeRemove(it) }diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.ktindex 9a33a1d..39102f9 100644--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt@@ -3,7 +3,8 @@ package com.gotcha.serviceimport java.util.regex.Pattern/**- * A structured, semantic action surfaced in the assistive-ball menu.+ * A structured, semantic action surfaced in the assistive-ball menu or the Lens+ * action menu.** [prompt] is either a plain LLM prompt (currency conversion, chat reply) or a* native-intent directive encoded with [SmartActionDetector.ACTION_PREFIX]. The@@ -14,12 +15,18 @@ data class SmartAction(val label: String, val prompt: String)/*** Lightweight text scanner that recognises structured data types — physical- * addresses, phone numbers, foreign-currency prices, calendar events, and chat- * messages — and turns the first match into a specialised [SmartAction].+ * addresses, phone numbers, foreign-currency prices, and calendar events — and+ * turns them into specialised [SmartAction]s.*- * Detection order is most-specific first so a phone number is not mistaken for a- * street address and vice-versa. Chat detection is opt-in (clipboard only) since- * its heuristic is intentionally loose.+ * Two entry points with deliberately different aggressiveness:+ * - [detect] powers *proactive* offers (passive screen scans + clipboard). It is+ * conservative: only phone, address, and (clipboard-only) chat, and it returns+ * at most one action. Currency and calendar are intentionally excluded here+ * because a screen often shows several prices/dates and we cannot know which+ * one the user means — that ambiguity is resolved by the user in Lens mode.+ * - [detectContextual] powers the *Lens* menu, where the user has already framed+ * a specific region, so ambiguity is gone. It returns every distinct action+ * found in the selection (currency, calendar, phone, address).*/object SmartActionDetector {@@ -29,6 +36,13 @@ object SmartActionDetector {const val TYPE_DIAL = "DIAL"const val TYPE_CALENDAR = "CALENDAR"+ /**+ * Fetch a URL's content and summarize it. Payload is the URL. Unlike the other+ * types this does not fire an OS intent — the host fetches the page and hands+ * the text to the LLM. See [AssistiveBallService.handleFetchAndSummarize].+ */+ const val TYPE_FETCH = "FETCH"+/** Separator between the encoded action type and its payload. */const val PAYLOAD_SEP = "|"@@ -37,8 +51,21 @@ object SmartActionDetector {Pattern.CASE_INSENSITIVE)+ /**+ * Phone numbers. Deliberately strict to avoid firing on bare digit runs like+ * order IDs or tracking numbers. A match requires ONE of:+ * - a `+` country code (separators then optional), or+ * - a parenthesised area code `(415) 555-2671`, or+ * - explicit separators between the 3-3-4 groups `415-555-2671`.+ * A plain `4155552671` (no separators, no parens, no `+`) does NOT match.+ * Digit-boundary guards stop it matching inside a longer number.+ */private val phonePattern: Pattern = Pattern.compile(- "(\\+\\d{1,2}\\s)?\\(?\\d{3}\\)?[\\s.-]?\\d{3}[\\s.-]?\\d{4}"+ "(?<![\\d])(" ++ "\\+\\d{1,3}[\\s.-]?\\(?\\d{2,4}\\)?[\\s.-]?\\d{3,4}[\\s.-]?\\d{3,4}" ++ "|\\(\\d{3}\\)\\s?\\d{3}[\\s.-]?\\d{4}" ++ "|\\d{3}[\\s.-]\\d{3}[\\s.-]\\d{4}" ++ ")(?![\\d])")private val currencyPattern: Pattern = Pattern.compile(@@ -53,57 +80,25 @@ object SmartActionDetector {Pattern.CASE_INSENSITIVE)+ /** First http(s):// URL or bare www./domain in a block of text. */+ private val urlPattern: Pattern = Pattern.compile(+ "(https?://[^\\s]+" ++ "|www\\.[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}[^\\s]*" ++ "|[a-zA-Z0-9-]+\\.(com|org|net|io|dev|app|co|gov|edu|ai)(/[^\\s]*)?)",+ Pattern.CASE_INSENSITIVE+ )+/**- * Return the first structured [SmartAction] found in [text], or null if none- * apply. Set [allowChat] for clipboard text so the loose chat-reply heuristic- * can fire (it is suppressed for passive screen scans to avoid noise).+ * Proactive detection for passive scans / clipboard. Conservative: returns at+ * most one action, and never offers currency or calendar (too ambiguous when+ * a screen shows several). Set [allowChat] for clipboard text so the loose+ * chat-reply heuristic can fire.*/fun detect(text: String, allowChat: Boolean = false): SmartAction? {if (text.isBlank()) return null- phonePattern.matcher(text).let { m ->- if (m.find()) {- val number = m.group().trim()- // Guard against matching a 10-digit run inside an address/id: require- // the match not be immediately embedded in a longer digit sequence.- return SmartAction(- label = "📞 Phone number detected. Dial?",- prompt = encode(TYPE_DIAL, number)- )- }- }-- addressPattern.matcher(text).let { m ->- if (m.find()) {- val address = m.group().trim()- return SmartAction(- label = "📍 Address detected. Navigate?",- prompt = encode(TYPE_NAVIGATE, address)- )- }- }-- currencyPattern.matcher(text).let { m ->- if (m.find()) {- val price = m.group().trim()- return SmartAction(- label = "💵 Currency detected. Convert?",- prompt = "Convert the price \"$price\" to USD and to common major " +- "currencies (EUR, GBP, INR). Show the approximate exchange rate " +- "you used. Keep it brief."- )- }- }-- calendarPattern.matcher(text).let { m ->- if (m.find()) {- val event = m.group().trim()- return SmartAction(- label = "📅 Event detected. Schedule?",- prompt = encode(TYPE_CALENDAR, event)- )- }- }+ detectPhone(text)?.let { return it }+ detectAddress(text)?.let { return it }if (allowChat && looksLikeChatMessage(text)) {return SmartAction(@@ -116,6 +111,63 @@ object SmartActionDetector {return null}+ /**+ * Contextual detection for Lens mode. The user has framed a specific region,+ * so every distinct action found is offered (order: currency, calendar, phone,+ * address). Returns an empty list when nothing structured is present.+ */+ fun detectContextual(text: String): List<SmartAction> {+ if (text.isBlank()) return emptyList()+ val actions = mutableListOf<SmartAction>()+ detectCurrency(text)?.let { actions.add(it) }+ detectCalendar(text)?.let { actions.add(it) }+ detectPhone(text)?.let { actions.add(it) }+ detectAddress(text)?.let { actions.add(it) }+ return actions+ }++ private fun detectPhone(text: String): SmartAction? {+ val m = phonePattern.matcher(text)+ if (!m.find()) return null+ val number = m.group().trim()+ return SmartAction(+ label = "📞 Dial $number?",+ prompt = encode(TYPE_DIAL, number)+ )+ }++ private fun detectAddress(text: String): SmartAction? {+ val m = addressPattern.matcher(text)+ if (!m.find()) return null+ val address = m.group().trim()+ return SmartAction(+ label = "📍 Navigate to address?",+ prompt = encode(TYPE_NAVIGATE, address)+ )+ }++ private fun detectCurrency(text: String): SmartAction? {+ val m = currencyPattern.matcher(text)+ if (!m.find()) return null+ val price = m.group().trim()+ return SmartAction(+ label = "💵 Convert $price?",+ prompt = "Convert the price \"$price\" to USD and to common major " ++ "currencies (EUR, GBP, INR). Show the approximate exchange rate " ++ "you used. Keep it brief."+ )+ }++ private fun detectCalendar(text: String): SmartAction? {+ val m = calendarPattern.matcher(text)+ if (!m.find()) return null+ val event = m.group().trim()+ return SmartAction(+ label = "📅 Add \"$event\" to calendar?",+ prompt = encode(TYPE_CALENDAR, event)+ )+ }+/*** Loose heuristic for a copied chat bubble: short-ish, conversational text* that either carries a "Sender: message" prefix or reads like a question/@@ -134,6 +186,25 @@ object SmartActionDetector {private fun encode(type: String, payload: String): String ="$ACTION_PREFIX$type$PAYLOAD_SEP$payload"+ /** Build a native "fetch this URL and summarize" action. */+ fun fetchAction(url: String): SmartAction =+ SmartAction(label = "🔗 Summarize link?", prompt = encode(TYPE_FETCH, url.trim()))++ /**+ * Extract the first http(s) URL from [text], normalising a bare `www.`/domain+ * match to an https:// URL. Returns null when no plausible URL is present.+ */+ fun extractUrl(text: String): String? {+ val m = urlPattern.matcher(text)+ if (!m.find()) return null+ val raw = m.group().trim().trimEnd('.', ',', ')', ']', '"', '\'')+ return when {+ raw.startsWith("http://", ignoreCase = true) ||+ raw.startsWith("https://", ignoreCase = true) -> raw+ else -> "https://$raw"+ }+ }+/** True when [prompt] encodes a native intent (vs. a plain LLM prompt). */fun isNativeAction(prompt: String): Boolean = prompt.startsWith(ACTION_PREFIX)diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.ktindex c88d70f..63de815 100644--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt@@ -4,24 +4,34 @@ import android.annotation.SuppressLintimport android.content.Contextimport android.graphics.Canvasimport android.graphics.Color+import android.graphics.LinearGradientimport android.graphics.Paint-import android.graphics.PorterDuff+import android.graphics.Path+import android.graphics.RadialGradientimport android.graphics.Rectimport android.graphics.RectF+import android.graphics.Shaderimport android.view.MotionEventimport android.view.Viewimport kotlin.math.maximport kotlin.math.min+import kotlin.random.Random/**- * Full-screen, semi-transparent overlay that lets the user drag a bounding box- * to select a screen region ("Lens" mode). While dragging, the selected region- * is punched clear of the dim scrim so the user sees exactly what they're- * capturing. On release, [onSelection] fires with the selected [Rect] in view- * pixels (empty/degenerate selections are ignored).+ * Full-screen premium "Lens" overlay. The user draws ANY free-form shape; on+ * release its bounding rectangle (max width/height of the drawn path) becomes the+ * selection. [onSelection] fires with that [Rect] in view pixels; a tap (no real+ * drag) calls [onCancel].*- * The view is added to the WindowManager by [ScreenLensController]; it is focusable- * and touchable so it intercepts the drag gesture.+ * Visual treatment (matches the app logo's pink/blue theme):+ * - a soft pink glow bleeding in from all four screen edges,+ * - drifting glowing particles (pink + blue) whose density is higher near the+ * edges and sparse in the centre,+ * - while drawing, the traced path is stroked in a pink→blue gradient and its+ * live bounding box is outlined.+ *+ * The particle field animates via [postInvalidateOnAnimation]; it is deterministic+ * only in look, not in exact positions (seeded from the view size).*/@SuppressLint("ViewConstructor")class ScreenCropOverlayView(@@ -30,102 +40,221 @@ class ScreenCropOverlayView(private val onCancel: () -> Unit) : View(context) {- private var startX = 0f- private var startY = 0f- private var currentX = 0f- private var currentY = 0f- private var selecting = false+ private val density = resources.displayMetrics.density- private val scrimPaint = Paint().apply {- color = Color.parseColor("#99000000")- }- private val clearPaint = Paint().apply {- xfermode = android.graphics.PorterDuffXfermode(PorterDuff.Mode.CLEAR)+ // ---- Free-form drawing state ----+ private val path = Path()+ private var minX = 0f+ private var minY = 0f+ private var maxX = 0f+ private var maxY = 0f+ private var drawing = false+ private var moved = false++ // ---- Paints ----+ private val dimPaint = Paint().apply { color = Color.parseColor("#66101018") }+ private val edgeGlowPaint = Paint(Paint.ANTI_ALIAS_FLAG)+ private val pathPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.STROKE+ strokeWidth = 4f * density+ strokeCap = Paint.Cap.ROUND+ strokeJoin = Paint.Join.ROUND}- private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ private val boxPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {style = Paint.Style.STROKE- color = Color.CYAN- strokeWidth = 2f * resources.displayMetrics.density+ strokeWidth = 1.5f * density+ color = Color.parseColor("#CCE081C0")+ pathEffect = android.graphics.DashPathEffect(floatArrayOf(12f * density, 8f * density), 0f)}+ private val particlePaint = Paint(Paint.ANTI_ALIAS_FLAG)private val hintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {color = Color.WHITE- textSize = 14f * resources.displayMetrics.density+ textSize = 15f * densitytextAlign = Paint.Align.CENTER+ setShadowLayer(6f, 0f, 0f, Color.parseColor("#E081C0"))}+ private val particles = ArrayList<Particle>()+ private var lastFrameNs = 0L+init {- // Enable an offscreen layer so PorterDuff.CLEAR punches through the scrim.- setLayerType(LAYER_TYPE_HARDWARE, null)isFocusableInTouchMode = true+ // Software layer keeps radial/linear gradient + shadow rendering correct.+ setLayerType(LAYER_TYPE_SOFTWARE, null)+ }++ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {+ super.onSizeChanged(w, h, oldw, oldh)+ buildEdgeGlow(w, h)+ seedParticles(w, h)+ }++ private fun buildEdgeGlow(w: Int, h: Int) {+ // A large radial gradient that is transparent in the centre and pink at the+ // rim, giving an edge-vignette wash.+ val cx = w / 2f+ val cy = h / 2f+ val radius = max(w, h) * 0.75f+ edgeGlowPaint.shader = RadialGradient(+ cx, cy, radius,+ intArrayOf(+ Color.TRANSPARENT,+ Color.TRANSPARENT,+ Color.parseColor("#22E081C0"),+ Color.parseColor("#553E7BFF"),+ Color.parseColor("#66FF5FBF")+ ),+ floatArrayOf(0f, 0.45f, 0.72f, 0.9f, 1f),+ Shader.TileMode.CLAMP+ )+ }++ private fun seedParticles(w: Int, h: Int) {+ particles.clear()+ if (w == 0 || h == 0) return+ val rnd = Random(w * 31L + h)+ // Density scales with screen area; edge-biased placement via rejection.+ val target = ((w * h) / (26000f * density)).toInt().coerceIn(40, 220)+ var placed = 0+ var guard = 0+ while (placed < target && guard < target * 12) {+ guard+++ val x = rnd.nextFloat() * w+ val y = rnd.nextFloat() * h+ // edgeScore ~1 at edges, ~0 at centre.+ val ex = 1f - (2f * x / w - 1f).let { it * it }+ val ey = 1f - (2f * y / h - 1f).let { it * it }+ val centreness = (1f - ex) * (1f - ey) // ~1 at centre corners... invert below+ // Keep more particles near edges: accept with prob higher when centreness low.+ val keepProb = 0.15f + 0.85f * (1f - centreness)+ if (rnd.nextFloat() > keepProb) continue+ particles.add(+ Particle(+ x = x,+ y = y,+ vx = (rnd.nextFloat() - 0.5f) * 14f * density,+ vy = (rnd.nextFloat() - 0.5f) * 14f * density,+ radius = (1.2f + rnd.nextFloat() * 2.6f) * density,+ pink = rnd.nextBoolean(),+ phase = rnd.nextFloat() * 6.283f,+ twinkle = 0.6f + rnd.nextFloat() * 1.8f+ )+ )+ placed+++ }}override fun onDraw(canvas: Canvas) {super.onDraw(canvas)- canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), scrimPaint)- if (selecting) {- val r = currentRectF()- canvas.drawRect(r, clearPaint)- canvas.drawRect(r, borderPaint)- } else {+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), dimPaint)+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), edgeGlowPaint)++ stepAndDrawParticles(canvas)++ if (drawing && moved) {+ // Gradient stroke for the traced path.+ pathPaint.shader = LinearGradient(+ minX, minY, maxX, maxY,+ Color.parseColor("#FF6FC0"), Color.parseColor("#5B8CFF"),+ Shader.TileMode.CLAMP+ )+ canvas.drawPath(path, pathPaint)+ canvas.drawRect(RectF(minX, minY, maxX, maxY), boxPaint)+ } else if (!drawing) {canvas.drawText(- "Drag to select a region • tap outside to cancel",+ "Draw around anything • tap to cancel",width / 2f,height * 0.12f,hintPaint)}+ postInvalidateOnAnimation()+ }++ private fun stepAndDrawParticles(canvas: Canvas) {+ val now = System.nanoTime()+ val dt = if (lastFrameNs == 0L) 0.016f else ((now - lastFrameNs) / 1_000_000_000f).coerceIn(0f, 0.05f)+ lastFrameNs = now+ val t = now / 1_000_000_000f+ val w = width.toFloat()+ val h = height.toFloat()+ for (p in particles) {+ p.x += p.vx * dt+ p.y += p.vy * dt+ // Wrap around edges so the field stays populated.+ if (p.x < -p.radius) p.x = w + p.radius+ if (p.x > w + p.radius) p.x = -p.radius+ if (p.y < -p.radius) p.y = h + p.radius+ if (p.y > h + p.radius) p.y = -p.radius++ val glowAlpha = (0.35f + 0.65f * (0.5f + 0.5f * kotlin.math.sin(t * p.twinkle + p.phase)))+ val core = if (p.pink) 0xFF5FBF else 0x5B8CFF+ val a = (glowAlpha * 255).toInt().coerceIn(0, 255)+ // Outer glow.+ particlePaint.shader = RadialGradient(+ p.x, p.y, p.radius * 3.2f,+ Color.argb((a * 0.5f).toInt(), (core shr 16) and 0xFF, (core shr 8) and 0xFF, core and 0xFF),+ Color.TRANSPARENT,+ Shader.TileMode.CLAMP+ )+ canvas.drawCircle(p.x, p.y, p.radius * 3.2f, particlePaint)+ // Bright core.+ particlePaint.shader = null+ particlePaint.color = Color.argb(a, 255, 255, 255)+ canvas.drawCircle(p.x, p.y, p.radius * 0.6f, particlePaint)+ }}override fun onTouchEvent(event: MotionEvent): Boolean {when (event.action) {MotionEvent.ACTION_DOWN -> {- startX = event.x- startY = event.y- currentX = event.x- currentY = event.y- selecting = true- invalidate()+ drawing = true+ moved = false+ path.reset()+ path.moveTo(event.x, event.y)+ minX = event.x+ maxX = event.x+ minY = event.y+ maxY = event.y}MotionEvent.ACTION_MOVE -> {- currentX = event.x- currentY = event.y- invalidate()+ path.lineTo(event.x, event.y)+ minX = min(minX, event.x)+ maxX = max(maxX, event.x)+ minY = min(minY, event.y)+ maxY = max(maxY, event.y)+ if (max(maxX - minX, maxY - minY) > 8f * density) moved = true}MotionEvent.ACTION_UP -> {- selecting = false- val rect = currentRect()- if (rect.width() > MIN_SIZE_PX && rect.height() > MIN_SIZE_PX) {+ drawing = false+ val rect = Rect(minX.toInt(), minY.toInt(), maxX.toInt(), maxY.toInt())+ if (moved && rect.width() > MIN_SIZE_PX && rect.height() > MIN_SIZE_PX) {onSelection(rect)} else {- // A tap (no real drag) cancels Lens mode.onCancel()}- invalidate()}MotionEvent.ACTION_CANCEL -> {- selecting = false+ drawing = falseonCancel()}}return true}- private fun currentRectF(): RectF = RectF(- min(startX, currentX),- min(startY, currentY),- max(startX, currentX),- max(startY, currentY)+ @Suppress("LongParameterList")+ private class Particle(+ var x: Float,+ var y: Float,+ val vx: Float,+ val vy: Float,+ val radius: Float,+ val pink: Boolean,+ val phase: Float,+ val twinkle: Float)- private fun currentRect(): Rect {- val l = min(startX, currentX).toInt()- val t = min(startY, currentY).toInt()- val r = max(startX, currentX).toInt()- val b = max(startY, currentY).toInt()- return Rect(l, t, r, b)- }-private companion object {- val MIN_SIZE_PX get() = 24+ const val MIN_SIZE_PX = 24}}diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.ktindex d73742c..6c39be6 100644--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt@@ -1,6 +1,7 @@package com.gotcha.serviceimport org.junit.Assert.assertEquals+import org.junit.Assert.assertFalseimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrue@@ -8,42 +9,61 @@ import org.junit.Testclass SmartActionDetectorTest {+ // ---- Proactive detect() ----+@Test- fun `detects phone number and encodes a dial action`() {+ fun `detects punctuated phone number and encodes a dial action`() {val action = SmartActionDetector.detect("Call me at (415) 555-2671 tomorrow")assertNotNull(action)- assertTrue(action!!.label.contains("Phone"))+ assertTrue(action!!.label.contains("Dial"))assertTrue(SmartActionDetector.isNativeAction(action.prompt))val (type, payload) = SmartActionDetector.decode(action.prompt)!!assertEquals(SmartActionDetector.TYPE_DIAL, type)assertTrue(payload.contains("555"))}+ @Test+ fun `detects dashed phone number`() {+ val action = SmartActionDetector.detect("Reach us on 415-555-2671")+ assertNotNull(action)+ assertEquals(SmartActionDetector.TYPE_DIAL, SmartActionDetector.decode(action!!.prompt)!!.first)+ }++ @Test+ fun `detects international phone number`() {+ val action = SmartActionDetector.detect("Ring +44 20 7946 0958 for support")+ assertNotNull(action)+ assertEquals(SmartActionDetector.TYPE_DIAL, SmartActionDetector.decode(action!!.prompt)!!.first)+ }++ @Test+ fun `does not treat a bare digit run as a phone number`() {+ // Order id / tracking number — no separators, no parens, no +.+ assertNull(SmartActionDetector.detect("Your order 4155552671 has shipped"))+ }++ @Test+ fun `does not match digits embedded in a longer number`() {+ assertNull(SmartActionDetector.detect("SKU 004155552671003 in stock"))+ }+@Testfun `detects street address and encodes a navigate action`() {val action = SmartActionDetector.detect("Meet at 1600 Amphitheatre Parkway Way for lunch")assertNotNull(action)- assertTrue(action!!.label.contains("Address"))+ assertTrue(action!!.label.contains("Navigate"))val (type, _) = SmartActionDetector.decode(action.prompt)!!assertEquals(SmartActionDetector.TYPE_NAVIGATE, type)}@Test- fun `detects foreign currency and returns a plain LLM prompt`() {- val action = SmartActionDetector.detect("The jacket costs €89.99 in Berlin")- assertNotNull(action)- assertTrue(action!!.label.contains("Currency"))- // Currency conversion is an LLM query, not a native intent.- assertTrue(!SmartActionDetector.isNativeAction(action.prompt))+ fun `proactive detect never offers currency`() {+ assertNull(SmartActionDetector.detect("The jacket costs €89.99 in Berlin"))}@Test- fun `detects calendar event and encodes a calendar action`() {- val action = SmartActionDetector.detect("Let's schedule a meeting on Monday")- assertNotNull(action)- assertTrue(action!!.label.contains("Event"))- val (type, _) = SmartActionDetector.decode(action.prompt)!!- assertEquals(SmartActionDetector.TYPE_CALENDAR, type)+ fun `proactive detect never offers calendar`() {+ assertNull(SmartActionDetector.detect("Let's schedule a meeting on Monday"))}@Test@@ -65,6 +85,30 @@ class SmartActionDetectorTest {assertNull(SmartActionDetector.detect(" "))}+ // ---- Lens-mode detectContextual() ----++ @Test+ fun `contextual detection finds currency`() {+ val actions = SmartActionDetector.detectContextual("The jacket costs €89.99")+ assertTrue(actions.any { it.label.contains("Convert") })+ // Currency conversion is an LLM query, not a native intent.+ val currency = actions.first { it.label.contains("Convert") }+ assertFalse(SmartActionDetector.isNativeAction(currency.prompt))+ }++ @Test+ fun `contextual detection finds calendar event`() {+ val actions = SmartActionDetector.detectContextual("Team meeting on Monday")+ val cal = actions.firstOrNull { it.label.contains("calendar") }+ assertNotNull(cal)+ assertEquals(SmartActionDetector.TYPE_CALENDAR, SmartActionDetector.decode(cal!!.prompt)!!.first)+ }++ @Test+ fun `contextual detection returns empty for plain prose`() {+ assertTrue(SmartActionDetector.detectContextual("just some words here").isEmpty())+ }+@Testfun `decode returns null for non-native prompts`() {assertNull(SmartActionDetector.decode("Just a normal prompt"))