package com.cottondb.days import android.app.AlarmManager import android.app.Application import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import androidx.test.core.app.ApplicationProvider import com.cottondb.shell.RebootReceiver import com.cottondb.shell.ReminderReceiver import com.cottondb.shell.Reminders import com.cottondb.shell.core.CottonCore import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.jsonObject import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowAlarmManager import java.io.File /** * Days' alerts proven hard on Android (coordinator, 24 Nov 2026): set on their minute, kept through a kill and a * restart, moved and cleared as the core's plan says, set again when the leave for exact alarms changes, and run after * a background sync. The core is a stand-in that diffs as `reminders.reconcile` does (its own tests prove the plan: * cotton-ffi `phone::reminders::tests`). Every event is invented. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35], application = Application::class) class DaysAlertsHoldTest { private val context = ApplicationProvider.getApplicationContext() private val alarms = context.getSystemService(AlarmManager::class.java) private val repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "apps/registry.json").isFile } /** What the core wants standing: identifier to instant. */ private val wanted = linkedMapOf() private val heldAsked = mutableListOf>() private val core: suspend (String, JsonObject) -> JsonObject = { _, request -> val held = (request["args"]!!.jsonObject["held"] as JsonArray).map { (it as JsonPrimitive).content }.toSet() heldAsked += held val schedule = wanted.filterKeys { it !in held }.map { (id, at) -> """{"identifier":"$id","at":"$at","title":"Invented review","body":"Starts in 10 minutes"}""" } val cancel = held.filter { it.startsWith("cotton:") && it !in wanted }.map { "\"$it\"" } CottonCore.json.parseToJsonElement("""{"schedule":[${schedule.joinToString()}],"cancel":[${cancel.joinToString()}],"noop":${schedule.isEmpty() && cancel.isEmpty()}}""").jsonObject } private fun pass() = runBlocking { Reminders.pass(context, "Asia/Kolkata", core) } private fun standing() = shadowOf(alarms).scheduledAlarms.map { shadowOf(it.operation!!).savedIntent.data!!.schemeSpecificPart }.toSet() private val first = "cotton:event:event-1:20261125T1020" private val firstAt = "2026-11-25T04:50:00Z" @After fun reset() = ShadowAlarmManager.reset() @Test fun an_alert_is_set_on_its_minute_and_survives_the_app_being_killed() { ShadowAlarmManager.setCanScheduleExactAlarms(true) wanted[first] = firstAt pass() val alarm = shadowOf(alarms).scheduledAlarms.single() assertEquals(java.time.Instant.parse(firstAt).toEpochMilli(), alarm.triggerAtMs) assertEquals("exact, waking the phone", AlarmManager.RTC_WAKEUP, alarm.type) assertTrue("allowed while idle", alarm.isAllowWhileIdle) // A process killed (swiped away, or Android reclaiming it) keeps its alarms: they are the system's, and the // next pass finds the alarm standing and changes nothing. pass() assertEquals(setOf(first), heldAsked.last()) assertEquals(1, shadowOf(alarms).scheduledAlarms.size) } @Test fun moved_the_old_alert_goes_and_the_new_one_is_set_and_deleted_it_goes() { ShadowAlarmManager.setCanScheduleExactAlarms(true) wanted[first] = firstAt pass() wanted.clear(); wanted["cotton:event:event-1:20261126T1020"] = "2026-11-26T04:50:00Z" pass() assertEquals(setOf("cotton:event:event-1:20261126T1020"), standing()) assertFalse("the moved alert's PendingIntent goes too", Reminders.standing(context, first)) wanted.clear() pass() assertTrue("a deleted event leaves no alarm", standing().isEmpty()) assertTrue(Reminders.Ledger(context).held().isEmpty()) } @Test fun alarms_android_dropped_are_set_again_not_trusted_from_the_ledger() { ShadowAlarmManager.setCanScheduleExactAlarms(true) wanted[first] = firstAt pass() // A force-stop or an update: Android cancels the app's alarms and PendingIntents, the ledger still names them. shadowOf(alarms).scheduledAlarms.forEach { it.operation!!.cancel() } ShadowAlarmManager.reset() assertEquals(setOf(first), Reminders.Ledger(context).held()) pass() assertEquals("the pass asks with nothing held", emptySet(), heldAsked.last()) assertEquals(setOf(first), standing()) } @Test fun the_leave_for_exact_alarms_changing_sets_every_alarm_again() { ShadowAlarmManager.setCanScheduleExactAlarms(false) wanted[first] = firstAt pass() assertEquals("without leave, the ten-minute window", Reminders.WINDOW, shadowOf(alarms).scheduledAlarms.single().windowLengthMs) ShadowAlarmManager.setCanScheduleExactAlarms(true) pass() assertEquals("granted, nothing counts held", emptySet(), heldAsked.last()) val alarm = shadowOf(alarms).scheduledAlarms.single() assertEquals("and the alert is set on its minute", 0L, alarm.windowLengthMs) assertTrue(alarm.isAllowWhileIdle) } @Test fun a_fired_alert_is_posted_and_no_longer_held() { ShadowAlarmManager.setCanScheduleExactAlarms(true) wanted[first] = firstAt pass() val fired = shadowOf(shadowOf(alarms).scheduledAlarms.single().operation!!).savedIntent ReminderReceiver().onReceive(context, fired) val posted = shadowOf(context.getSystemService(NotificationManager::class.java)).allNotifications.single() assertEquals("Invented review", shadowOf(posted).contentTitle) assertFalse(Reminders.standing(context, first)) assertTrue(Reminders.Ledger(context).held().isEmpty()) } /** RULE: what puts every alarm back is wired: a restart, an update, a clock or zone change, and leave granted; and the background sync runs the pass. */ @Test fun the_alarms_come_back_after_a_restart_and_a_sync_with_the_app_closed() { val manifest = File(repo, "apps/android/app/src/days/AndroidManifest.xml").readText() for (action in listOf( "android.intent.action.BOOT_COMPLETED", "android.intent.action.MY_PACKAGE_REPLACED", "android.intent.action.TIME_SET", "android.intent.action.TIMEZONE_CHANGED", "android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED", )) assertTrue("Days' RebootReceiver hears $action", manifest.contains(action)) val worker = File(repo, "apps/android/shell/src/main/kotlin/com/cottondb/shell/Transfers.kt").readText() .substringAfter("class PassWorker").substringBefore("\n}\n") assertTrue("the background sync's slice runs the reminder pass", worker.contains("app.reminders()")) // The receiver keeps the ledger: what is held is what still stands (a restart drops it, an update keeps it). Reminders.Ledger(context).keep(setOf(first)) RebootReceiver().onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED)) assertEquals(setOf(first), Reminders.Ledger(context).held()) } @Test fun an_alarm_kept_through_an_update_is_cancelled_when_the_core_no_longer_wants_it() { ShadowAlarmManager.setCanScheduleExactAlarms(true) val dayOnly = "cotton:todo:todo-1:20261125T0900" wanted[dayOnly] = "2026-11-25T03:30:00Z" pass() // The update: Android keeps the app's alarms, and the receiver runs the pass again. RebootReceiver().onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED)) wanted.clear() // the new core keeps a day-only to-do quiet pass() assertEquals("the pass asked with the alarm held", setOf(dayOnly), heldAsked.last()) assertTrue("and it is cancelled, not orphaned", standing().isEmpty()) assertFalse(Reminders.standing(context, dayOnly)) } }