// The notification service: taps in, reminders out. // // It replaces three mount sites at once — the reminder pass and the two tap // tables — because in Swift they are one object's jobs rather than hooks side // by side. // // **What it does NOT own**, and each is named because the seam is easy to // blur: `/settings#notifications` and every switch on it is 4h's; `/alarms` and // its whole AlarmKit subsystem are 4e's (this lane shares only the `alarm` KIND // its tap table routes and the `alarms` category its prefs hold); the app-icon // BADGE and the background-sync cycle are 4g's, and all this lane does about // badges is the foreground handler's `no .badge`. // // **Buffering is `PendingTaps`', not this object's.** A tap that arrives before // the boot gate resolves is HELD there and replayed exactly once when it does. // The old 300 ms `COLD_START_SETTLE_MS` does not port and its absence // is not a dropped behaviour: the beat existed to let the router's // `index → home` redirect land before the deep link stacked on top, and // `PendingTaps` replaces the beat with the FACT — the buffer drains when the // stack exists. Same rule, expressed structurally instead of by a timer. // // **The dedupe set outlives every view.** It is keyed on the notification's own // identifier, falling back to the payload's `notificationId` and then to the // literal `"unknown"`, and it lives on this object rather than in a `View` // because a re-created view must not re-handle a tap it already acted on. import CottonKit import CottonValues import Foundation // For the environment key at the foot of this file — the seam the todo // screen reaches the one prompt through. import SwiftUI import UserNotifications @MainActor @Observable public final class NotificationsModel { /// What the OS says right now. Re-read on every foreground, because the /// person can change it in Settings while the app is in the background. public private(set) var permission: NotificationPermission = .undetermined /// The person's switches, as this device holds them. public private(set) var prefs: NotificationPrefs /// What the last reminder pass did. For the test, and for a future screen. public private(set) var lastPass: ReminderPassOutcome? private let core: any CottonCalling private let centre: any ReminderCentre private let authority: any NotificationAuthority private let preferences: any NotificationPreferenceSource public private(set) var preferenceProblem: String? private let facts: any DeviceFactsSource private let bridge: NotificationBridge /// The permission-change subscription, held so it is not dropped. See /// `start(taps:)` for why this model is the one that listens. private var permissionChanges: (@Sendable () -> Void)? /// Whether this app keeps reminders at all. Comms, Words and Story do not (Android runs the pass in Days /// alone): their pass is the master switch off, which clears any Cotton reminder they hold, so Comms, allowed /// to notify for its messages, never doubles Days' alerts. private let reminds: Bool private let timeZone: @Sendable () -> String private let now: @Sendable () -> Date /// The held databases other than the personal one, each reconciled for /// its own reminders (`ReminderDatabases`); nil while the held list is /// not known. private let databases: @MainActor () -> [String]? /// The `data`-event debounce. 600 ms in the app, ported from /// `useNotificationEngine`; a test names zero, because a real wait in a /// test is a test that is slow and flaky for the same reason. private let settle: Duration /// The pushes iOS is showing in Notification Centre, as receipts /// (`DeliveredPushes.read` in the app; nothing in a test, where there is /// no notification centre to ask). private let delivered: @Sendable () async -> [PushReceipt] /// The pushes whose receipt this launch has told, so a foreground does /// not tell the same one again; the serving Mac keeps the first anyway. private var told: Set = [] /// The taps already acted on. See the file header. private var handled: Set = [] private var pending: PendingTaps? private var debounce: Task? /// The overlap guard, ported: a pass that is asked for while one is running /// sets `dirty` and the running one goes round again. private var running = false private var dirty = false public init( core: any CottonCalling, centre: any ReminderCentre = SystemReminderCentre(), authority: any NotificationAuthority = SystemNotificationAuthority(), preferences: any NotificationPreferenceSource, initialPrefs: NotificationPrefs? = nil, facts: any DeviceFactsSource = SystemDeviceFacts(), bridge: NotificationBridge = .shared, settle: Duration = .milliseconds(600), timeZone: @escaping @Sendable () -> String = { TimeZone.current.identifier }, now: @escaping @Sendable () -> Date = { Date() }, databases: @escaping @MainActor () -> [String]? = { [] }, delivered: @escaping @Sendable () async -> [PushReceipt] = { [] }, reminds: Bool = true ) { self.reminds = reminds self.core = core self.centre = centre self.authority = authority self.preferences = preferences self.facts = facts self.bridge = bridge self.settle = settle self.timeZone = timeZone self.now = now self.databases = databases self.delivered = delivered prefs = initialPrefs ?? NotificationPrefs(enabled: false, categories: [:]) } // ── The mount ───────────────────────────────────────────────────────── /// Attach to the tap bridge and run once. /// /// `taps` is the boot gate's buffer: a resolved route goes to it, and IT /// decides whether the stack exists yet. public func start(taps: PendingTaps) async { pending = taps bridge.attach { [weak self] tap in guard let self else { return } self.deliver(tap) } // A push this phone met — presented while open, or tapped — is told // to the serving Mac as its receipt. bridge.attachReceipts { [weak self] receipt in Task { @MainActor [weak self] in await self?.tell(receipt) } } // The permission can be granted somewhere that is NOT this model's own // ask: `/settings#notifications` is the one screen whose subject is the // permission, and its Allow button goes through the same authority. // Everything a grant is supposed to trigger — APNs registration and the // reminder pass — lives in `refresh()`, and the // only other thing that calls it is `foreground()`. Without this the // person would grant on that screen and get nothing scheduled until // they backgrounded the app and came back. // // Held for the life of the model rather than unsubscribed: this one is // built once with the app and outlives every screen that could ask. permissionChanges = NotificationPermissionChanges.shared.subscribe { [weak self] in Task { @MainActor [weak self] in await self?.refresh() } } await refresh() } /// The scene came forward: re-read the permission, reconcile. public func foreground() async { await refresh() } private func refresh() async { permission = await authority.read() if permission == .granted { // Only once granted, never before and never as part of asking. await authority.registerForRemoteNotifications() } await runPass() // What iOS showed while the app was away is in Notification Centre: // each server push there is owed its receipt too. for receipt in await delivered() { await tell(receipt) } } // ── Receipts ────────────────────────────────────────────────────────── /// Tell the serving Mac this phone met a push (`device.pushAck`). /// /// A push counts as reaching the owner when the PHONE says it showed it, /// not when Apple answers 2xx (architect, 12 Oct 2026) — Test push waits /// for exactly this. **A failure blocks nothing**: the push is untold /// again, and the next foreground finds it in Notification Centre. func tell(_ receipt: PushReceipt) async { guard told.insert(receipt.pushId).inserted else { return } do { _ = try await core.callJSON(CottonMethod.devicePushAck, receipt) } catch { told.remove(receipt.pushId) } } // ── Invalidation ────────────────────────────────────────────────────── /// A `data` event moved something. Reconcile, debounced. /// /// It does not read `tables`: the desired set is decided from todos, /// events, people and moods, and naming those here would be a second copy /// of the crate's own query list — one that goes quiet rather than red when /// the engine starts reading a fifth. public func receive(_ event: ClientEvent) { // Rows moved, not bytes: a thumbnail landing is not a notifications // pass (`ClientEvent.localMediaOrigin`). guard case .data = event, !event.isLocalMediaArrival else { return } debounce?.cancel() debounce = Task { [weak self] in guard let self else { return } if self.settle > .zero { try? await Task.sleep(for: self.settle) if Task.isCancelled { return } } await self.runPass() } } // ── The pass ────────────────────────────────────────────────────────── /// Reconcile what iOS holds against what the crate says should exist. @discardableResult public func preparePreferences() async -> Bool { do { prefs = try await preferences.read() preferenceProblem = nil return true } catch { preferenceProblem = (error as? CottonCallError)?.message ?? ShellLines.line("reminders", "notifications.unreadable") return false } } /// Reconcile what iOS holds against what the crate says should exist. public func runPass() async { if running { dirty = true return } running = true defer { running = false } repeat { dirty = false guard await preparePreferences() else { return } var forThisApp = prefs if !reminds { forThisApp.enabled = false } lastPass = await ReminderPass(core: core, centre: centre) .run(timeZone: timeZone(), prefs: forThisApp, permission: permission, others: databases()) } while dirty } // ── The token ───────────────────────────────────────────────────────── /// Tell the server to forget this device. Before a leave, and before /// sign-out. /// /// Never throws and never reports: a person handing back a phone must not /// be trapped by a deregistration that could not reach the server. @discardableResult public func forgetToken() async -> PushForgotten { guard let facts = facts.read() else { return PushForgotten(forgotten: false, reason: "no_device_id") } return await PushRegistrar.forget(deviceId: facts.deviceId, through: core) } // ── The ask ─────────────────────────────────────────────────────────── /// The prompt, spent. /// /// Already decided — granted in Settings, or denied there — asks nothing /// but still records that the moment passed, so it is not re-checked on /// every todo from here on. private func ask() async { let current = await authority.read() if current == .undetermined { permission = await authority.ask() } else { permission = current } do { try await preferences.markAsked(at: CottonDate.format(now())) prefs = try await preferences.read() preferenceProblem = nil } catch { preferenceProblem = (error as? CottonCallError)?.message ?? ShellLines.line("reminders", "notifications.unsaved") } if permission == .granted { await authority.registerForRemoteNotifications() } // A grant is a reason to schedule and a denial is a reason to WIPE, so // both run the pass. await runPass() } /// The reason card's answer, from the act that earned a reminder (Days: the core's `request_notifications` /// with its `leave` words). Continue asks iOS when it has not decided; Not now asks nothing. Either way the /// moment is spent, recorded with the core, and a pass runs. public func answerAsk(allow: Bool) async { if allow { await ask() return } permission = await authority.read() do { try await preferences.markAsked(at: CottonDate.format(now())) prefs = try await preferences.read() preferenceProblem = nil } catch { preferenceProblem = (error as? CottonCallError)?.message ?? ShellLines.line("reminders", "notifications.unsaved") } await runPass() } // ── Taps ────────────────────────────────────────────────────────────── /// One tap, resolved and acted on. Exactly once. func deliver(_ tap: NotificationTap) { let key = NotificationTaps.dedupeKey(tap) guard !handled.contains(key) else { return } handled.insert(key) // To the boot gate's buffer, which opens now or holds until the stack // exists — with the database the record lives in, when the payload // names one. Nil is an unmapped type, an unreadable payload, or a kind // that leads nowhere: opening the app is the whole response, never a // guess at the nearest screen. if let link = NotificationTaps.link(tap) { pending?.arrive(link) } } } // ── The one prompt, reachable from the screen that spends it ──────────────── /// The root's notifications model, handed down. /// /// Optional and defaulting to nothing, for `cottonSync`'s reason: a screen /// rendered outside the app — a preview, a gallery specimen, a unit test — /// has no notifications model, and inventing one would put a live /// `UNUserNotificationCenter` behind a specimen. A screen that finds nothing /// here asks nothing, which is the correct behaviour everywhere the app itself /// is not running. /// /// It exists because the VALUE MOMENT belongs to a screen: giving a todo an /// hour is the first act in this app that only pays off if something speaks at /// that hour. The prompt itself is `askIfUndecided`, from the person's act, /// never a launch; its flag is the same `NotificationPrefs.askedAt` the Settings /// screen and the chat lane's first send read. private struct CottonNotificationsKey: EnvironmentKey { static let defaultValue: NotificationsModel? = nil } extension EnvironmentValues { public var cottonNotifications: NotificationsModel? { get { self[CottonNotificationsKey.self] } set { self[CottonNotificationsKey.self] = newValue } } } // ── What Notification Centre holds ────────────────────────────────────────── /// The server pushes iOS is showing in Notification Centre, as receipts — /// each one a push this phone showed while the app was away. public enum DeliveredPushes { public static func read() async -> [PushReceipt] { await UNUserNotificationCenter.current().deliveredNotifications().compactMap { shown in PushReceipt.of( userInfo: NotificationTaps.value(of: shown.request.content.userInfo), date: shown.date, how: .delivered) } } }