// The OS permission, and the one inline ask.//// **Registration never prompts.** The prompt is spent from exactly two places// — `/settings#notifications` (4h's screen) and one inline moment — and the// token path is not one of them. That separation is structural:// ``NotificationAuthority/read()`` cannot prompt and// ``NotificationAuthority/ask()`` is the only function that can.//// **The inline ask, and why there are two moments.** iOS grants exactly one// prompt per install. Cotton spends it the first time someone gives a todo an// HOUR — the only action in the app that has no point unless something says the// hour has come, so the question and the reason are the same gesture. Giving a// todo a DAY does not trigger it: a date is filing, and plenty of people// schedule days without ever wanting to be interrupted. Chat is the second// moment: the first message someone SENDS, because the reply is the whole// reason for a push and a person who installed Cotton to talk to somebody may// never give a todo an hour. Whichever comes first spends the prompt; the other// then finds `askedAt` set and stays quiet.importFoundation#if canImport(UIKit)import UIKit#endif/// Three states, because "not granted" hides the only distinction that matters:/// `undetermined` can still be asked, `denied` cannot and needs Settings.publicenumNotificationPermission: String, Sendable, CaseIterable {case grantedcase deniedcase undetermined}/// The OS, behind a seam.publicprotocolNotificationAuthority: Sendable {/// What the OS currently thinks. NEVER prompts.func read() async -> NotificationPermission/// Ask. Only ever called from a moment the person can connect to the/// question — the caller owns that judgement, this owns the prompt.func ask() async -> NotificationPermission/// Ask APNs for a token. Called only once the permission is `granted`,/// never before and never as part of asking.func registerForRemoteNotifications() async}/// Who wants to know when the answer changes.////// A `Set` kept for exactly this, and it exists for ONE named failure:/// *without it, whatever hands the push token to the server keeps its stale/// "undetermined" until the next foreground, and the first message someone sent/// earns no reply push until they backgrounded the app.*////// That is not hypothetical here. `/settings#notifications` is the one screen/// whose SUBJECT is the permission, and its Allow button reaches/// `NotificationAuthority.ask()` — while APNs registration, the token hand-off/// and the reminder pass all live behind `NotificationsModel.refresh()`, which/// otherwise runs only from `RootView`'s `.active` arm. Granting on that screen/// would schedule nothing until the app was backgrounded and brought back.////// It lives HERE, beside the authority that fires it, rather than beside the/// screen that made it necessary: the asker and the reader are in different/// lanes, and a broadcast whose publisher and subscriber are in different files/// only works if there is one of it.////// A `final class` with a lock rather than an actor, because a subscriber has/// to be told SYNCHRONOUSLY inside the ask that changed the answer, which is/// what makes "once per ask" assertable.publicfinalclassNotificationPermissionChanges: @unchecked Sendable {/// The one every real reader shares, which is what makes a broadcast from/// `SystemNotificationAuthority` reach a subscriber somewhere else.publicstaticlet shared = NotificationPermissionChanges()privatelet lock = NSLock()privatevar listeners: [Int: @Sendable () -> Void] = [:]privatevar nextId = 0publicinit() {}/// Subscribe, and get the unsubscribe back — the TypeScript's own shape,/// which is what makes "stops telling a subscriber that unsubscribed"/// expressible without a token type.publicfunc subscribe(_ listener: @escaping @Sendable () -> Void) -> @Sendable () -> Void { lock.lock() nextId += 1let id = nextId listeners[id] = listener lock.unlock()return { [weakself] inguardletselfelse { return }self.lock.lock()self.listeners[id] = nilself.lock.unlock() } }/// Tell everyone. Called once per ask, whatever the answer — including a/// refusal, because "they said no" is a change too.publicfunc notify() { lock.lock()let current = Array(listeners.values) lock.unlock()for listener in current { listener() } }}/// The real one — over ``CapabilityAuthority``, which is the one place in this/// app that talks to `UNUserNotificationCenter` (and to every other permission/// API).////// **This type survives the move because it does something the authority does/// not**: it BROADCASTS. `NotificationPermissionChanges` is what tells the/// reminder pass and the token hand-off that the answer changed, and without/// that a permission granted on the settings screen schedules nothing until the/// app is backgrounded and brought back. So the ask goes through the authority/// and the broadcast stays here — three callers already reach this shape, and/// `NotificationAuthority` is the seam their tests fake.publicstructSystemNotificationAuthority: NotificationAuthority {privatelet capabilities: any CapabilityAuthoritypublicinit(capabilities: any CapabilityAuthority = SystemCapabilityAuthority()) {self.capabilities = capabilities }publicfunc read() async -> NotificationPermission {// A permission read must never be the thing that breaks a screen, so an// unreadable state reads as "cannot schedule" and the settings block// says so.Self.permission(await capabilities.status(.notifications)) }publicfunc ask() async -> NotificationPermission {// Broadcast ONCE per ask, whatever the answer, and from the one place// every asker goes through — the settings screen's Allow button, the// inline ask and the alarms screen all land here. A refusal is a change// too: the reminder pass wipes on `denied` exactly as it schedules on// `granted`.defer { NotificationPermissionChanges.shared.notify() }returnSelf.permission(await capabilities.ask(.notifications)) }/// Three states from five, and the fold is deliberate: this screen's/// question is only ever "can it be asked, or does it need Settings", and/// `restricted` and `unavailable` answer that the same way `denied` does.publicstaticfunc permission(_ access: CapabilityAccess) -> NotificationPermission {switch access {case .authorized: return .grantedcase .notDetermined: return .undeterminedcase .denied, .restricted, .unavailable: return .denied } } @MainActorpublicfunc registerForRemoteNotifications() async { #if canImport(UIKit) UIApplication.shared.registerForRemoteNotifications() #else// The Mac never registers for remote notifications: it IS the server// that would send them. `CottonKit` compiles for macOS since H2, and// this authority is only ever constructed by the phone's app target. #endif }}