// 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.importCottonKitimportCottonValuesimportFoundation// For the environment key at the foot of this file — the seam the todo// screen reaches the one prompt through.importSwiftUIimportUserNotifications@MainActor@ObservablepublicfinalclassNotificationsModel {/// 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.publicprivate(set) var permission: NotificationPermission = .undetermined/// The person's switches, as this device holds them.publicprivate(set) var prefs: NotificationPrefs/// What the last reminder pass did. For the test, and for a future screen.publicprivate(set) var lastPass: ReminderPassOutcome?privatelet core: any CottonCallingprivatelet centre: any ReminderCentreprivatelet authority: any NotificationAuthorityprivatelet preferences: any NotificationPreferenceSourcepublicprivate(set) var preferenceProblem: String?privatelet facts: any DeviceFactsSourceprivatelet bridge: NotificationBridge/// The permission-change subscription, held so it is not dropped. See/// `start(taps:)` for why this model is the one that listens.privatevar 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.privatelet reminds: Boolprivatelet timeZone: @Sendable () -> Stringprivatelet 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.privatelet 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.privatelet 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).privatelet 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.privatevar told: Set<String> = []/// The taps already acted on. See the file header.privatevar handled: Set<String> = []privatevar pending: PendingTaps?privatevar debounce: Task<Void, Never>?/// The overlap guard, ported: a pass that is asked for while one is running/// sets `dirty` and the running one goes round again.privatevar running = falseprivatevar dirty = falsepublicinit( 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 = remindsself.core = coreself.centre = centreself.authority = authorityself.preferences = preferencesself.facts = factsself.bridge = bridgeself.settle = settleself.timeZone = timeZoneself.now = nowself.databases = databasesself.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.publicfunc start(taps: PendingTaps) async { pending = taps bridge.attach { [weakself] tap inguardletselfelse { 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 { [weakself] receipt inTask { @MainActor [weakself] inawaitself?.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 { [weakself] inTask { @MainActor [weakself] inawaitself?.refresh() } }await refresh() }/// The scene came forward: re-read the permission, reconcile.publicfunc foreground() async {await refresh() }privatefunc 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 inawait 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 { _ = tryawait 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.publicfunc receive(_ event: ClientEvent) {// Rows moved, not bytes: a thumbnail landing is not a notifications// pass (`ClientEvent.localMediaOrigin`).guardcase .data = event, !event.isLocalMediaArrival else { return } debounce?.cancel() debounce = Task { [weakself] inguardletselfelse { return }ifself.settle > .zero {try? awaitTask.sleep(for: self.settle)ifTask.isCancelled { return } }awaitself.runPass() } }// ── The pass ──────────────────────────────────────────────────────────/// Reconcile what iOS holds against what the crate says should exist. @discardableResultpublicfunc preparePreferences() async -> Bool {do { prefs = tryawait preferences.read() preferenceProblem = nilreturntrue } catch { preferenceProblem = (error as? CottonCallError)?.message ?? ShellLines.line("reminders", "notifications.unreadable")returnfalse } }/// Reconcile what iOS holds against what the crate says should exist.publicfunc runPass() async {if running { dirty = truereturn } running = truedefer { running = false }repeat { dirty = falseguardawait preparePreferences() else { return }var forThisApp = prefsif !reminds { forThisApp.enabled = false } lastPass = awaitReminderPass(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. @discardableResultpublicfunc forgetToken() async -> PushForgotten {guardlet facts = facts.read() else {returnPushForgotten(forgotten: false, reason: "no_device_id") }returnawaitPushRegistrar.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.privatefunc ask() async {let current = await authority.read()if current == .undetermined { permission = await authority.ask() } else { permission = current }do {tryawait preferences.markAsked(at: CottonDate.format(now())) prefs = tryawait 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.publicfunc answerAsk(allow: Bool) async {if allow {await ask()return } permission = await authority.read()do {tryawait preferences.markAsked(at: CottonDate.format(now())) prefs = tryawait 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.iflet 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.privatestructCottonNotificationsKey: EnvironmentKey {staticlet defaultValue: NotificationsModel? = nil}extensionEnvironmentValues {publicvar 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.publicenumDeliveredPushes {publicstaticfunc read() async -> [PushReceipt] {await UNUserNotificationCenter.current().deliveredNotifications().compactMap { shown inPushReceipt.of( userInfo: NotificationTaps.value(of: shown.request.content.userInfo), date: shown.date, how: .delivered) } }}