package com.cottondb.daysimport android.app.AlarmManagerimport android.app.Applicationimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Intentimport androidx.test.core.app.ApplicationProviderimport com.cottondb.shell.RebootReceiverimport com.cottondb.shell.ReminderReceiverimport com.cottondb.shell.Remindersimport com.cottondb.shell.core.CottonCoreimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.jsonObjectimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.Shadows.shadowOfimport org.robolectric.annotation.Configimport org.robolectric.shadows.ShadowAlarmManagerimport 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)classDaysAlertsHoldTest {privateval context = ApplicationProvider.getApplicationContext<Application>()privateval alarms = context.getSystemService(AlarmManager::class.java)privateval repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "apps/registry.json").isFile }/** What the core wants standing: identifier to instant. */privateval wanted = linkedMapOf<String, String>()privateval heldAsked = mutableListOf<Set<String>>()privateval core: suspend (String, JsonObject) -> JsonObject = { _, request ->val held = (request["args"]!!.jsonObject["held"] asJsonArray).map { (it asJsonPrimitive).content }.toSet() heldAsked += heldval 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 }privatefun pass() = runBlocking { Reminders.pass(context, "Asia/Kolkata", core) }privatefun standing() = shadowOf(alarms).scheduledAlarms.map { shadowOf(it.operation!!).savedIntent.data!!.schemeSpecificPart }.toSet()privateval first = "cotton:event:event-1:20261125T1020"privateval 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<String>(), 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<String>(), 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!!).savedIntentReminderReceiver().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)) }}