Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(lens): open grouped chips, and give calendar events a real start
Durganshu Mishra65613120f106
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 8e5dbeb..46cecee 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -416,6 +416,40 @@ class AssistiveBallService : Service() {* an Android system intent — navigate on a map, open the dialer, or create a* calendar event. Failures are surfaced on the ball's error card.*/+ /**+ * Build the "new event" intent from a `yyyy-MM-dd|HH:mm|title` payload.+ *+ * The date has to be resolved before it gets here: handed the words "Monday"+ * or "Jul 26", a calendar app has nothing to resolve them against and drops+ * the event on today. A payload with no parseable date — anything encoded+ * before this format existed — still opens the composer with a title, which+ * is what the old behaviour was.+ */+ private fun calendarInsertIntent(payload: String): Intent {+ val parts = payload.split(SmartActionDetector.PAYLOAD_SEP, limit = CALENDAR_PAYLOAD_FIELDS)+ val title = parts.getOrNull(2)?.takeIf { it.isNotBlank() } ?: payload+ return Intent(Intent.ACTION_INSERT).apply {+ data = android.provider.CalendarContract.Events.CONTENT_URI+ putExtra(android.provider.CalendarContract.Events.TITLE, title)++ val date = parts.getOrNull(0)+ ?.takeIf { it.isNotBlank() }+ ?.let { runCatching { java.time.LocalDate.parse(it) }.getOrNull() }+ ?: return@apply+ val time = parts.getOrNull(1)+ ?.takeIf { it.isNotBlank() }+ ?.let { runCatching { java.time.LocalTime.parse(it) }.getOrNull() }++ val start = if (time != null) date.atTime(time) else date.atStartOfDay()+ val beginMs = start.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()+ val durationMs = if (time != null) DEFAULT_EVENT_DURATION_MS else DAY_MS+ putExtra(android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginMs)+ putExtra(android.provider.CalendarContract.EXTRA_EVENT_END_TIME, beginMs + durationMs)+ // A day with no clock time is an all-day event, not one starting at midnight.+ putExtra(android.provider.CalendarContract.EXTRA_EVENT_ALL_DAY, time == null)+ }+ }+private fun handleNativeAction(prompt: String) {val decoded = SmartActionDetector.decode(prompt) ?: returnval (type, payload) = decoded@@ -425,11 +459,7 @@ class AssistiveBallService : Service() {Intent(Intent.ACTION_VIEW, android.net.Uri.parse("geo:0,0?q=" + android.net.Uri.encode(payload)))SmartActionDetector.TYPE_DIAL ->Intent(Intent.ACTION_DIAL, android.net.Uri.parse("tel:" + android.net.Uri.encode(payload)))- SmartActionDetector.TYPE_CALENDAR ->- Intent(Intent.ACTION_INSERT).apply {- data = android.provider.CalendarContract.Events.CONTENT_URI- putExtra(android.provider.CalendarContract.Events.TITLE, payload)- }+ SmartActionDetector.TYPE_CALENDAR -> calendarInsertIntent(payload)SmartActionDetector.TYPE_SMS ->Intent(Intent.ACTION_SENDTO, android.net.Uri.parse("smsto:" + android.net.Uri.encode(payload)))SmartActionDetector.TYPE_VIEW ->@@ -930,6 +960,11 @@ class AssistiveBallService : Service() {/** Cap on fetched page text handed to the LLM for link summarization. */private const val MAX_FETCH_CHARS = 12000+ /** `date|time|title` — see [calendarInsertIntent]. */+ private const val CALENDAR_PAYLOAD_FIELDS = 3+ private const val DEFAULT_EVENT_DURATION_MS = 60L * 60L * 1000L+ private const val DAY_MS = 24L * 60L * 60L * 1000L+@Volatilevar instance: AssistiveBallService? = nullprivate setdiff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex d86373f..134b682 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -406,7 +406,7 @@ class GotchaAccessibilityService : AccessibilityService() {return selected.mapNotNull { candidate ->val bounds = placeable.firstOrNull { it.entity === candidate.entity }?.boundsOnScreen?: return@mapNotNull null- AnnotatedEntity(candidate.entity, bounds, candidate.groupCount)+ AnnotatedEntity(candidate.entity, bounds, candidate.members)}}diff --git a/app/src/main/java/com/gotcha/service/ScreenLensController.kt b/app/src/main/java/com/gotcha/service/ScreenLensController.ktindex 8178e6e..4f0f9ba 100644--- a/app/src/main/java/com/gotcha/service/ScreenLensController.kt+++ b/app/src/main/java/com/gotcha/service/ScreenLensController.kt@@ -93,6 +93,18 @@ class ScreenLensController(onAnnotatedEntitySelected = { prompt ->cancel()onContextualAction(prompt)+ },+ // A grouped chip opens its members instead of firing one of them.+ // The Lens overlay stays up behind the menu: picking from a list+ // of prices is a choice, and closing the thing they are listed on+ // would leave nothing to choose against.+ onAnnotatedGroupSelected = { group ->+ showActionMenu(+ group.members+ .mapNotNull { it.primaryAction }+ .distinctBy { it.prompt }+ .take(MAX_GROUP_MENU_ITEMS)+ )})overlay.setAnnotatedEntities(annotatedEntities)@@ -622,6 +634,9 @@ class ScreenLensController(const val CHIP_ICON_DP = 18const val CHIP_ICON_GAP_DP = 3const val MENU_WIDTH_DP = 240++ /** Cap on a grouped chip's menu — past this it is a list, not a choice. */+ const val MAX_GROUP_MENU_ITEMS = 8const val GAP_DP = 12const val EDGE_MARGIN_DP = 12}diff --git a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt b/app/src/main/java/com/gotcha/service/SmartActionDetector.ktindex 8aa4da8..5ff264a 100644--- a/app/src/main/java/com/gotcha/service/SmartActionDetector.kt+++ b/app/src/main/java/com/gotcha/service/SmartActionDetector.kt@@ -2,6 +2,7 @@ package com.gotcha.serviceimport java.time.DayOfWeekimport java.time.LocalDate+import java.time.LocalTimeimport java.util.regex.Pattern/**@@ -79,17 +80,26 @@ data class DetectedEntity(data class AnnotatedEntity(val entity: DetectedEntity,val boundsOnScreen: android.graphics.Rect,- val groupCount: Int = 1-)+ /** Every detection the chip stands for, [entity] included. */+ val members: List<DetectedEntity> = listOf(entity)+) {+ val groupCount: Int get() = members.size+}/**- * An entity that survived annotation ranking, with the number of detections it- * represents.+ * An entity that survived annotation ranking, together with the detections it+ * was chosen to represent.+ *+ * [members] is carried rather than a bare count so a tap on "12 prices" can open+ * all twelve. A chip that promises a group and delivers one of them is worse+ * than not grouping at all.*/data class AnnotationCandidate(val entity: DetectedEntity,- val groupCount: Int = 1-)+ val members: List<DetectedEntity> = listOf(entity)+) {+ val groupCount: Int get() = members.size+}/*** Lightweight text scanner that recognises structured data types — physical@@ -137,6 +147,8 @@ object SmartActionDetector {private const val CONFIDENCE_EVENT_BARE_TIME = 0.5fprivate const val CHIP_LABEL_MAX = 18private const val DAYS_IN_WEEK = 7+ private const val HOURS_ON_A_CLOCK = 12+ private const val MAX_MINUTE = 59/*** Street addresses: supports single-line and multi-line house numbers, street names,@@ -216,6 +228,11 @@ object SmartActionDetector {Pattern.CASE_INSENSITIVE)+ private val timeOfDayPattern: Pattern = Pattern.compile(+ "\\b(\\d{1,2})(?::(\\d{2}))?\\s?([ap])\\.?\\s?m\\.?",+ Pattern.CASE_INSENSITIVE+ )+/*** Enhanced URL pattern supporting scheme, bare domain/www, query params, ports, IP addresses.*/@@ -383,14 +400,14 @@ object SmartActionDetector {}val unique = byValue.values.mapNotNull { group ->val best = group.maxByOrNull { calculateScore(it) } ?: return@mapNotNull null- AnnotationCandidate(best, group.size)+ AnnotationCandidate(best, group)}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) {+ val occurrences = ranked.flatMap { it.members }+ if (occurrences.size >= repetitionThreshold) {kept.add(AnnotationCandidate(ranked.first().entity, occurrences))} else {kept.addAll(ranked.take(maxPerType))@@ -753,6 +770,40 @@ object SmartActionDetector {return null}+ /** The clock time named in [event], or null when it names only a day. */+ internal fun timeOfDayOf(event: String): LocalTime? {+ val m = timeOfDayPattern.matcher(event)+ if (!m.find()) return null+ val rawHour = m.group(1)?.toIntOrNull() ?: return null+ if (rawHour !in 1..HOURS_ON_A_CLOCK) return null+ val minute = m.group(2)?.toIntOrNull() ?: 0+ if (minute !in 0..MAX_MINUTE) return null+ val pm = m.group(3)?.lowercase() == "p"+ val hour = when {+ rawHour == HOURS_ON_A_CLOCK && !pm -> 0+ rawHour == HOURS_ON_A_CLOCK -> HOURS_ON_A_CLOCK+ pm -> rawHour + HOURS_ON_A_CLOCK+ else -> rawHour+ }+ return runCatching { LocalTime.of(hour, minute) }.getOrNull()+ }++ /**+ * The calendar payload: `yyyy-MM-dd|HH:mm|title`, either of the first two+ * fields blank when the text did not say.+ *+ * The date is carried resolved rather than raw because the receiving app+ * cannot resolve it — handed "Monday", a calendar has no idea which one, and+ * the event lands on today. Left as text rather than epoch millis so the+ * detector stays free of a timezone.+ */+ private fun calendarPayload(event: String, date: LocalDate?, time: LocalTime?): String =+ listOf(+ date?.toString().orEmpty(),+ time?.toString().orEmpty(),+ event+ ).joinToString(PAYLOAD_SEP)+private fun detectCalendars(text: String, out: MutableList<DetectedEntity>, today: LocalDate) {val m = calendarPattern.matcher(text)while (m.find()) {@@ -778,7 +829,7 @@ object SmartActionDetector {val actions = listOf(SmartAction(label = "📅 Add to calendar: ${snippet(event, 24)}",- prompt = encode(TYPE_CALENDAR, event),+ prompt = encode(TYPE_CALENDAR, calendarPayload(event, date, timeOfDayOf(event))),actionType = ActionType.NATIVE_CALENDAR,isPrimary = true),diff --git a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.ktindex 8a14ca5..e5b3840 100644--- a/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt+++ b/app/src/main/java/com/gotcha/ui/ScreenCropOverlayView.kt@@ -46,7 +46,8 @@ class ScreenCropOverlayView(private val onSelection: (Rect) -> Unit,private val onCancel: () -> Unit,private val onReselectStart: () -> Unit = {},- private val onAnnotatedEntitySelected: (prompt: String) -> Unit = {}+ private val onAnnotatedEntitySelected: (prompt: String) -> Unit = {},+ private val onAnnotatedGroupSelected: (AnnotatedEntity) -> Unit = {}) : View(context) {private val density = resources.displayMetrics.density@@ -604,9 +605,8 @@ class ScreenCropOverlayView(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+ val item = hit.item ?: continue+ if (fireAnnotation(item)) return true}getLocationOnScreen(scratchLocation)@@ -633,7 +633,20 @@ class ScreenCropOverlayView(}}- val prompt = best?.entity?.primaryAction?.prompt ?: return false+ return fireAnnotation(best ?: return false)+ }++ /**+ * Act on [item]: run its action, or open the group when the chip stands for+ * more than one detection. "12 prices" that converts a single price is a+ * chip lying about what it is.+ */+ private fun fireAnnotation(item: AnnotatedEntity): Boolean {+ if (item.groupCount > 1) {+ onAnnotatedGroupSelected(item)+ return true+ }+ val prompt = item.entity.primaryAction?.prompt ?: return falseonAnnotatedEntitySelected(prompt)return true}diff --git a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.ktindex ebe1b77..4108c89 100644--- a/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt+++ b/app/src/test/java/com/gotcha/service/SmartActionDetectorTest.kt@@ -471,4 +471,56 @@ class SmartActionDetectorTest {fun `selectForAnnotation on an empty list is empty`() {assertTrue(SmartActionDetector.selectForAnnotation(emptyList()).isEmpty())}++ @Test+ fun `a grouped candidate carries every member, not just a count`() {+ val catalogue = (1..12).joinToString("\n") { "Item $it — €${it * 10}.00" }+ val entities = SmartActionDetector.detectAll(catalogue)+ val grouped = SmartActionDetector.selectForAnnotation(entities)+ .first { it.entity.type == EntityType.CURRENCY }++ assertEquals(grouped.groupCount, grouped.members.size)+ assertTrue("the representative must be one of its own members", grouped.entity in grouped.members)+ assertTrue(+ "every member needs an action, or the group menu has dead rows",+ grouped.members.all { it.primaryAction != null }+ )+ // Distinct prices, so the menu is twelve real choices rather than one repeated.+ assertEquals(grouped.members.size, grouped.members.map { it.normalizedValue }.distinct().size)+ }++ // ---- Calendar payloads carry a resolved start ----++ private fun calendarPayload(text: String, today: LocalDate): String {+ val entity = SmartActionDetector.detectAll(text, today = today)+ .first { it.type == EntityType.CALENDAR }+ return SmartActionDetector.decode(entity.primaryAction!!.prompt)!!.second+ }++ @Test+ fun `a dated event carries the resolved day and time`() {+ val payload = calendarPayload("Design review Aug 14, 2026 at 9:30 a.m.", LocalDate.of(2026, 8, 1))+ val parts = payload.split("|", limit = 3)+ assertEquals("2026-08-14", parts[0])+ assertEquals("09:30", parts[1])+ assertTrue("the title should survive", parts[2].contains("Aug 14"))+ }++ @Test+ fun `an event with no clock time leaves the time field blank`() {+ val payload = calendarPayload("Team meeting on Monday", LocalDate.of(2026, 8, 5))+ val parts = payload.split("|", limit = 3)+ // Wednesday Aug 5 → the coming Monday. A calendar app handed the word+ // "Monday" would have dropped this on today instead.+ assertEquals("2026-08-10", parts[0])+ assertEquals("", parts[1])+ }++ @Test+ fun `midday and midnight convert correctly`() {+ assertEquals(java.time.LocalTime.of(12, 0), SmartActionDetector.timeOfDayOf("lunch at 12 pm"))+ assertEquals(java.time.LocalTime.of(0, 30), SmartActionDetector.timeOfDayOf("12:30 am"))+ assertEquals(java.time.LocalTime.of(15, 0), SmartActionDetector.timeOfDayOf("3 p.m."))+ assertNull(SmartActionDetector.timeOfDayOf("sometime Monday"))+ }}diff --git a/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt b/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.ktindex 2bf8e8c..7f396d2 100644--- a/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt+++ b/app/src/test/java/com/gotcha/ui/ScreenCropOverlayViewTest.kt@@ -16,6 +16,7 @@ import com.gotcha.ui.theme.Skinsimport com.gotcha.ui.theme.overlaySkinimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalse+import org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@@ -75,37 +76,41 @@ class ScreenCropOverlayViewTest {// ---- Annotation chips ----+ private fun urlEntity(value: String) = 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+ )+ )+ )+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- )- )- ),+ entity = urlEntity(value),boundsOnScreen = Rect(left, top, right, bottom),- groupCount = groupCount+ members = (0 until groupCount).map { urlEntity(if (it == 0) value else "$value-$it") })/** A laid-out view that has drawn one frame, so chips have been placed. */private fun drawnViewWith(entities: List<AnnotatedEntity>,- onSelected: (String) -> Unit = {}+ onSelected: (String) -> Unit = {},+ onGroupSelected: (AnnotatedEntity) -> Unit = {}): ScreenCropOverlayView {val view = ScreenCropOverlayView(context,colors = overlaySkin(context, Skins.DEFAULT_ID),onSelection = {},onCancel = {},- onAnnotatedEntitySelected = onSelected+ onAnnotatedEntitySelected = onSelected,+ onAnnotatedGroupSelected = onGroupSelected)view.measure(View.MeasureSpec.makeMeasureSpec(WIDTH, View.MeasureSpec.EXACTLY),@@ -171,19 +176,48 @@ class ScreenCropOverlayViewTest {listOf(annotation(0, 0, WIDTH, HEIGHT, "outer-container"),annotation(100, 500, 300, 560, "inner-target")- )- ) { selected = it }+ ),+ onSelected = { selected = it }+ )tap(view, 200f, 530f)assertEquals("@@SMART:VIEW|inner-target", selected)}@Test- fun `a grouped annotation is labelled by count`() {+ fun `tapping a grouped chip opens the group, not one of its members`() {+ // A chip reading "7 links" that follows a single link is lying about what+ // it is — the whole point of collapsing is that the rest stay reachable.+ var single: String? = null+ var group: AnnotatedEntity? = nullval view = drawnViewWith(- listOf(annotation(40, 400, 400, 440, "example.com", groupCount = 7))+ listOf(annotation(40, 400, 400, 440, "example.com", groupCount = 7)),+ onSelected = { single = it },+ onGroupSelected = { group = it })- assertEquals(1, view.drawnChipRects().size)++ val chip = view.drawnChipRects().single()+ tap(view, chip.centerX(), chip.centerY())++ assertNull("a grouped chip must not fire a member's action", single)+ assertEquals(7, group?.members?.size)+ }++ @Test+ fun `tapping an ungrouped chip fires its action directly`() {+ var single: String? = null+ var group: AnnotatedEntity? = null+ val view = drawnViewWith(+ listOf(annotation(40, 400, 400, 440, "example.com")),+ onSelected = { single = it },+ onGroupSelected = { group = it }+ )++ val chip = view.drawnChipRects().single()+ tap(view, chip.centerX(), chip.centerY())++ assertEquals("@@SMART:VIEW|example.com", single)+ assertNull(group)}private companion object {