// The alarm reconciler and its gate, ported from // // The rules these pin are the ones a port loses quietly: which backend gets // swept, what an UNKNOWN actual set means, and the two halves of "a one-shot // that is gone has usually fired". import CottonKit import CottonValues import XCTest @testable import CottonUI private func cal(_ zone: String) -> Calendar { var out = Calendar(identifier: .gregorian) out.timeZone = TimeZone(identifier: zone)! out.locale = Locale(identifier: "en_US_POSIX") return out } private let ist = cal("Asia/Kolkata") private func at(_ iso: String) -> Date { CottonDate.parse(iso, calendar: ist)! } /// Synthetic throughout: an id of zeroes and a word nobody said. private func alarm( _ id: String, hour: Int = 7, minute: Int = 30, days: [Int] = [], enabled: Bool = true, label: String = "", sound: Bool = true ) -> Alarm { var out = Alarm() out.id = id out.hour = hour out.minute = minute out.repeatDays = days out.enabled = enabled out.label = label out.sound = sound return out } private func input( _ alarms: [Alarm], backend: AlarmBackend = .alarmkit, alarmKit: [String]? = [], notifications: [String]? = [], ledger: AlarmLedger = [:], canSchedule: Bool = true, now: Date = at("2026-09-09T06:00:00+05:30") ) -> ReconcileInput { ReconcileInput( alarms: alarms, backend: backend, actualAlarmKitIds: alarmKit, actualNotificationKeys: notifications, ledger: ledger, canSchedule: canSchedule, now: now, calendar: ist ) } final class AlarmPlanTests: XCTestCase { // ── planAlarms and the signature ────────────────────────────────────── func testDesiresOnlyEnabledAlarms() { let planned = planAlarms([alarm("a"), alarm("b", enabled: false)], backend: .alarmkit) XCTAssertEqual(planned.map(\.id), ["a"]) } func testNormalizesRepeatDaysSoAReorderIsNotAChange() { let one = alarmSignature(alarm("a", days: [3, 1, 1]), backend: .alarmkit) let two = alarmSignature(alarm("a", days: [1, 3]), backend: .alarmkit) XCTAssertEqual(one, two) } func testTheBackendIsPartOfTheSignatureSoAFlipReschedulesEverything() { XCTAssertNotEqual( alarmSignature(alarm("a"), backend: .alarmkit), alarmSignature(alarm("a"), backend: .notification) ) } func testSilencingAnAlarmMovesItsSignatureSoThePhoneIsTold() { // Neither backend will say what an already-scheduled alarm SOUNDS // like, so without this the switch would be a row edit the device // never heard about until the person also moved the time. XCTAssertNotEqual( alarmSignature(alarm("a", sound: true), backend: .notification), alarmSignature(alarm("a", sound: false), backend: .notification) ) } // ── the fallback's keys ─────────────────────────────────────────────── func testAOneShotIsOneKeyAndARepeatIsOnePerWeekday() { // iOS repeats a calendar trigger on a SINGLE weekday, so a Mon/Wed // alarm is two standing requests. let one = planAlarms([alarm("a")], backend: .notification)[0] XCTAssertEqual(fallbackKeys(one), ["cotton:alarm:a"]) let many = planAlarms([alarm("b", days: [1, 3])], backend: .notification)[0] XCTAssertEqual(fallbackKeys(many), ["cotton:alarm:b:1", "cotton:alarm:b:3"]) } func testTheNamespaceClaimsOnlyItsOwn() { XCTAssertTrue(isAlarmKey("cotton:alarm:a")) XCTAssertFalse(isAlarmKey("cotton:todo:a")) XCTAssertFalse(isAlarmKey("alarm:a")) } func testRotatesIsoOntoApplesSundayFirstNumbering() { // Getting this wrong fires Monday's alarm on Sunday — silent, and once // a week. XCTAssertEqual([1, 2, 3, 4, 5, 6, 7].map(isoToAppleWeekday), [2, 3, 4, 5, 6, 7, 1]) } // ── nextOneShotAt ───────────────────────────────────────────────────── func testAOneShotIsLaterTodayWhenItsTimeIsStillAhead() { let now = at("2026-09-09T06:00:00+05:30") XCTAssertEqual( nextOneShotAt(hour: 7, minute: 30, now: now, calendar: ist), at("2026-09-09T07:30:00+05:30") ) } func testAOneShotRollsToTomorrowOnceItsTimeHasPassedAndAtTheExactMinute() { // Exactly now must roll over: an alarm for the instant the pass ran is // an alarm that has already had its moment. XCTAssertEqual( nextOneShotAt(hour: 7, minute: 30, now: at("2026-09-09T08:00:00+05:30"), calendar: ist), at("2026-09-10T07:30:00+05:30") ) XCTAssertEqual( nextOneShotAt(hour: 7, minute: 30, now: at("2026-09-09T07:30:00+05:30"), calendar: ist), at("2026-09-10T07:30:00+05:30") ) } // ── the diff ────────────────────────────────────────────────────────── func testSchedulesANewAlarmOntoTheBackendThatIsLive() { let loud = reconcileAlarms(input([alarm("a")])) XCTAssertEqual(loud.scheduleAlarmKit.map(\.id), ["a"]) XCTAssertTrue(loud.scheduleNotifications.isEmpty) let quiet = reconcileAlarms(input([alarm("a")], backend: .notification)) XCTAssertEqual(quiet.scheduleNotifications.map(\.id), ["a"]) XCTAssertTrue(quiet.scheduleAlarmKit.isEmpty) } func testDoesNothingWhenTheDeviceAlreadyMatchesTheLedger() { let row = alarm("a") let ledger = ["a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .alarmkit), firesAt: 1)] let plan = reconcileAlarms(input([row], alarmKit: ["a"], ledger: ledger)) XCTAssertTrue(plan.scheduleAlarmKit.isEmpty) XCTAssertTrue(plan.cancelAlarmKit.isEmpty) } func testReschedulesWhenTheTimeMovedEvenThoughTheIdIsStillLive() { // Neither backend says what a scheduled alarm SAYS, so an edit is // invisible by id. The signature is the whole defence. let ledger = ["a": AlarmLedgerEntry(signature: "alarmkit|7|30||sound|")] let plan = reconcileAlarms(input([alarm("a", minute: 45)], alarmKit: ["a"], ledger: ledger)) XCTAssertEqual(plan.scheduleAlarmKit.map(\.id), ["a"]) } func testHealsADeviceWhoseAlarmsWereWipedWhileTheLedgerLookedFine() { let row = alarm("a", days: [1]) let ledger = ["a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .alarmkit))] let plan = reconcileAlarms(input([row], alarmKit: [], ledger: ledger)) XCTAssertEqual(plan.scheduleAlarmKit.map(\.id), ["a"]) } func testCancelsADisabledAlarmRatherThanJustSkippingIt() { let plan = reconcileAlarms(input([alarm("a", enabled: false)], alarmKit: ["a"])) XCTAssertEqual(plan.cancelAlarmKit, ["a"]) XCTAssertTrue(plan.scheduleAlarmKit.isEmpty) } func testCancelsAnAlarmThatWasDeletedOutright() { let plan = reconcileAlarms(input([], alarmKit: ["gone"])) XCTAssertEqual(plan.cancelAlarmKit, ["gone"]) } func testSweepsTheFallbacksLeftoversWhenPermissionPromotesItToTheLoudPath() { // Granting permission mid-life flips the backend. Without the sweep the // person gets a ring AND a buzz. let plan = reconcileAlarms( input([alarm("a", days: [1, 3])], notifications: ["cotton:alarm:a:1", "cotton:alarm:a:3"]) ) XCTAssertEqual(plan.scheduleAlarmKit.map(\.id), ["a"]) XCTAssertEqual(plan.cancelNotifications.sorted(), ["cotton:alarm:a:1", "cotton:alarm:a:3"]) } func testSweepsAlarmKitWhenPermissionIsRevokedAndTheFallbackTakesOver() { let plan = reconcileAlarms(input([alarm("a")], backend: .notification, alarmKit: ["a"])) XCTAssertEqual(plan.cancelAlarmKit, ["a"]) XCTAssertEqual(plan.scheduleNotifications.map(\.id), ["a"]) } func testNeverCancelsAnotherPartOfTheAppsOwnReminders() { // A reconciler that cancelled "everything not in my desired set" would // silently delete every todo, event and birthday reminder in the tray. let plan = reconcileAlarms( input( [alarm("a")], backend: .notification, notifications: ["cotton:todo:t1", "cotton:event:e1", "cotton:alarm:old"] ) ) XCTAssertEqual(plan.cancelNotifications, ["cotton:alarm:old"]) } func testTreatsAnUnknownActualSetAsUnknownRatherThanEmpty() { // With a set we could not read, nothing is provably absent — so only a // signature change acts. Reading `nil` as empty would rewrite the // person's alarms on every single foreground. let row = alarm("a") let ledger = ["a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .alarmkit))] let plan = reconcileAlarms(input([row], alarmKit: nil, ledger: ledger)) XCTAssertTrue(plan.scheduleAlarmKit.isEmpty) XCTAssertTrue(plan.cancelAlarmKit.isEmpty) } func testStillSchedulesAChangedAlarmWhenTheActualSetIsUnknown() { let plan = reconcileAlarms(input([alarm("a")], alarmKit: nil, ledger: ["a": AlarmLedgerEntry(signature: "stale")])) XCTAssertEqual(plan.scheduleAlarmKit.map(\.id), ["a"]) } func testReschedulesAFallbackAlarmWhenOneOfItsWeekdayKeysWentMissing() { // Every key it needs must be there. One missing weekday is a Wednesday // that silently stops happening. let row = alarm("a", days: [1, 3]) let ledger = ["a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .notification))] let plan = reconcileAlarms( input([row], backend: .notification, notifications: ["cotton:alarm:a:1"], ledger: ledger) ) XCTAssertEqual(plan.scheduleNotifications.map(\.id), ["a"]) } // ── the gate, inside the diff ───────────────────────────────────────── func testDesiresNothingAndRecordsNothingWhenTheDeviceWillNotRing() { // Recording nothing is the load-bearing half: it is what makes the // whole set re-plan the moment the gate opens again. The bug before the // rewrite was exactly this — a signature recorded as done for an alarm // iOS had filed in a queue it would never present, so no later pass // repaired it, not even after the person granted permission. let plan = reconcileAlarms(input([alarm("a")], canSchedule: false)) XCTAssertTrue(plan.scheduleAlarmKit.isEmpty) XCTAssertTrue(plan.scheduleNotifications.isEmpty) XCTAssertTrue(plan.nextLedger.isEmpty) } func testSweepsTheDeviceWhenThePersonSwitchesAlarmsOff() { let plan = reconcileAlarms( input( [alarm("a")], backend: .notification, alarmKit: ["a"], notifications: ["cotton:alarm:a"], canSchedule: false ) ) XCTAssertEqual(plan.cancelAlarmKit, ["a"]) XCTAssertEqual(plan.cancelNotifications, ["cotton:alarm:a"]) } func testStillNeverTouchesAnotherEnginesRemindersWithTheGateShut() { let plan = reconcileAlarms( input( [alarm("a")], backend: .notification, notifications: ["cotton:todo:t1", "cotton:alarm:a"], canSchedule: false ) ) XCTAssertEqual(plan.cancelNotifications, ["cotton:alarm:a"]) } // ── a one-shot that has fired ───────────────────────────────────────── func testAFiredOneShotIsNotReArmedAndIsReportedSoTheRowGetsSwitchedOff() { // Read as merely "missing", every one-shot the person ever set gets // re-armed on the next foreground — for the next day, and the day after // that, for ever. "Wake me once" would become a daily alarm. let now = at("2026-09-09T08:00:00+05:30") let row = alarm("a") let ledger = [ "a": AlarmLedgerEntry( signature: alarmSignature(row, backend: .notification), firesAt: Int(at("2026-09-09T07:30:00+05:30").timeIntervalSince1970 * 1000) ) ] let plan = reconcileAlarms( input([row], backend: .notification, notifications: [], ledger: ledger, now: now) ) XCTAssertEqual(plan.firedOnce, ["a"]) XCTAssertTrue(plan.scheduleNotifications.isEmpty) // The entry is KEPT, so a failed switch-off is retried next pass rather // than re-arming the alarm. XCTAssertNotNil(plan.nextLedger["a"]?.firesAt) } func testAOneShotIsReArmedWhenItsFireTimeIsStillAheadBecauseThatIsAWipedDevice() { let now = at("2026-09-09T06:00:00+05:30") let row = alarm("a") let ledger = [ "a": AlarmLedgerEntry( signature: alarmSignature(row, backend: .notification), firesAt: Int(at("2026-09-09T07:30:00+05:30").timeIntervalSince1970 * 1000) ) ] let plan = reconcileAlarms( input([row], backend: .notification, notifications: [], ledger: ledger, now: now) ) XCTAssertEqual(plan.scheduleNotifications.map(\.id), ["a"]) XCTAssertTrue(plan.firedOnce.isEmpty) } func testAOneShotEditedAfterItFiredIsReArmedRatherThanReported() { let now = at("2026-09-09T08:00:00+05:30") let ledger = [ "a": AlarmLedgerEntry( signature: "notification|7|30||sound|", firesAt: Int(at("2026-09-09T07:30:00+05:30").timeIntervalSince1970 * 1000) ) ] let plan = reconcileAlarms( input([alarm("a", minute: 45)], backend: .notification, notifications: [], ledger: ledger, now: now) ) XCTAssertEqual(plan.scheduleNotifications.map(\.id), ["a"]) XCTAssertTrue(plan.firedOnce.isEmpty) } func testARepeatingAlarmWhoseKeyIsGoneIsReArmedBecauseItCannotHaveFiredAway() { // A weekly trigger never leaves the queue on its own, so absent really // does mean wiped. let now = at("2026-09-09T08:00:00+05:30") let row = alarm("a", days: [1, 3]) let ledger = ["a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .notification))] let plan = reconcileAlarms( input([row], backend: .notification, notifications: [], ledger: ledger, now: now) ) XCTAssertEqual(plan.scheduleNotifications.map(\.id), ["a"]) XCTAssertTrue(plan.firedOnce.isEmpty) } func testAnIdlePassDoesNotPushAOneShotsFireTimeForward() { // Recomputing `firesAt` on an unchanged alarm would push it forward // every pass, so it would never be in the past and the rule above would // never fire — the bug that rule exists to fix, reintroduced by a line // of stale-looking housekeeping. let row = alarm("a") let fires = Int(at("2026-09-09T07:30:00+05:30").timeIntervalSince1970 * 1000) let ledger = [ "a": AlarmLedgerEntry(signature: alarmSignature(row, backend: .notification), firesAt: fires) ] let plan = reconcileAlarms( input( [row], backend: .notification, notifications: ["cotton:alarm:a"], ledger: ledger, now: at("2026-09-09T06:00:00+05:30") ) ) XCTAssertEqual(plan.nextLedger["a"]?.firesAt, fires) } } // ── the gate itself ───────────────────────────────────────────────────────── private struct StubPreferences: AlarmPreferences { var alarmsEnabled: Bool } private struct StubAuthorizer: AlarmAuthorizer { var available: Bool var alarmKit: AlarmAuthorization var notifications: AlarmAuthorization /// Set when the gate asked the notification permission — the loud path must /// never ask it. final class Asked: @unchecked Sendable { var value = false } var asked = Asked() /// Set when AlarmKit's prompt was raised — at most once, and only when due. var requested = Asked() func alarmKitAvailable() -> Bool { available } func alarmKitAuthorization() async -> AlarmAuthorization { alarmKit } func requestAlarmKitAuthorization() async -> AlarmAuthorization { requested.value = true return .authorized } func notificationAuthorization() async -> AlarmAuthorization { asked.value = true return notifications } } final class AlarmGateTests: XCTestCase { private func gate( alarmsOn: Bool = true, available: Bool = false, alarmKit: AlarmAuthorization = .unavailable, notifications: AlarmAuthorization = .authorized ) async -> (AlarmGate, StubAuthorizer) { let authorizer = StubAuthorizer( available: available, alarmKit: alarmKit, notifications: notifications ) let resolved = await resolveAlarmGate( preferences: StubPreferences(alarmsEnabled: alarmsOn), authorizer: authorizer ) return (resolved, authorizer) } func testOpensWhenTheFallbackIsLiveAndNotificationsAreAllowed() async { let (out, _) = await gate() XCTAssertEqual(out.backend, .notification) XCTAssertTrue(out.canSchedule) XCTAssertNil(out.silence) } func testShutsWhenTheNotificationPermissionWasNeverAskedFor() async { let (out, _) = await gate(notifications: .notDetermined) XCTAssertFalse(out.canSchedule) XCTAssertEqual(out.silence, .permissionUndetermined) } func testTellsARefusedPermissionFromAnUnaskedOne() async { // iOS never re-prompts a refusal, so the two need different sentences: // one is a tap in the app, the other is a trip to Settings. let (out, _) = await gate(notifications: .denied) XCTAssertEqual(out.silence, .permissionDenied) } func testShutsOnThePersonsOwnAlarmsSwitchWhichReadNothingForAYear() async { let (out, _) = await gate(alarmsOn: false) XCTAssertFalse(out.canSchedule) XCTAssertEqual(out.silence, .switchedOff) } func testReportsThePersonsOwnSwitchFirstWhenBothAreShut() async { // Their decision rather than the platform's, and the one they can undo // without leaving the app. Telling somebody to grant a permission they // will then find changed nothing is the worse wrong answer. let (out, _) = await gate(alarmsOn: false, notifications: .denied) XCTAssertEqual(out.silence, .switchedOff) } func testNeverAsksTheNotificationPermissionAboutARealAlarm() async { // Being on AlarmKit at all IS its authorization having been granted, // and a real alarm does not travel through the notification permission. let (out, authorizer) = await gate(available: true, alarmKit: .authorized, notifications: .denied) XCTAssertEqual(out.backend, .alarmkit) XCTAssertTrue(out.canSchedule) XCTAssertFalse(authorizer.asked.value) } func testStillHonoursTheAlarmsSwitchOnTheLoudBackend() async { let (out, _) = await gate(alarmsOn: false, available: true, alarmKit: .authorized) XCTAssertEqual(out.backend, .alarmkit) XCTAssertFalse(out.canSchedule) XCTAssertEqual(out.silence, .switchedOff) } func testAnUnauthorizedAlarmKitFallsBackToTheQuieterPath() async { let (out, _) = await gate(available: true, alarmKit: .notDetermined) XCTAssertEqual(out.backend, .notification) } } // ── when AlarmKit's prompt is raised ──────────────────────────────────────── final class AlarmKitAskTests: XCTestCase { private func ask( alarmsOn: Bool = true, available: Bool = true, alarmKit: AlarmAuthorization = .notDetermined, enabled: [Bool] = [true], setHere: Bool = true ) async -> (asked: Bool, prompted: Bool) { let authorizer = StubAuthorizer(available: available, alarmKit: alarmKit, notifications: .notDetermined) let alarms = enabled.map { on -> Alarm in var alarm = Alarm() alarm.enabled = on return alarm } let asked = await askForAlarmKitIfDue( authorizer, preferences: StubPreferences(alarmsEnabled: alarmsOn), alarms: alarms, setHere: setHere ) return (asked, authorizer.requested.value) } /// RULE: A launch raises no permission prompt — AlarmKit is asked only on the pass after the person sets or switches on an alarm on this phone, never because an enabled alarm (one another device set) is read (294 row 4, walker293: the prompt rose over Me at first launch). func testAPassThePersonDidNotCauseAsksNothing() async { let launch = await ask(setHere: false) XCTAssertFalse(launch.prompted, "an enabled alarm read at launch is not the person's act") let set = await ask(setHere: true) XCTAssertTrue(set.prompted) } func testAsksOnceAnAlarmIsSwitchedOnAndNobodyHasBeenAsked() async { // The defect: nothing called the request, so AlarmKit stayed // undetermined for ever and no alarm could ever ring loudly. let out = await ask() XCTAssertTrue(out.asked) XCTAssertTrue(out.prompted) } func testDoesNotSpendThePromptOnAListWithNothingSwitchedOn() async { let none = await ask(enabled: []) let off = await ask(enabled: [false, false]) XCTAssertFalse(none.prompted, "an empty alarm list is not a reason to ask") XCTAssertFalse(off.prompted, "alarms that are all off are not a reason to ask") } func testNeverAsksAgainOnceTheAnswerIsKnown() async { let denied = await ask(alarmKit: .denied) let granted = await ask(alarmKit: .authorized) XCTAssertFalse(denied.prompted, "iOS does not re-prompt a refusal; asking is a no-op at best") XCTAssertFalse(granted.prompted) } func testNeverAsksWhereAlarmKitDoesNotExist() async { let out = await ask(available: false, alarmKit: .unavailable) XCTAssertFalse(out.prompted) } func testNeverAsksWhileThePersonsOwnAlarmsSwitchIsOff() async { let out = await ask(alarmsOn: false) XCTAssertFalse(out.prompted, "they turned alarms off; a permission prompt would contradict them") } }