Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat: enhance alarm management with system clock app integration and fallback
Durganshu Mishra86e0329a3661
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 9fff911..c7cded9 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -62,6 +62,13 @@<action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent>+ <!-- Needed on API 30+ so set_alarm / delete_alarm can resolve the system clock app. -->+ <intent>+ <action android:name="android.intent.action.SET_ALARM" />+ </intent>+ <intent>+ <action android:name="android.intent.action.DISMISS_ALARM" />+ </intent></queries><applicationdiff --git a/app/src/main/java/com/gotcha/tools/AlarmTool.kt b/app/src/main/java/com/gotcha/tools/AlarmTool.ktindex 3b18b6e..0d98abb 100644--- a/app/src/main/java/com/gotcha/tools/AlarmTool.kt+++ b/app/src/main/java/com/gotcha/tools/AlarmTool.kt@@ -2,11 +2,16 @@ package com.gotcha.toolsimport android.app.AlarmManagerimport android.app.PendingIntent+import android.content.ActivityNotFoundExceptionimport android.content.Contextimport android.content.Intentimport android.content.SharedPreferencesimport android.os.Build+import android.provider.AlarmClock+import java.text.SimpleDateFormatimport java.util.Calendar+import java.util.Date+import java.util.Localeimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObject@@ -19,6 +24,25 @@ import kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.put+/**+ * Hybrid alarm management: alarms are created in the system clock app via+ * [AlarmClock.ACTION_SET_ALARM] when a clock app handles it (so they appear in+ * its alarm list and ring with the full alarm UI), with a shadow record kept in+ * SharedPreferences so list/edit/delete by ID still work. Devices without a+ * compatible clock app fall back to local AlarmManager alarms.+ *+ * Limitations of the delegated path:+ * - Alarms the user creates manually in the clock app cannot be enumerated;+ * only the system-wide next alarm is visible (via getNextAlarmClock).+ * - Editing/deleting a clock-app alarm uses ACTION_DISMISS_ALARM, which is+ * best-effort: some clock apps only disable the alarm or skip the next+ * occurrence of a recurring alarm instead of removing it.+ * - The shadow list desyncs if the user edits Gotcha-created alarms directly+ * in the clock app.+ *+ * Timers always stay local: there is no intent to cancel a running clock-app+ * timer, which would break delete_timer.+ */class AlarmTool(private val context: Context) {private val prefs: SharedPreferences = context.getSharedPreferences("gotcha_alarms", Context.MODE_PRIVATE)@@ -40,25 +64,35 @@ class AlarmTool(private val context: Context) {fun setAlarm(hour: Int, minute: Int, message: String? = null, days: List<String>? = null, vibrate: Boolean? = null): ToolResult {if (hour !in 0..23) return ToolResult.error("Hour must be 0-23.")if (minute !in 0..59) return ToolResult.error("Minute must be 0-59.")- exactAlarmError()?.let { return it }val dayInts = parseDays(days)- val id = nextId++val label = message?.takeIf { it.isNotBlank() }+ val triggerAt = if (dayInts.isEmpty()) nextAlarmTime(hour, minute, dayInts) else null- val record = AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true)+ val dayStr = if (dayInts.isNotEmpty()) " (${days?.joinToString(",")})" else ""+ val extra = buildString {+ if (dayInts.isNotEmpty()) append(" repeating$dayStr")+ if (vibrate == false) append(" silent")+ }++ // Prefer the system clock app so the alarm shows up in its list and+ // rings with the full alarm UI (snooze/dismiss, alarm sound).+ if (dispatchClockIntent(buildSetAlarmIntent(hour, minute, label, dayInts, vibrate ?: true))) {+ val id = nextId+++ saveAlarm(AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true, system = true, triggerAt = triggerAt))+ return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra in the system clock app (id=$id).".format(hour, minute))+ }++ // No compatible clock app — schedule locally via AlarmManager.+ exactAlarmError()?.let { return it }+ val id = nextId+++ val record = AlarmRecord(id, hour, minute, dayInts, label, vibrate ?: true, triggerAt = triggerAt)try {scheduleAlarm(record)} catch (e: SecurityException) {return ToolResult.error(exactAlarmDeniedMessage(e))}saveAlarm(record)-- val dayStr = if (dayInts.isNotEmpty()) " (${days?.joinToString(",")})" else ""- val extra = buildString {- if (dayInts.isNotEmpty()) append(" repeating$dayStr")- if (vibrate == false) append(" silent")- }- return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra (id=$id).".format(hour, minute))+ return ToolResult.ok("Set alarm '$label' for %02d:%02d$extra (id=$id). No clock app handled it, so it was scheduled in-app and rings as a notification.".format(hour, minute))}fun setTimer(seconds: Int, message: String? = null, hours: Int? = null, minutes: Int? = null): ToolResult {@@ -85,21 +119,35 @@ class AlarmTool(private val context: Context) {}fun listAlarms(): ToolResult {- val alarms = loadAlarms()- if (alarms.isEmpty()) return ToolResult.ok("No alarms set.")+ var alarms = loadAlarms()++ // One-shot clock-app alarms that already rang: Gotcha never sees them+ // fire, so prune by stored trigger time instead.+ val now = System.currentTimeMillis()+ val expired = alarms.filter { it.system && it.days.isEmpty() && it.triggerAt != null && it.triggerAt < now }+ if (expired.isNotEmpty()) {+ alarms = alarms - expired.toSet()+ saveAlarms(alarms)+ }+val sb = StringBuilder()- alarms.forEach { a ->- if (!isScheduled(alarmRequestCode(a.id))) {- // Registration was lost (reboot, force-stop) — re-register from storage.- try { scheduleAlarm(a) } catch (_: SecurityException) {}+ if (alarms.isEmpty()) {+ sb.append("No alarms set by this assistant.")+ } else {+ alarms.forEach { a ->+ if (!a.system && !isScheduled(alarmRequestCode(a.id))) {+ // Registration was lost (reboot, force-stop) — re-register from storage.+ try { scheduleAlarm(a) } catch (_: SecurityException) {}+ }+ val dayStr = if (a.days.isNotEmpty()) {+ a.days.mapNotNull { e -> dayNames.entries.firstOrNull { it.value == e }?.key?.take(3) }.joinToString(",")+ } else "once"+ sb.append("- $dayStr %02d:%02d".format(a.hour, a.minute))+ if (a.label != null) sb.append(" ${a.label}")+ sb.append(" (id=${a.id}, ${if (a.system) "clock app" else "in-app"})\n")}- val dayStr = if (a.days.isNotEmpty()) {- a.days.mapNotNull { e -> dayNames.entries.firstOrNull { it.value == e }?.key?.take(3) }.joinToString(",")- } else "once"- sb.append("- $dayStr %02d:%02d".format(a.hour, a.minute))- if (a.label != null) sb.append(" ${a.label}")- sb.append(" (id=${a.id})\n")}+ nextSystemAlarmLine()?.let { sb.append("\n").append(it) }return ToolResult.ok(sb.trimEnd().toString())}@@ -121,17 +169,35 @@ class AlarmTool(private val context: Context) {val alarms = loadAlarmsMutable()val idx = alarms.indexOfFirst { it.id == id }if (idx == -1) return ToolResult.error("Alarm $id not found.")- exactAlarmError()?.let { return it }val old = alarms[idx]+ val newDays = if (days != null) parseDays(days) else old.daysval record = AlarmRecord(id = id,hour = hour ?: old.hour,minute = minute ?: old.minute,- days = if (days != null) parseDays(days) else old.days,+ days = newDays,label = message ?: old.label,- vibrate = vibrate ?: old.vibrate+ vibrate = vibrate ?: old.vibrate,+ system = old.system,+ triggerAt = if (newDays.isEmpty()) nextAlarmTime(hour ?: old.hour, minute ?: old.minute, newDays) else null)++ if (old.system) {+ // No edit intent exists: dismiss the old alarm (best effort) and create a new one.+ dismissSystemAlarm(old)+ if (!dispatchClockIntent(buildSetAlarmIntent(record.hour, record.minute, record.label, record.days, record.vibrate))) {+ return ToolResult.error("Alarm $id lives in the system clock app but no clock app handled the update intent. Edit it in the clock app directly.")+ }+ alarms[idx] = record+ saveAlarms(alarms)+ return ToolResult.ok(+ "Updated alarm $id in the system clock app. The old version was dismissed best-effort — " ++ "if a duplicate or disabled alarm remains, ask the user to remove it in the clock app."+ )+ }++ exactAlarmError()?.let { return it }try {scheduleAlarm(record)} catch (e: SecurityException) {@@ -152,9 +218,20 @@ class AlarmTool(private val context: Context) {fun doDeleteAlarm(id: Long): ToolResult {val alarms = loadAlarmsMutable()- if (alarms.none { it.id == id }) return ToolResult.error("Alarm $id not found.")- cancelPendingIntent(alarmRequestCode(id))+ val a = alarms.firstOrNull { it.id == id } ?: return ToolResult.error("Alarm $id not found.")saveAlarms(alarms.filter { it.id != id })+ if (a.system) {+ val dismissed = dismissSystemAlarm(a)+ return if (dismissed) {+ ToolResult.ok(+ "Deleted alarm $id. It lived in the system clock app, so it was dismissed best-effort — " ++ "some clock apps only disable it or skip the next occurrence; the user can verify in the clock app."+ )+ } else {+ ToolResult.ok("Removed alarm $id from this assistant's list, but no clock app handled the dismiss intent — ask the user to delete it in the clock app.")+ }+ }+ cancelPendingIntent(alarmRequestCode(id))return ToolResult.ok("Deleted alarm $id.")}@@ -174,7 +251,7 @@ class AlarmTool(private val context: Context) {return ToolResult.ok("Deleted timer $id.")}- // ---- firing callbacks (from AlarmReceiver) ----+ // ---- firing callbacks (from AlarmReceiver, local alarms/timers only) ----/** Reschedules a recurring alarm for its next occurrence, or removes a* one-shot alarm from storage so list_alarms stays accurate. */@@ -193,15 +270,16 @@ class AlarmTool(private val context: Context) {saveTimers(loadTimers().filter { it.id != id })}- /** Re-registers everything in storage with AlarmManager and drops expired- * timers. Called after boot, since registrations don't survive a reboot. */+ /** Re-registers local alarms/timers with AlarmManager and drops expired+ * timers. Called after boot, since registrations don't survive a reboot.+ * Clock-app alarms are the clock app's responsibility and are skipped. */fun rescheduleAll() {val now = System.currentTimeMillis()val allTimers = loadTimers()val timers = allTimers.filter { it.triggerAt > now }if (timers.size != allTimers.size) saveTimers(timers)try {- loadAlarms().forEach { scheduleAlarm(it) }+ loadAlarms().filter { !it.system }.forEach { scheduleAlarm(it) }timers.forEach { scheduleTimer(it) }} catch (_: SecurityException) {// Exact-alarm permission was revoked; nothing can be re-registered@@ -209,7 +287,53 @@ class AlarmTool(private val context: Context) {}}- // ---- scheduling ----+ // ---- system clock app delegation ----++ private fun buildSetAlarmIntent(hour: Int, minute: Int, label: String?, dayInts: List<Int>, vibrate: Boolean) =+ Intent(AlarmClock.ACTION_SET_ALARM).apply {+ putExtra(AlarmClock.EXTRA_HOUR, hour)+ putExtra(AlarmClock.EXTRA_MINUTES, minute)+ if (label != null) putExtra(AlarmClock.EXTRA_MESSAGE, label)+ if (dayInts.isNotEmpty()) putExtra(AlarmClock.EXTRA_DAYS, ArrayList(dayInts))+ putExtra(AlarmClock.EXTRA_VIBRATE, vibrate)+ putExtra(AlarmClock.EXTRA_SKIP_UI, true)+ }++ private fun dismissSystemAlarm(a: AlarmRecord): Boolean {+ val intent = Intent(AlarmClock.ACTION_DISMISS_ALARM).apply {+ putExtra(AlarmClock.EXTRA_ALARM_SEARCH_MODE, AlarmClock.ALARM_SEARCH_MODE_TIME)+ putExtra(AlarmClock.EXTRA_HOUR, a.hour)+ putExtra(AlarmClock.EXTRA_MINUTES, a.minute)+ putExtra(AlarmClock.EXTRA_SKIP_UI, true)+ }+ return dispatchClockIntent(intent)+ }++ /** Fires an AlarmClock intent at the clock app. Returns false if no app+ * handles it, so callers can fall back to local scheduling. */+ private fun dispatchClockIntent(intent: Intent): Boolean {+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (intent.resolveActivity(context.packageManager) == null) return false+ return try {+ context.startActivity(intent)+ true+ } catch (_: ActivityNotFoundException) {+ false+ } catch (_: SecurityException) {+ false+ }+ }++ /** The next alarm scheduled system-wide, from any app — the only part of+ * other apps' alarms Android exposes. */+ private fun nextSystemAlarmLine(): String? {+ val next = alarmManager().nextAlarmClock ?: return null+ val time = SimpleDateFormat("EEE MMM d HH:mm", Locale.getDefault()).format(Date(next.triggerTime))+ val pkg = next.showIntent?.creatorPackage+ return "Next system-wide alarm (any app): $time" + (if (pkg != null) " (set by $pkg)" else "")+ }++ // ---- local scheduling ----// Alarms and timers share the next_id counter, so they need disjoint// PendingIntent request-code spaces: positive for alarms, negative for timers.@@ -263,7 +387,8 @@ class AlarmTool(private val context: Context) {private data class AlarmRecord(val id: Long, val hour: Int, val minute: Int,- val days: List<Int>, val label: String?, val vibrate: Boolean+ val days: List<Int>, val label: String?, val vibrate: Boolean,+ val system: Boolean = false, val triggerAt: Long? = null)private data class TimerRecord(@@ -288,6 +413,8 @@ class AlarmTool(private val context: Context) {put("days", daysArr)if (a.label != null) put("label", a.label)put("vibrate", a.vibrate)+ put("system", a.system)+ if (a.triggerAt != null) put("triggerAt", a.triggerAt)})}}@@ -307,7 +434,9 @@ class AlarmTool(private val context: Context) {minute = minute,days = o["days"]?.jsonArray?.mapNotNull { it.jsonPrimitive.intOrNull } ?: emptyList(),label = o["label"]?.jsonPrimitive?.content,- vibrate = o["vibrate"]?.jsonPrimitive?.booleanOrNull ?: true+ vibrate = o["vibrate"]?.jsonPrimitive?.booleanOrNull ?: true,+ system = o["system"]?.jsonPrimitive?.booleanOrNull ?: false,+ triggerAt = o["triggerAt"]?.jsonPrimitive?.content?.toLongOrNull())}.filterNotNull()} catch (_: Exception) { emptyList() }@@ -364,7 +493,14 @@ class AlarmTool(private val context: Context) {private fun parseDays(days: List<String>?): List<Int> {if (days.isNullOrEmpty()) return emptyList()- return days.mapNotNull { d -> dayNames[d.trim().lowercase()] }.distinct()+ return days.flatMap { d ->+ when (val key = d.trim().lowercase()) {+ "weekdays" -> listOf(Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY)+ "weekend", "weekends" -> listOf(Calendar.SATURDAY, Calendar.SUNDAY)+ "daily", "everyday" -> dayNumbers.toList()+ else -> listOfNotNull(dayNames[key])+ }+ }.distinct()}private fun nextAlarmTime(hour: Int, minute: Int, days: List<Int>, skipToday: Boolean = false): Long {diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex 54b37d4..5c67d02 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -550,7 +550,9 @@ object ToolDefinitions {val setAlarm = tool("set_alarm","Set an alarm at a given hour and minute. Supports repeating by day of week and silent mode. " +- "Returns an alarm ID that can be used to edit or delete it later. " ++ "The alarm is created in the system clock app when one is available (visible in its alarm " ++ "list, rings with the full alarm UI); otherwise it falls back to an in-app alarm that rings " ++ "as a notification. Returns an alarm ID that can be used to edit or delete it later. " +"List alarms with list_alarms. Edit with edit_alarm. Delete with delete_alarm.",schema {putJsonObject("properties") {@@ -585,7 +587,8 @@ object ToolDefinitions {val setTimer = tool("set_timer",- "Start a countdown timer. Returns a timer ID that can be used to delete it later. " ++ "Start a countdown timer. Timers are managed in-app (a notification fires when done), not in " ++ "the system clock app. Returns a timer ID that can be used to delete it later. " +"List timers with list_timers. Delete with delete_timer.",schema {putJsonObject("properties") {@@ -882,7 +885,10 @@ object ToolDefinitions {val listAlarms = tool("list_alarms",- "List all active alarms set by set_alarm, with their IDs, times, labels, and recurrence.",+ "List all active alarms set by set_alarm, with their IDs, times, labels, and recurrence, plus " ++ "the next alarm scheduled system-wide by any app. Alarms the user created manually in the " ++ "clock app cannot be enumerated (Android exposes only the single next one); tell the user " ++ "to check the clock app if they ask about alarms not in this list.",schema { putJsonObject("properties") {} })@@ -895,7 +901,9 @@ object ToolDefinitions {val editAlarm = tool("edit_alarm","Edit an existing alarm by ID. Only the fields you provide will be changed. " +- "Get the alarm ID from list_alarms.",+ "Get the alarm ID from list_alarms. For alarms living in the system clock app this is " ++ "done by dismissing the old alarm and creating a new one, which is best-effort — relay " ++ "any caveat in the result to the user.",schema {putJsonObject("properties") {putJsonObject("alarm_id") {@@ -931,7 +939,9 @@ object ToolDefinitions {val deleteAlarm = tool("delete_alarm","Permanently delete an alarm by ID. Requires explicit user confirmation (destructive action). " +- "Get the alarm ID from list_alarms.",+ "Get the alarm ID from list_alarms. For alarms living in the system clock app the delete " ++ "is best-effort (some clock apps only disable the alarm or skip its next occurrence) — " ++ "relay any caveat in the result to the user.",schema {putJsonObject("properties") {putJsonObject("alarm_id") {