Repository Public License
1// ORIX Alarm2// File: App/Sources/ORIXAlarmApp.swift3// Description: App entry point: builds the app model (AlarmKit or fake service), handles launch options, lifecycle and deep links.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI910/// Launch arguments used by UI tests, screenshots and manual debugging.11struct LaunchOptions {12 var uiTest = false // -ORIXUITest YES : fake alarm service, isolated storage13 var reset = false // -ORIXReset YES : start from empty storage14 var demo = false // -ORIXDemo YES : sample alarms and two weeks of synthetic history15 var mission: MissionKind? // -ORIXMission math : open a mission preview at launch16 var level: Int? // -ORIXLevel 1...417 var seed: UInt64? // -ORIXSeed n18 var tab: AppTab? // -ORIXTab alarms19 var skipOnboarding = false // -ORIXSkipOnboarding YES20 var denyAlarms = false // -ORIXDenyAlarms YES : fake service refuses authorization21 var simulateWake = false // -ORIXSimulateWake YES : UI tests, the fake system rings and stops an alarm with a one-question mission22 var probeAlarm: String? // -ORIXProbeAlarm plain|snooze|mission : DEBUG, real AlarmKit alarm at the next minute (simulator validation)2324 static let current: LaunchOptions = {25 let d = UserDefaults.standard26 var o = LaunchOptions()27 o.uiTest = d.bool(forKey: "ORIXUITest"); o.reset = d.bool(forKey: "ORIXReset"); o.demo = d.bool(forKey: "ORIXDemo")28 o.mission = d.string(forKey: "ORIXMission").flatMap(MissionKind.init(rawValue:))29 o.level = d.object(forKey: "ORIXLevel") == nil ? nil : d.integer(forKey: "ORIXLevel")30 o.seed = d.string(forKey: "ORIXSeed").flatMap(UInt64.init)31 o.tab = d.string(forKey: "ORIXTab").flatMap(AppTab.init(rawValue:))32 o.skipOnboarding = d.bool(forKey: "ORIXSkipOnboarding"); o.denyAlarms = d.bool(forKey: "ORIXDenyAlarms")33 o.probeAlarm = d.string(forKey: "ORIXProbeAlarm"); o.simulateWake = d.bool(forKey: "ORIXSimulateWake")34 return o35 }()36}3738@main39struct ORIXAlarmApp: App {40 @State private var model: AppModel41 @Environment(\.scenePhase) private var scenePhase4243 init() {44 let options = LaunchOptions.current45 let isUnitTesting = NSClassFromString("XCTestCase") != nil46 if options.uiTest || isUnitTesting {47 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ORIXAlarm-UITest", isDirectory: true)48 if options.reset || isUnitTesting { try? FileManager.default.removeItem(at: directory) }49 let service = FakeAlarmService(authorization: options.denyAlarms ? .denied : .notDetermined)50 if options.denyAlarms { service.authorizationOnRequest = .denied }51 _model = State(initialValue: AppModel(service: service, directory: directory))52 } else {53 if options.reset { try? FileManager.default.removeItem(at: AppGroup.directory) }54 _model = State(initialValue: AppModel(service: AlarmKitService()))55 }56 AppDependencies.model = _model.wrappedValue57 }5859 var body: some Scene {60 WindowGroup {61 RootView()62 .environment(model)63 .task {64 let options = LaunchOptions.current65 if options.skipOnboarding || options.demo { model.updateSettings { $0.hasCompletedOnboarding = true } }66 await model.start()67 if options.demo { await model.loadDemoData() }68 _ = NightstandLaunch.openIfRequested(model: model) // -ORIXNightstandDemo YES69 if let tab = options.tab { model.selectedTab = tab }70 if UserDefaults.standard.bool(forKey: "ORIXEditor") { model.editingAlarm = model.alarms.first ?? model.makeDraftAlarm() } // -ORIXEditor YES (screenshots)71 if options.simulateWake, options.uiTest, let fake = model.service as? FakeAlarmService {72 var alarm = AlarmDefinition(name: "Simulated", time: ClockTime(hour: 7, minute: 0), weekdays: Weekday.everyDay)73 alarm.scenario = WakeScenario(missions: [MissionStep(kind: .math, difficulty: .easy, rounds: 1)], requiresConfirmation: true)74 await model.save(alarm)75 fake.simulateFire(systemID: alarm.id)76 try? await Task.sleep(for: .milliseconds(300))77 fake.stop(systemID: alarm.id) // observed by the model exactly like a user stop78 }79 #if DEBUG80 if let probe = options.probeAlarm { await Self.scheduleProbe(probe, model: model) }81 #endif82 if let kind = options.mission {83 model.previewMissions([MissionStep(kind: kind, difficulty: .fixed(level: options.level ?? 2), rounds: 2)], name: kind.title, seed: options.seed ?? 1)84 }85 }86 .onChange(of: scenePhase) { _, phase in87 if phase == .active { Task { await model.activate() } }88 }89 .onOpenURL { url in DeepLink.handle(url, model: model) }90 }91 }92}9394#if DEBUG95extension ORIXAlarmApp {96 /// Schedules a real one-time alarm for the next minute boundary at least 20 s away and logs what the system reports.97 static func scheduleProbe(_ variant: String, model: AppModel) async {98 let log = URL(fileURLWithPath: "/tmp/orix-alarm-probe/probe.log")99 func note(_ line: String) {100 try? FileManager.default.createDirectory(at: log.deletingLastPathComponent(), withIntermediateDirectories: true)101 let text = ((try? String(contentsOf: log, encoding: .utf8)) ?? "") + "\(Date.now.formatted(date: .omitted, time: .standard)) \(line)\n"102 try? text.write(to: log, atomically: true, encoding: .utf8)103 }104 let authorization = await model.requestAuthorization()105 note("authorization=\(authorization.rawValue)")106 let target = Date.now.addingTimeInterval(80)107 let c = Calendar.current.dateComponents([.hour, .minute], from: target)108 let autostop = variant.hasSuffix("-autostop")109 let variant = variant.replacingOccurrences(of: "-autostop", with: "")110 var scenario = WakeScenario(snooze: variant == "snooze" ? SnoozePolicy(baseMinutes: 1, maxCount: 1) : .none, requiresConfirmation: variant == "mission")111 if variant == "mission" { scenario.missions = [MissionStep(kind: .math, difficulty: .easy, rounds: 1)] }112 let alarm = AlarmDefinition(name: "Probe", time: ClockTime(hour: c.hour ?? 0, minute: c.minute ?? 0), scenario: scenario)113 let error = await model.save(alarm)114 note("variant=\(variant) time=\(alarm.time.hour):\(alarm.time.minute) saveError=\(error ?? "none") status=\(model.status(for: alarm.id).rawValue)")115 Task {116 var alertingSamples = 0117 for _ in 0..<150 {118 try? await Task.sleep(for: .seconds(2))119 // "-autostop": stop through AlarmKit itself after a few seconds, as the system Stop control does,120 // to exercise the observation path without driving the simulator's alert UI.121 if autostop, (try? model.service.snapshots())?.contains(where: { $0.state == .alerting }) == true {122 alertingSamples += 1123 if alertingSamples == 4 { model.service.stop(systemID: alarm.id); note("probe called AlarmManager.stop") }124 }125 let states = (try? model.service.snapshots())?.map { "\($0.state.rawValue)" }.joined(separator: ",") ?? "unreadable"126 let events = model.events.map(\.kind.rawValue).joined(separator: ",")127 note("system=[\(states)] events=[\(events)] enabled=\(model.alarm(alarm.id)?.isEnabled ?? false) mission=\(model.missionRun != nil)")128 }129 }130 }131}132#endif133134/// Gives App Intents access to the running model (intents run in the app process).135enum AppDependencies {136 static var model: AppModel?137}138139enum DeepLink {140 /// orixalarm://new, orixalarm://alarms, orixalarm://today, orixalarm://sleep, orixalarm://alarm/<uuid>141 static func handle(_ url: URL, model: AppModel) {142 guard url.scheme == "orixalarm" else { return }143 switch url.host() {144 case "new": model.selectedTab = .alarms; model.editingAlarm = model.makeDraftAlarm()145 case "alarms": model.selectedTab = .alarms146 case "sleep": model.selectedTab = .sleep147 case "insights": model.selectedTab = .insights148 case "alarm":149 model.selectedTab = .alarms150 if let id = UUID(uuidString: url.lastPathComponent), let alarm = model.alarm(id) { model.editingAlarm = alarm }151 default: model.selectedTab = .today152 }153 }154}155