Cotton code
138 lines · 6.3 KB · SwiftRaw
// What the OS has to be asked for, and what it answered.//// **One layer, because the crashes were never about permission.** Three// separate features each asked the OS in their own way and each built their// platform object on their own schedule, and the app died three different ways// for it: an `AVAudioEngine` whose input node was touched before the audio// session had a category (an `AVAudioIONodeImpl` NSException — SIGABRT, no// Bugsink event), an `AVCaptureSession` started inside its own configuration// window, and a speech-permission completion handed a main-actor closure. All// three are the same mistake in three costumes: the platform object was built,// or touched, before the OS had said yes.//// So there is ONE order in this app, and it is the whole rule:////   ask → configure the session → construct the object → read its format →//   install the tap → start//// ``CapabilityAuthority/gate(_:)`` is the first step, and a feature calls it// BEFORE it constructs anything. `CapabilityGateSweepTests` is what keeps the// OS-asking APIs inside the one file that may call them.//// **A refusal is a STATE, not an error** — the Mac's `probe()` rule, ported:// nothing retries against a decision only the person can make. A denied// capability gets a sentence and a button to Settings// (`CottonUI/Capabilities/CapabilityRefusal.swift`), never a second prompt and// never a spinner.import Foundation/// Everything this app has to ask the OS for.////// A `String` raw value so a test, a log line and a sweep can name one; and/// `CaseIterable` so "every capability has a sentence" is assertable rather/// than a hand-typed list.public enum DeviceCapability: String, CaseIterable, Sendable {    case microphone    case speech    case camera    case contacts    case notifications    /// Reading the photo library. **Full access**, because that is what a    /// whole-library sync needs.    case photoLibrary    /// Saving ONE picture into the photo library. A separate ask with a    /// separate usage string, and iOS treats them separately too.    case photoLibraryAdd    /// Reaching the Mac on this network. Without it every byte between a phone    /// and the Mac across the room goes out through the relay and back — a    /// first copy of 246 MB took most of an hour that way (11 Oct 2026). iOS    /// gives this one no status to read: see `SystemCapabilityAuthority`.    case localNetwork    /// Reading Apple Health: Cotton Health alone, read-only, asked at its    /// Read Apple Health door and never at launch. HealthKit hides a read    /// refusal, so once asked the answer stands `authorized` and a type the    /// person turned off simply reads empty. Only Cotton Health links    /// HealthKit (`CottonHealthKit`, which attaches its asking to    /// ``SystemCapabilityAuthority``); in any other app it is `unavailable`.    case appleHealth}/// Where a capability stands. **Five states, and only one of them can be/// asked.**////// `denied` and `restricted` are not failures to retry: they are decisions,/// and the only way through either is Settings (or, for `restricted`, nobody —/// a profile or parental control made it). `unavailable` is the device saying/// it has no such hardware at all, which no permission can fix.public enum CapabilityAccess: Equatable, Sendable {    case authorized    case notDetermined    case denied    case restricted    case unavailable    /// The one state that admits a prompt. Everything else is decided, and    /// asking again would show nothing — iOS grants one prompt per install.    public var canBeAsked: Bool { self == .notDetermined }    /// Settings is the way through — so the refusal gets a button rather than    /// a retry.    public var settingsWouldHelp: Bool { self == .denied }}/// What a gate answered: everything is granted, or the FIRST thing that was/// not, with where it stands.////// The blocked capability is carried because the sentence differs — "Microphone/// access is off" and "Speech recognition is off" send a person to two/// different rows in Settings, and a feature that says the wrong one teaches/// them the app is broken.public enum CapabilityGateResult: Equatable, Sendable {    case ready    case blocked(DeviceCapability, CapabilityAccess)    public var isReady: Bool { self == .ready }}/// The OS, behind one seam.////// Two functions and no third: what the answer IS, and asking for it. Neither/// throws, because neither can fail in a way a caller could act on — an/// unreadable state is `denied`, which is what a caller does about it anyway.public protocol CapabilityAuthority: Sendable {    /// What the OS currently thinks. **NEVER prompts** — a screen may read this    /// on arrival.    func status(_ capability: DeviceCapability) async -> CapabilityAccess    /// Ask, and answer where it stands AFTER the prompt.    ///    /// **Never a `Bool`**: "false" hides the only distinction that matters,    /// which is whether Settings would help. And an already-decided capability    /// is never re-prompted — the answer comes straight back from    /// ``status(_:)``, because iOS shows nothing the second time and a caller    /// that believed it had asked would wait for an answer that never came.    func ask(_ capability: DeviceCapability) async -> CapabilityAccess}extension CapabilityAuthority {    /// Ask for everything a feature needs, IN ORDER, and stop at the first    /// refusal.    ///    /// The order is the feature's, and it matters: dictation asks for the    /// microphone and then speech recognition, which is the order Apple's own    /// dictation uses and the order a person reads as one question in two    /// parts. Stopping at the first refusal is the other half — stacking a    /// second prompt on top of a "Don't Allow" is how an app reads as one that    /// will not take no for an answer.    ///    /// **This is called BEFORE any platform object is constructed.** That is    /// the rule the whole layer exists for.    public func gate(_ capabilities: [DeviceCapability]) async -> CapabilityGateResult {        for capability in capabilities {            let access = await ask(capability)            guard access == .authorized else { return .blocked(capability, access) }        }        return .ready    }}