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.
fix(lens): stop annotating every match on dense screens
Durganshu Mishrab81a622c6757
diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex d9d6cf6..d86373f 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -347,7 +347,7 @@ class GotchaAccessibilityService : AccessibilityService() {*/fun extractScreenEntitiesWithBounds(): List<AnnotatedEntity> {val root = hostRoot() ?: return emptyList()- val nodes = mutableListOf<Pair<String, android.graphics.Rect>>()+ val nodes = mutableListOf<ScreenTextNode>()fun findValidBounds(node: AccessibilityNodeInfo): android.graphics.Rect? {var curr: AccessibilityNodeInfo? = node@@ -364,11 +364,18 @@ class GotchaAccessibilityService : AccessibilityService() {fun walk(node: AccessibilityNodeInfo?) {if (node == null) return- val txt = (node.text?.toString() ?: node.contentDescription?.toString())?.trim()- if (!txt.isNullOrBlank()) {- val rect = findValidBounds(node)- if (rect != null) {- nodes.add(Pair(txt, rect))+ val visible = node.text?.toString()?.trim()+ val described = node.contentDescription?.toString()?.trim()+ val rect = if (!visible.isNullOrBlank() || !described.isNullOrBlank()) findValidBounds(node) else null+ if (rect != null) {+ if (!visible.isNullOrBlank()) nodes.add(ScreenTextNode(visible, rect, derived = false))+ // Both are kept when they disagree, rather than `text ?: description`.+ // A node that *renders* "3 hours ago" while *describing* itself as+ // "Jul 26, 2026" is a formatted-timestamp widget telling us so, and+ // collapsing the two threw that signal away. Anything found only in+ // the description is marked so ranking can weigh it lower.+ if (!described.isNullOrBlank() && !described.equals(visible, ignoreCase = true)) {+ nodes.add(ScreenTextNode(described, rect, derived = !visible.isNullOrBlank()))}}for (i in 0 until node.childCount) {@@ -382,38 +389,94 @@ class GotchaAccessibilityService : AccessibilityService() {if (nodes.isEmpty()) return emptyList()val fullTextBuilder = StringBuilder()- val nodeRanges = mutableListOf<Pair<IntRange, android.graphics.Rect>>()- for ((txt, rect) in nodes) {+ val nodeRanges = mutableListOf<Pair<IntRange, ScreenTextNode>>()+ for (node in nodes) {val startIdx = fullTextBuilder.length- fullTextBuilder.append(txt).append("\n")+ fullTextBuilder.append(node.text).append("\n")val endIdx = fullTextBuilder.length- nodeRanges.add(Pair(startIdx..endIdx, rect))+ nodeRanges.add(Pair(startIdx..endIdx, node))}val fullText = fullTextBuilder.toString()val entities = SmartActionDetector.detectAll(fullText, allowChat = false)- val annotated = mutableListOf<AnnotatedEntity>()+ val placeable = discardOversizedBounds(locateEntities(entities, nodeRanges))+ val selected = SmartActionDetector.selectForAnnotation(placeable.map { it.entity })+ // Matched by identity, not equality: selection hands back the very objects+ // it was given, and two genuinely distinct detections can compare equal.+ return selected.mapNotNull { candidate ->+ val bounds = placeable.firstOrNull { it.entity === candidate.entity }?.boundsOnScreen+ ?: return@mapNotNull null+ AnnotatedEntity(candidate.entity, bounds, candidate.groupCount)+ }+ }+ /**+ * Map each entity onto the union of the bounds of the nodes its span covers.+ *+ * An entity that turned up *only* in nodes' contentDescriptions is weighted+ * down rather than dropped: that it was never rendered as text is a reason to+ * doubt it, not proof it is wrong.+ */+ private fun locateEntities(+ entities: List<DetectedEntity>,+ nodeRanges: List<Pair<IntRange, ScreenTextNode>>+ ): List<AnnotatedEntity> {+ val located = mutableListOf<AnnotatedEntity>()for (entity in entities) {val unionRect = android.graphics.Rect()var count = 0- for ((range, rect) in nodeRanges) {- if (range.first <= entity.span.last && entity.span.first <= range.last) {- if (count == 0) {- unionRect.set(rect)- } else {- unionRect.union(rect)- }- count++- }+ var derivedOnly = true+ for ((range, node) in nodeRanges) {+ if (range.first > entity.span.last || entity.span.first > range.last) continue+ if (count == 0) unionRect.set(node.bounds) else unionRect.union(node.bounds)+ if (!node.derived) derivedOnly = false+ count+++ }+ if (count == 0 || unionRect.width() <= 0 || unionRect.height() <= 0) continue+ val weighted = if (derivedOnly) {+ entity.copy(confidence = entity.confidence * SmartActionDetector.DERIVED_TEXT_CONFIDENCE_SCALE)+ } else {+ entity}- if (count > 0 && unionRect.width() > 0 && unionRect.height() > 0) {- annotated.add(AnnotatedEntity(entity, unionRect))+ located.add(AnnotatedEntity(weighted, unionRect))+ }+ return located+ }++ /**+ * Drop annotations whose bounds are too big to mean anything.+ *+ * `findValidBounds` climbs to a parent when a text node is smaller than 10px,+ * which for a compact timestamp can walk all the way up to the list container+ * — so the "annotation" is a box around the entire feed. Two things give that+ * away without knowing the app: it covers most of the screen, or it wholly+ * contains another annotation's bounds.+ */+ private fun discardOversizedBounds(items: List<AnnotatedEntity>): List<AnnotatedEntity> {+ if (items.size <= 1) return items+ val metrics = resources.displayMetrics+ val screenArea = metrics.widthPixels.toLong() * metrics.heightPixels.toLong()+ val maxArea = (screenArea * SmartActionDetector.MAX_ANNOTATION_SCREEN_FRACTION).toLong()++ return items.filter { item ->+ val bounds = item.boundsOnScreen+ val area = bounds.width().toLong() * bounds.height().toLong()+ if (screenArea > 0 && area > maxArea) return@filter false+ items.none { other ->+ other !== item &&+ bounds.contains(other.boundsOnScreen) &&+ bounds != other.boundsOnScreen}}- return annotated}+ /** One piece of text on screen, and whether it came from a node's description rather than its label. */+ private data class ScreenTextNode(+ val text: String,+ val bounds: android.graphics.Rect,+ val derived: Boolean+ )+fun longPressByText(query: String): Boolean {val root = rootInActiveWindow ?: return falseval match = findClickable(root, query.lowercase())diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.ktindex 2c52bc4..8aa4da8 100644--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt@@ -1,5 +1,7 @@package com.gotcha.service+import java.time.DayOfWeek+import java.time.LocalDateimport java.util.regex.Pattern/**@@ -69,10 +71,24 @@ data class DetectedEntity(/*** An entity mapped to absolute screen bounds for the Lens auto-annotate overlay.+ *+ * [groupCount] is how many detections this one stands for. A screen listing a+ * dozen prices collapses to a single annotation with `groupCount = 12` rather+ * than a dozen chips — see [SmartActionDetector.selectForAnnotation].*/data class AnnotatedEntity(val entity: DetectedEntity,- val boundsOnScreen: android.graphics.Rect+ val boundsOnScreen: android.graphics.Rect,+ val groupCount: Int = 1+)++/**+ * An entity that survived annotation ranking, with the number of detections it+ * represents.+ */+data class AnnotationCandidate(+ val entity: DetectedEntity,+ val groupCount: Int = 1)/**@@ -101,6 +117,27 @@ object SmartActionDetector {/** Separator between the encoded action type and its payload. */const val PAYLOAD_SEP = "|"+ /** Most annotations Lens will draw at once, however many entities the screen holds. */+ const val MAX_ANNOTATIONS = 5++ /** Most annotations of a single type, so one noisy type cannot crowd out the rest. */+ const val MAX_ANNOTATIONS_PER_TYPE = 2++ /** At this many detections of a type, the screen is a list and the type collapses to one chip. */+ const val REPETITION_THRESHOLD = 3++ /** Largest share of the screen an annotation's bounds may cover before it is discarded. */+ const val MAX_ANNOTATION_SCREEN_FRACTION = 0.35f++ /** Confidence multiplier for an entity found only in a node's contentDescription. */+ const val DERIVED_TEXT_CONFIDENCE_SCALE = 0.6f++ private const val CONFIDENCE_EVENT_WORDED = 0.85f+ private const val CONFIDENCE_EVENT_DATED = 0.8f+ private const val CONFIDENCE_EVENT_BARE_TIME = 0.5f+ private const val CHIP_LABEL_MAX = 18+ private const val DAYS_IN_WEEK = 7+/*** Street addresses: supports single-line and multi-line house numbers, street names,* suffixes, optional unit/suite/building, and city/state/zip tails across line breaks.@@ -149,6 +186,36 @@ object SmartActionDetector {Pattern.CASE_INSENSITIVE)+ /**+ * The event vocabulary, deliberately frozen.+ *+ * It is the same list `calendarPattern`'s first alternative already carried,+ * reused here only as a *weak positive* signal for confidence. Precision now+ * comes from tense ([eventDateOf]) and from repetition+ * ([selectForAnnotation]) — neither of which needs a word list — so this one+ * does not have to grow every time an app phrases something new.+ */+ private val eventKeywordPattern: Pattern = Pattern.compile(+ "\\b(meeting|appointment|event|call|lunch|dinner|reminder|deadline)\\b",+ Pattern.CASE_INSENSITIVE+ )++ private val monthPrefixes =+ listOf("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")+ private val weekdayPrefixes =+ listOf("mon", "tue", "wed", "thu", "fri", "sat", "sun")++ private val explicitDatePattern: Pattern = Pattern.compile(+ "\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\\.?\\s+" ++ "(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(\\d{4}))?",+ Pattern.CASE_INSENSITIVE+ )++ private val weekdayNamePattern: Pattern = Pattern.compile(+ "\\b(mon|tue|wed|thu|fri|sat|sun)[a-z]*\\b",+ Pattern.CASE_INSENSITIVE+ )+/*** Enhanced URL pattern supporting scheme, bare domain/www, query params, ports, IP addresses.*/@@ -179,7 +246,8 @@ object SmartActionDetector {text: String,allowChat: Boolean = false,targetCurrency: String = "USD",- targetLanguage: String = "English"+ targetLanguage: String = "English",+ today: LocalDate = LocalDate.now()): List<DetectedEntity> {if (text.isBlank()) return emptyList()@@ -207,7 +275,7 @@ object SmartActionDetector {detectCurrencies(text, rawEntities, targetCurrency)// 7. Calendar- detectCalendars(text, rawEntities)+ detectCalendars(text, rawEntities, today)// 8. Tracking numbersdetectTracking(text, rawEntities)@@ -285,6 +353,101 @@ object SmartActionDetector {return entities.mapNotNull { it.primaryAction }}+ /**+ * Choose which detections are worth drawing on screen.+ *+ * Lens used to annotate every match, which is how a GitHub PR list ends up+ * with seven overlapping "Add to calendar" chips and a shopping page with one+ * "Convert" chip per price. Three passes fix that without knowing anything+ * about the app:+ *+ * 1. Exact repeats of the same value collapse to one.+ * 2. A type appearing [repetitionThreshold] times or more is list *metadata*,+ * not a call to action, and collapses to a single grouped chip. This is+ * right even when every detection is correct — a calendar app showing+ * eight real events still should not produce eight overlapping chips.+ * 3. What survives is capped at [maxPerType] per type and [max] overall, so a+ * misclassification costs one wasted chip rather than a covered screen.+ */+ fun selectForAnnotation(+ entities: List<DetectedEntity>,+ max: Int = MAX_ANNOTATIONS,+ maxPerType: Int = MAX_ANNOTATIONS_PER_TYPE,+ repetitionThreshold: Int = REPETITION_THRESHOLD+ ): List<AnnotationCandidate> {+ if (entities.isEmpty()) return emptyList()++ val byValue = LinkedHashMap<Pair<EntityType, String>, MutableList<DetectedEntity>>()+ for (entity in entities) {+ byValue.getOrPut(entity.type to entity.normalizedValue) { mutableListOf() }.add(entity)+ }+ val unique = byValue.values.mapNotNull { group ->+ val best = group.maxByOrNull { calculateScore(it) } ?: return@mapNotNull null+ AnnotationCandidate(best, group.size)+ }++ val kept = mutableListOf<AnnotationCandidate>()+ for ((_, group) in unique.groupBy { it.entity.type }) {+ val ranked = group.sortedByDescending { calculateScore(it.entity) }+ val occurrences = group.sumOf { it.groupCount }+ if (occurrences >= repetitionThreshold) {+ kept.add(AnnotationCandidate(ranked.first().entity, occurrences))+ } else {+ kept.addAll(ranked.take(maxPerType))+ }+ }++ return kept+ .sortedWith(+ compareByDescending<AnnotationCandidate> { calculateScore(it.entity) }+ .thenByDescending { it.groupCount }+ )+ .take(max)+ }++ /**+ * The compact label for an annotation chip: an icon plus the value itself,+ * or a count when the chip stands for a group.+ *+ * The verb ("Add to calendar", "Convert to USD") belongs in the menu that+ * opens on tap, not on a pill sitting over somebody else's UI — it is the+ * same word on every chip of a type, and it is what made the chips wide+ * enough to bury the screen underneath them.+ */+ fun chipLabel(entity: DetectedEntity, groupCount: Int = 1): String {+ val icon = iconFor(entity.type)+ if (groupCount > 1) return "$icon $groupCount ${pluralFor(entity.type)}"+ return "$icon ${snippet(entity.normalizedValue, CHIP_LABEL_MAX)}"+ }++ private fun iconFor(type: EntityType): String = when (type) {+ EntityType.QR_CODE, EntityType.BARCODE -> "⬛"+ EntityType.OTP -> "🔑"+ EntityType.PHONE -> "📞"+ EntityType.ADDRESS -> "📍"+ EntityType.EMAIL -> "📧"+ EntityType.URL -> "🌐"+ EntityType.CALENDAR -> "📅"+ EntityType.CURRENCY -> "💵"+ EntityType.TRACKING_NUMBER -> "📦"+ EntityType.CHAT_REPLY -> "💬"+ EntityType.GENERIC_TEXT -> "✨"+ }++ private fun pluralFor(type: EntityType): String = when (type) {+ EntityType.QR_CODE, EntityType.BARCODE -> "codes"+ EntityType.OTP -> "codes"+ EntityType.PHONE -> "numbers"+ EntityType.ADDRESS -> "addresses"+ EntityType.EMAIL -> "emails"+ EntityType.URL -> "links"+ EntityType.CALENDAR -> "dates"+ EntityType.CURRENCY -> "prices"+ EntityType.TRACKING_NUMBER -> "packages"+ EntityType.CHAT_REPLY -> "messages"+ EntityType.GENERIC_TEXT -> "items"+ }+private fun detectOtps(text: String, out: MutableList<DetectedEntity>) {val m = potentialCodePattern.matcher(text)while (m.find()) {@@ -542,10 +705,76 @@ object SmartActionDetector {}}- private fun detectCalendars(text: String, out: MutableList<DetectedEntity>) {+ /**+ * The date [event] refers to, or null when it names no resolvable day.+ *+ * A bare `Dec 12` resolves to the *next* December 12th, because that is what+ * a person writing it means. Weekday names resolve forwards for the same+ * reason, so neither can ever come back as a past date.+ */+ @Suppress("ReturnCount")+ internal fun eventDateOf(event: String, today: LocalDate): LocalDate? {+ val lower = event.lowercase()+ if (lower.contains("today")) return today+ if (lower.contains("tomorrow")) return today.plusDays(1)++ val m = explicitDatePattern.matcher(event)+ if (m.find()) {+ val month = monthPrefixes.indexOf(m.group(1)?.lowercase()?.take(3).orEmpty()) + 1+ val day = m.group(2)?.toIntOrNull()+ if (month >= 1 && day != null) {+ val year = m.group(3)?.toIntOrNull()+ if (year != null) {+ return runCatching { LocalDate.of(year, month, day) }.getOrNull()+ }+ val thisYear = runCatching { LocalDate.of(today.year, month, day) }.getOrNull()+ return when {+ thisYear == null -> null+ thisYear.isBefore(today) -> thisYear.plusYears(1)+ else -> thisYear+ }+ }+ }++ val w = weekdayNamePattern.matcher(event)+ if (w.find()) {+ val idx = weekdayPrefixes.indexOf(w.group(1)?.lowercase()?.take(3).orEmpty())+ if (idx >= 0) {+ val target = DayOfWeek.of(idx + 1)+ var day = today+ var guard = 0+ while (day.dayOfWeek != target && guard < DAYS_IN_WEEK) {+ day = day.plusDays(1)+ guard+++ }+ return day+ }+ }+ return null+ }++ private fun detectCalendars(text: String, out: MutableList<DetectedEntity>, today: LocalDate) {val m = calendarPattern.matcher(text)while (m.find()) {val event = m.group().trim()++ // A date that has already passed is a timestamp, not an event. "merged+ // 3 hours ago" reaches us as `Jul 26, 2026`; so does "posted Mar 4".+ // Checking tense is arithmetic rather than a vocabulary of timestamp+ // words, so it holds for apps whose phrasing we have never seen — and+ // the parse is needed anyway to give the calendar intent a real start+ // time instead of a raw string to guess at.+ val date = eventDateOf(event, today)+ if (date != null && date.isBefore(today)) continue++ val confidence = when {+ eventKeywordPattern.matcher(event).find() -> CONFIDENCE_EVENT_WORDED+ date != null -> CONFIDENCE_EVENT_DATED+ // A bare time with neither a date nor an event word ("3 pm") is the+ // thinnest thing this pattern matches. Ranking should treat it that way.+ else -> CONFIDENCE_EVENT_BARE_TIME+ }+val actions = listOf(SmartAction(label = "📅 Add to calendar: ${snippet(event, 24)}",@@ -565,7 +794,7 @@ object SmartActionDetector {rawValue = event,normalizedValue = event,span = m.start()..m.end(),- confidence = 0.8f,+ confidence = confidence,actions = actions))diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.ktindex 9ea5745..8a14ca5 100644--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt@@ -15,6 +15,7 @@ import android.view.MotionEventimport android.view.Viewimport androidx.core.graphics.ColorUtilsimport com.gotcha.service.AnnotatedEntity+import com.gotcha.service.SmartActionDetectorimport com.gotcha.ui.theme.OverlaySkinimport kotlin.math.maximport kotlin.math.min@@ -141,6 +142,15 @@ class ScreenCropOverlayView(private val blueGlowShader by lazy { unitGlowShader(PARTICLE_BLUE) }private val glowMatrix = android.graphics.Matrix()+ /** Where each chip was actually drawn, so [onTouchEvent] can hit-test what is on screen. */+ private class ChipHit {+ val rect = RectF()+ var item: AnnotatedEntity? = null+ }++ private val chipHits = ArrayList<ChipHit>()+ private var drawnChipCount = 0+/** Scratch, reused by [drawAnnotatedEntities] and [onTouchEvent]. */private val scratchLocation = IntArray(2)private val scratchRect = RectF()@@ -201,8 +211,13 @@ class ScreenCropOverlayView(@androidx.annotation.VisibleForTestinginternal fun decorationColors(): IntArray = intArrayOf(dimPaint.color, hintPaint.color)+ /** Where chips actually landed on the last frame, for tests. */+ @androidx.annotation.VisibleForTesting+ internal fun drawnChipRects(): List<RectF> = (0 until drawnChipCount).map { RectF(chipHits[it].rect) }+fun setAnnotatedEntities(entities: List<AnnotatedEntity>) {this.annotatedEntities = entities+ drawnChipCount = 0postInvalidateOnAnimation()}@@ -357,12 +372,25 @@ class ScreenCropOverlayView(return null}+ /**+ * Boxes and chips for whatever the detector decided is worth showing.+ *+ * Two rules keep this legible on a busy screen. Only the top-ranked+ * annotation carries its full verb — "🌐 Open: github.com/…" — because the+ * verb is identical on every chip of a type and it is what made them wide+ * enough to bury the app underneath. And a chip that cannot find a clear spot+ * is not drawn at all: its box still marks the thing, which is better than a+ * label stacked on another label.+ */private fun drawAnnotatedEntities(canvas: Canvas) {getLocationOnScreen(scratchLocation)val viewOffsetX = scratchLocation[0].toFloat()val viewOffsetY = scratchLocation[1].toFloat()+ val radius = colors.buttonRadiusDp * density+ val padding = CHIP_PADDING_DP * density+ drawnChipCount = 0- for (item in annotatedEntities) {+ for ((index, item) in annotatedEntities.withIndex()) {val bounds = item.boundsOnScreenval rectF = scratchRectrectF.set(@@ -371,23 +399,19 @@ class ScreenCropOverlayView(bounds.right.toFloat() - viewOffsetX,bounds.bottom.toFloat() - viewOffsetY)-- // Draw bounding box- val radius = colors.buttonRadiusDp * densitycanvas.drawRoundRect(rectF, radius, radius, entityBoxPaint)- // Draw primary action chip pill anchored above the boxval action = item.entity.primaryAction ?: continue- val labelStr = action.label- val textWidth = entityChipTextPaint.measureText(labelStr)- val chipW = textWidth + 16f * density- val chipH = 24f * density+ val labelStr = if (index == 0 && item.groupCount == 1) {+ action.label+ } else {+ SmartActionDetector.chipLabel(item.entity, item.groupCount)+ }+ val chipW = entityChipTextPaint.measureText(labelStr) + padding * 2f+ val chipH = CHIP_HEIGHT_DP * density+ if (!placeChip(rectF, chipW, chipH)) continue- val chipLeft = (rectF.left).coerceIn(8f * density, width - chipW - 8f * density)- val chipTop = (rectF.top - chipH - 4f * density).coerceAtLeast(8f * density)val chipRect = scratchChipRect- chipRect.set(chipLeft, chipTop, chipLeft + chipW, chipTop + chipH)-canvas.drawRoundRect(chipRect, radius, radius, entityChipBgPaint)canvas.drawRoundRect(chipRect, radius, radius, entityBoxPaint)// Centred off the font's own metrics rather than a fixed baseline:@@ -395,10 +419,45 @@ class ScreenCropOverlayView(// offset would drift as soon as that scale moved.val fm = entityChipTextPaint.fontMetricsval baseline = chipRect.centerY() - (fm.ascent + fm.descent) / 2f- canvas.drawText(labelStr, chipLeft + 8f * density, baseline, entityChipTextPaint)+ canvas.drawText(labelStr, chipRect.left + padding, baseline, entityChipTextPaint)+ recordChip(chipRect, item)}}+ /**+ * Find a clear spot for a [w]×[h] chip near [box], writing it into+ * [scratchChipRect]. Above the box first, then below; false when both are+ * taken or off-screen, which the caller reads as "draw no label".+ */+ private fun placeChip(box: RectF, w: Float, h: Float): Boolean {+ val gap = CHIP_GAP_DP * density+ val margin = CHIP_MARGIN_DP * density+ val left = box.left.coerceIn(margin, (width - w - margin).coerceAtLeast(margin))+ val candidates = floatArrayOf(box.top - h - gap, box.bottom + gap)+ for (top in candidates) {+ if (top < margin || top + h > height - margin) continue+ scratchChipRect.set(left, top, left + w, top + h)+ var clear = true+ for (i in 0 until drawnChipCount) {+ if (RectF.intersects(chipHits[i].rect, scratchChipRect)) {+ clear = false+ break+ }+ }+ if (clear) return true+ }+ return false+ }++ /** Remember a drawn chip so a tap can find it. Pooled — this runs every frame. */+ private fun recordChip(rect: RectF, item: AnnotatedEntity) {+ while (chipHits.size <= drawnChipCount) chipHits.add(ChipHit())+ val hit = chipHits[drawnChipCount]+ hit.rect.set(rect)+ hit.item = item+ drawnChipCount+++ }+private fun drawScreenBorder(canvas: Canvas) {val inset = screenBorderGlowPaint.strokeWidth / 2f + 1fval r = RectF(inset, inset, width - inset, height - inset)@@ -527,35 +586,64 @@ class ScreenCropOverlayView(return RadialGradient(0f, 0f, 1f, centre, Color.TRANSPARENT, Shader.TileMode.CLAMP)}+ /**+ * Fire the annotation under ([touchX], [touchY]), if any.+ *+ * Chips are tested before boxes, and among boxes the *smallest* containing+ * one wins. Accessibility bounds nest — one entity's box can wholly contain+ * another's — and this used to take whichever came first in list order, so a+ * tap on an inner chip was answered by the container around it.+ */+ private fun selectAnnotationAt(touchX: Float, touchY: Float): Boolean {+ // Only `frozenRect`, deliberately not `drawing`: ACTION_DOWN sets that+ // flag before the ACTION_UP that gets us here, so testing it would reject+ // every tap. A tap is a press with no movement, and the chips it is+ // hit-testing against are the ones from the last frame before the press —+ // which is exactly what the user was looking at when they aimed.+ if (frozenRect != null) return false+ for (i in 0 until drawnChipCount) {+ val hit = chipHits[i]+ if (!hit.rect.contains(touchX, touchY)) continue+ val prompt = hit.item?.entity?.primaryAction?.prompt ?: continue+ onAnnotatedEntitySelected(prompt)+ return true+ }++ getLocationOnScreen(scratchLocation)+ val viewOffsetX = scratchLocation[0].toFloat()+ val viewOffsetY = scratchLocation[1].toFloat()+ val slop = ENTITY_TOUCH_SLOP_DP * density+ val expanded = scratchRect+ var best: AnnotatedEntity? = null+ var bestArea = Float.MAX_VALUE++ for (item in annotatedEntities) {+ val bounds = item.boundsOnScreen+ expanded.set(+ bounds.left.toFloat() - viewOffsetX - slop,+ bounds.top.toFloat() - viewOffsetY - slop,+ bounds.right.toFloat() - viewOffsetX + slop,+ bounds.bottom.toFloat() - viewOffsetY + slop+ )+ if (!expanded.contains(touchX, touchY)) continue+ val area = expanded.width() * expanded.height()+ if (area < bestArea) {+ bestArea = area+ best = item+ }+ }++ val prompt = best?.entity?.primaryAction?.prompt ?: return false+ onAnnotatedEntitySelected(prompt)+ return true+ }+override fun onTouchEvent(event: MotionEvent): Boolean {if (captureMode) return false// Check if touch hits an annotated entity box/chipif (event.action == MotionEvent.ACTION_UP && !moved) {- getLocationOnScreen(scratchLocation)- val viewOffsetX = scratchLocation[0].toFloat()- val viewOffsetY = scratchLocation[1].toFloat()-- val touchX = event.x- val touchY = event.y- val chipH = 24f * density- val expandedBounds = scratchRect- for (item in annotatedEntities) {- val bounds = item.boundsOnScreen- expandedBounds.set(- bounds.left.toFloat() - viewOffsetX - 16f,- bounds.top.toFloat() - viewOffsetY - chipH - 16f,- bounds.right.toFloat() - viewOffsetX + 16f,- bounds.bottom.toFloat() - viewOffsetY + 16f- )- if (expandedBounds.contains(touchX, touchY)) {- val prompt = item.entity.primaryAction?.prompt- if (prompt != null) {- onAnnotatedEntitySelected(prompt)- return true- }- }- }+ if (selectAnnotationAt(event.x, event.y)) return true}when (event.action) {@@ -625,5 +713,10 @@ class ScreenCropOverlayView(const val GLOW_ALPHA = 0x55const val BRACKET_LEN_DP = 20fconst val BRACKET_MAX_FRACTION = 0.6f+ const val CHIP_HEIGHT_DP = 24f+ const val CHIP_PADDING_DP = 8f+ const val CHIP_GAP_DP = 4f+ const val CHIP_MARGIN_DP = 8f+ const val ENTITY_TOUCH_SLOP_DP = 8f}}diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.ktindex 09fe25f..ebe1b77 100644--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt@@ -6,6 +6,7 @@ import org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Test+import java.time.LocalDateclass SmartActionDetectorTest {@@ -329,4 +330,145 @@ class SmartActionDetectorTest {assertEquals(EntityType.QR_CODE, entities.first().type)assertTrue(entities.first().normalizedValue.contains("HomeNet"))}++ // ---- Tense: a past date is a timestamp, not an event ----++ @Test+ fun `past dates are not calendar events`() {+ val entities = SmartActionDetector.detectAll(+ "Rebase #53 by DevUser2 was merged Jul 26, 2026",+ today = LocalDate.of(2026, 8, 1)+ )+ assertTrue(+ "A merge timestamp is not something to put on a calendar",+ entities.none { it.type == EntityType.CALENDAR }+ )+ }++ @Test+ fun `future dates are still calendar events`() {+ val entities = SmartActionDetector.detectAll(+ "Design review Aug 14, 2026",+ today = LocalDate.of(2026, 8, 1)+ )+ assertTrue(entities.any { it.type == EntityType.CALENDAR })+ }++ @Test+ fun `a date without a year resolves to the next occurrence, never the past`() {+ val today = LocalDate.of(2026, 12, 20)+ assertEquals(LocalDate.of(2027, 1, 4), SmartActionDetector.eventDateOf("Jan 4", today))+ assertEquals(LocalDate.of(2026, 12, 25), SmartActionDetector.eventDateOf("Dec 25", today))+ }++ @Test+ fun `weekday and relative names resolve forwards`() {+ val wednesday = LocalDate.of(2026, 8, 5)+ assertEquals(wednesday, SmartActionDetector.eventDateOf("today", wednesday))+ assertEquals(wednesday.plusDays(1), SmartActionDetector.eventDateOf("tomorrow", wednesday))+ // The coming Monday, not the one just gone.+ assertEquals(LocalDate.of(2026, 8, 10), SmartActionDetector.eventDateOf("Monday", wednesday))+ }++ @Test+ fun `an event word outranks a bare time`() {+ val today = LocalDate.of(2026, 8, 1)+ val worded = SmartActionDetector.detectAll("Dinner tomorrow", today = today)+ .first { it.type == EntityType.CALENDAR }+ val bare = SmartActionDetector.detectAll("Doors open 8 pm", today = today)+ .first { it.type == EntityType.CALENDAR }+ assertTrue(bare.confidence < worded.confidence)+ }++ // ---- Annotation selection ----++ /** The screen from the bug report: a PR list whose every row carries a merge timestamp. */+ private val pullRequestList = """+ Open: github.com/<org>/Gotcha+ 1 Open 30 Closed+ Rebase #53 by DevUser2 was merged Jul 26, 2026+ Feature test coverage manifest #52 by DevUser was merged Jul 26, 2026+ Merging dev #51 by DevUser was merged Jul 26, 2026+ Storage overhaul #50 by DevUser was merged Jul 26, 2026+ Add connector framework #35 by DevUser was merged Jul 25, 2026+ feat(audio/vision) #34 by DevUser was merged Jul 25, 2026+ Onboarding #33 by DevUser was merged Jul 23, 2026+ """.trimIndent()++ @Test+ fun `a list of merge timestamps produces no calendar annotations`() {+ val entities = SmartActionDetector.detectAll(pullRequestList, today = LocalDate.of(2026, 8, 1))+ val selected = SmartActionDetector.selectForAnnotation(entities)+ assertTrue(+ "Merge timestamps should not be annotated at all",+ selected.none { it.entity.type == EntityType.CALENDAR }+ )+ assertTrue("The repo link is what is worth surfacing here", selected.isNotEmpty())+ assertEquals(EntityType.URL, selected.first().entity.type)+ }++ @Test+ fun `annotations are capped however busy the screen is`() {+ val entities = SmartActionDetector.detectAll(pullRequestList, today = LocalDate.of(2026, 8, 1))+ val selected = SmartActionDetector.selectForAnnotation(entities)+ assertTrue(+ "Expected at most ${SmartActionDetector.MAX_ANNOTATIONS}, got ${selected.size}",+ selected.size <= SmartActionDetector.MAX_ANNOTATIONS+ )+ }++ @Test+ fun `a repeated type collapses to a single grouped annotation`() {+ val catalogue = (1..12).joinToString("\n") { "Item $it — €${it * 10}.00" }+ val entities = SmartActionDetector.detectAll(catalogue)+ val prices = entities.filter { it.type == EntityType.CURRENCY }+ assertTrue("Fixture should detect many prices", prices.size >= 10)++ val selected = SmartActionDetector.selectForAnnotation(entities)+ val currency = selected.filter { it.entity.type == EntityType.CURRENCY }+ assertEquals("Twelve prices are a catalogue, not twelve calls to action", 1, currency.size)+ assertEquals(prices.size, currency.first().groupCount)+ assertEquals("💵 ${prices.size} prices", SmartActionDetector.chipLabel(currency.first().entity, prices.size))+ }++ @Test+ fun `no single type may crowd out the others`() {+ val text = """+ Call (415) 555-2671 or (415) 555-9900.+ Visit https://example.com/help+ """.trimIndent()+ val selected = SmartActionDetector.selectForAnnotation(SmartActionDetector.detectAll(text))+ val perType = selected.groupBy { it.entity.type }+ for ((type, group) in perType) {+ assertTrue(+ "$type took ${group.size} slots",+ group.size <= SmartActionDetector.MAX_ANNOTATIONS_PER_TYPE+ )+ }+ assertTrue("The lone URL should survive four emails", perType.containsKey(EntityType.URL))+ }++ @Test+ fun `identical values collapse before ranking`() {+ val selected = SmartActionDetector.selectForAnnotation(SmartActionDetector.detectAll(text))+ val emails = selected.filter { it.entity.type == EntityType.EMAIL }+ assertEquals(1, emails.size)+ assertEquals(3, emails.first().groupCount)+ }++ @Test+ fun `chip labels drop the verb and keep the value`() {+ val entity = SmartActionDetector.detectAll("Visit https://example.com/help")+ .first { it.type == EntityType.URL }+ val label = SmartActionDetector.chipLabel(entity)+ assertTrue(label.startsWith("🌐"))+ assertFalse("The verb belongs in the menu, not the chip", label.contains("Open:"))+ }++ @Test+ fun `selectForAnnotation on an empty list is empty`() {+ assertTrue(SmartActionDetector.selectForAnnotation(emptyList()).isEmpty())+ }}diff --git a/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt b/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.ktindex 35be9b6..2bf8e8c 100644--- a/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt+++ b/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt@@ -1,10 +1,21 @@package com.gotcha.uiimport android.content.Context+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Rect+import android.graphics.RectF+import android.view.MotionEvent+import android.view.Viewimport androidx.test.core.app.ApplicationProvider+import com.gotcha.service.AnnotatedEntity+import com.gotcha.service.DetectedEntity+import com.gotcha.service.EntityType+import com.gotcha.service.SmartActionimport com.gotcha.ui.theme.Skinsimport com.gotcha.ui.theme.overlaySkinimport org.junit.Assert.assertEquals+import org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@@ -61,4 +72,122 @@ class ScreenCropOverlayViewTest {val vellum = viewFor(Skins.Vellum.id).decorationColors()assertEquals(android.graphics.Color.WHITE, vellum[1])}++ // ---- Annotation chips ----++ private fun annotation(left: Int, top: Int, right: Int, bottom: Int, value: String, groupCount: Int = 1) =+ AnnotatedEntity(+ entity = DetectedEntity(+ type = EntityType.URL,+ rawValue = value,+ normalizedValue = value,+ span = 0..value.length,+ confidence = 0.9f,+ actions = listOf(+ SmartAction(+ label = "🌐 Open: $value",+ prompt = "@@SMART:VIEW|$value",+ isPrimary = true+ )+ )+ ),+ boundsOnScreen = Rect(left, top, right, bottom),+ groupCount = groupCount+ )++ /** A laid-out view that has drawn one frame, so chips have been placed. */+ private fun drawnViewWith(+ entities: List<AnnotatedEntity>,+ onSelected: (String) -> Unit = {}+ ): ScreenCropOverlayView {+ val view = ScreenCropOverlayView(+ context,+ colors = overlaySkin(context, Skins.DEFAULT_ID),+ onSelection = {},+ onCancel = {},+ onAnnotatedEntitySelected = onSelected+ )+ view.measure(+ View.MeasureSpec.makeMeasureSpec(WIDTH, View.MeasureSpec.EXACTLY),+ View.MeasureSpec.makeMeasureSpec(HEIGHT, View.MeasureSpec.EXACTLY)+ )+ view.layout(0, 0, WIDTH, HEIGHT)+ view.setAnnotatedEntities(entities)+ view.draw(Canvas(Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888)))+ return view+ }++ private fun tap(view: View, x: Float, y: Float) {+ for (action in intArrayOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP)) {+ val event = MotionEvent.obtain(0L, 0L, action, x, y, 0)+ view.onTouchEvent(event)+ event.recycle()+ }+ }++ @Test+ fun `chips never overlap each other`() {+ // Rows 30px apart: every chip wants the same strip of screen, which is+ // how the PR list ended up with labels stacked on labels.+ val stacked = (0 until 5).map { i ->+ annotation(40, 300 + i * 30, 400, 320 + i * 30, "example.com/$i")+ }+ val rects = drawnViewWith(stacked).drawnChipRects()+ assertTrue("nothing was drawn at all", rects.isNotEmpty())+ for (i in rects.indices) {+ for (j in i + 1 until rects.size) {+ assertFalse(+ "chip $i and chip $j overlap: ${rects[i]} vs ${rects[j]}",+ RectF.intersects(rects[i], rects[j])+ )+ }+ }+ }++ @Test+ fun `only the top-ranked chip carries the verb`() {+ val view = drawnViewWith(+ listOf(+ annotation(40, 200, 400, 240, "example.com/first"),+ annotation(40, 600, 400, 640, "example.com/second")+ )+ )+ // Both chips found room, so the second one's compact label is what+ // narrowed the bar — not a placement failure.+ assertEquals(2, view.drawnChipRects().size)+ val (first, second) = view.drawnChipRects()+ assertTrue(+ "the compact chip should be narrower than the one carrying 'Open:'",+ second.width() < first.width()+ )+ }++ @Test+ fun `a tap inside nested bounds picks the innermost entity`() {+ // Accessibility bounds nest — a timestamp's bounds can climb to the whole+ // list container. List order used to decide, so the container won.+ var selected: String? = null+ val view = drawnViewWith(+ listOf(+ annotation(0, 0, WIDTH, HEIGHT, "outer-container"),+ annotation(100, 500, 300, 560, "inner-target")+ )+ ) { selected = it }++ tap(view, 200f, 530f)+ assertEquals("@@SMART:VIEW|inner-target", selected)+ }++ @Test+ fun `a grouped annotation is labelled by count`() {+ val view = drawnViewWith(+ listOf(annotation(40, 400, 400, 440, "example.com", groupCount = 7))+ )+ assertEquals(1, view.drawnChipRects().size)+ }++ private companion object {+ const val WIDTH = 1080+ const val HEIGHT = 1920+ }}