SPB Git

Repository Public License

AppModel.swift 30.5 KB 567 lines swift

1// ORIX Alarm2// File: App/Sources/AppModel.swift3// Description: Single source of truth of the app: library, history, runtime occurrences, system alarm scheduling and reconciliation, mission runs.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import Foundation9import Observation10import WidgetKit1112enum AppTab: String, CaseIterable, Hashable { case today, alarms, studio, sleep, insights }1314/// A mission sequence being played (after an alarm, or as a preview from the editor).15struct MissionRun: Identifiable, Equatable {16    let id = UUID()17    var alarmID: UUID?18    var alarmName: String19    var occurrenceID: UUID20    var missions: [ResolvedMission]21    var requiresConfirmation: Bool22    var isPreview: Bool23    var startedAt: Date24}2526@Observable27final class AppModel {28    // MARK: State29    private(set) var library: Library30    private(set) var history: History31    private(set) var runtime: RuntimeState32    private(set) var authorization: AlarmAuthorization33    /// Verified system status per alarm definition (result of the last reconciliation).34    private(set) var statuses: [UUID: SystemAlarmStatus] = [:]35    /// Last scheduling error per alarm, shown next to the alarm until it is scheduled successfully.36    private(set) var schedulingErrors: [UUID: String] = [:]37    /// Set when the stored data had to be recovered or reset at launch.38    var storageNotice: LoadOutcome?39    var missionRun: MissionRun?40    var selectedTab: AppTab = .today41    /// Alarm being edited in the editor sheet (new or existing).42    var editingAlarm: AlarmDefinition?43    /// Alarm shown in Nightstand mode.44    var nightstandAlarmID: UUID?45    /// Focus timer currently counting down, if any.46    private(set) var focusTimerEnd: Date?4748    // MARK: Dependencies49    let service: any SystemAlarmService50    let now: () -> Date51    var calendar: Calendar52    private let libraryStore: JSONFileStore<Library>53    private let historyStore: JSONFileStore<History>54    private let runtimeStore: JSONFileStore<RuntimeState>55    private var observation: Task<Void, Never>?56    /// System alarms last seen alerting, and stops the app itself requested (snooze), to tell a user stop from our own.57    private var alertingSystemIDs: Set<UUID> = []58    private var selfStoppedSystemIDs: Set<UUID> = []59    /// Widgets are only fed from the real shared container (never from tests or UI-test storage).60    private let feedsWidgets: Bool61    static let focusTimerID = UUID(uuidString: "0F0C0500-71EE-4000-8000-000000000001")!6263    init(service: any SystemAlarmService, directory: URL = AppGroup.directory, now: @escaping () -> Date = { .now }, calendar: Calendar = .autoupdatingCurrent) {64        self.service = service; self.now = now; self.calendar = calendar65        feedsWidgets = directory == AppGroup.directory66        libraryStore = JSONFileStore(directory: directory, name: "library", schemaVersion: Library.schemaVersion)67        historyStore = JSONFileStore(directory: directory, name: "history", schemaVersion: History.schemaVersion)68        runtimeStore = JSONFileStore(directory: directory, name: "runtime", schemaVersion: RuntimeState.schemaVersion)69        let lib = libraryStore.load(default: Library())70        let hist = historyStore.load(default: History())71        library = lib.value; history = hist.value72        runtime = runtimeStore.load(default: RuntimeState()).value73        authorization = service.authorization74        let worst = [lib.outcome, hist.outcome].first { $0 == .resetAfterCorruption } ?? [lib.outcome, hist.outcome].first { $0 == .recoveredFromBackup }75        storageNotice = worst76        Haptics.isEnabled = library.settings.hapticsEnabled77        SoundFX.isEnabled = library.settings.soundEffectsEnabled78    }7980    // MARK: Derived values81    var alarms: [AlarmDefinition] { library.alarms.sorted { ($0.time, $0.createdAt) < ($1.time, $1.createdAt) } }82    var settings: AppSettings { library.settings }83    var qrTags: [QRTag] { library.qrTags }84    var sleepPlan: SleepPlan { library.sleepPlan }85    var savedScenarios: [SavedScenario] { library.savedScenarios }86    var events: [WakeEvent] { history.events }8788    func alarm(_ id: UUID) -> AlarmDefinition? { library.alarms.first { $0.id == id } }89    func nextFireDate(for alarm: AlarmDefinition) -> Date? { Recurrence.nextFireDate(for: alarm, after: now(), calendar: calendar) }90    var nextAlarm: (alarm: AlarmDefinition, date: Date)? { Recurrence.nextAlarm(in: library.alarms, after: now(), calendar: calendar) }91    func status(for id: UUID) -> SystemAlarmStatus { statuses[id] ?? (alarm(id)?.isEnabled == true ? .unverifiable : .off) }92    func statistics(days: Int) -> WakeStatistics { WakeStatistics.recent(events: history.events, days: days, now: now(), calendar: calendar) }93    func validationIssues(for alarm: AlarmDefinition) -> [Recurrence.ValidationIssue] {94        Recurrence.validate(alarm, qrTags: library.qrTags, now: now(), calendar: calendar)95    }96    var suggestions: [AdaptiveEngine.Suggestion] { AdaptiveEngine.suggestions(alarms: library.alarms, history: history.events, now: now()) }9798    // MARK: Lifecycle99    /// Call once at launch: connects the alarm intents, observes the system and reconciles.100    func start() async {101        await IntentBridge.shared.install { [weak self] event in await self?.handle(event) }102        observation?.cancel()103        let stream = service.updates()104        observation = Task { [weak self] in105            for await snapshots in stream { await self?.systemChanged(snapshots) }106        }107        await reconcile()108    }109110    /// Call whenever the app becomes active.111    func activate() async {112        authorization = service.authorization113        await reconcile()114        presentPendingMissionIfNeeded()115    }116117    @discardableResult118    func requestAuthorization() async -> AlarmAuthorization {119        authorization = await service.requestAuthorization()120        if authorization == .authorized { await reconcile() }121        return authorization122    }123124    // MARK: Alarm CRUD125    /// Inserts or updates an alarm, then registers it with the system. Returns the scheduling error, if any.126    @discardableResult127    func save(_ alarm: AlarmDefinition) async -> String? {128        var a = alarm129        a.updatedAt = now()130        a.name = a.name.trimmingCharacters(in: .whitespacesAndNewlines)131        if a.scenario.missions.count > WakeScenario.maxMissionSteps { a.scenario.missions = Array(a.scenario.missions.prefix(WakeScenario.maxMissionSteps)) }132        if let i = library.alarms.firstIndex(where: { $0.id == a.id }) { library.alarms[i] = a } else { library.alarms.append(a) }133        persistLibrary()134        return await sync(a)135    }136137    func delete(_ id: UUID) {138        cancelSystemAlarms(for: id)139        library.alarms.removeAll { $0.id == id }140        statuses[id] = nil; schedulingErrors[id] = nil141        runtime.prune(keeping: Set(library.alarms.map(\.id))); persistRuntime()142        persistLibrary()143    }144145    func setEnabled(_ id: UUID, _ enabled: Bool) async {146        guard var a = alarm(id), a.isEnabled != enabled else { return }147        a.isEnabled = enabled148        await save(a)149    }150151    @discardableResult152    func duplicate(_ id: UUID) async -> AlarmDefinition? {153        guard let source = alarm(id) else { return nil }154        var copy = source155        copy.id = UUID(); copy.createdAt = now(); copy.isEnabled = false156        copy.name = source.name.isEmpty ? "" : source.name + " copy"157        copy.scenario.missions = copy.scenario.missions.map { var m = $0; m.id = UUID(); return m }158        await save(copy)159        return copy160    }161162    /// A blank alarm using the user's defaults (not saved yet).163    func makeDraftAlarm() -> AlarmDefinition {164        let base = calendar.dateComponents([.hour, .minute], from: now().addingTimeInterval(8 * 3600))165        var scenario = WakeScenario(); scenario.snooze = library.settings.defaultSnooze166        return AlarmDefinition(time: ClockTime(hour: base.hour ?? 7, minute: ((base.minute ?? 0) / 5) * 5), soundID: library.settings.defaultSoundID,167                               scenario: scenario, createdAt: now(), updatedAt: now())168    }169170    // MARK: Library edits171    func updateSettings(_ change: (inout AppSettings) -> Void) {172        change(&library.settings); Haptics.isEnabled = library.settings.hapticsEnabled173        SoundFX.isEnabled = library.settings.soundEffectsEnabled; persistLibrary()174    }175    func updateSleepPlan(_ change: (inout SleepPlan) -> Void) {176        change(&library.sleepPlan); persistLibrary()177        let plan = library.sleepPlan178        Task { await SleepReminders.sync(plan: plan) }179    }180    func saveScenario(_ scenario: SavedScenario) {181        if let i = library.savedScenarios.firstIndex(where: { $0.id == scenario.id }) { library.savedScenarios[i] = scenario } else { library.savedScenarios.append(scenario) }182        persistLibrary()183    }184    func deleteScenario(_ id: UUID) { library.savedScenarios.removeAll { $0.id == id }; persistLibrary() }185    func moveScenarios(from source: IndexSet, to destination: Int) {186        var list = library.savedScenarios187        let moved = source.map { list[$0] }188        for i in source.sorted(by: >) { list.remove(at: i) }189        let offset = source.filter { $0 < destination }.count190        list.insert(contentsOf: moved, at: destination - offset)191        library.savedScenarios = list; persistLibrary()192    }193    /// Registers a QR code. Only a SHA-256 digest of its content is kept.194    @discardableResult195    func addQRTag(label: String, payload: String) -> QRTag {196        let tag = QRTag(label: label.trimmingCharacters(in: .whitespacesAndNewlines), payloadDigest: StableID.digest(of: payload), createdAt: now())197        library.qrTags.append(tag); persistLibrary()198        return tag199    }200    func removeQRTag(_ id: UUID) { library.qrTags.removeAll { $0.id == id }; persistLibrary() }201    func qrTag(_ id: UUID?) -> QRTag? { library.qrTags.first { $0.id == id } }202    func qrPayloadMatches(_ payload: String, tagID: UUID?) -> Bool {203        guard let tag = qrTag(tagID) else { return false }204        return StableID.digest(of: payload) == tag.payloadDigest205    }206207    // MARK: System scheduling208    private func request(for a: AlarmDefinition) -> SystemAlarmRequest {209        let hasMission = !a.scenario.missions.isEmpty || a.scenario.requiresConfirmation210        return SystemAlarmRequest(systemID: a.id, alarmID: a.id, title: a.name.isEmpty ? "Alarm" : a.name,211                                  trigger: .relative(time: a.time, weekdays: a.weekdays),212                                  soundFileName: SoundCatalog.alarmSound(a.soundID).fileName, role: .alarm,213                                  offersSnooze: a.scenario.snooze.duration(forSnooze: 1) != nil, opensMission: hasMission)214    }215216    private func cancelSystemAlarms(for id: UUID) {217        service.cancel(systemID: id)218        StableID.allSnoozeIDs(for: id).forEach { service.cancel(systemID: $0) }219    }220221    /// Makes the system match one definition. Returns an error message on failure.222    @discardableResult223    private func sync(_ a: AlarmDefinition) async -> String? {224        defer { refreshStatuses(); writeWidgetSnapshot() }225        guard a.isEnabled else {226            cancelSystemAlarms(for: a.id)227            schedulingErrors[a.id] = nil; runtime.expectedFire[a.id] = nil; persistRuntime()228            return nil229        }230        do {231            service.cancel(systemID: a.id)232            try await service.schedule(request(for: a))233            authorization = service.authorization234            schedulingErrors[a.id] = nil235            runtime.expectedFire[a.id] = Recurrence.nextFireDate(for: a, after: now(), calendar: calendar)236            persistRuntime()237            record(WakeEvent(alarmID: a.id, occurrenceID: a.id, kind: .scheduled, date: now()))238            return nil239        } catch {240            authorization = service.authorization241            let message = error.localizedDescription242            schedulingErrors[a.id] = message243            record(WakeEvent(alarmID: a.id, occurrenceID: a.id, kind: .schedulingFailed, date: now(), note: message))244            return message245        }246    }247248    private var keptSystemIDs: Set<UUID> {249        var keep: Set<UUID> = [Self.focusTimerID]250        for (alarmID, o) in runtime.occurrences {251            if let until = o.snoozedUntil, until > now().addingTimeInterval(-60) { keep.insert(StableID.snoozeID(for: alarmID, number: max(o.snoozesUsed, 1))) }252        }253        return keep254    }255256    private func refreshStatuses() {257        statuses = Reconciler.reconcile(definitions: library.alarms, system: try? service.snapshots(), keep: keptSystemIDs).statuses258    }259260    /// Compares what the app believes with what the system holds and repairs the difference.261    func reconcile() async {262        authorization = service.authorization263        noteFiresThatHappenedWhileAway()264        let system = try? service.snapshots()265        if let system { acknowledgeStopsThatHappenedWhileAway(system: system) }266        let result = Reconciler.reconcile(definitions: library.alarms, system: system, keep: keptSystemIDs)267        for action in result.actions {268            switch action {269            case .schedule(let id), .reschedule(let id):270                if let a = alarm(id) { await sync(a) }271            case .cancelOrphan(let id):272                service.cancel(systemID: id)273            }274        }275        refreshStatuses()276        if let snaps = system, let timer = snaps.first(where: { $0.id == Self.focusTimerID }) {277            if timer.state == .scheduled { focusTimerEnd = nil }278        } else if system != nil { focusTimerEnd = nil }279        writeWidgetSnapshot()280    }281282    /// An alarm whose expected fire date is in the past rang while the app was not observing: record it as a fact283    /// derived from the schedule, and retire one-time alarms.284    private func noteFiresThatHappenedWhileAway() {285        let current = now()286        var changed = false287        for a in library.alarms where a.isEnabled {288            guard let expected = runtime.expectedFire[a.id], expected <= current else { continue }289            if runtime.occurrences[a.id].map({ abs($0.firedAt.timeIntervalSince(expected)) > 120 && $0.firedAt < expected }) ?? true {290                let (occurrence, _) = runtime.noteFired(alarmID: a.id, at: expected)291                record(WakeEvent(alarmID: a.id, occurrenceID: occurrence.id, kind: .fired, date: expected, note: "from-schedule"))292            }293            if a.isRecurring {294                runtime.expectedFire[a.id] = Recurrence.nextFireDate(for: a, after: current, calendar: calendar)295            } else {296                runtime.expectedFire[a.id] = nil297                retireOneTimeAlarm(a.id)298            }299            changed = true300        }301        if changed { persistRuntime() }302    }303304    private func retireOneTimeAlarm(_ id: UUID) {305        guard let i = library.alarms.firstIndex(where: { $0.id == id }), !library.alarms[i].isRecurring, library.alarms[i].isEnabled else { return }306        library.alarms[i].isEnabled = false307        runtime.expectedFire[id] = nil308        persistLibrary()309    }310311    private func alarmID(forSystemID id: UUID) -> UUID? {312        if alarm(id) != nil { return id }313        return library.alarms.first { StableID.allSnoozeIDs(for: $0.id).contains(id) }?.id314    }315316    /// Observes the system directly. This path does not depend on the alarm intents being delivered: an alarm seen317    /// alerting and then no longer alerting was stopped by the user (unless the app stopped it itself to snooze).318    private func systemChanged(_ snapshots: [SystemAlarmSnapshot]) async {319        let nowAlerting = Set(snapshots.filter { $0.state == .alerting }.map(\.id))320        for id in nowAlerting.subtracting(alertingSystemIDs) {321            if let alarmID = alarmID(forSystemID: id) { noteFired(alarmID: alarmID, at: now()) }322        }323        let ended = alertingSystemIDs.subtracting(nowAlerting)324        alertingSystemIDs = nowAlerting325        for id in ended {326            if selfStoppedSystemIDs.remove(id) != nil { continue }327            if snapshots.contains(where: { $0.id == id && ($0.state == .countdown || $0.state == .paused) }) { continue }328            if id == Self.focusTimerID { focusTimerEnd = nil; continue }329            if let alarmID = alarmID(forSystemID: id) { await handle(.stopped(systemID: id, alarmID: alarmID)) }330        }331        refreshStatuses()332    }333334    /// At activation: an open occurrence that is neither alerting nor snoozing any more was stopped while the app335    /// was not observing. Recorded with a note, since the stop itself was not seen.336    private func acknowledgeStopsThatHappenedWhileAway(system: [SystemAlarmSnapshot]) {337        let current = now()338        let busy = Set(system.filter { $0.state != .scheduled }.map(\.id))339        for a in library.alarms {340            guard let o = runtime.openOccurrence(for: a.id, now: current), o.acknowledgedAt == nil, o.missionFinishedAt == nil else { continue }341            if let until = o.snoozedUntil, until > current { continue }342            if busy.contains(a.id) || !busy.isDisjoint(with: StableID.allSnoozeIDs(for: a.id)) { continue }343            runtime.update(a.id) { $0.acknowledgedAt = current; $0.snoozedUntil = nil }344            record(WakeEvent(alarmID: a.id, occurrenceID: o.id, kind: .acknowledged, date: current, note: "from-system-state"))345        }346        persistRuntime()347    }348349    @discardableResult350    private func noteFired(alarmID: UUID, at date: Date) -> Occurrence {351        let (occurrence, isNew) = runtime.noteFired(alarmID: alarmID, at: date)352        if isNew {353            record(WakeEvent(alarmID: alarmID, occurrenceID: occurrence.id, kind: .fired, date: date))354            if statuses[alarmID] == .confirmed { schedulingErrors[alarmID] = nil }   // a snooze error from a previous morning is obsolete355        }356        if let a = alarm(alarmID), a.isRecurring {357            runtime.expectedFire[alarmID] = Recurrence.nextFireDate(for: a, after: date.addingTimeInterval(61), calendar: calendar)358        } else { runtime.expectedFire[alarmID] = nil }359        persistRuntime()360        return occurrence361    }362363    // MARK: Intent events364    func handle(_ event: AlarmIntentEvent) async {365        switch event {366        case .stopped(let systemID, let alarmID), .openMission(let systemID, let alarmID):367            if systemID == Self.focusTimerID { focusTimerEnd = nil; return }368            guard alarm(alarmID) != nil else { return }369            let occurrence = noteFired(alarmID: alarmID, at: now())370            // The same stop can be reported twice (intent and system observation): record it once.371            if occurrence.acknowledgedAt == nil || occurrence.snoozedUntil != nil {372                runtime.update(alarmID) { $0.acknowledgedAt = self.now(); $0.snoozedUntil = nil }373                persistRuntime()374                record(WakeEvent(alarmID: alarmID, occurrenceID: occurrence.id, kind: .acknowledged, date: now()))375            }376            if systemID == alarmID { retireOneTimeAlarm(alarmID) }377            refreshStatuses(); writeWidgetSnapshot()378            presentPendingMissionIfNeeded()379        case .snoozeRequested(let systemID, let alarmID):380            await snooze(systemID: systemID, alarmID: alarmID)381        }382    }383384    /// Applies the alarm's snooze policy: stops the current alert and schedules the follow-up countdown.385    func snooze(systemID: UUID, alarmID: UUID) async {386        guard let a = alarm(alarmID) else { service.stop(systemID: systemID); return }387        let occurrence = noteFired(alarmID: alarmID, at: now())388        let number = occurrence.snoozesUsed + 1389        if alertingSystemIDs.contains(systemID) { selfStoppedSystemIDs.insert(systemID) }390        service.stop(systemID: systemID)391        if systemID == alarmID { retireOneTimeAlarm(alarmID) }392        guard let duration = a.scenario.snooze.duration(forSnooze: number) else {393            // No snooze left: behaves like a stop.394            await handle(.stopped(systemID: systemID, alarmID: alarmID)); return395        }396        let hasMission = !a.scenario.missions.isEmpty || a.scenario.requiresConfirmation397        let follow = SystemAlarmRequest(systemID: StableID.snoozeID(for: alarmID, number: number), alarmID: alarmID,398                                        title: a.name.isEmpty ? "Alarm" : a.name, trigger: .countdown(duration: duration),399                                        soundFileName: SoundCatalog.alarmSound(a.soundID).fileName, role: .snooze,400                                        offersSnooze: a.scenario.snooze.duration(forSnooze: number + 1) != nil, opensMission: hasMission)401        do {402            try await service.schedule(follow)403            runtime.update(alarmID) { $0.snoozesUsed = number; $0.snoozedUntil = self.now().addingTimeInterval(duration); $0.acknowledgedAt = nil }404            persistRuntime()405            record(WakeEvent(alarmID: alarmID, occurrenceID: occurrence.id, kind: .snoozed, date: now(), duration: duration))406        } catch {407            // The follow-up could not be scheduled: never leave the user without an alarm silently.408            schedulingErrors[alarmID] = error.localizedDescription409            record(WakeEvent(alarmID: alarmID, occurrenceID: occurrence.id, kind: .schedulingFailed, date: now(), note: "snooze: " + error.localizedDescription))410            await handle(.stopped(systemID: systemID, alarmID: alarmID))411        }412        refreshStatuses()413    }414415    // MARK: Missions416    /// Presents the wake mission of the most recent open occurrence that still needs it.417    func presentPendingMissionIfNeeded() {418        guard missionRun == nil else { return }419        let current = now()420        let candidates = library.alarms.filter { runtime.needsMission(for: $0, now: current) }421        guard let a = candidates.max(by: { (runtime.occurrences[$0.id]?.firedAt ?? .distantPast) < (runtime.occurrences[$1.id]?.firedAt ?? .distantPast) }),422              let o = runtime.occurrences[a.id] else { return }423        let pendingSteps = o.missionFinishedAt == nil ? a.scenario.missions : []424        let resolved = AdaptiveEngine.resolve(pendingSteps, history: history.events, snoozesUsed: o.snoozesUsed, policy: a.scenario.snooze,425                                              seed: UInt64(truncatingIfNeeded: o.id.hashValue))426        missionRun = MissionRun(alarmID: a.id, alarmName: a.name, occurrenceID: o.id, missions: resolved,427                                requiresConfirmation: a.scenario.requiresConfirmation, isPreview: false, startedAt: current)428        if !resolved.isEmpty { record(WakeEvent(alarmID: a.id, occurrenceID: o.id, kind: .missionStarted, date: current)) }429        Haptics.prepare(); SoundFX.prepare()430    }431432    /// Plays a sequence without recording anything (editor preview, practice).433    func previewMissions(_ steps: [MissionStep], name: String = "Preview", seed: UInt64 = .random(in: 0...UInt64.max)) {434        missionRun = makePreviewRun(steps, name: name, seed: seed)435    }436437    /// A preview run to present locally (for example from inside a sheet) with `MissionRunnerView(run:onClose:)`.438    func makePreviewRun(_ steps: [MissionStep], name: String = "Preview", seed: UInt64 = .random(in: 0...UInt64.max)) -> MissionRun {439        let resolved = AdaptiveEngine.resolve(steps, history: history.events, snoozesUsed: 0, policy: .none, seed: seed)440        return MissionRun(alarmID: nil, alarmName: name, occurrenceID: UUID(), missions: resolved, requiresConfirmation: false, isPreview: true, startedAt: now())441    }442443    func missionStepCompleted(_ run: MissionRun, mission: ResolvedMission, outcome: MissionOutcome) {444        guard !run.isPreview, let alarmID = run.alarmID else { return }445        record(WakeEvent(alarmID: alarmID, occurrenceID: run.occurrenceID, kind: .missionStepCompleted, date: now(), missionKind: mission.kind,446                         level: mission.level, duration: outcome.duration, mistakes: outcome.mistakes, rounds: max(outcome.rounds, 1)))447    }448449    /// The whole sequence ended, either completed or through the emergency exit.450    func missionSequenceEnded(_ run: MissionRun, bypassed: Bool) {451        guard !run.isPreview, let alarmID = run.alarmID else { return }452        runtime.update(alarmID) { $0.missionFinishedAt = self.now(); $0.bypassed = bypassed }453        persistRuntime()454        if !run.missions.isEmpty || bypassed {455            record(WakeEvent(alarmID: alarmID, occurrenceID: run.occurrenceID, kind: bypassed ? .missionBypassed : .missionCompleted, date: now(),456                             duration: now().timeIntervalSince(run.startedAt)))457        }458    }459460    func confirmWake(_ run: MissionRun) {461        guard !run.isPreview, let alarmID = run.alarmID else { return }462        runtime.update(alarmID) { $0.confirmedAt = self.now(); if $0.missionFinishedAt == nil { $0.missionFinishedAt = self.now() } }463        persistRuntime()464        record(WakeEvent(alarmID: alarmID, occurrenceID: run.occurrenceID, kind: .wakeConfirmed, date: now()))465        writeWidgetSnapshot()466    }467468    func dismissMissionRun() { missionRun = nil }469470    // MARK: Focus timer471    @discardableResult472    func startFocusTimer(minutes: Int) async -> String? {473        let duration = TimeInterval(min(max(minutes, 1), 180) * 60)474        service.cancel(systemID: Self.focusTimerID)475        do {476            try await service.schedule(SystemAlarmRequest(systemID: Self.focusTimerID, alarmID: Self.focusTimerID, title: "Focus Timer",477                                                          trigger: .countdown(duration: duration), soundFileName: SoundCatalog.alarmSound("minimal-tones").fileName,478                                                          role: .focusTimer, offersSnooze: false, opensMission: false))479            focusTimerEnd = now().addingTimeInterval(duration)480            return nil481        } catch { return error.localizedDescription }482    }483    func cancelFocusTimer() { service.cancel(systemID: Self.focusTimerID); focusTimerEnd = nil }484485    // MARK: History, export, reset486    func record(_ event: WakeEvent) {487        history.record(event)488        try? historyStore.save(history)489    }490491    func exportArchive() throws -> Data { try ExportArchive(exportedAt: now(), library: library, history: history).encoded() }492493    /// Replaces the library and history with an exported archive, then reschedules everything.494    func importArchive(_ data: Data) async throws {495        let archive = try ExportArchive.decode(data)496        library.alarms.forEach { cancelSystemAlarms(for: $0.id) }497        library = archive.library; history = archive.history; runtime = RuntimeState()498        persistLibrary(); persistRuntime(); try? historyStore.save(history)499        await reconcile()500    }501502    func eraseEverything() async {503        library.alarms.forEach { cancelSystemAlarms(for: $0.id) }504        cancelFocusTimer()505        let keepOnboarding = library.settings.hasCompletedOnboarding506        library = Library(); library.settings.hasCompletedOnboarding = keepOnboarding507        history = History(); runtime = RuntimeState(); statuses = [:]; schedulingErrors = [:]508        persistLibrary(); persistRuntime(); try? historyStore.save(history)509        await SleepReminders.sync(plan: library.sleepPlan)510        await reconcile()511    }512513    // MARK: Persistence514    private func persistLibrary() {515        try? libraryStore.save(library)516        writeWidgetSnapshot()517    }518    private func persistRuntime() { try? runtimeStore.save(runtime) }519520    private func writeWidgetSnapshot() {521        guard feedsWidgets else { return }522        let stats = statistics(days: 7)523        let snapshot = WidgetSnapshot(generatedAt: now(), alarms: alarms.map { a in524            .init(id: a.id, name: a.name, hour: a.time.hour, minute: a.time.minute, weekdays: a.weekdays.map(\.rawValue).sorted(),525                  isEnabled: a.isEnabled && status(for: a.id) != .missing, missionCount: a.scenario.missions.count,526                  symbol: ScenarioTemplates.template(a.scenario.templateID)?.symbol ?? "alarm.fill")527        }, confirmedDays: stats.days.filter { $0.confirmed > 0 }.map(\.day), currentStreak: stats.currentStreak)528        let previous = WidgetSnapshot.load()529        guard snapshot.alarms != previous.alarms || snapshot.confirmedDays != previous.confirmedDays || snapshot.currentStreak != previous.currentStreak else { return }530        snapshot.save()531        WidgetCenter.shared.reloadAllTimelines()532    }533534    // MARK: Demo data (screenshots, UI tests)535    func loadDemoData() async {536        guard library.alarms.isEmpty else { return }537        var weekday = ScenarioTemplates.all[1].makeAlarm(now: now()); weekday.name = "Workday"538        var gentle = ScenarioTemplates.all[0].makeAlarm(now: now()); gentle.weekdays = Weekday.weekend; gentle.time = ClockTime(hour: 8, minute: 30)539        var gym = ScenarioTemplates.all[2].makeAlarm(now: now()); gym.isEnabled = false540        for a in [weekday, gentle, gym] { await save(a) }541        // Two weeks of plausible mornings, clearly synthetic (only in demo mode).542        var generator = SeededGenerator(seed: 42)543        for dayOffset in (1...14).reversed() {544            guard let day = calendar.date(byAdding: .day, value: -dayOffset, to: calendar.startOfDay(for: now())) else { continue }545            let fire = day.addingTimeInterval(6.5 * 3600)546            let occurrence = UUID()547            history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .fired, date: fire))548            let snoozes = Int.random(in: 0...2, using: &generator)549            var t = fire550            for _ in 0..<snoozes { history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .snoozed, date: t.addingTimeInterval(20), duration: 360)); t += 380 }551            history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .acknowledged, date: t.addingTimeInterval(15)))552            if dayOffset == 9 { history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .missionBypassed, date: t.addingTimeInterval(40))); continue }553            var cursor = t.addingTimeInterval(25)554            for kind in [MissionKind.math, .memoryMatrix, .steps] {555                let duration = Double.random(in: 18...70, using: &generator)556                cursor += duration557                history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .missionStepCompleted, date: cursor, missionKind: kind,558                                         level: 2 + (dayOffset < 5 ? 1 : 0), duration: duration, mistakes: Int.random(in: 0...2, using: &generator), rounds: 3))559            }560            history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .missionCompleted, date: cursor, duration: cursor.timeIntervalSince(t)))561            history.record(WakeEvent(alarmID: weekday.id, occurrenceID: occurrence, kind: .wakeConfirmed, date: cursor.addingTimeInterval(Double.random(in: 5...240, using: &generator))))562        }563        try? historyStore.save(history)564        writeWidgetSnapshot()565    }566}567
Files main
Menu

Theme