diff --git a/Normal/App/AppContainer.swift b/Normal/App/AppContainer.swift index 5141f48..f9cd81d 100644 --- a/Normal/App/AppContainer.swift +++ b/Normal/App/AppContainer.swift @@ -1,8 +1,6 @@ -import SwiftData import SwiftUI struct AppContainer: View { - @Query private var allSettings: [Settings] @State private var screenTimeService: ScreenTimeService @State private var timedUnblockService: TimedUnblockService @State private var nfcService = NFCService.shared @@ -40,14 +38,5 @@ struct AppContainer: View { .environment(donationService) .environment(usageLimitService) .environment(unlockInbox) - .task { mirrorCustomDomainsEnabled() } - .onChange(of: allSettings.first?.enableCustomDomains ?? false) { _, enabled in - scheduleService.mirrorCustomDomainsEnabled(enabled) - screenTimeService.reconcile() - } - } - - private func mirrorCustomDomainsEnabled() { - scheduleService.mirrorCustomDomainsEnabled(allSettings.first?.enableCustomDomains ?? false) } } diff --git a/Normal/App/AppServices.swift b/Normal/App/AppServices.swift index 314d48c..98dee3e 100644 --- a/Normal/App/AppServices.swift +++ b/Normal/App/AppServices.swift @@ -35,7 +35,7 @@ final class AppServices { timedUnblock = TimedUnblockService( activityCenter: center, sharedStore: store, - onExpiration: { screenTime.reconcile() } + onExpirationAt: { screenTime.reconcile(at: $0) } ) schedule = ScheduleService(activityCenter: center, sharedStore: store) appReview = AppReviewService( @@ -50,7 +50,7 @@ final class AppServices { } else { let screenTime = ScreenTimeService() self.screenTime = screenTime - timedUnblock = TimedUnblockService(onExpiration: { screenTime.reconcile() }) + timedUnblock = TimedUnblockService(onExpirationAt: { screenTime.reconcile(at: $0) }) schedule = ScheduleService() appReview = AppReviewService() emergencyUnblock = EmergencyUnblockService(ledger: KeychainEmergencyUnblockLedger()) diff --git a/Normal/App/ContentView.swift b/Normal/App/ContentView.swift index 496348a..e0be189 100644 --- a/Normal/App/ContentView.swift +++ b/Normal/App/ContentView.swift @@ -12,6 +12,7 @@ struct ContentView: View { @Query private var allSettings: [Settings] @Query private var schedules: [BlockSchedule] @Query private var usageLimits: [UsageLimit] + @Query private var selectedApps: [SelectedApps] @State private var navigationCoordinator = NavigationCoordinator() @@ -56,6 +57,7 @@ struct ContentView: View { private func onAppear() { if let settings { emergencyUnblockService.reconcile(into: settings) + scheduleService.mirrorCustomDomainsEnabled(settings.enableCustomDomains) } timedUnblockService.reconcile(screenTimeService: screenTimeService) @@ -73,12 +75,20 @@ struct ContentView: View { } } + private var mainSelectionConstraint: SelectionConstraint? { + selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings?.enableCustomDomains ?? false) + } + /// Re-registers every `DeviceActivity` we depend on. Usage limits ride along /// with schedules: their threshold events use `includesPastActivity`, so /// re-registering mid-day cannot hand back an allowance already spent. private func reregisterActivities() { guard settings?.hasCompletedOnboarding == true else { return } - scheduleService.registerAll(schedules, screenTimeService: screenTimeService) + scheduleService.registerAll( + schedules, + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint + ) reregisterUsageLimits() } diff --git a/Normal/Models/BlockSchedule.swift b/Normal/Models/BlockSchedule.swift index b582408..b21839d 100644 --- a/Normal/Models/BlockSchedule.swift +++ b/Normal/Models/BlockSchedule.swift @@ -115,19 +115,91 @@ final class BlockSchedule: Identifiable { ) } - func hasSameRules(as dto: ScheduleDTO) -> Bool { + func latestStart(atOrBefore date: Date, calendar: Calendar = .current) -> Date? { + ScheduleWindow.latestStart( + atOrBefore: date, + startHour: startHour, + startMinute: startMinute, + weekdays: weekdays, + calendar: calendar + ) + } + + struct Snapshot { + let name: String + let selection: FamilyActivitySelection + let startHour: Int + let startMinute: Int + let durationMinutes: Int + let weekdays: Set + let shouldBlock: Bool + let isTimed: Bool + let isEnabled: Bool + let customDomains: [String] + + init(_ schedule: BlockSchedule) { + name = schedule.name + selection = schedule.selection + startHour = schedule.startHour + startMinute = schedule.startMinute + durationMinutes = schedule.durationMinutes + weekdays = schedule.weekdays + shouldBlock = schedule.shouldBlock + isTimed = schedule.isTimed + isEnabled = schedule.isEnabled + customDomains = schedule.customDomains + } + + func restore(to schedule: BlockSchedule) { + schedule.name = name + schedule.selection = selection + schedule.startHour = startHour + schedule.startMinute = startMinute + schedule.durationMinutes = durationMinutes + schedule.weekdays = weekdays + schedule.shouldBlock = shouldBlock + schedule.isTimed = isTimed + schedule.isEnabled = isEnabled + schedule.customDomains = customDomains + } + } + + func hasSameTimingAndMode(as dto: ScheduleDTO) -> Bool { startHour == dto.startHour && startMinute == dto.startMinute && effectiveDurationMinutes == dto.durationMinutes && weekdays == dto.weekdays && shouldBlock == dto.shouldBlock && isTimed == dto.isTimed - && customDomains == dto.customDomains - && (try? FamilyActivitySelection.fromData(dto.selectionData)) == selection } - func toDTO(activatedAt: Date? = nil) -> ScheduleDTO? { - guard let data = try? selection.toData() else { return nil } + func hasSameRules( + as dto: ScheduleDTO, + constrainedTo main: SelectionConstraint? = nil + ) -> Bool { + let previousSelection = try? FamilyActivitySelection.fromData(dto.selectionData) + let effectiveSelection = main?.constrain(selection, previous: previousSelection) ?? selection + let effectiveDomains = main?.intersect(customDomains) ?? customDomains + return hasSameTimingAndMode(as: dto) + && Set(effectiveDomains.compactMap(DomainNormalizer.normalize)) + == Set(dto.customDomains.compactMap(DomainNormalizer.normalize)) + && previousSelection == effectiveSelection + } + + func toDTO( + activatedAt: Date? = nil, + constrainedTo main: SelectionConstraint? = nil, + previousSelection: FamilyActivitySelection? = nil, + confirmedRemovals: FamilyActivitySelection? = nil + ) -> ScheduleDTO? { + let effectiveSelection = + main?.constrain( + selection, + previous: previousSelection, + confirmedRemovals: confirmedRemovals + ) ?? selection + let effectiveDomains = main?.intersect(customDomains) ?? customDomains + guard let data = try? effectiveSelection.toData() else { return nil } return ScheduleDTO( id: id, name: name, @@ -138,7 +210,7 @@ final class BlockSchedule: Identifiable { weekdays: weekdays, shouldBlock: shouldBlock, isTimed: isTimed, - customDomains: customDomains, + customDomains: effectiveDomains, isEnabled: isEnabled, activatedAt: activatedAt ) diff --git a/Normal/Models/SelectionConstraint.swift b/Normal/Models/SelectionConstraint.swift new file mode 100644 index 0000000..9c78e21 --- /dev/null +++ b/Normal/Models/SelectionConstraint.swift @@ -0,0 +1,75 @@ +import FamilyControls +import Foundation + +struct SelectionConstraint { + let selection: FamilyActivitySelection + let customDomains: [String] + let customDomainsEnabled: Bool + + var effectiveCustomDomains: [String] { + customDomainsEnabled ? customDomains : [] + } + + func constrain( + _ otherSelection: FamilyActivitySelection, + previous: FamilyActivitySelection? = nil, + confirmedRemovals: FamilyActivitySelection? = nil + ) -> FamilyActivitySelection { + var result = otherSelection + result.applicationTokens = Self.constrain( + otherSelection.applicationTokens, + main: selection.applicationTokens, + previous: previous?.applicationTokens, + confirmedRemovals: confirmedRemovals?.applicationTokens + ) + result.webDomainTokens = Self.constrain( + otherSelection.webDomainTokens, + main: selection.webDomainTokens, + previous: previous?.webDomainTokens, + confirmedRemovals: confirmedRemovals?.webDomainTokens + ) + result.categoryTokens = Self.constrain( + otherSelection.categoryTokens, + main: selection.categoryTokens, + previous: previous?.categoryTokens, + confirmedRemovals: confirmedRemovals?.categoryTokens + ) + return result + } + + func intersect(_ otherDomains: [String]) -> [String] { + CustomDomains.subset(otherDomains, of: effectiveCustomDomains) + } + + func needsSync(selection otherSelection: FamilyActivitySelection, customDomains otherDomains: [String]) -> Bool { + if !otherSelection.isSubset(of: selection) { + return true + } + if customDomainsEnabled, CustomDomains.needsResync(otherDomains, main: customDomains) { + return true + } + return false + } + + private static func constrain( + _ scheduleTokens: Set, + main: Set, + previous: Set?, + confirmedRemovals: Set? + ) -> Set { + guard !main.isEmpty else { return [] } + let baseline = previous.map { $0.intersection(scheduleTokens) } ?? [] + let retained = confirmedRemovals.map { baseline.subtracting($0) } ?? baseline + return retained.union(scheduleTokens.intersection(main)) + } +} + +extension SelectedApps { + func effectiveConstraint(customDomainsEnabled: Bool) -> SelectionConstraint { + SelectionConstraint( + selection: selection, + customDomains: customDomains, + customDomainsEnabled: customDomainsEnabled + ) + } +} diff --git a/Normal/Modifiers/LiveActivitySync.swift b/Normal/Modifiers/LiveActivitySync.swift index cbf967f..ce929e6 100644 --- a/Normal/Modifiers/LiveActivitySync.swift +++ b/Normal/Modifiers/LiveActivitySync.swift @@ -6,13 +6,23 @@ private struct LiveActivitySyncModifier: ViewModifier { @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var groups: [AppGroup] @Query private var settingsRows: [Settings] + private struct GroupTitle: Equatable { + let id: UUID + let name: String + } + private var liveActivityEnabled: Bool { settingsRows.first?.showTimedUnblockLiveActivity ?? true } + private var groupTitles: [GroupTitle] { + groups.map { GroupTitle(id: $0.id, name: $0.name) } + } + func body(content: Content) -> some View { content .onChange(of: timedUnblockService.activeUnblocks) { _, _ in reconcile() } + .onChange(of: groupTitles) { _, _ in reconcile() } .onChange(of: liveActivityEnabled) { _, _ in reconcile() } .onAppear { reconcile() } } diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index fc6ae10..6b91702 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -26,10 +26,25 @@ private struct WidgetActionResponder: ViewModifier { let keyType: KeyType? } + private struct GroupSnapshot: Equatable { + let id: UUID + let name: String + let sortIndex: Int + let lastUpdated: Date + } + private var unblockDurations: [TimedUnblockDuration] { allSettings.first?.unblockDurations ?? TimedUnblockDuration.presets } + private var groupsFingerprint: [GroupSnapshot] { + groups.map { GroupSnapshot(id: $0.id, name: $0.name, sortIndex: $0.sortIndex, lastUpdated: $0.lastUpdated) } + } + + private var customDomainsEnabled: Bool { + allSettings.first?.enableCustomDomains ?? false + } + func body(content: Content) -> some View { content .protectedAction( @@ -47,7 +62,8 @@ private struct WidgetActionResponder: ViewModifier { .onChange(of: unlockInbox.pending, initial: true) { _, _ in takeInboxRequest() } .onChange(of: scenePhase) { _, _ in takeInboxRequest() } .onChange(of: screenTimeService.authorizationState) { _, _ in takeInboxRequest() } - .onChange(of: groups) { _, _ in syncGroups() } + .onChange(of: groupsFingerprint) { _, _ in syncGroups() } + .onChange(of: customDomainsEnabled) { _, _ in syncGroups() } .onChange(of: keys) { _, _ in syncWidget() } .onChange(of: screenTimeService.lastUpdate) { _, _ in syncWidget() } .onChange(of: unblockDurations) { _, _ in syncWidget() } diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index 04f3710..d23c0c4 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -587,6 +587,9 @@ "Couldn't confirm your location. Open Normal to check it?" : { "comment" : "Text displayed in a notification when a timed unblock is already running for all apps.", "isCommentAutoGenerated" : true + }, + "Couldn't Save Selection" : { + }, "Couldn't start the unblock. Open Normal and try again." : { "comment" : "Error when unblocking an app fails.", @@ -595,6 +598,15 @@ "Couldn't Unblock" : { "comment" : "Title of an alert shown when an unblock with the default duration fails.", "isCommentAutoGenerated" : true + }, + "Couldn't update blocking state right now. Please try again." : { + + }, + "Couldn't update this schedule right now. Please try again." : { + + }, + "Couldn't update your selection right now. Please try again." : { + }, "Create a schedule to automatically block or unblock apps at set times." : { "comment" : "A footer message in the Schedules view that instructs the user on how to create schedules.", @@ -826,6 +838,9 @@ "Getting one" : { "comment" : "A subheading within the \"Where to place them\" card, explaining how to get a QR code or barcode.", "isCommentAutoGenerated" : true + }, + "Global keys can be deleted in the Keys tab." : { + }, "Go to App Select to choose which apps to manage before creating schedules." : { @@ -1386,6 +1401,9 @@ "Schedule" : { "comment" : "The title of the view that lists schedules.", "isCommentAutoGenerated" : true + }, + "Schedule Notice" : { + }, "Schedules" : { "comment" : "The title of the screen where users can view and manage their schedules.", diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index 63b200b..ea7cf5b 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -1,4 +1,6 @@ +import FamilyControls import Foundation +import SwiftData import UIKit enum BlockActions { @@ -49,13 +51,192 @@ enum BlockActions { screenTimeService: screenTimeService ) case .permanent: - screenTimeService.unblockPermanently(grant, settings: settings) + guard screenTimeService.unblockPermanently(grant, settings: settings) else { + throw TimedUnblockStorageError.unavailable + } + if grant.target.group == nil { + timedUnblockService.clearAll() + } else if let group = grant.target.group, timedUnblockService.isGroupUnblockActive(groupId: group.id) { + timedUnblockService.cancelGroup(groupId: group.id) + } timing = .exact } playHaptic() return timing } + static func unblockOrphanedShields( + proof: KeyProof, + settings: Settings, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService + ) throws { + guard proof.coversAllApps else { return } + guard screenTimeService.unblockAll(blockAllPreventsAppDelete: settings.blockAllPreventsAppDelete) else { + throw TimedUnblockStorageError.unavailable + } + timedUnblockService.clearAll() + playHaptic() + } + + @discardableResult + static func updateMainSelection( + from oldSelection: FamilyActivitySelection, + oldCustomDomains: [String], + to newSelection: FamilyActivitySelection, + newCustomDomains: [String], + schedules: [BlockSchedule], + settings: Settings, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService, + scheduleService: ScheduleService + ) -> Bool { + let constraint = SelectionConstraint( + selection: newSelection, + customDomains: newCustomDomains, + customDomainsEnabled: settings.enableCustomDomains + ) + let effectiveNewDomains = constraint.effectiveCustomDomains + let effectiveOldDomains = settings.enableCustomDomains ? oldCustomDomains : [] + let confirmedRemovals = oldSelection.confirmedRemovals(movingTo: newSelection) + let becameEmpty = newSelection.isEmpty && effectiveNewDomains.isEmpty + let schedulePlan = scheduleService.prepareConstrainedSync( + schedules, + constrainedTo: constraint, + confirmedRemovals: confirmedRemovals + ) + if timedUnblockService.isMainUnblockActive { + guard + timedUnblockService.updateMainSelection( + newSelection, + customDomains: effectiveNewDomains, + from: oldSelection, + previousCustomDomains: effectiveOldDomains, + screenTimeService: screenTimeService, + preservingPermanentSchedules: schedulePlan.schedulesToPreserve, + at: schedulePlan.now, + beforeRetiringOnEmpty: { + scheduleService.commitConstrainedSync(schedulePlan) + } + ) + else { return false } + if !becameEmpty { + let changedGroupTimers = timedUnblockService.pruneGroupUnblocks( + removing: confirmedRemovals, + keeping: newSelection, + customDomains: effectiveNewDomains + ) + scheduleService.commitConstrainedSync(schedulePlan) + if changedGroupTimers || schedulePlan.hasChanges { + screenTimeService.reconcile() + } + } + return true + } else { + guard + screenTimeService.unblockRemovedFromMain( + from: oldSelection, + customDomains: effectiveOldDomains, + to: newSelection, + customDomains: effectiveNewDomains, + clearAppDeletion: becameEmpty, + appDeletionCutoff: nil, + preservingPermanentSchedules: schedulePlan.schedulesToPreserve, + at: schedulePlan.now + ) + else { return false } + scheduleService.commitConstrainedSync(schedulePlan) + let changedGroupTimers: Bool + if becameEmpty { + changedGroupTimers = !timedUnblockService.activeUnblocks.isEmpty + timedUnblockService.clearAll() + } else { + changedGroupTimers = timedUnblockService.pruneGroupUnblocks( + removing: confirmedRemovals, + keeping: newSelection, + customDomains: effectiveNewDomains + ) + } + if changedGroupTimers || schedulePlan.hasChanges { + screenTimeService.reconcile() + } + return true + } + } + + @discardableResult + static func setCustomDomainsEnabled( + _ enabled: Bool, + settings: Settings, + schedules: [BlockSchedule], + mainSelection: SelectedApps?, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService, + scheduleService: ScheduleService + ) -> Bool { + let previousEnabled = settings.enableCustomDomains + if enabled { + let schedulePlan = scheduleService.prepareConstrainedSync( + schedules, + constrainedTo: mainSelection?.effectiveConstraint(customDomainsEnabled: true) + ) + scheduleService.mirrorCustomDomainsEnabled(true) + guard + screenTimeService.reconcile( + preservingPermanentSchedules: schedulePlan.schedulesToPreserve, + at: schedulePlan.now + ) + else { + scheduleService.mirrorCustomDomainsEnabled(previousEnabled) + return false + } + settings.enableCustomDomains = true + scheduleService.commitConstrainedSync(schedulePlan) + if schedulePlan.hasChanges { + screenTimeService.reconcile() + } + return true + } + let schedulePlan = scheduleService.prepareConstrainedSync( + schedules, + constrainedTo: mainSelection?.effectiveConstraint(customDomainsEnabled: false) + ) + scheduleService.mirrorCustomDomainsEnabled(false) + let mainHasNoApps = mainSelection?.selection.isEmpty ?? true + let cleared = timedUnblockService.handleCustomDomainsDisabled( + clearAppDeletionWhenNoMainTimer: mainHasNoApps, + screenTimeService: screenTimeService, + preservingPermanentSchedules: schedulePlan.schedulesToPreserve, + at: schedulePlan.now, + beforeRetiringMainTimer: { + scheduleService.commitConstrainedSync(schedulePlan) + } + ) + guard cleared else { + scheduleService.mirrorCustomDomainsEnabled(previousEnabled) + return false + } + settings.enableCustomDomains = false + if schedulePlan.hasChanges { + screenTimeService.reconcile() + } + return true + } + + static func deleteGroup( + _ group: AppGroup, + keys: [Key], + from context: ModelContext, + timedUnblockService: TimedUnblockService, + screenTimeService: any ScreenTimeProviding + ) { + let hadTimedUnblock = timedUnblockService.isGroupUnblockActive(groupId: group.id) + group.deleteCascading(keys: keys, from: context) + if hadTimedUnblock { + timedUnblockService.cancelGroup(groupId: group.id, screenTimeService: screenTimeService) + } + } + static func emergencyUnblock( schedules: [BlockSchedule], screenTimeService: any ScreenTimeProviding, diff --git a/Normal/Services/DeviceActivityProviding.swift b/Normal/Services/DeviceActivityProviding.swift deleted file mode 100644 index d7aef8f..0000000 --- a/Normal/Services/DeviceActivityProviding.swift +++ /dev/null @@ -1,28 +0,0 @@ -import DeviceActivity -import Foundation - -extension DeviceActivityProviding { - func syncHeartbeat(sharedStore: any SharedStoreProviding, at date: Date) { - let name = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) - let monitored = monitoredActivityNames - let dailyLimitsNeeded = - monitored.contains(SharedConstants.usageLimitsActivityName) - || DailyLimitMonitoring.eventSpecs( - for: sharedStore.loadUsageLimits(), - period: sharedStore.usagePeriod, - on: date - ).contains(where: \.isArmable) - let needed = - sharedStore.loadSchedules().contains { $0.isEffectivelyEnabled(monitoredActivities: monitored) } - || dailyLimitsNeeded - || sharedStore.loadTimedUnblocks().contains { $0.endDate > date } - let heartbeat = DeviceActivityScheduleFactory.heartbeat() - let current = registeredSchedule(for: name) - if needed { - guard current?.hasSameWindow(as: heartbeat) != true else { return } - try? startMonitoring(name, during: heartbeat, events: [:]) - } else if current != nil || monitored.contains(name.rawValue) { - stopMonitoring([name]) - } - } -} diff --git a/Normal/Services/DeviceActivityScheduleFactory.swift b/Normal/Services/DeviceActivityScheduleFactory.swift index e4aa5da..391035a 100644 --- a/Normal/Services/DeviceActivityScheduleFactory.swift +++ b/Normal/Services/DeviceActivityScheduleFactory.swift @@ -21,10 +21,6 @@ enum DeviceActivityScheduleFactory { } static func heartbeat() -> DeviceActivitySchedule { - DeviceActivitySchedule( - intervalStart: DateComponents(minute: 0, second: 0), - intervalEnd: DateComponents(minute: 30, second: 0), - repeats: true - ) + .heartbeat } } diff --git a/Normal/Services/LiveActivityManager.swift b/Normal/Services/LiveActivityManager.swift index 3644faa..465531f 100644 --- a/Normal/Services/LiveActivityManager.swift +++ b/Normal/Services/LiveActivityManager.swift @@ -31,15 +31,30 @@ enum LiveActivityManager { static func reconcile(active: [String: Date], titles: [String: String], startDates: [String: Date] = [:]) { guard ActivityAuthorizationInfo().areActivitiesEnabled else { return } + func title(for id: String) -> String { + titles[id] ?? String(localized: "Apps") + } + let all = Activity.activities for activity in all where !isRunning(activity.activityState) { Task { await activity.end(nil, dismissalPolicy: .immediate) } } let running = all.filter { isRunning($0.activityState) } - let runningByID = Dictionary( - running.map { ($0.attributes.unblockID, $0) }, - uniquingKeysWith: { first, _ in first } - ) + var runningByID: [String: Activity] = [:] + for activity in running { + let id = activity.attributes.unblockID + if let existing = runningByID[id] { + let desiredTitle = title(for: id) + if existing.attributes.title != desiredTitle, activity.attributes.title == desiredTitle { + runningByID[id] = activity + Task { await existing.end(nil, dismissalPolicy: .immediate) } + } else { + Task { await activity.end(nil, dismissalPolicy: .immediate) } + } + } else { + runningByID[id] = activity + } + } let plan = LiveActivityPlan(activeIDs: Set(active.keys), runningIDs: Set(runningByID.keys)) for id in plan.toEnd { @@ -49,13 +64,29 @@ enum LiveActivityManager { for id in plan.toUpdate { guard let activity = runningByID[id], let endDate = active[id] else { continue } - Task { await activity.update(content(endingAt: endDate)) } + let desiredTitle = title(for: id) + let newContent = content(endingAt: endDate) + if activity.attributes.title != desiredTitle { + let attributes = TimedUnblockActivityAttributes( + title: desiredTitle, + unblockID: id, + startDate: startDates[id] ?? activity.attributes.startDate + ) + do { + _ = try Activity.request(attributes: attributes, content: newContent) + Task { await activity.end(nil, dismissalPolicy: .immediate) } + } catch { + Task { await activity.update(newContent) } + } + } else { + Task { await activity.update(newContent) } + } } for id in plan.toStart { guard let endDate = active[id] else { continue } let attributes = TimedUnblockActivityAttributes( - title: titles[id] ?? String(localized: "Apps"), + title: title(for: id), unblockID: id, startDate: startDates[id] ?? .now ) diff --git a/Normal/Services/ScheduleService.swift b/Normal/Services/ScheduleService.swift index dadb9d3..8c511e3 100644 --- a/Normal/Services/ScheduleService.swift +++ b/Normal/Services/ScheduleService.swift @@ -44,16 +44,41 @@ final class ScheduleService { func registerAll( _ schedules: [BlockSchedule], - screenTimeService: any ScreenTimeProviding + screenTimeService: any ScreenTimeProviding, + constrainedTo main: SelectionConstraint? = nil ) { - syncAllToSharedStore(schedules) - let wanted = Set(schedules.filter(\.isEnabled).map { activityName(for: $0).rawValue }) + let now = clock() + let monitored = activityCenter.monitoredActivityNames + let previousByID = loadPreviousByID() + let pending = resolvePendingPermanentSchedules( + schedules: schedules, + previousByID: previousByID, + monitored: monitored, + constrainedTo: main, + screenTimeService: screenTimeService, + at: now + ) + persistSchedules( + schedules, + previousByID: previousByID, + reactivated: pending.reactivated, + constrainedTo: main, + keepingUnchanged: pending.keepingUnchanged, + appending: pending.retainedOrphans + ) + let wanted = Set( + schedules + .filter { $0.isEnabled || pending.keepingUnchanged[$0.id] != nil } + .map { activityName(for: $0).rawValue } + + pending.retainedOrphans.map { SharedConstants.scheduleActivityName(for: $0.id) } + ) let stale = activityCenter.monitoredActivityNames.filter { $0.hasPrefix("schedule_") && !wanted.contains($0) } if !stale.isEmpty { activityCenter.stopMonitoring(stale.map { DeviceActivityName($0) }) } - activityCenter.syncHeartbeat(sharedStore: sharedStore, at: clock()) - for schedule in schedules where schedule.isEnabled && !isRegistered(schedule) { + activityCenter.syncHeartbeat(sharedStore: sharedStore, at: now) + for schedule in schedules + where schedule.isEnabled && pending.keepingUnchanged[schedule.id] == nil && !isRegistered(schedule) { try? sync(schedule) } screenTimeService.reconcile() @@ -71,21 +96,69 @@ final class ScheduleService { func remove( _ schedule: BlockSchedule, remaining: [BlockSchedule], - screenTimeService: any ScreenTimeProviding - ) { - activityCenter.stopMonitoring([activityName(for: schedule)]) - syncAllToSharedStore(remaining) - activityCenter.syncHeartbeat(sharedStore: sharedStore, at: clock()) + screenTimeService: any ScreenTimeProviding, + constrainedTo main: SelectionConstraint? = nil + ) throws { + let now = clock() + let monitored = activityCenter.monitoredActivityNames + let previousByID = loadPreviousByID() + if let previous = previousByID[schedule.id], + !previous.isTimed, + previous.isEffectivelyEnabled(monitoredActivities: monitored) + { + guard screenTimeService.preservePermanentSchedule(previous, at: now) else { + throw ScheduleRegistrationError.storageUnavailable + } + } + let pending = resolvePendingPermanentSchedules( + schedules: remaining, + previousByID: previousByID, + monitored: monitored, + constrainedTo: main, + excludingOrphanID: schedule.id, + screenTimeService: screenTimeService, + at: now + ) + let targetActivity = activityName(for: schedule) + let otherResolvedOrphans = pending.resolvedOrphanActivities.filter { $0 != targetActivity } + if !otherResolvedOrphans.isEmpty { + activityCenter.stopMonitoring(otherResolvedOrphans) + } + activityCenter.stopMonitoring([targetActivity]) + persistSchedules( + remaining, + previousByID: previousByID, + reactivated: pending.reactivated, + constrainedTo: main, + keepingUnchanged: pending.keepingUnchanged, + appending: pending.retainedOrphans + ) + for resolved in pending.resolvedSchedules where !resolved.isEnabled || !isRegistered(resolved) { + try? sync(resolved) + } + activityCenter.syncHeartbeat(sharedStore: sharedStore, at: now) screenTimeService.reconcile() } func toggleEnabled( _ schedule: BlockSchedule, allSchedules: [BlockSchedule], - screenTimeService: any ScreenTimeProviding + screenTimeService: any ScreenTimeProviding, + constrainedTo main: SelectionConstraint? = nil ) throws { + let wasEnabled = schedule.isEnabled schedule.isEnabled.toggle() - try syncAndPersist(schedule, allSchedules: allSchedules, screenTimeService: screenTimeService) + do { + try syncAndPersist( + schedule, + allSchedules: allSchedules, + screenTimeService: screenTimeService, + constrainedTo: main + ) + } catch ScheduleRegistrationError.storageUnavailable { + schedule.isEnabled = wasEnabled + throw ScheduleRegistrationError.storageUnavailable + } } func disableAll( @@ -98,37 +171,409 @@ final class ScheduleService { for schedule in schedules { try? sync(schedule) } - syncAllToSharedStore(schedules) + let remainingScheduleActivities = activityCenter.monitoredActivityNames.filter { $0.hasPrefix("schedule_") } + if !remainingScheduleActivities.isEmpty { + activityCenter.stopMonitoring(remainingScheduleActivities.map { DeviceActivityName($0) }) + } + let previousByID = loadPreviousByID() + sharedStore.saveSchedules( + schedules.compactMap { schedule in + if let previous = previousByID[schedule.id] { + return ScheduleDTO( + id: previous.id, + name: schedule.name, + selectionData: previous.selectionData, + startHour: previous.startHour, + startMinute: previous.startMinute, + durationMinutes: previous.durationMinutes, + weekdays: previous.weekdays, + shouldBlock: previous.shouldBlock, + isTimed: previous.isTimed, + customDomains: previous.customDomains, + isEnabled: false, + activatedAt: previous.activatedAt + ) + } + return schedule.toDTO() + } + ) activityCenter.syncHeartbeat(sharedStore: sharedStore, at: clock()) screenTimeService.reconcile() } - func syncAllToSharedStore(_ schedules: [BlockSchedule], activating activatedID: UUID? = nil) { - var previous: [UUID: Date] = [:] - for dto in sharedStore.loadSchedules() { - previous[dto.id] = dto.activatedAt + func syncAllToSharedStore( + _ schedules: [BlockSchedule], + constrainedTo main: SelectionConstraint? = nil + ) { + let previousByID = loadPreviousByID() + let pending = resolvePendingPermanentSchedules( + schedules: schedules, + previousByID: previousByID, + monitored: activityCenter.monitoredActivityNames, + constrainedTo: main, + screenTimeService: nil, + at: clock() + ) + persistSchedules( + schedules, + previousByID: previousByID, + constrainedTo: main, + keepingUnchanged: pending.keepingUnchanged, + appending: pending.retainedOrphans + ) + } + + struct ConstrainedSyncPlan { + fileprivate let schedules: [BlockSchedule] + fileprivate let previousByID: [UUID: ScheduleDTO] + fileprivate let constrainedTo: SelectionConstraint? + fileprivate let confirmedRemovals: FamilyActivitySelection? + fileprivate let pending: PendingPermanentResolution + let now: Date + let schedulesToPreserve: [ScheduleDTO] + let hasChanges: Bool + } + + func prepareConstrainedSync( + _ schedules: [BlockSchedule], + constrainedTo main: SelectionConstraint?, + confirmedRemovals: FamilyActivitySelection? = nil + ) -> ConstrainedSyncPlan { + let previousDTOs = sharedStore.loadSchedules() + let now = clock() + guard !schedules.isEmpty || !previousDTOs.isEmpty else { + return ConstrainedSyncPlan( + schedules: schedules, + previousByID: [:], + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + pending: PendingPermanentResolution(), + now: now, + schedulesToPreserve: [], + hasChanges: false + ) } - sharedStore.saveSchedules( - schedules.compactMap { schedule in - schedule.toDTO(activatedAt: schedule.id == activatedID ? clock() : previous[schedule.id]) - }) + var previousByID: [UUID: ScheduleDTO] = [:] + for dto in previousDTOs { + previousByID[dto.id] = dto + } + let monitored = activityCenter.monitoredActivityNames + var pending = PendingPermanentResolution() + var schedulesToPreserve: [ScheduleDTO] = [] + let currentIDs = Set(schedules.map(\.id)) + for dto in previousByID.values where !currentIDs.contains(dto.id) { + guard !dto.isTimed, dto.isEffectivelyEnabled(monitoredActivities: monitored) else { continue } + schedulesToPreserve.append(dto) + pending.resolvedOrphanActivities.append( + DeviceActivityName(SharedConstants.scheduleActivityName(for: dto.id)) + ) + } + for schedule in schedules { + guard let previous = previousByID[schedule.id], + !previous.isTimed, + previous.isEffectivelyEnabled(monitoredActivities: monitored), + needsPreservation( + schedule: schedule, + previous: previous, + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + onlyIfScopeChangedBeyondMain: true + ) + else { continue } + schedulesToPreserve.append(previous) + if schedule.isEnabled { + pending.reactivated[schedule.id] = permanentActivationDate( + for: schedule, + previous: previous, + wasEnabled: true, + now: now + ) + } + pending.resolvedSchedules.append(schedule) + } + return ConstrainedSyncPlan( + schedules: schedules, + previousByID: previousByID, + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + pending: pending, + now: now, + schedulesToPreserve: schedulesToPreserve, + hasChanges: true + ) + } + + func commitConstrainedSync(_ plan: ConstrainedSyncPlan) { + guard plan.hasChanges else { return } + persistSchedules( + plan.schedules, + previousByID: plan.previousByID, + reactivated: plan.pending.reactivated, + constrainedTo: plan.constrainedTo, + confirmedRemovals: plan.confirmedRemovals + ) + applyPendingMonitorChanges(plan.pending, syncHeartbeatAt: plan.now) + } + + @discardableResult + func syncConstrained( + _ schedules: [BlockSchedule], + constrainedTo main: SelectionConstraint?, + confirmedRemovals: FamilyActivitySelection? = nil, + screenTimeService: any ScreenTimeProviding + ) -> Bool { + let previousDTOs = sharedStore.loadSchedules() + guard !schedules.isEmpty || !previousDTOs.isEmpty else { return false } + var previousByID: [UUID: ScheduleDTO] = [:] + for dto in previousDTOs { + previousByID[dto.id] = dto + } + let now = clock() + let pending = resolvePendingPermanentSchedules( + schedules: schedules, + previousByID: previousByID, + monitored: activityCenter.monitoredActivityNames, + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + screenTimeService: screenTimeService, + onlyIfScopeChangedBeyondMain: true, + at: now + ) + persistSchedules( + schedules, + previousByID: previousByID, + reactivated: pending.reactivated, + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + keepingUnchanged: pending.keepingUnchanged, + appending: pending.retainedOrphans + ) + applyPendingMonitorChanges(pending, syncHeartbeatAt: now) + return true } func syncAndPersist( _ schedule: BlockSchedule, allSchedules: [BlockSchedule], - screenTimeService: any ScreenTimeProviding + screenTimeService: any ScreenTimeProviding, + constrainedTo main: SelectionConstraint? = nil ) throws { - let previous = sharedStore.loadSchedules().first { $0.id == schedule.id } - let wasEnabled = previous?.isEffectivelyEnabled(monitoredActivities: activityCenter.monitoredActivityNames) == true - let rulesChanged = previous.map { !schedule.hasSameRules(as: $0) } ?? true - let activates = schedule.isEnabled && (!wasEnabled || (schedule.isTimed && rulesChanged)) - syncAllToSharedStore(allSchedules, activating: activates ? schedule.id : nil) + let previousByID = loadPreviousByID() + let monitored = activityCenter.monitoredActivityNames + let previous = previousByID[schedule.id] + let wasEnabled = previous?.isEffectivelyEnabled(monitoredActivities: monitored) == true + let rulesChanged = previous.map { !schedule.hasSameRules(as: $0, constrainedTo: main) } ?? true + let activates = schedule.isEnabled && (!wasEnabled || rulesChanged) + let now = clock() + if let previous, !previous.isTimed, wasEnabled, !schedule.isEnabled || rulesChanged { + guard screenTimeService.preservePermanentSchedule(previous, at: now) else { + throw ScheduleRegistrationError.storageUnavailable + } + } + let pending = resolvePendingPermanentSchedules( + schedules: allSchedules, + previousByID: previousByID, + monitored: monitored, + constrainedTo: main, + excluding: schedule.id, + screenTimeService: screenTimeService, + at: now + ) + let activationDate = + activates + ? permanentActivationDate( + for: schedule, + previous: previous, + wasEnabled: wasEnabled, + now: now + ) + : nil + persistSchedules( + allSchedules, + previousByID: previousByID, + activating: activates ? schedule.id : nil, + activatedAt: activationDate, + reactivated: pending.reactivated, + constrainedTo: main, + keepingUnchanged: pending.keepingUnchanged, + appending: pending.retainedOrphans + ) + applyPendingMonitorChanges(pending) screenTimeService.reconcile() - activityCenter.syncHeartbeat(sharedStore: sharedStore, at: clock()) + activityCenter.syncHeartbeat(sharedStore: sharedStore, at: now) try sync(schedule) } + fileprivate struct PendingPermanentResolution { + var keepingUnchanged: [UUID: ScheduleDTO] = [:] + var reactivated: [UUID: Date] = [:] + var retainedOrphans: [ScheduleDTO] = [] + var resolvedOrphanActivities: [DeviceActivityName] = [] + var resolvedSchedules: [BlockSchedule] = [] + } + + private func loadPreviousByID() -> [UUID: ScheduleDTO] { + var previousByID: [UUID: ScheduleDTO] = [:] + for dto in sharedStore.loadSchedules() { + previousByID[dto.id] = dto + } + return previousByID + } + + private func resolvePendingPermanentSchedules( + schedules: [BlockSchedule], + previousByID: [UUID: ScheduleDTO], + monitored: Set, + constrainedTo main: SelectionConstraint?, + confirmedRemovals: FamilyActivitySelection? = nil, + excluding targetID: UUID? = nil, + excludingOrphanID: UUID? = nil, + screenTimeService: (any ScreenTimeProviding)?, + onlyIfScopeChangedBeyondMain: Bool = false, + at now: Date + ) -> PendingPermanentResolution { + var result = PendingPermanentResolution() + let currentIDs = Set(schedules.map(\.id)) + for dto in previousByID.values where !currentIDs.contains(dto.id) && dto.id != excludingOrphanID { + guard !dto.isTimed, dto.isEffectivelyEnabled(monitoredActivities: monitored) else { continue } + if let screenTimeService, screenTimeService.preservePermanentSchedule(dto, at: now) { + result.resolvedOrphanActivities.append( + DeviceActivityName(SharedConstants.scheduleActivityName(for: dto.id)) + ) + } else { + result.retainedOrphans.append(dto) + } + } + for schedule in schedules where schedule.id != targetID { + guard let previous = previousByID[schedule.id], + !previous.isTimed, + previous.isEffectivelyEnabled(monitoredActivities: monitored), + needsPreservation( + schedule: schedule, + previous: previous, + constrainedTo: main, + confirmedRemovals: confirmedRemovals, + onlyIfScopeChangedBeyondMain: onlyIfScopeChangedBeyondMain + ) + else { continue } + if let screenTimeService, screenTimeService.preservePermanentSchedule(previous, at: now) { + if schedule.isEnabled { + result.reactivated[schedule.id] = permanentActivationDate( + for: schedule, + previous: previous, + wasEnabled: true, + now: now + ) + } + result.resolvedSchedules.append(schedule) + } else { + result.keepingUnchanged[schedule.id] = previous + } + } + return result + } + + private func needsPreservation( + schedule: BlockSchedule, + previous: ScheduleDTO, + constrainedTo main: SelectionConstraint?, + confirmedRemovals: FamilyActivitySelection?, + onlyIfScopeChangedBeyondMain: Bool + ) -> Bool { + guard schedule.isEnabled else { return true } + guard onlyIfScopeChangedBeyondMain else { + return !schedule.hasSameRules(as: previous, constrainedTo: main) + } + guard schedule.hasSameTimingAndMode(as: previous) else { return true } + let oldSelection = try? FamilyActivitySelection.fromData(previous.selectionData) + let newSelection = + main?.constrain( + schedule.selection, + previous: oldSelection, + confirmedRemovals: confirmedRemovals + ) ?? schedule.selection + let selectionChanged = + if let oldSelection { + newSelection + != (main?.constrain( + oldSelection, + previous: oldSelection, + confirmedRemovals: confirmedRemovals + ) ?? oldSelection) + } else { + !newSelection.isEmpty + } + let newDomains = Set( + (main?.intersect(schedule.customDomains) ?? schedule.customDomains) + .compactMap(DomainNormalizer.normalize) + ) + let constrainedOldDomains = Set( + (main?.intersect(previous.customDomains) ?? previous.customDomains) + .compactMap(DomainNormalizer.normalize) + ) + return selectionChanged || newDomains != constrainedOldDomains + } + + private func persistSchedules( + _ schedules: [BlockSchedule], + previousByID: [UUID: ScheduleDTO], + activating activatedID: UUID? = nil, + activatedAt activationDate: Date? = nil, + reactivated: [UUID: Date] = [:], + constrainedTo main: SelectionConstraint? = nil, + confirmedRemovals: FamilyActivitySelection? = nil, + keepingUnchanged: [UUID: ScheduleDTO] = [:], + appending retained: [ScheduleDTO] = [] + ) { + let resolvedActivation = activationDate ?? clock() + let saved = schedules.compactMap { schedule -> ScheduleDTO? in + if let unchanged = keepingUnchanged[schedule.id] { + return unchanged + } + let previous = previousByID[schedule.id] + let previousSelection = previous.flatMap { try? FamilyActivitySelection.fromData($0.selectionData) } + let nextActivatedAt = + reactivated[schedule.id] + ?? (schedule.id == activatedID ? resolvedActivation : previous?.activatedAt) + return schedule.toDTO( + activatedAt: nextActivatedAt, + constrainedTo: main, + previousSelection: previousSelection, + confirmedRemovals: confirmedRemovals + ) + } + sharedStore.saveSchedules(saved + retained) + } + + private func applyPendingMonitorChanges(_ pending: PendingPermanentResolution, syncHeartbeatAt date: Date? = nil) { + if !pending.resolvedOrphanActivities.isEmpty { + activityCenter.stopMonitoring(pending.resolvedOrphanActivities) + } + for schedule in pending.resolvedSchedules where !schedule.isEnabled || !isRegistered(schedule) { + try? sync(schedule) + } + if let date, !pending.resolvedOrphanActivities.isEmpty || !pending.resolvedSchedules.isEmpty { + activityCenter.syncHeartbeat(sharedStore: sharedStore, at: date) + } + } + + private func permanentActivationDate( + for schedule: BlockSchedule, + previous: ScheduleDTO?, + wasEnabled: Bool, + now: Date + ) -> Date { + guard !schedule.isTimed, + wasEnabled, + let previous, + !previous.isTimed, + let latestStart = schedule.latestStart(atOrBefore: now), + latestStart < now || latestStart == previous.latestStart(atOrBefore: now) + else { return now } + let cutoff = latestStart.addingTimeInterval(TimeInterval(schedule.effectiveDurationMinutes * 60)) + return max(now, cutoff) + } + private func activityName(for schedule: BlockSchedule) -> DeviceActivityName { DeviceActivityName(SharedConstants.scheduleActivityName(for: schedule.id)) } @@ -151,13 +596,22 @@ final class ScheduleService { } } -enum ScheduleRegistrationError: LocalizedError { +enum ScheduleRegistrationError: LocalizedError, Equatable { case tooManyActivities + case storageUnavailable var errorDescription: String? { - String( - localized: - "Saved, but iOS only tracks 20 schedules and timers at once, so this schedule may start or end up to 30 minutes late. Turn off another schedule to make it exact." - ) + switch self { + case .tooManyActivities: + String( + localized: + "Saved, but iOS only tracks 20 schedules and timers at once, so this schedule may start or end up to 30 minutes late. Turn off another schedule to make it exact." + ) + case .storageUnavailable: + String( + localized: + "Couldn't update this schedule right now. Please try again." + ) + } } } diff --git a/Normal/Services/ScreenTimeProviding.swift b/Normal/Services/ScreenTimeProviding.swift index a8353f0..bb37f96 100644 --- a/Normal/Services/ScreenTimeProviding.swift +++ b/Normal/Services/ScreenTimeProviding.swift @@ -19,24 +19,107 @@ protocol ScreenTimeProviding: AnyObject { customDomains: [String], blockAllPreventsAppDelete: Bool ) - func unblockAll(blockAllPreventsAppDelete: Bool) + @discardableResult + func unblockAll(blockAllPreventsAppDelete: Bool) -> Bool func block(selection: FamilyActivitySelection, customDomains: [String]) - func unblock(selection: FamilyActivitySelection, customDomains: [String]) + @discardableResult + func unblock(selection: FamilyActivitySelection, customDomains: [String]) -> Bool + @discardableResult func updateMainList( from old: FamilyActivitySelection, customDomains oldDomains: [String], to new: FamilyActivitySelection, customDomains newDomains: [String], - addedBlockedAsOf addedDate: Date - ) + addedBlockedAsOf addedDate: Date, + unconfirmedRemovalBefore: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at date: Date? + ) -> Bool + @discardableResult + func unblockRemovedFromMain( + from old: FamilyActivitySelection, + customDomains oldDomains: [String], + to new: FamilyActivitySelection, + customDomains newDomains: [String], + clearAppDeletion: Bool, + appDeletionCutoff: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at date: Date? + ) -> Bool + @discardableResult + func clearCustomDomains( + clearAppDeletion: Bool, + appDeletionCutoff: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at date: Date? + ) -> Bool + @discardableResult + func preservePermanentSchedule(_ previous: ScheduleDTO, at date: Date) -> Bool func removeAllRestrictions() - func reconcile() + @discardableResult + func reconcile(preservingPermanentSchedules: [ScheduleDTO], at date: Date?) -> Bool func activeShieldCount() -> Int func blockStatus(selection: FamilyActivitySelection?, customDomains: [String]?) -> BlockStatus - func hasActiveCustomDomainFilter() -> Bool } extension ScreenTimeProviding { + @discardableResult + func reconcile(at date: Date? = nil) -> Bool { + reconcile(preservingPermanentSchedules: [], at: date) + } + + @discardableResult + func updateMainList( + from old: FamilyActivitySelection, + customDomains oldDomains: [String], + to new: FamilyActivitySelection, + customDomains newDomains: [String], + addedBlockedAsOf addedDate: Date, + unconfirmedRemovalBefore: Date? = nil + ) -> Bool { + updateMainList( + from: old, + customDomains: oldDomains, + to: new, + customDomains: newDomains, + addedBlockedAsOf: addedDate, + unconfirmedRemovalBefore: unconfirmedRemovalBefore, + preservingPermanentSchedules: [], + at: nil + ) + } + + @discardableResult + func unblockRemovedFromMain( + from old: FamilyActivitySelection, + customDomains oldDomains: [String], + to new: FamilyActivitySelection, + customDomains newDomains: [String], + clearAppDeletion: Bool, + appDeletionCutoff: Date? = nil + ) -> Bool { + unblockRemovedFromMain( + from: old, + customDomains: oldDomains, + to: new, + customDomains: newDomains, + clearAppDeletion: clearAppDeletion, + appDeletionCutoff: appDeletionCutoff, + preservingPermanentSchedules: [], + at: nil + ) + } + + @discardableResult + func clearCustomDomains(clearAppDeletion: Bool, appDeletionCutoff: Date?) -> Bool { + clearCustomDomains( + clearAppDeletion: clearAppDeletion, + appDeletionCutoff: appDeletionCutoff, + preservingPermanentSchedules: [], + at: nil + ) + } + func ifAuthorized(_ action: @MainActor @escaping () -> Void) { Task { if await ensureAuthorized() { diff --git a/Normal/Services/ScreenTimeService.swift b/Normal/Services/ScreenTimeService.swift index 6356d08..8e5c6ae 100644 --- a/Normal/Services/ScreenTimeService.swift +++ b/Normal/Services/ScreenTimeService.swift @@ -113,12 +113,13 @@ final class ScreenTimeService: ScreenTimeProviding { let now = clock() state.blockAll(selection, customDomains: customDomains, at: now) if blockAllPreventsAppDelete { - state.setAppDeletionBlocked(true, at: now) + state.setAppDeletionBlocked(true, ownedByBlockAll: true, at: now) } } } - func unblockAll(blockAllPreventsAppDelete: Bool) { + @discardableResult + func unblockAll(blockAllPreventsAppDelete: Bool) -> Bool { reconcile { state in let now = clock() state.unblockAll(at: now) @@ -132,31 +133,151 @@ final class ScreenTimeService: ScreenTimeProviding { reconcile { $0.block(selection, customDomains: customDomains, at: clock()) } } - func unblock(selection: FamilyActivitySelection, customDomains: [String] = []) { + @discardableResult + func unblock(selection: FamilyActivitySelection, customDomains: [String] = []) -> Bool { reconcile { $0.unblock(selection, customDomains: customDomains, at: clock()) } } + @discardableResult func updateMainList( from old: FamilyActivitySelection, customDomains oldDomains: [String], to new: FamilyActivitySelection, customDomains newDomains: [String], - addedBlockedAsOf addedDate: Date - ) { - reconcile { state in - state.unblock( - old.subtracting(new), - customDomains: oldDomains.filter { !newDomains.contains($0) }, - at: clock() + addedBlockedAsOf addedDate: Date, + unconfirmedRemovalBefore: Date? = nil, + preservingPermanentSchedules preservedSchedules: [ScheduleDTO] = [], + at date: Date? = nil + ) -> Bool { + let oldNormalized = Set(oldDomains.compactMap(DomainNormalizer.normalize)) + let newNormalized = Set(newDomains.compactMap(DomainNormalizer.normalize)) + let confirmed = old.confirmedRemovals(movingTo: new) + let unconfirmed = old.subtracting(new).subtracting(confirmed) + let clearAllApps = new.applicationTokens.isEmpty && !old.applicationTokens.isEmpty + let clearAllWebDomains = new.webDomainTokens.isEmpty && !old.webDomainTokens.isEmpty + let clearAllCategories = new.categoryTokens.isEmpty && !old.categoryTokens.isEmpty + let effectiveDate = date ?? clock() + return reconcile(at: effectiveDate) { state in + for previous in preservedSchedules { + ShieldResolver.materializePermanentSchedule(previous, into: &state, at: effectiveDate) + } + clearTokens( + in: &state, + confirmed: confirmed, + clearAllApps: clearAllApps, + clearAllWebDomains: clearAllWebDomains, + clearAllCategories: clearAllCategories ) + if !unconfirmed.isEmpty { + state.applications.clearBlocked(unconfirmed.applicationTokens, before: unconfirmedRemovalBefore) + state.webDomains.clearBlocked(unconfirmed.webDomainTokens, before: unconfirmedRemovalBefore) + state.categories.clearBlocked(unconfirmed.categoryTokens, before: unconfirmedRemovalBefore) + } + state.customDomains.clearBlocked(Array(oldNormalized.subtracting(newNormalized))) state.block( new.subtracting(old), - customDomains: newDomains.filter { !oldDomains.contains($0) }, + customDomains: Array(newNormalized.subtracting(oldNormalized)), at: addedDate ) } } + @discardableResult + func unblockRemovedFromMain( + from old: FamilyActivitySelection, + customDomains oldDomains: [String], + to new: FamilyActivitySelection, + customDomains newDomains: [String], + clearAppDeletion: Bool, + appDeletionCutoff: Date? = nil, + preservingPermanentSchedules preservedSchedules: [ScheduleDTO] = [], + at date: Date? = nil + ) -> Bool { + let oldNormalized = Set(oldDomains.compactMap(DomainNormalizer.normalize)) + let newNormalized = Set(newDomains.compactMap(DomainNormalizer.normalize)) + let removedSelection = old.confirmedRemovals(movingTo: new) + let removedDomains = Array(oldNormalized.subtracting(newNormalized)) + let clearAllApps = new.applicationTokens.isEmpty && (!old.applicationTokens.isEmpty || clearAppDeletion) + let clearAllWebDomains = new.webDomainTokens.isEmpty && (!old.webDomainTokens.isEmpty || clearAppDeletion) + let clearAllCategories = new.categoryTokens.isEmpty && (!old.categoryTokens.isEmpty || clearAppDeletion) + guard + !removedSelection.isEmpty + || !removedDomains.isEmpty + || clearAllApps + || clearAllWebDomains + || clearAllCategories + || clearAppDeletion + || !preservedSchedules.isEmpty + else { return true } + let effectiveDate = date ?? clock() + return reconcile(at: effectiveDate) { state in + for previous in preservedSchedules { + ShieldResolver.materializePermanentSchedule(previous, into: &state, at: effectiveDate) + } + clearTokens( + in: &state, + confirmed: removedSelection, + clearAllApps: clearAllApps, + clearAllWebDomains: clearAllWebDomains, + clearAllCategories: clearAllCategories + ) + state.customDomains.clearBlocked(removedDomains) + if clearAppDeletion { + state.clearBlockAllOwnedAppDeletion(at: effectiveDate, ifNotNewerThan: appDeletionCutoff) + } + } + } + + private func clearTokens( + in state: inout ManualBlockState, + confirmed: FamilyActivitySelection, + clearAllApps: Bool, + clearAllWebDomains: Bool, + clearAllCategories: Bool + ) { + if clearAllApps { + state.applications.clearBlocked() + } else { + state.applications.clearBlocked(confirmed.applicationTokens) + } + if clearAllWebDomains { + state.webDomains.clearBlocked() + } else { + state.webDomains.clearBlocked(confirmed.webDomainTokens) + } + if clearAllCategories { + state.categories.clearBlocked() + } else { + state.categories.clearBlocked(confirmed.categoryTokens) + } + } + + @discardableResult + func clearCustomDomains( + clearAppDeletion: Bool, + appDeletionCutoff: Date?, + preservingPermanentSchedules preservedSchedules: [ScheduleDTO] = [], + at date: Date? = nil + ) -> Bool { + let effectiveDate = date ?? clock() + return reconcile(at: effectiveDate) { state in + for previous in preservedSchedules { + ShieldResolver.materializePermanentSchedule(previous, into: &state, at: effectiveDate) + } + state.customDomains.clearBlocked() + if clearAppDeletion { + state.clearBlockAllOwnedAppDeletion(at: effectiveDate, ifNotNewerThan: appDeletionCutoff) + } + } + } + + @discardableResult + func preservePermanentSchedule(_ previous: ScheduleDTO, at date: Date) -> Bool { + reconcile(at: date) { state in + ShieldResolver.materializePermanentSchedule(previous, into: &state, at: date) + } + } + func removeAllRestrictions() { reconcile { state in let now = clock() @@ -194,20 +315,31 @@ final class ScreenTimeService: ScreenTimeProviding { } } - func reconcile() { - reconcile { _ in } + @discardableResult + func reconcile(preservingPermanentSchedules preservedSchedules: [ScheduleDTO] = [], at date: Date? = nil) -> Bool { + guard !preservedSchedules.isEmpty else { + return reconcile(at: date) { _ in } + } + let effectiveDate = date ?? clock() + return reconcile(at: effectiveDate) { state in + for previous in preservedSchedules { + ShieldResolver.materializePermanentSchedule(previous, into: &state, at: effectiveDate) + } + } } - private func reconcile(_ update: (inout ManualBlockState) -> Void) { + @discardableResult + private func reconcile(at date: Date? = nil, _ update: (inout ManualBlockState) -> Void) -> Bool { let plan = ShieldReconciler.reconcile( sharedStore: sharedStore, shields: shield, monitoredActivities: activityCenter.monitoredActivityNames, - at: clock(), + at: date ?? clock(), update: update ) CallbackLog.record("app reconcile: \(plan.map { "\($0.applications.count) apps" } ?? "skipped, data protected")") notifyUpdate() + return plan != nil } func activeShieldCount() -> Int { @@ -225,8 +357,8 @@ final class ScreenTimeService: ScreenTimeProviding { return shield.isShielded(token) } - func hasActiveCustomDomainFilter() -> Bool { + func isCustomDomainShielded(_ domain: String) -> Bool { _ = lastUpdate - return shield.hasActiveCustomDomainFilter() + return shield.isCustomDomainShielded(domain) } } diff --git a/Normal/Services/ShieldStoring.swift b/Normal/Services/ShieldStoring.swift index 140a705..5315dcf 100644 --- a/Normal/Services/ShieldStoring.swift +++ b/Normal/Services/ShieldStoring.swift @@ -22,8 +22,8 @@ extension ShieldStoring { currentShields().isShielded(token) } - func hasActiveCustomDomainFilter() -> Bool { - !currentShields().customDomains.isEmpty + func isCustomDomainShielded(_ domain: String) -> Bool { + currentShields().isCustomDomainShielded(domain) } } @@ -60,6 +60,11 @@ extension ShieldPlan { case .category(let t): categories.contains(t) } } + + func isCustomDomainShielded(_ domain: String) -> Bool { + guard let normalized = DomainNormalizer.normalize(domain) else { return false } + return customDomains.contains(normalized) + } } final class ManagedSettingsShieldStore: ShieldStoring { diff --git a/Normal/Services/TimedUnblockService.swift b/Normal/Services/TimedUnblockService.swift index 68bb274..6b8bc91 100644 --- a/Normal/Services/TimedUnblockService.swift +++ b/Normal/Services/TimedUnblockService.swift @@ -8,7 +8,7 @@ import Observation final class TimedUnblockService { private let activityCenter: any DeviceActivityProviding private let sharedStore: any SharedStoreProviding - private let onExpiration: @MainActor @Sendable () -> Void + private let onExpiration: @MainActor @Sendable (Date) -> Bool private let clock: () -> Date private(set) var activeUnblocks: [String: Date] = [:] @@ -20,15 +20,29 @@ final class TimedUnblockService { activityCenter: any DeviceActivityProviding = DeviceActivityCenter(), sharedStore: any SharedStoreProviding = SharedStore(), clock: @escaping () -> Date = { .now }, - onExpiration: @escaping @MainActor @Sendable () -> Void + onExpirationAt: @escaping @MainActor @Sendable (Date) -> Bool ) { self.activityCenter = activityCenter self.sharedStore = sharedStore self.clock = clock - self.onExpiration = onExpiration + onExpiration = onExpirationAt restoreState() } + convenience init( + activityCenter: any DeviceActivityProviding = DeviceActivityCenter(), + sharedStore: any SharedStoreProviding = SharedStore(), + clock: @escaping () -> Date = { .now }, + onExpiration: @escaping @MainActor @Sendable () -> Bool + ) { + self.init( + activityCenter: activityCenter, + sharedStore: sharedStore, + clock: clock, + onExpirationAt: { _ in onExpiration() } + ) + } + var isMainUnblockActive: Bool { activeUnblocks[Self.mainID] != nil } @@ -116,9 +130,43 @@ final class TimedUnblockService { return timing } - func cancelGroup(groupId: UUID) { - cancelMonitoring(activityName: SharedConstants.groupTimedUnblockActivityName(for: groupId)) - forget(id: groupId.uuidString) + func cancelGroup( + groupId: UUID, + screenTimeService: (any ScreenTimeProviding)? = nil + ) { + let id = groupId.uuidString + let activityName = SharedConstants.groupTimedUnblockActivityName(for: groupId) + guard let screenTimeService else { + cancelMonitoring(activityName: activityName) + forget(id: id) + syncHeartbeat() + return + } + if let existing = sharedStore.findTimedUnblock(activityName: activityName) { + let now = clock() + let expired = TimedUnblockDTO( + id: existing.id, + selectionData: existing.selectionData, + endDate: min(existing.endDate, now), + activityName: existing.activityName, + isGroupUnblock: existing.isGroupUnblock, + blockAllPreventsAppDelete: existing.blockAllPreventsAppDelete, + customDomains: existing.customDomains, + startDate: existing.startDate + ) + sharedStore.upsertTimedUnblock(expired) + cancelExpiration(id: id) + activeUnblocks.removeValue(forKey: id) + if screenTimeService.reconcile(at: now) { + sharedStore.removeTimedUnblocks(matching: [expired]) + cancelMonitoring(activityName: activityName) + } + } else { + forget(id: id) + if screenTimeService.reconcile() { + cancelMonitoring(activityName: activityName) + } + } syncHeartbeat() } @@ -153,24 +201,61 @@ final class TimedUnblockService { syncHeartbeat() } + @discardableResult func updateMainSelection( _ selection: FamilyActivitySelection, customDomains: [String] = [], - screenTimeService: any ScreenTimeProviding - ) { - guard let endDate = activeUnblocks[Self.mainID] else { return } + from previousSelection: FamilyActivitySelection? = nil, + previousCustomDomains: [String]? = nil, + screenTimeService: any ScreenTimeProviding, + preservingPermanentSchedules: [ScheduleDTO] = [], + at date: Date? = nil, + beforeRetiringOnEmpty: () -> Void = {} + ) -> Bool { + guard let endDate = activeUnblocks[Self.mainID] else { return true } let activityName = SharedConstants.mainTimedUnblockActivityName let existing = sharedStore.findTimedUnblock(activityName: activityName) - let previous = + let dtoSelection = existing.flatMap { try? FamilyActivitySelection.fromData($0.selectionData) } ?? FamilyActivitySelection() - screenTimeService.updateMainList( - from: previous, - customDomains: existing?.customDomains ?? [], - to: selection, - customDomains: customDomains, - addedBlockedAsOf: (existing?.startDate ?? clock()).addingTimeInterval(-1) - ) + let dtoDomains = existing?.customDomains ?? [] + let previous = previousSelection ?? dtoSelection + let previousDomains = previousCustomDomains ?? dtoDomains + let hadItems = !previous.isEmpty || !previousDomains.isEmpty || !dtoSelection.isEmpty || !dtoDomains.isEmpty + + if hadItems, selection.isEmpty, customDomains.isEmpty { + guard + screenTimeService.unblockRemovedFromMain( + from: previous, + customDomains: previousDomains, + to: selection, + customDomains: customDomains, + clearAppDeletion: true, + appDeletionCutoff: existing.map(ShieldResolver.startDate(of:)), + preservingPermanentSchedules: preservingPermanentSchedules, + at: date + ) + else { return false } + beforeRetiringOnEmpty() + clearAll() + screenTimeService.reconcile() + return true + } + + let mainStartDate = existing.map { ShieldResolver.startDate(of: $0) } ?? clock() + let addedDate = mainStartDate.addingTimeInterval(-1) + guard + screenTimeService.updateMainList( + from: previous, + customDomains: previousDomains, + to: selection, + customDomains: customDomains, + addedBlockedAsOf: addedDate, + unconfirmedRemovalBefore: mainStartDate, + preservingPermanentSchedules: preservingPermanentSchedules, + at: date + ) + else { return false } try? persist( id: Self.mainID, selection: selection, @@ -182,22 +267,172 @@ final class TimedUnblockService { scheduleTask: false, blockAllPreventsAppDelete: existing?.blockAllPreventsAppDelete ) + return true + } + + func updateGroupSelection( + groupId: UUID, + selection: FamilyActivitySelection, + customDomains: [String] = [], + screenTimeService: (any ScreenTimeProviding)? = nil + ) { + narrowGroupUnblock(groupId: groupId, screenTimeService: screenTimeService) { existing, existingSelection in + ( + selection.intersection(existingSelection), + CustomDomains.subset(customDomains, of: existing.customDomains) + ) + } + } + + private var activeGroupIDs: [UUID] { + activeUnblocks.keys.compactMap(UUID.init(uuidString:)) } - func updateGroupSelection(groupId: UUID, selection: FamilyActivitySelection, customDomains: [String] = []) { + @discardableResult + func pruneGroupUnblocks( + removing removedSelection: FamilyActivitySelection, + keeping selection: FamilyActivitySelection, + customDomains: [String] + ) -> Bool { + var changed = false + for groupID in activeGroupIDs { + if narrowGroupUnblock(groupId: groupID, screenTimeService: nil) { existing, existingSelection in + var effectiveSelection = existingSelection.subtracting(removedSelection) + if selection.applicationTokens.isEmpty { + effectiveSelection.applicationTokens.removeAll() + } + if selection.webDomainTokens.isEmpty { + effectiveSelection.webDomainTokens.removeAll() + } + if selection.categoryTokens.isEmpty { + effectiveSelection.categoryTokens.removeAll() + } + return ( + effectiveSelection, + CustomDomains.subset(existing.customDomains, of: customDomains) + ) + } { + changed = true + } + } + return changed + } + + @discardableResult + private func narrowGroupUnblock( + groupId: UUID, + screenTimeService: (any ScreenTimeProviding)?, + transform: (TimedUnblockDTO, FamilyActivitySelection) -> (FamilyActivitySelection, [String]) + ) -> Bool { let id = groupId.uuidString - guard let endDate = activeUnblocks[id] else { return } + guard let endDate = activeUnblocks[id] else { return false } let activityName = SharedConstants.groupTimedUnblockActivityName(for: groupId) + guard let existing = sharedStore.findTimedUnblock(activityName: activityName), + let existingSelection = try? FamilyActivitySelection.fromData(existing.selectionData) + else { + cancelGroup(groupId: groupId, screenTimeService: screenTimeService) + return true + } + let hadItems = !existingSelection.isEmpty || !existing.customDomains.isEmpty + let (effectiveSelection, effectiveDomains) = transform(existing, existingSelection) + if hadItems, effectiveSelection.isEmpty, effectiveDomains.isEmpty { + cancelGroup(groupId: groupId, screenTimeService: screenTimeService) + return true + } + guard effectiveSelection != existingSelection || effectiveDomains != existing.customDomains else { + return false + } try? persist( id: id, - selection: selection, - customDomains: customDomains, - startDate: sharedStore.findTimedUnblock(activityName: activityName)?.startDate, + selection: effectiveSelection, + customDomains: effectiveDomains, + startDate: existing.startDate, endDate: endDate, activityName: activityName, isGroupUnblock: true, scheduleTask: false ) + screenTimeService?.reconcile() + return true + } + + @discardableResult + func handleCustomDomainsDisabled( + clearAppDeletionWhenNoMainTimer: Bool = false, + screenTimeService: any ScreenTimeProviding, + preservingPermanentSchedules: [ScheduleDTO] = [], + at date: Date? = nil, + beforeRetiringMainTimer: () -> Void = {} + ) -> Bool { + var clearAppDeletion = activeUnblocks[Self.mainID] == nil && clearAppDeletionWhenNoMainTimer + var appDeletionCutoff: Date? + var mainTimerToRetire = false + var mainTimerToStrip: (TimedUnblockDTO, FamilyActivitySelection, Date)? + if let endDate = activeUnblocks[Self.mainID] { + let activityName = SharedConstants.mainTimedUnblockActivityName + if let existing = sharedStore.findTimedUnblock(activityName: activityName), + !existing.customDomains.isEmpty + { + let selection = + (try? FamilyActivitySelection.fromData(existing.selectionData)) ?? FamilyActivitySelection() + if selection.isEmpty { + mainTimerToRetire = true + clearAppDeletion = true + appDeletionCutoff = ShieldResolver.startDate(of: existing) + } else { + mainTimerToStrip = (existing, selection, endDate) + } + } + } + + guard + screenTimeService.clearCustomDomains( + clearAppDeletion: clearAppDeletion, + appDeletionCutoff: appDeletionCutoff, + preservingPermanentSchedules: preservingPermanentSchedules, + at: date + ) + else { return false } + + beforeRetiringMainTimer() + + if mainTimerToRetire { + cancelMonitoring(activityName: SharedConstants.mainTimedUnblockActivityName) + forget(id: Self.mainID) + syncHeartbeat() + } else if let (existing, selection, endDate) = mainTimerToStrip { + try? persist( + id: Self.mainID, + selection: selection, + customDomains: [], + startDate: existing.startDate, + endDate: endDate, + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + scheduleTask: false, + blockAllPreventsAppDelete: existing.blockAllPreventsAppDelete + ) + } + + var changedGroupTimers = false + for groupID in activeGroupIDs { + let activityName = SharedConstants.groupTimedUnblockActivityName(for: groupID) + guard let existing = sharedStore.findTimedUnblock(activityName: activityName), + !existing.customDomains.isEmpty + else { continue } + let selection = + (try? FamilyActivitySelection.fromData(existing.selectionData)) ?? FamilyActivitySelection() + if narrowGroupUnblock(groupId: groupID, screenTimeService: nil) { _, existingSelection in + (selection.intersection(existingSelection), []) + } { + changedGroupTimers = true + } + } + + if mainTimerToRetire || changedGroupTimers { + screenTimeService.reconcile() + } + return true } private func persist( @@ -237,20 +472,38 @@ final class TimedUnblockService { private func scheduleExpiration(id: String, at date: Date) { cancelExpiration(id: id) - let interval = date.timeIntervalSinceNow - guard interval > 0 else { - activeUnblocks.removeValue(forKey: id) + guard date > clock() else { + expire(id: id) return } expirationTasks[id] = Task { - try? await Task.sleep(for: .seconds(interval)) + while !Task.isCancelled { + let interval = date.timeIntervalSince(clock()) + guard interval > 0 else { break } + try? await Task.sleep(for: .seconds(interval)) + } guard !Task.isCancelled else { return } - activeUnblocks.removeValue(forKey: id) - expirationTasks.removeValue(forKey: id) - onExpiration() + expire(id: id) } } + private func expire(id: String) { + let now = clock() + let matching = sharedStore.loadTimedUnblocks().filter { $0.id == id } + if let active = matching.first(where: { $0.endDate > now }) { + activeUnblocks[id] = active.endDate + scheduleExpiration(id: id, at: active.endDate) + return + } + let expired = matching.filter { $0.endDate <= now } + activeUnblocks.removeValue(forKey: id) + expirationTasks.removeValue(forKey: id) + if onExpiration(now) { + sharedStore.removeTimedUnblocks(matching: expired) + } + syncHeartbeat() + } + private func cancelExpiration(id: String) { expirationTasks[id]?.cancel() expirationTasks.removeValue(forKey: id) @@ -312,14 +565,31 @@ final class TimedUnblockService { } func reconcile(screenTimeService: any ScreenTimeProviding) { - screenTimeService.reconcile() - for unblock in sharedStore.loadTimedUnblocks() { - if unblock.endDate > clock() { + let now = clock() + var expiredDTOs: [TimedUnblockDTO] = [] + let stored = sharedStore.loadTimedUnblocks() + let storedIDs = Set(stored.map(\.id)) + for staleID in Array(activeUnblocks.keys) where !storedIDs.contains(staleID) { + cancelExpiration(id: staleID) + activeUnblocks.removeValue(forKey: staleID) + } + for unblock in stored { + if unblock.endDate > now { activeUnblocks[unblock.id] = unblock.endDate scheduleExpiration(id: unblock.id, at: unblock.endDate) } else { - sharedStore.removeTimedUnblock(id: unblock.id) + cancelExpiration(id: unblock.id) + activeUnblocks.removeValue(forKey: unblock.id) + expiredDTOs.append(unblock) + } + } + if !expiredDTOs.isEmpty { + let planTime = max(now, clock()) + if screenTimeService.reconcile(at: planTime) { + sharedStore.removeTimedUnblocks(matching: expiredDTOs) } + } else { + screenTimeService.reconcile() } syncHeartbeat() } @@ -347,3 +617,11 @@ enum UnblockTiming: Equatable { case exact case mayEndLate } + +enum TimedUnblockStorageError: LocalizedError, Equatable { + case unavailable + + var errorDescription: String? { + String(localized: "Couldn't update blocking state right now. Please try again.") + } +} diff --git a/Normal/Services/UnblockTarget.swift b/Normal/Services/UnblockTarget.swift index ba61ce6..ab205c4 100644 --- a/Normal/Services/UnblockTarget.swift +++ b/Normal/Services/UnblockTarget.swift @@ -92,13 +92,14 @@ extension ScreenTimeProviding { blockStatus(selection: target.selection, customDomains: target.customDomains(settings: settings)) } - func unblockPermanently(_ grant: UnblockGrant, settings: Settings) { + @discardableResult + func unblockPermanently(_ grant: UnblockGrant, settings: Settings) -> Bool { let target = grant.target switch target { case .all: - unblockAll(blockAllPreventsAppDelete: settings.blockAllPreventsAppDelete) + return unblockAll(blockAllPreventsAppDelete: settings.blockAllPreventsAppDelete) case .group: - unblock(selection: target.selection, customDomains: target.customDomains(settings: settings)) + return unblock(selection: target.selection, customDomains: target.customDomains(settings: settings)) } } } diff --git a/Normal/Shared/Components/ReorderableListView.swift b/Normal/Shared/Components/ReorderableListView.swift index e77e6ce..54cf065 100644 --- a/Normal/Shared/Components/ReorderableListView.swift +++ b/Normal/Shared/Components/ReorderableListView.swift @@ -3,13 +3,13 @@ import SwiftUI struct ReorderableListView: View { let items: [T] let rowContent: (T) -> Content - let onMove: (IndexSet, Int) -> Void + let onMove: ((IndexSet, Int) -> Void)? let footer: Footer init( items: [T], @ViewBuilder rowContent: @escaping (T) -> Content, - onMove: @escaping (IndexSet, Int) -> Void, + onMove: ((IndexSet, Int) -> Void)?, @ViewBuilder footer: () -> Footer = { EmptyView() } ) { self.items = items diff --git a/Normal/Shared/Util/FamilyControlsUtil.swift b/Normal/Shared/Util/FamilyControlsUtil.swift index 365ebff..f71f9c8 100644 --- a/Normal/Shared/Util/FamilyControlsUtil.swift +++ b/Normal/Shared/Util/FamilyControlsUtil.swift @@ -78,6 +78,21 @@ extension FamilyActivitySelection { && webDomainTokens.isSubset(of: other.webDomainTokens) && categoryTokens.isSubset(of: other.categoryTokens) } + + func confirmedRemovals(movingTo next: FamilyActivitySelection) -> FamilyActivitySelection { + var result = FamilyActivitySelection() + result.applicationTokens = applicationTokens.confirmedRemovals(movingTo: next.applicationTokens) + result.webDomainTokens = webDomainTokens.confirmedRemovals(movingTo: next.webDomainTokens) + result.categoryTokens = categoryTokens.confirmedRemovals(movingTo: next.categoryTokens) + return result + } +} + +extension Set { + fileprivate func confirmedRemovals(movingTo next: Self) -> Self { + guard next.isEmpty || next.isSubset(of: self) else { return [] } + return subtracting(next) + } } enum SelectedTokenKind: Hashable { diff --git a/Normal/Views/AppSelect/AppSelectView.swift b/Normal/Views/AppSelect/AppSelectView.swift index 8686f58..86eb78c 100644 --- a/Normal/Views/AppSelect/AppSelectView.swift +++ b/Normal/Views/AppSelect/AppSelectView.swift @@ -5,6 +5,7 @@ import SwiftUI struct AppSelectView: View { @Environment(ScreenTimeService.self) private var screenTimeService @Environment(TimedUnblockService.self) private var timedUnblockService + @Environment(ScheduleService.self) private var scheduleService @Environment(\.modelContext) private var modelContext @Query private var selectedApps: [SelectedApps] @@ -13,16 +14,21 @@ struct AppSelectView: View { @Query private var allSettings: [Settings] @State private var showSelectionChangeAlert = false + @State private var showSaveErrorAlert = false @State private var isFamilyActivityPickerPresented = false @State private var selection = FamilyActivitySelection() @State private var customDomains: [String] = [] + private var settings: Settings { + allSettings.unwrapped + } + private var mainSelection: SelectedApps? { selectedApps.first } private var customDomainsEnabled: Bool { - allSettings.first?.enableCustomDomains ?? false + settings.enableCustomDomains } private var effectiveCustomDomains: [String] { @@ -94,6 +100,7 @@ struct AppSelectView: View { .alert(selectionChangeWarning?.title ?? "", isPresented: $showSelectionChangeAlert) { Button("Cancel", role: .cancel) {} Button("Continue", role: .destructive) { + guard !isBlocked else { return } isFamilyActivityPickerPresented = true } } message: { @@ -101,6 +108,11 @@ struct AppSelectView: View { Text(selectionChangeWarning.message) } } + .alert("Couldn't Save Selection", isPresented: $showSaveErrorAlert) { + Button("OK", role: .cancel) {} + } message: { + Text("Couldn't update your selection right now. Please try again.") + } .familyActivityPicker(isPresented: $isFamilyActivityPickerPresented, selection: $selection) .onAppear { if let mainSelection { @@ -109,12 +121,14 @@ struct AppSelectView: View { } } .onChange(of: selection, persistSelection) - .onChange(of: customDomains) { _, _ in persistCustomDomains() } + .onChange(of: customDomains, persistCustomDomains) } } private func onUpdateSelectionButton() { + guard !isBlocked else { return } screenTimeService.ifAuthorized { + guard !isBlocked else { return } if selectionChangeWarning == nil { isFamilyActivityPickerPresented = true } else { @@ -124,31 +138,63 @@ struct AppSelectView: View { } private func persistSelection(_: FamilyActivitySelection, _ new: FamilyActivitySelection) { - if let existing = mainSelection { - existing.selection = new - existing.lastUpdated = .now - } else { - modelContext.insert(SelectedApps(selection: new, customDomains: customDomains)) + let storedSelection = mainSelection?.selection ?? FamilyActivitySelection() + guard new != storedSelection else { return } + guard !isBlocked else { + selection = storedSelection + return } - timedUnblockService.updateMainSelection( - new, - customDomains: effectiveCustomDomains, - screenTimeService: screenTimeService + commitMainSelection( + selection: new, + customDomains: mainSelection?.customDomains ?? customDomains ) } - private func persistCustomDomains() { + private func persistCustomDomains(_: [String], _ new: [String]) { + let storedDomains = mainSelection?.customDomains ?? [] + guard new != storedDomains else { return } + if isBlocked { + let storedSet = Set(storedDomains.compactMap(DomainNormalizer.normalize)) + let newSet = Set(new.compactMap(DomainNormalizer.normalize)) + guard storedSet.isSubset(of: newSet) else { + customDomains = storedDomains + return + } + } + commitMainSelection( + selection: mainSelection?.selection ?? selection, + customDomains: new + ) + } + + private func commitMainSelection(selection nextSelection: FamilyActivitySelection, customDomains nextDomains: [String]) { + let storedSelection = mainSelection?.selection ?? FamilyActivitySelection() + let storedDomains = mainSelection?.customDomains ?? [] + guard + BlockActions.updateMainSelection( + from: storedSelection, + oldCustomDomains: storedDomains, + to: nextSelection, + newCustomDomains: nextDomains, + schedules: schedules, + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService, + scheduleService: scheduleService + ) + else { + selection = storedSelection + customDomains = storedDomains + showSaveErrorAlert = true + return + } if let existing = mainSelection { - existing.customDomains = customDomains + existing.selection = nextSelection + existing.customDomains = nextDomains existing.lastUpdated = .now } else { - modelContext.insert(SelectedApps(selection: selection, customDomains: customDomains)) + modelContext.insert(SelectedApps(selection: nextSelection, customDomains: nextDomains)) } - timedUnblockService.updateMainSelection( - selection, - customDomains: effectiveCustomDomains, - screenTimeService: screenTimeService - ) } } diff --git a/Normal/Views/Groups/GroupFormSheet.swift b/Normal/Views/Groups/GroupFormSheet.swift index e7c7701..bfdecd9 100644 --- a/Normal/Views/Groups/GroupFormSheet.swift +++ b/Normal/Views/Groups/GroupFormSheet.swift @@ -78,8 +78,12 @@ struct GroupFormSheet: View { existing == nil } + private var isBlocked: Bool { + screenTimeService.activeShieldCount() > 0 + } + private var isReadOnly: Bool { - !isNew && screenTimeService.activeShieldCount() > 0 + !isNew && isBlocked } private var customDomainsEnabled: Bool { @@ -164,7 +168,7 @@ struct GroupFormSheet: View { .navigationTitle(isReadOnly ? "Group" : (isNew ? "New Group" : "Edit Group")) .navigationBarTitleDisplayMode(.inline) .bottomFooter { - if isReadOnly { + if isBlocked { FooterMessage(text: BlockedMessage.groups) } } @@ -180,7 +184,7 @@ struct GroupFormSheet: View { ToolbarItem(placement: .confirmationAction) { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) - .disabled(!canSave) + .disabled(!canSave || isBlocked) } } } @@ -209,8 +213,9 @@ struct GroupFormSheet: View { } private var groupKeyDeleteAction: ((IndexSet) -> Void)? { - guard !isReadOnly else { return nil } + guard !isBlocked else { return nil } return { offsets in + guard !isBlocked else { return } for index in offsets { modelContext.delete(groupKeys[index]) } @@ -291,6 +296,7 @@ struct GroupFormSheet: View { } label: { Label("Add Key", systemImage: "plus") } + .disabled(isBlocked) } } header: { Text("Group Keys (Optional)") @@ -300,8 +306,14 @@ struct GroupFormSheet: View { } private func deleteGroup() { - guard let existing else { return } - existing.deleteCascading(keys: allKeys, from: modelContext) + guard let existing, !isBlocked else { return } + BlockActions.deleteGroup( + existing, + keys: allKeys, + from: modelContext, + timedUnblockService: timedUnblockService, + screenTimeService: screenTimeService + ) dismiss() } @@ -326,6 +338,7 @@ struct GroupFormSheet: View { } private func save() { + guard !isBlocked else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } @@ -341,7 +354,8 @@ struct GroupFormSheet: View { timedUnblockService.updateGroupSelection( groupId: existing.id, selection: selection, - customDomains: effectiveCustomDomains + customDomains: effectiveCustomDomains, + screenTimeService: screenTimeService ) } else { let nextIndex = SortIndexing.nextIndex(after: allGroups, sortIndex: \.sortIndex) diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index 16bbf1b..8fdd69e 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -52,16 +52,8 @@ struct GroupListCardView: View { } private var needsSync: Bool { - guard let main = selectedApps.first else { return false } - if !appGroup.selection.isSubset(of: main.selection) { - return true - } - if settings.enableCustomDomains, - CustomDomains.needsResync(appGroup.customDomains, main: main.customDomains) - { - return true - } - return false + selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings.enableCustomDomains) + .needsSync(selection: appGroup.selection, customDomains: appGroup.customDomains) ?? false } var body: some View { @@ -80,7 +72,7 @@ struct GroupListCardView: View { } .opacity(needsSync ? DS.Opacity.dim : 1) .onTapGesture { - if needsSync { + if needsSync, !isBlocked { isReselecting = true } else { isEditing = true @@ -89,7 +81,7 @@ struct GroupListCardView: View { .editDeleteContextMenu( isDisabled: isBlocked, onEdit: { - if needsSync { + if needsSync, !isBlocked { isReselecting = true } else { isEditing = true @@ -101,14 +93,37 @@ struct GroupListCardView: View { GroupFormSheet(existing: appGroup) } .sheet(isPresented: $isReselecting) { - SelectAppsForGroupSheet(selection: reselectionBinding, customDomains: reselectionDomainsBinding) + SelectAppsForGroupSheet( + selection: .constant(appGroup.selection), + customDomains: .constant(appGroup.customDomains), + saveBlockedMessage: isBlocked ? BlockedMessage.groups : nil + ) { newSelection, newDomains in + guard !isBlocked else { return false } + appGroup.selection = newSelection + appGroup.customDomains = newDomains + appGroup.lastUpdated = .now + timedUnblockService.updateGroupSelection( + groupId: appGroup.id, + selection: newSelection, + customDomains: settings.enableCustomDomains ? newDomains : [], + screenTimeService: screenTimeService + ) + return true + } } .deleteConfirmation( title: "Delete Group?", itemName: appGroup.name, isPresented: $showDeleteConfirmation, onDelete: { - appGroup.deleteCascading(keys: allKeys, from: modelContext) + guard !isBlocked else { return } + BlockActions.deleteGroup( + appGroup, + keys: allKeys, + from: modelContext, + timedUnblockService: timedUnblockService, + screenTimeService: screenTimeService + ) } ) } @@ -155,36 +170,6 @@ struct GroupListCardView: View { ) } - private var reselectionBinding: Binding { - Binding( - get: { appGroup.selection }, - set: { newValue in - appGroup.selection = newValue - appGroup.lastUpdated = .now - timedUnblockService.updateGroupSelection( - groupId: appGroup.id, - selection: newValue, - customDomains: customDomains - ) - } - ) - } - - private var reselectionDomainsBinding: Binding<[String]> { - Binding( - get: { appGroup.customDomains }, - set: { newValue in - appGroup.customDomains = newValue - appGroup.lastUpdated = .now - timedUnblockService.updateGroupSelection( - groupId: appGroup.id, - selection: appGroup.selection, - customDomains: settings.enableCustomDomains ? newValue : [] - ) - } - ) - } - private var syncWarningText: some View { Text("Your selection changed. Please re-select apps or domains in this group.") .font(.subheadline) diff --git a/Normal/Views/Groups/GroupsView.swift b/Normal/Views/Groups/GroupsView.swift index 7f3a0a1..11be2e9 100644 --- a/Normal/Views/Groups/GroupsView.swift +++ b/Normal/Views/Groups/GroupsView.swift @@ -3,7 +3,6 @@ import SwiftUI struct GroupsView: View { @Environment(ScreenTimeService.self) private var screenTimeService - @Environment(\.modelContext) private var modelContext @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var appGroups: [AppGroup] @Query private var selectedApps: [SelectedApps] @@ -16,7 +15,7 @@ struct GroupsView: View { @State private var unblockAlert: UnblockAlert? private var hasSelection: Bool { - selectedApps.first?.selection.isEmpty == false + selectedApps.first?.hasItemsToBlock(customDomainsEnabled: allSettings.unwrapped.enableCustomDomains) == true } private var isBlocked: Bool { @@ -26,6 +25,11 @@ struct GroupsView: View { var body: some View { NavigationStack { content + .bottomFooter { + if isBlocked, hasSelection || !appGroups.isEmpty { + FooterMessage(text: BlockedMessage.groups) + } + } .navigationTitle("App Groups") .settingsToolbar() .toolbar { @@ -57,13 +61,9 @@ struct GroupsView: View { durationGrant: $durationGrant, unblockAlert: $unblockAlert ) - }, onMove: move + }, + onMove: isBlocked ? nil : { move(from: $0, to: $1) } ) - .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.groups) - } - } // Host the key prompt on the stable list, scoped to whichever card // triggered it, instead of on the card row. .protectedAction( @@ -81,6 +81,7 @@ struct GroupsView: View { } private func move(from source: IndexSet, to destination: Int) { + guard !isBlocked else { return } _ = SortIndexing.reorder(appGroups, from: source, to: destination, sortIndex: \.sortIndex) } @@ -94,6 +95,7 @@ struct GroupsView: View { } actions: { Button("Create Group", action: openSheet) .buttonStyle(.borderedProminent) + .disabled(isBlocked) } } else { ContentUnavailableView { @@ -105,6 +107,10 @@ struct GroupsView: View { } private func openSheet() { - screenTimeService.ifAuthorized { isShowingSheet = true } + guard !isBlocked else { return } + screenTimeService.ifAuthorized { + guard !isBlocked else { return } + isShowingSheet = true + } } } diff --git a/Normal/Views/Groups/SelectAppsForGroupSheet.swift b/Normal/Views/Groups/SelectAppsForGroupSheet.swift index 1d8fd1d..62ac6aa 100644 --- a/Normal/Views/Groups/SelectAppsForGroupSheet.swift +++ b/Normal/Views/Groups/SelectAppsForGroupSheet.swift @@ -10,6 +10,9 @@ struct SelectAppsForGroupSheet: View { @Binding var selection: FamilyActivitySelection var customDomains: Binding<[String]>? + var saveBlockedMessage: LocalizedStringKey? + var saveErrorMessage: String? + var onSave: ((FamilyActivitySelection, [String]) -> Bool)? @State private var workingSelection = FamilyActivitySelection() @State private var workingDomains: [String] = [] @@ -38,6 +41,14 @@ struct SelectAppsForGroupSheet: View { var body: some View { NavigationStack { content + .bottomFooter { + if let saveBlockedMessage { + FooterMessage(text: saveBlockedMessage) + } else if let saveErrorMessage { + MessageView(message: saveErrorMessage, color: .red) + .padding() + } + } .navigationTitle("Select Apps") .navigationBarTitleDisplayMode(.inline) .toolbar { @@ -46,11 +57,20 @@ struct SelectAppsForGroupSheet: View { } ToolbarItem(placement: .confirmationAction) { Button("Done") { - selection = workingSelection - customDomains?.wrappedValue = workingDomains + let filteredDomains = CustomDomains.subset(workingDomains, of: mainDomains) + if let onSave { + guard saveBlockedMessage == nil, onSave(workingSelection, filteredDomains) else { return } + } else { + selection = workingSelection + customDomains?.wrappedValue = filteredDomains + } dismiss() } .fontWeight(.semibold) + .disabled( + saveBlockedMessage != nil + || (onSave != nil && workingSelection.isEmpty && (!showsDomains || workingDomains.isEmpty)) + ) } } } diff --git a/Normal/Views/Home/HomeView.swift b/Normal/Views/Home/HomeView.swift index b6160c5..6d9f5a5 100644 --- a/Normal/Views/Home/HomeView.swift +++ b/Normal/Views/Home/HomeView.swift @@ -9,7 +9,6 @@ struct HomeView: View { @Environment(\.requestReview) private var requestReview @Query private var selectedApps: [SelectedApps] - @Query private var keys: [Key] @Query private var allSettings: [Settings] @State private var authAction: ProtectedAction? @@ -24,10 +23,6 @@ struct HomeView: View { allSettings.unwrapped } - private func customDomains(for selection: SelectedApps) -> [String] { - settings.enableCustomDomains ? selection.customDomains : [] - } - var body: some View { NavigationStack { List { @@ -49,6 +44,31 @@ struct HomeView: View { Text("Please select apps to block in the selection tab.") .foregroundStyle(.secondary) } + if screenTimeService.activeShieldCount() > 0 { + Section { + Button { + authAction = .weaken { proof in + do { + try BlockActions.unblockOrphanedShields( + proof: proof, + settings: settings, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + } catch { + unblockAlert = .failed(error) + } + } + } label: { + Label("Unblock All", systemImage: "lock.open.fill") + .foregroundStyle(.red) + } + .accessibilityIdentifier("home.unblockAll") + } + } + if screenTimeService.isAppDeleteDisabled { + AppDeleteToggleView() + } } } .protectedAction($authAction, defaultKeyType: settings.defaultKeyType) diff --git a/Normal/Views/Home/MainBlockButtonView.swift b/Normal/Views/Home/MainBlockButtonView.swift index 15d3615..244ca9d 100644 --- a/Normal/Views/Home/MainBlockButtonView.swift +++ b/Normal/Views/Home/MainBlockButtonView.swift @@ -29,6 +29,7 @@ struct MainBlockButtonView: View { private var canShowUnblock: Bool { blockStatus.canUnblockAll(timedUnblockActive: timedUnblockService.isMainUnblockActive) + || (!timedUnblockService.isMainUnblockActive && screenTimeService.activeShieldCount() > 0) } var body: some View { diff --git a/Normal/Views/Home/StatusDetailView.swift b/Normal/Views/Home/StatusDetailView.swift index f537849..1f84d54 100644 --- a/Normal/Views/Home/StatusDetailView.swift +++ b/Normal/Views/Home/StatusDetailView.swift @@ -106,7 +106,7 @@ struct StatusDetailView: View { Label(domain, systemImage: "globe") .labelStyle(.titleAndIcon) .frame(maxWidth: .infinity, alignment: .leading) - let status: BlockStatus = overallStatus == .none ? .none : .all + let status: BlockStatus = screenTimeService.isCustomDomainShielded(domain) ? .all : .none StatusBadge( title: LocalizedStringKey(status.shortLabel), systemImage: status.icon, diff --git a/Normal/Views/Key/GroupKeysViewer.swift b/Normal/Views/Key/GroupKeysViewer.swift index 95bb0e1..8654c23 100644 --- a/Normal/Views/Key/GroupKeysViewer.swift +++ b/Normal/Views/Key/GroupKeysViewer.swift @@ -51,6 +51,7 @@ struct GroupKeysViewer: View { } private func delete(_ offsets: IndexSet, in keys: [Key]) { + guard !isBlocked else { return } for index in offsets { modelContext.delete(keys[index]) } diff --git a/Normal/Views/Key/KeyFormSheet.swift b/Normal/Views/Key/KeyFormSheet.swift index a975aab..8339ca1 100644 --- a/Normal/Views/Key/KeyFormSheet.swift +++ b/Normal/Views/Key/KeyFormSheet.swift @@ -35,8 +35,12 @@ struct KeyFormSheet: View { existing == nil } + private var isBlocked: Bool { + screenTimeService.activeShieldCount() > 0 && (!isNew || !keys.isEmpty) + } + private var isReadOnly: Bool { - !isNew && screenTimeService.activeShieldCount() > 0 + !isNew && isBlocked } private var isLastKey: Bool { @@ -132,18 +136,15 @@ struct KeyFormSheet: View { .accessibilityIdentifier("key.deleteButton") } } - - if isReadOnly { - Section { - } footer: { - Text(BlockedMessage.keys) - .frame(maxWidth: .infinity, alignment: .center) - } - } } } .navigationTitle(navigationTitle) .navigationBarTitleDisplayMode(.inline) + .bottomFooter { + if isBlocked { + FooterMessage(text: BlockedMessage.keys) + } + } .toolbar { if isReadOnly { ToolbarItem(placement: .confirmationAction) { @@ -157,7 +158,7 @@ struct KeyFormSheet: View { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) .accessibilityIdentifier("key.saveButton") - .disabled(!canSave) + .disabled(!canSave || isBlocked) } } } @@ -213,12 +214,13 @@ struct KeyFormSheet: View { } private func deleteKey() { - guard let existing, keys.count > 1 else { return } + guard let existing, !isBlocked, Key.canDelete(existing, in: keys) else { return } modelContext.delete(existing) dismiss() } private func save() { + guard !isBlocked else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } diff --git a/Normal/Views/Key/KeyListCardView.swift b/Normal/Views/Key/KeyListCardView.swift index 132e89f..0de5ecc 100644 --- a/Normal/Views/Key/KeyListCardView.swift +++ b/Normal/Views/Key/KeyListCardView.swift @@ -54,7 +54,10 @@ struct KeyListCardView: View { title: "Delete Key?", itemName: key.name, isPresented: $showDeleteConfirmation, - onDelete: { modelContext.delete(key) } + onDelete: { + guard !isBlocked, Key.canDelete(key, in: keys) else { return } + modelContext.delete(key) + } ) .alert("Can't Delete Key", isPresented: $showLastKeyAlert) { Button("OK", role: .cancel) {} diff --git a/Normal/Views/Key/KeysEmptyStateView.swift b/Normal/Views/Key/KeysEmptyStateView.swift index 8d94174..2c09060 100644 --- a/Normal/Views/Key/KeysEmptyStateView.swift +++ b/Normal/Views/Key/KeysEmptyStateView.swift @@ -1,6 +1,7 @@ import SwiftUI struct KeysEmptyStateView: View { + var isAddDisabled = false let onAddKey: () -> Void private var noKeysDescription: LocalizedStringKey { @@ -37,5 +38,6 @@ struct KeysEmptyStateView: View { .buttonStyle(.borderedProminent) .controlSize(.large) .frame(maxWidth: .infinity) + .disabled(isAddDisabled) } } diff --git a/Normal/Views/Key/KeysView.swift b/Normal/Views/Key/KeysView.swift index 0fbe234..2c98971 100644 --- a/Normal/Views/Key/KeysView.swift +++ b/Normal/Views/Key/KeysView.swift @@ -12,7 +12,7 @@ struct KeysView: View { @State private var isShowingGroupKeys = false private var isBlocked: Bool { - screenTimeService.activeShieldCount() > 0 && !keys.isEmpty + screenTimeService.activeShieldCount() > 0 && (!keys.isEmpty || !groupKeys.isEmpty) } var body: some View { @@ -24,6 +24,7 @@ struct KeysView: View { .toolbar { ToolbarItem(placement: .primaryAction) { Button { + guard !isBlocked else { return } isShowingSheet.toggle() } label: { Label("Add Key", systemImage: "plus") @@ -41,22 +42,33 @@ struct KeysView: View { private var content: some View { Group { if keys.isEmpty { - KeysEmptyStateView { isShowingSheet = true } + KeysEmptyStateView(isAddDisabled: isBlocked) { + guard !isBlocked else { return } + isShowingSheet = true + } } else { ReorderableListView( items: keys, rowContent: { key in KeyListCardView(key: key) - }, onMove: move, footer: { groupKeysRow }) + }, + onMove: isBlocked ? nil : { move(from: $0, to: $1) }, + footer: { groupKeysRow } + ) } } .bottomFooter { - if isBlocked { - FooterMessage(text: BlockedMessage.keys) - } else if keys.isEmpty, !groupKeys.isEmpty { - groupKeysLink - .padding(.horizontal, DS.Spacing.lg) - .padding(.bottom, DS.Spacing.sm) + if isBlocked || (keys.isEmpty && !groupKeys.isEmpty) { + VStack(spacing: DS.Spacing.sm) { + if keys.isEmpty, !groupKeys.isEmpty { + groupKeysLink + .padding(.horizontal, DS.Spacing.lg) + .padding(.bottom, isBlocked ? 0 : DS.Spacing.sm) + } + if isBlocked { + FooterMessage(text: BlockedMessage.keys) + } + } } } } @@ -101,6 +113,7 @@ struct KeysView: View { } private func move(from source: IndexSet, to destination: Int) { + guard !isBlocked else { return } _ = SortIndexing.reorder(keys, from: source, to: destination, sortIndex: \.sortIndex) } } diff --git a/Normal/Views/Key/LocationKeyInfoSheet.swift b/Normal/Views/Key/LocationKeyInfoSheet.swift index 9fff440..b585ab7 100644 --- a/Normal/Views/Key/LocationKeyInfoSheet.swift +++ b/Normal/Views/Key/LocationKeyInfoSheet.swift @@ -7,11 +7,15 @@ struct LocationKeyInfoSheet: View { let key: Key let currentLocation: CLLocation? - let canDelete: Bool + let deleteDisabledReason: LocalizedStringKey? let onDelete: () -> Void @State private var showDeleteConfirmation = false + private var canDelete: Bool { + deleteDisabledReason == nil + } + private var tint: Color { key.radiusKind?.zoneColor ?? .accentColor } @@ -57,8 +61,8 @@ struct LocationKeyInfoSheet: View { .controlSize(.large) .disabled(!canDelete) - if !canDelete { - Text("At least one key must exist. Add another key before deleting this one.") + if let deleteDisabledReason { + Text(deleteDisabledReason) .font(.caption) .foregroundStyle(.secondary) } diff --git a/Normal/Views/Key/LocationPickerSheet.swift b/Normal/Views/Key/LocationPickerSheet.swift index dd96ad4..0aaa042 100644 --- a/Normal/Views/Key/LocationPickerSheet.swift +++ b/Normal/Views/Key/LocationPickerSheet.swift @@ -7,6 +7,7 @@ struct LocationPickerSheet: View { @Environment(\.dismiss) private var dismiss @Environment(\.modelContext) private var modelContext @Environment(LocationService.self) private var locationService + @Environment(ScreenTimeService.self) private var screenTimeService @Environment(\.dynamicTypeSize) private var dynamicTypeSize @Query private var keys: [Key] @@ -21,6 +22,23 @@ struct LocationPickerSheet: View { @State private var permissionDenied = false @State private var inspectedKey: Key? + private func deleteDisabledReason(for key: Key) -> LocalizedStringKey? { + if screenTimeService.activeShieldCount() > 0 && !keys.isEmpty { + return "Unblock all apps to delete keys." + } + if groupID != nil, key.groupID != groupID { + return "Global keys can be deleted in the Keys tab." + } + if !Key.canDelete(key, in: keys) { + return "At least one key must exist. Add another key before deleting this one." + } + return nil + } + + private func canDelete(_ key: Key) -> Bool { + deleteDisabledReason(for: key) == nil + } + private var existingZones: [Key] { Key.scoped(keys, toGroup: groupID) .filter { $0.type == .location && $0.radiusKind == kind && $0.coordinate != nil } @@ -66,7 +84,7 @@ struct LocationPickerSheet: View { LocationKeyInfoSheet( key: key, currentLocation: currentLocation, - canDelete: Key.canDelete(key, in: keys), + deleteDisabledReason: deleteDisabledReason(for: key), onDelete: { delete(key) } ) } @@ -125,7 +143,7 @@ struct LocationPickerSheet: View { } private func delete(_ key: Key) { - guard Key.canDelete(key, in: keys) else { return } + guard canDelete(key) else { return } modelContext.delete(key) inspectedKey = nil } diff --git a/Normal/Views/Schedules/ScheduleCardView.swift b/Normal/Views/Schedules/ScheduleCardView.swift index d26031c..a12f77c 100644 --- a/Normal/Views/Schedules/ScheduleCardView.swift +++ b/Normal/Views/Schedules/ScheduleCardView.swift @@ -15,8 +15,12 @@ struct ScheduleCardView: View { let schedule: BlockSchedule + private var settings: Settings { + allSettings.unwrapped + } + private var customDomains: [String] { - (allSettings.first?.enableCustomDomains ?? false) ? schedule.customDomains : [] + settings.enableCustomDomains ? schedule.customDomains : [] } @State private var isEditing = false @@ -24,6 +28,8 @@ struct ScheduleCardView: View { @State private var showDeleteConfirmation = false @State private var showToggleConfirmation = false @State private var error: Error? + @State private var pendingReselectionError: Error? + @State private var reselectionError: String? private var isBlocked: Bool { screenTimeService.activeShieldCount() > 0 @@ -33,23 +39,28 @@ struct ScheduleCardView: View { Key.hasGlobalKey(in: keys) } + private var mainSelectionConstraint: SelectionConstraint? { + selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings.enableCustomDomains) + } + private var needsSync: Bool { - guard let main = selectedApps.first else { return false } - if !schedule.selection.isSubset(of: main.selection) { - return true - } - if allSettings.first?.enableCustomDomains ?? false, - CustomDomains.needsResync(schedule.customDomains, main: main.customDomains) - { - return true - } - return false + mainSelectionConstraint?.needsSync(selection: schedule.selection, customDomains: schedule.customDomains) ?? false } private var isLocked: Bool { isBlocked || !hasGlobalKey || needsSync } + private var reselectionBlockedMessage: LocalizedStringKey? { + if isBlocked { + BlockedMessage.schedules + } else if !hasGlobalKey { + "Add a key in the Keys tab to manage schedules." + } else { + nil + } + } + var body: some View { GlassCard { header @@ -62,17 +73,17 @@ struct ScheduleCardView: View { } .opacity((schedule.isEnabled && !isLocked) ? 1 : DS.Opacity.dim) .onTapGesture { - if needsSync { + if needsSync, !isBlocked, hasGlobalKey { isReselecting = true } else if !isLocked || isBlocked { isEditing = true } } .editDeleteContextMenu( - isDisabled: isLocked && !needsSync, - isDuplicateDisabled: needsSync, + isDisabled: isBlocked || !hasGlobalKey, + isDuplicateDisabled: needsSync || isBlocked || !hasGlobalKey, onEdit: { - if needsSync { + if needsSync, !isBlocked, hasGlobalKey { isReselecting = true } else { isEditing = true @@ -84,8 +95,45 @@ struct ScheduleCardView: View { .sheet(isPresented: $isEditing) { ScheduleFormSheet(existing: schedule) } - .sheet(isPresented: $isReselecting) { - SelectAppsForGroupSheet(selection: reselectionBinding, customDomains: reselectionDomainsBinding) + .sheet( + isPresented: $isReselecting, + onDismiss: { + reselectionError = nil + if let pendingReselectionError { + error = pendingReselectionError + self.pendingReselectionError = nil + } + } + ) { + SelectAppsForGroupSheet( + selection: .constant(schedule.selection), + customDomains: .constant(schedule.customDomains), + saveBlockedMessage: reselectionBlockedMessage, + saveErrorMessage: reselectionError + ) { newSelection, newDomains in + guard !isBlocked, hasGlobalKey else { return false } + reselectionError = nil + let previousSelection = schedule.selection + let previousDomains = schedule.customDomains + schedule.selection = newSelection + schedule.customDomains = newDomains + do { + try scheduleService.syncAndPersist( + schedule, + allSchedules: allSchedules, + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint + ) + } catch ScheduleRegistrationError.storageUnavailable { + schedule.selection = previousSelection + schedule.customDomains = previousDomains + reselectionError = ScheduleRegistrationError.storageUnavailable.errorDescription + return false + } catch { + pendingReselectionError = error + } + return true + } } .alert( schedule.isEnabled ? "Disable Schedule?" : "Enable Schedule?", @@ -104,6 +152,16 @@ struct ScheduleCardView: View { : "\(schedule.name) will start running." ) } + .alert( + "Schedule Notice", + isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } }) + ) { + Button("OK", role: .cancel) { error = nil } + } message: { + if let error { + Text(error.localizedDescription) + } + } .deleteConfirmation( title: "Delete Schedule?", itemName: schedule.name, @@ -230,34 +288,6 @@ struct ScheduleCardView: View { .foregroundStyle(.secondary) } - private var reselectionBinding: Binding { - Binding( - get: { schedule.selection }, - set: { newValue in - schedule.selection = newValue - try? scheduleService.syncAndPersist( - schedule, - allSchedules: allSchedules, - screenTimeService: screenTimeService - ) - } - ) - } - - private var reselectionDomainsBinding: Binding<[String]> { - Binding( - get: { schedule.customDomains }, - set: { newValue in - schedule.customDomains = newValue - try? scheduleService.syncAndPersist( - schedule, - allSchedules: allSchedules, - screenTimeService: screenTimeService - ) - } - ) - } - private var enabledBinding: Binding { Binding( get: { schedule.isEnabled }, @@ -266,11 +296,13 @@ struct ScheduleCardView: View { } private func toggleEnabled() { + guard !isBlocked, hasGlobalKey else { return } do { try scheduleService.toggleEnabled( schedule, allSchedules: allSchedules, - screenTimeService: screenTimeService + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint ) } catch { self.error = error @@ -278,18 +310,29 @@ struct ScheduleCardView: View { } private func duplicateSchedule() { + guard !isBlocked, hasGlobalKey, !needsSync else { return } let ordered = allSchedules.sorted { $0.sortIndex < $1.sortIndex } let copy = schedule.duplicate(named: CopyNaming.name(for: schedule.name, existing: allSchedules.map(\.name))) withAnimation { modelContext.insert(copy) let reordered = SortIndexing.insert(copy, after: schedule, in: ordered, sortIndex: \.sortIndex) - scheduleService.syncAllToSharedStore(reordered) + scheduleService.syncAllToSharedStore(reordered, constrainedTo: mainSelectionConstraint) } } private func deleteSchedule() { + guard !isBlocked, hasGlobalKey else { return } let remaining = allSchedules.filter { $0.id != schedule.id } - scheduleService.remove(schedule, remaining: remaining, screenTimeService: screenTimeService) - modelContext.delete(schedule) + do { + try scheduleService.remove( + schedule, + remaining: remaining, + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint + ) + modelContext.delete(schedule) + } catch { + self.error = error + } } } diff --git a/Normal/Views/Schedules/ScheduleFormSheet.swift b/Normal/Views/Schedules/ScheduleFormSheet.swift index 0cdb364..18eade7 100644 --- a/Normal/Views/Schedules/ScheduleFormSheet.swift +++ b/Normal/Views/Schedules/ScheduleFormSheet.swift @@ -12,6 +12,7 @@ struct ScheduleFormSheet: View { @Query private var allSchedules: [BlockSchedule] @Query private var allSettings: [Settings] @Query private var selectedApps: [SelectedApps] + @Query private var keys: [Key] let existing: BlockSchedule? @@ -121,14 +122,16 @@ struct ScheduleFormSheet: View { weekdaySection.disabled(isReadOnly) errorSection if !isNew, !isReadOnly { - deleteSection + deleteSection.disabled(!hasGlobalKey) } } .navigationTitle(isReadOnly ? "Schedule" : (isNew ? "New Schedule" : "Edit Schedule")) .navigationBarTitleDisplayMode(.inline) .bottomFooter { - if isReadOnly { + if isBlocked { FooterMessage(text: BlockedMessage.schedules) + } else if !hasGlobalKey { + FooterMessage(text: "Add a key in the Keys tab to manage schedules.") } } .toolbar { @@ -143,7 +146,7 @@ struct ScheduleFormSheet: View { ToolbarItem(placement: .confirmationAction) { Button(isNew ? "Save" : "Update", action: save) .fontWeight(.semibold) - .disabled(!canSave) + .disabled(!canSave || isBlocked || !hasGlobalKey) } } } @@ -290,20 +293,48 @@ struct ScheduleFormSheet: View { screenTimeService.ifAuthorized { isShowingAppSelect = true } } + private var hasGlobalKey: Bool { + Key.hasGlobalKey(in: keys) + } + + private var mainSelectionConstraint: SelectionConstraint? { + selectedApps.first?.effectiveConstraint(customDomainsEnabled: customDomainsEnabled) + } + private func deleteSchedule() { - guard let existing else { return } + guard let existing, !isBlocked, hasGlobalKey else { return } let remaining = allSchedules.filter { $0.id != existing.id } - scheduleService.remove(existing, remaining: remaining, screenTimeService: screenTimeService) - modelContext.delete(existing) - dismiss() + error = nil + do { + try scheduleService.remove( + existing, + remaining: remaining, + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint + ) + modelContext.delete(existing) + dismiss() + } catch { + self.error = error + } } private func save() { + guard !isBlocked, hasGlobalKey else { return } let trimmed = name.trimmingCharacters(in: .whitespaces) guard !trimmed.isEmpty else { return } + error = nil let components = Calendar.current.dateComponents([.hour, .minute], from: startTime) - let durationMinutes = computedDurationMinutes + let durationMinutes: Int = + if isTimed { + computedDurationMinutes + } else if let existing, !existing.isTimed { + existing.durationMinutes + } else { + BlockSchedule.minimumDurationMinutes + } + let previousSnapshot = existing.map(BlockSchedule.Snapshot.init) let schedule: BlockSchedule if let target = existing ?? inserted { target.name = trimmed @@ -340,9 +371,15 @@ struct ScheduleFormSheet: View { try scheduleService.syncAndPersist( schedule, allSchedules: allSchedules.contains { $0.id == schedule.id } ? allSchedules : allSchedules + [schedule], - screenTimeService: screenTimeService + screenTimeService: screenTimeService, + constrainedTo: mainSelectionConstraint ) dismiss() + } catch ScheduleRegistrationError.storageUnavailable { + if let existing, let previousSnapshot { + previousSnapshot.restore(to: existing) + } + self.error = ScheduleRegistrationError.storageUnavailable } catch { self.error = error } diff --git a/Normal/Views/Schedules/SchedulesView.swift b/Normal/Views/Schedules/SchedulesView.swift index 4c27f0f..88848ee 100644 --- a/Normal/Views/Schedules/SchedulesView.swift +++ b/Normal/Views/Schedules/SchedulesView.swift @@ -10,11 +10,16 @@ struct SchedulesView: View { private var schedules: [BlockSchedule] @Query private var selectedApps: [SelectedApps] @Query private var keys: [Key] + @Query private var allSettings: [Settings] @State private var isShowingSheet = false + private var settings: Settings { + allSettings.unwrapped + } + private var hasAppSelection: Bool { - selectedApps.first?.selection.isEmpty == false + selectedApps.first?.hasItemsToBlock(customDomainsEnabled: settings.enableCustomDomains) == true } private var isBlocked: Bool { @@ -57,7 +62,8 @@ struct SchedulesView: View { items: schedules, rowContent: { schedule in ScheduleCardView(schedule: schedule) - }, onMove: move + }, + onMove: isBlocked ? nil : { move(from: $0, to: $1) } ) .bottomFooter { if let message = bottomMessage { @@ -68,8 +74,10 @@ struct SchedulesView: View { } private func move(from source: IndexSet, to destination: Int) { + guard !isBlocked else { return } let reordered = SortIndexing.reorder(schedules, from: source, to: destination, sortIndex: \.sortIndex) - scheduleService.syncAllToSharedStore(reordered) + let constraint = selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings.enableCustomDomains) + scheduleService.syncAllToSharedStore(reordered, constrainedTo: constraint) } private var bottomMessage: LocalizedStringKey? { @@ -115,6 +123,10 @@ struct SchedulesView: View { } private func openSheet() { - screenTimeService.ifAuthorized { isShowingSheet = true } + guard !isBlocked else { return } + screenTimeService.ifAuthorized { + guard !isBlocked else { return } + isShowingSheet = true + } } } diff --git a/Normal/Views/Settings/GeneralSettingsView.swift b/Normal/Views/Settings/GeneralSettingsView.swift index 50037eb..92caa5f 100644 --- a/Normal/Views/Settings/GeneralSettingsView.swift +++ b/Normal/Views/Settings/GeneralSettingsView.swift @@ -3,6 +3,10 @@ import SwiftUI struct GeneralSettingsView: View { @Environment(ScreenTimeService.self) private var screenTimeService + @Environment(ScheduleService.self) private var scheduleService + @Environment(TimedUnblockService.self) private var timedUnblockService + @Query private var schedules: [BlockSchedule] + @Query private var selectedApps: [SelectedApps] let settings: Settings let availableKeyTypes: [KeyType] @@ -24,21 +28,43 @@ struct GeneralSettingsView: View { } } - private var hasActiveFilter: Bool { - screenTimeService.hasActiveCustomDomainFilter() + private var isBlocked: Bool { + screenTimeService.activeShieldCount() > 0 + } + + private var cannotDisableCustomDomains: Bool { + settings.enableCustomDomains && isBlocked + } + + private var customDomainsBinding: Binding { + Binding( + get: { settings.enableCustomDomains }, + set: { enabled in + if !enabled, isBlocked { return } + BlockActions.setCustomDomainsEnabled( + enabled, + settings: settings, + schedules: schedules, + mainSelection: selectedApps.first, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService, + scheduleService: scheduleService + ) + } + ) } private var websitesSection: some View { Section { Toggle( "Enable Custom Websites", - isOn: Bindable(settings).enableCustomDomains + isOn: customDomainsBinding ) - .disabled(hasActiveFilter) + .disabled(cannotDisableCustomDomains) } header: { Text("Websites") } footer: { - if hasActiveFilter { + if cannotDisableCustomDomains { Text("Unblock all apps to turn this off.") } } diff --git a/NormalMonitor/NormalMonitor.swift b/NormalMonitor/NormalMonitor.swift index 5d68f66..cf2d6f0 100644 --- a/NormalMonitor/NormalMonitor.swift +++ b/NormalMonitor/NormalMonitor.swift @@ -65,10 +65,10 @@ final class NormalMonitor: DeviceActivityMonitor { let now = Date.now let before = store.currentShields() guard - let plan = ShieldReconciler.reconcile( + let plan = ShieldReconciler.reconcileMonitor( sharedStore: sharedStore, shields: store, - monitoredActivities: Set(center.activities.map(\.rawValue)), + activityCenter: center, at: now ) else { return } diff --git a/NormalTests/Services/AppBlockIntentPerformerTests.swift b/NormalTests/Services/AppBlockIntentPerformerTests.swift index 753ca5c..e9eb022 100644 --- a/NormalTests/Services/AppBlockIntentPerformerTests.swift +++ b/NormalTests/Services/AppBlockIntentPerformerTests.swift @@ -16,7 +16,7 @@ struct AppBlockIntentPerformerTests { init() throws { container = try InMemoryModelContainer.make() - timedUnblock = TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: {}) + timedUnblock = TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: { true }) performer = AppBlockIntentPerformer( container: container, screenTimeService: screenTime, diff --git a/NormalTests/Services/AppUnblockIntentPerformerTests.swift b/NormalTests/Services/AppUnblockIntentPerformerTests.swift index 8612d99..233716f 100644 --- a/NormalTests/Services/AppUnblockIntentPerformerTests.swift +++ b/NormalTests/Services/AppUnblockIntentPerformerTests.swift @@ -30,7 +30,7 @@ struct AppUnblockIntentPerformerTests { activityCenter: activity, sharedStore: store, clock: { clock.now }, - onExpiration: {} + onExpiration: { true } ) location = FakeLocationProvider( outcome: .location(Self.fix(latitude: 37.3349, longitude: -122.0090, at: now)), diff --git a/NormalTests/Services/BlockActionsTests.swift b/NormalTests/Services/BlockActionsTests.swift index 301ccb6..f7d6640 100644 --- a/NormalTests/Services/BlockActionsTests.swift +++ b/NormalTests/Services/BlockActionsTests.swift @@ -16,7 +16,7 @@ struct BlockActionsTests { } private func makeTimedUnblock() -> TimedUnblockService { - TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: {}) + TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: { true }) } private func makeSchedule() -> ScheduleService { diff --git a/NormalTests/Services/BlockingScenarioTests.swift b/NormalTests/Services/BlockingScenarioTests.swift index c87e342..d4d469b 100644 --- a/NormalTests/Services/BlockingScenarioTests.swift +++ b/NormalTests/Services/BlockingScenarioTests.swift @@ -219,7 +219,7 @@ struct BlockingScenarioTests { h.wake(at: h.at(10)) #expect(h.blocked == h.apps(1, 4)) - h.delete(work) + try h.delete(work) #expect(h.blocked == h.apps(1)) } diff --git a/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift b/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift new file mode 100644 index 0000000..fc9d064 --- /dev/null +++ b/NormalTests/Services/EditWhileBlockedEdgeCaseTests.swift @@ -0,0 +1,2087 @@ +import DeviceActivity +import FamilyControls +import Foundation +import SwiftData +import Testing + +@testable import Normal + +@MainActor +struct EditWhileBlockedEdgeCaseTests { + @Test func removingBlockedAppsFromMainSelectionUnblocksThemImmediately() { + let h = BlockingHarness(mainApps: [1, 2, 3], customDomains: ["a.com", "b.com"]) + h.blockAll() + #expect(h.blocked == h.apps(1, 2, 3)) + #expect(h.blockedDomains == ["a.com", "b.com"]) + + h.updateMain(apps: [1, 2], domains: ["a.com"]) + + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["a.com"]) + #expect(!h.screenTime.isCustomDomainShielded("b.com")) + #expect(h.screenTime.isCustomDomainShielded("a.com")) + } + + @Test func removingAppFromMainSelectionStopsActiveScheduleFromOrphaningIt() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 9) + let schedule = try h.addSchedule([1, 2], from: (9, 0), minutes: 120, block: true) + h.wake(at: h.at(9, 30)) + #expect(h.blocked == h.apps(1, 2)) + + h.updateMain(apps: [1]) + + let narrowed = TokenFixtures.selection(apps: [1]) + #expect(h.blocked == h.apps(1)) + #expect(!schedule.selection.isSubset(of: narrowed)) + let storedSelection = try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + #expect(storedSelection == narrowed) + h.wake(at: h.at(9, 30, dayOffset: 1)) + #expect(h.blocked == h.apps(1)) + } + + @Test func emptyingMainSelectionDuringTimedUnblockCancelsTimerAndLiftsAppDeletion() throws { + let h = BlockingHarness(mainApps: [1, 2]) + h.settings.blockAllPreventsAppDelete = true + h.blockAll() + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.timedUnblock.isMainUnblockActive) + #expect(!h.appDeletionBlocked) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: []) + + #expect(!h.timedUnblock.isMainUnblockActive) + h.wake(at: h.at(10, 35)) + #expect(h.blocked.isEmpty) + #expect(!h.appDeletionBlocked) + } + + @Test func editingGroupDuringTimedUnblockNeverExpandsUnblockToAddedBlockedApps() throws { + let h = BlockingHarness(mainApps: [1, 2, 3]) + let group = h.group([1, 2]) + h.blockAll() + + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.blocked == h.apps(3)) + + h.passTime(to: h.at(10, 5)) + h.timedUnblock.updateGroupSelection( + groupId: group.id, + selection: TokenFixtures.selection(apps: [1, 3]), + screenTimeService: h.screenTime + ) + + #expect(h.blocked == h.apps(2, 3)) + } + + @Test func deletingGroupDuringTimedUnblockCancelsItsTimerAndReconciles() throws { + let container = try InMemoryModelContainer.make() + let context = container.mainContext + let h = BlockingHarness(mainApps: [1, 2]) + let group = h.group([1]) + let groupKey = Key(name: "Social", type: .qr, rawValue: "G", groupID: group.id) + context.insert(group) + context.insert(groupKey) + try context.save() + + h.blockAll() + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.blocked == h.apps(2)) + + BlockActions.deleteGroup( + group, + keys: [groupKey], + from: context, + timedUnblockService: h.timedUnblock, + screenTimeService: h.screenTime + ) + try context.save() + + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked == h.apps(1, 2)) + #expect(try context.fetch(FetchDescriptor()).isEmpty) + } + + @Test func permanentUnblockAllCancelsActiveGroupTimedUnblocksSoLaterSchedulesRun() throws { + let h = BlockingHarness(mainApps: [1, 2]) + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .oneHour) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 5)) + let grant = try #require(UnblockGrant(.all(h.main), proof: KeyProof(keyGroupID: nil))) + try BlockActions.unblock( + grant, + for: .permanent, + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + + #expect(h.timedUnblock.activeUnblocks.isEmpty) + try h.addSchedule([1], from: (10, 30), minutes: 60, block: true) + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1)) + } + + @Test func editingPermanentScheduleRulesPreservesAppliedStateWithoutRetroactiveFiring() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + let permanent = try h.addSchedule([1], from: (9, 0), minutes: 15, block: true, timed: false) + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(11)) + permanent.selection = TokenFixtures.selection(apps: [1, 2]) + try h.save(permanent) + #expect(h.blocked == h.apps(1)) + + h.wake(at: h.at(9, 5, dayOffset: 1)) + #expect(h.blocked == h.apps(1, 2)) + } + + @Test func togglingAndDeletingOtherScheduleKeepsNeedsSyncScheduleConstrained() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 9, constrainSchedules: true) + let scheduleA = try h.addSchedule([1, 2], from: (10, 0), minutes: 120, block: true) + let scheduleB = try h.addSchedule([1], from: (13, 0), minutes: 60, block: true) + + h.passTime(to: h.at(9, 30)) + h.updateMain(apps: [1]) + + let narrowed = TokenFixtures.selection(apps: [1]) + try h.toggle(scheduleB) + let afterToggle = try FamilyActivitySelection.fromData( + #require(h.store.schedules.first { $0.id == scheduleA.id }?.selectionData) + ) + #expect(afterToggle == narrowed) + + try h.delete(scheduleB) + let afterRemove = try FamilyActivitySelection.fromData( + #require(h.store.schedules.first { $0.id == scheduleA.id }?.selectionData) + ) + #expect(afterRemove == narrowed) + + h.openApp(at: h.at(9, 45)) + let afterReopen = try FamilyActivitySelection.fromData( + #require(h.store.schedules.first { $0.id == scheduleA.id }?.selectionData) + ) + #expect(afterReopen == narrowed) + + h.wake(at: h.at(10, 30)) + #expect(h.blocked == h.apps(1)) + } + + @Test func editingGroupToDisjointAppsCancelsItsTimedUnblock() throws { + let h = BlockingHarness(mainApps: [1, 2, 3]) + let group = h.group([1, 2]) + h.blockAll() + + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 5)) + h.timedUnblock.updateGroupSelection( + groupId: group.id, + selection: TokenFixtures.selection(apps: [3]), + screenTimeService: h.screenTime + ) + + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked == h.apps(1, 2, 3)) + } + + @Test func removingGroupAppsFromMainSelectionCancelsGroupTimedUnblock() throws { + let h = BlockingHarness(mainApps: [1, 2, 3]) + let group = h.group([1, 2]) + h.blockAll() + + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: [3]) + + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked == h.apps(3)) + } + + @Test(arguments: [false, true]) + func renamingScheduleWithDisabledCustomDomainsDoesNotResetActivation(disabledAfterStart: Bool) throws { + let h = BlockingHarness(mainApps: [1], customDomains: ["reddit.com"], startingAt: 9, constrainSchedules: true) + if !disabledAfterStart { + h.settings.enableCustomDomains = false + h.scheduleService.mirrorCustomDomainsEnabled(false) + } + let weekday = Calendar.current.component(.weekday, from: h.day) + let schedule = try h.addSchedule( + [1], + domains: ["reddit.com"], + from: (9, 0), + minutes: 120, + block: true, + weekdays: [weekday] + ) + h.wake(at: h.at(9, 10)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(9, 20)) + h.screenTime.unblock(selection: TokenFixtures.selection(apps: [1])) + #expect(h.blocked.isEmpty) + + if disabledAfterStart { + h.passTime(to: h.at(9, 30)) + h.setCustomDomainsEnabled(false) + } + + h.passTime(to: h.at(9, 45)) + schedule.name = "Deep Focus" + try h.save(schedule) + #expect(h.blocked.isEmpty) + } + + @Test func disablingCustomDomainsClearsManualDomainStateAgainstResurrection() { + let h = BlockingHarness(mainApps: [1], customDomains: ["reddit.com"]) + h.blockAll() + #expect(h.blockedDomains == ["reddit.com"]) + + h.setCustomDomainsEnabled(false) + #expect(h.blockedDomains.isEmpty) + + h.setCustomDomainsEnabled(true) + #expect(h.blockedDomains.isEmpty) + } + + @Test func reEnablingCustomDomainsReSyncsScheduleDomainsToSharedStore() throws { + let h = BlockingHarness( + mainApps: [1, 2], + customDomains: ["reddit.com"], + startingAt: 9, + constrainSchedules: true + ) + let weekday = Calendar.current.component(.weekday, from: h.day) + _ = try h.addSchedule( + [1], + domains: ["reddit.com"], + from: (10, 0), + minutes: 120, + block: true, + weekdays: [weekday] + ) + #expect(h.store.schedules.first?.customDomains == ["reddit.com"]) + + h.passTime(to: h.at(9, 15)) + h.setCustomDomainsEnabled(false) + + h.updateMain(apps: [1]) + #expect(h.store.schedules.first?.customDomains == []) + + h.passTime(to: h.at(9, 30)) + h.setCustomDomainsEnabled(true) + + #expect(h.store.schedules.first?.customDomains == ["reddit.com"]) + h.wake(at: h.at(10, 15)) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func unblockingOrphanedShieldsRequiresGlobalProofAndClearsAllState() throws { + let h = BlockingHarness(mainApps: [1, 2]) + let group = h.group([1]) + h.settings.blockAllPreventsAppDelete = true + h.blockAll() + h.passTime(to: h.at(10)) + try h.unblockGroupTimed(group, .thirtyMinutes) + + try BlockActions.unblockOrphanedShields( + proof: KeyProof(keyGroupID: group.id), + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + #expect(h.blocked == h.apps(2)) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + let failingScreenTime = FakeScreenTimeService() + failingScreenTime.reconcileResult = false + #expect(throws: TimedUnblockStorageError.unavailable) { + try BlockActions.unblockOrphanedShields( + proof: KeyProof(keyGroupID: nil), + settings: h.settings, + screenTimeService: failingScreenTime, + timedUnblockService: h.timedUnblock + ) + } + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + try BlockActions.unblockOrphanedShields( + proof: KeyProof(keyGroupID: nil), + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + #expect(h.blocked.isEmpty) + #expect(!h.appDeletionBlocked) + #expect(h.timedUnblock.activeUnblocks.isEmpty) + } + + @Test func reEnablingCustomDomainsMidScheduleResumesScheduledDomainWithoutResurrectingManualUnblock() throws { + let h = BlockingHarness( + mainApps: [1], + customDomains: ["reddit.com", "news.com"], + startingAt: 9, + constrainSchedules: true + ) + let weekday = Calendar.current.component(.weekday, from: h.day) + _ = try h.addSchedule( + [1], + domains: ["reddit.com", "news.com"], + from: (9, 0), + minutes: 120, + block: true, + weekdays: [weekday] + ) + h.wake(at: h.at(9, 5)) + #expect(h.blockedDomains == ["reddit.com", "news.com"]) + + h.passTime(to: h.at(9, 10)) + h.screenTime.unblock(selection: FamilyActivitySelection(), customDomains: ["news.com"]) + #expect(h.blockedDomains == ["reddit.com"]) + + h.passTime(to: h.at(9, 30)) + h.setCustomDomainsEnabled(false) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 45)) + h.setCustomDomainsEnabled(true) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func reAddingAppToMainSelectionReconcilesActiveBlockScheduleImmediately() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + _ = try h.addSchedule([1, 2], from: (9, 0), minutes: 120, block: true) + + h.passTime(to: h.at(8, 30)) + h.updateMain(apps: [1]) + + h.wake(at: h.at(9, 15)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(9, 30)) + h.updateMain(apps: [1, 2]) + #expect(h.blocked == h.apps(1, 2)) + } + + @Test(arguments: [false, true]) + func materializedPermanentScheduleKeepsOrderingOverEarlierOppositeScheduleAfterTimedUnblockExpires( + laterBlocks: Bool + ) throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(9, 0)) + try h.unblockGroupTimed(group, .oneHour) + #expect(h.blocked == h.apps(2)) + + _ = try h.addSchedule([1], from: (9, 10), minutes: 15, block: !laterBlocks, timed: false) + let laterSchedule = try h.addSchedule([1], from: (9, 15), minutes: 15, block: laterBlocks, timed: false) + h.wake(at: h.at(9, 20)) + #expect(h.blocked == h.apps(2)) + + h.passTime(to: h.at(9, 30)) + laterSchedule.startHour = 11 + laterSchedule.startMinute = 0 + try h.save(laterSchedule) + #expect(h.blocked == h.apps(2)) + + h.wake(at: h.at(10, 1)) + #expect(h.blocked == (laterBlocks ? h.apps(1, 2) : h.apps(2))) + } + + @Test func materializedPermanentUnblockPreservesMidUnblockManualBlockUntilExpiry() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(9, 0)) + try h.unblockGroupTimed(group, .oneHour) + #expect(h.blocked == h.apps(2)) + + h.passTime(to: h.at(9, 5)) + h.screenTime.block(selection: TokenFixtures.selection(apps: [1])) + #expect(h.blocked == h.apps(1, 2)) + + let permUnblock = try h.addSchedule([1], from: (9, 15), minutes: 15, block: false, timed: false) + h.wake(at: h.at(9, 20)) + #expect(h.blocked == h.apps(1, 2)) + + h.passTime(to: h.at(9, 30)) + permUnblock.startHour = 11 + permUnblock.startMinute = 0 + try h.save(permUnblock) + #expect(h.blocked == h.apps(1, 2)) + + h.wake(at: h.at(10, 1)) + #expect(h.blocked == h.apps(2)) + } + + @Test func disablingAndDeletingFiredPermanentBlockDuringTimedUnblockPreservesBlockAfterExpiry() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + let disabledSchedule = try h.addSchedule([1], from: (9, 0), minutes: 15, block: true, timed: false) + let deletedSchedule = try h.addSchedule([2], from: (9, 0), minutes: 15, block: true, timed: false) + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1, 2)) + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(10, 5)) + try h.toggle(disabledSchedule) + try h.delete(deletedSchedule) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1, 2)) + } + + @Test func disablingAndDeletingFiredPermanentUnblockDoesNotRestoreOlderManualBlock() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + h.blockAll() + let disabledUnblock = try h.addSchedule([1], from: (9, 0), minutes: 15, block: false, timed: false) + let deletedUnblock = try h.addSchedule([2], from: (9, 0), minutes: 15, block: false, timed: false) + h.wake(at: h.at(9, 5)) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(11, 0)) + try h.toggle(disabledUnblock) + try h.delete(deletedUnblock) + #expect(h.blocked.isEmpty) + } + + @Test func editingMainSelectionDuringTimedUnblockDoesNotResurrectClearedCustomDomains() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["reddit.com"]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.thirtyMinutes) + + h.passTime(to: h.at(10, 5)) + h.setCustomDomainsEnabled(false) + + h.passTime(to: h.at(10, 10)) + h.setCustomDomainsEnabled(true) + + h.passTime(to: h.at(10, 15)) + h.updateMain(apps: [1, 2, 3]) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1, 2, 3)) + #expect(h.blockedDomains.isEmpty) + } + + @Test func wideningPermanentScheduleViaMainSelectionOrCustomDomainsDoesNotFireRetroactively() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["reddit.com"], startingAt: 8) + _ = try h.addSchedule([1, 2], domains: ["reddit.com"], from: (9, 0), minutes: 15, block: true, timed: false) + + h.passTime(to: h.at(8, 30)) + h.updateMain(apps: [1]) + h.setCustomDomainsEnabled(false) + + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(11, 0)) + h.updateMain(apps: [1, 2]) + h.setCustomDomainsEnabled(true) + + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + h.wake(at: h.at(9, 5, dayOffset: 1)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func disablingCustomDomainsDuringWebsiteOnlyTimedUnblockLiftsAppDeletionWithoutSuppressingRunningSchedule() + throws + { + let h = BlockingHarness(mainApps: [], customDomains: ["reddit.com"], startingAt: 9) + h.settings.blockAllPreventsAppDelete = true + _ = try h.addSchedule([], domains: ["reddit.com"], from: (9, 0), minutes: 120, block: true) + h.blockAll() + #expect(h.blockedDomains == ["reddit.com"]) + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(9, 10)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.timedUnblock.isMainUnblockActive) + #expect(!h.appDeletionBlocked) + + h.passTime(to: h.at(9, 15)) + h.setCustomDomainsEnabled(false) + #expect(!h.settings.enableCustomDomains) + #expect(!h.timedUnblock.isMainUnblockActive) + #expect(!h.appDeletionBlocked) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 20)) + h.setCustomDomainsEnabled(true) + #expect(h.blockedDomains == ["reddit.com"]) + #expect(!h.appDeletionBlocked) + + h.wake(at: h.at(9, 45)) + #expect(!h.appDeletionBlocked) + } + + @Test func permanentGroupUnblockCancelsActiveGroupTimedUnblock() throws { + let h = BlockingHarness(mainApps: [1, 2]) + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockGroupTimed(group, .oneHour) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 5)) + let grant = try #require(UnblockGrant(.group(group), proof: KeyProof(keyGroupID: group.id))) + try BlockActions.unblock( + grant, + for: .permanent, + settings: h.settings, + screenTimeService: h.screenTime, + timedUnblockService: h.timedUnblock + ) + + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + try h.addSchedule([1], from: (10, 30), minutes: 60, block: true) + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1, 2)) + } + + @Test func updateMainSelectionPrunesAndCancelsCoexistingGroupTimedUnblockDuringMainTimedUnblock() throws { + let h = BlockingHarness(mainApps: [1, 2, 3]) + h.settings.blockAllPreventsAppDelete = true + let group = h.group([1, 2]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.oneHour) + + h.passTime(to: h.at(10, 5)) + h.blockGroup(group) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.timedUnblock.isMainUnblockActive) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 10)) + h.updateMain(apps: [1, 3]) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + let narrowedDTO = try #require(h.store.timedUnblocks.first { $0.id == group.id.uuidString }) + #expect(try FamilyActivitySelection.fromData(narrowedDTO.selectionData) == TokenFixtures.selection(apps: [1])) + + h.passTime(to: h.at(10, 15)) + h.updateMain(apps: [3]) + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.timedUnblock.isMainUnblockActive) + + let group3 = h.group([3]) + h.blockGroup(group3) + try h.unblockGroupTimed(group3, .thirtyMinutes) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group3.id)) + + h.passTime(to: h.at(10, 20)) + h.updateMain(apps: []) + #expect(h.timedUnblock.activeUnblocks.isEmpty) + #expect(h.blocked.isEmpty) + #expect(!h.appDeletionBlocked) + } + + @Test func disablingCustomDomainsStripsMixedTimersAndCancelsDomainOnlyGroupTimer() throws { + let h = BlockingHarness(mainApps: [1], customDomains: ["reddit.com", "news.com"]) + let mixedGroup = h.group([1], domains: ["reddit.com"]) + let domainGroup = h.group([], domains: ["news.com"]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockGroupTimed(mixedGroup, .thirtyMinutes) + try h.unblockGroupTimed(domainGroup, .thirtyMinutes) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(10, 5)) + h.setCustomDomainsEnabled(false) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: mixedGroup.id)) + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: domainGroup.id)) + let mixedDTO = try #require(h.store.timedUnblocks.first { $0.id == mixedGroup.id.uuidString }) + #expect(mixedDTO.customDomains.isEmpty) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains.isEmpty) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(11, 0)) + h.setCustomDomainsEnabled(true) + h.blockAll() + try h.unblockAllTimed(.thirtyMinutes) + + h.passTime(to: h.at(11, 5)) + h.setCustomDomainsEnabled(false) + #expect(h.timedUnblock.isMainUnblockActive) + let mainDTO = try #require(h.store.timedUnblocks.first { $0.id == TimedUnblockService.mainID }) + #expect(mainDTO.customDomains.isEmpty) + + h.wake(at: h.at(11, 35)) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + } + + @Test func updateGroupSelectionFailsClosedWhenStoredDTOIsMissingOrCorrupt() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["reddit.com"]) + let group = h.group([1], domains: ["reddit.com"]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.blocked == h.apps(2)) + #expect(h.blockedDomains.isEmpty) + + let existing = try #require(h.store.timedUnblocks.first { $0.id == group.id.uuidString }) + h.store.timedUnblocks = [ + TimedUnblockDTO( + id: existing.id, + selectionData: Data([0xFF]), + endDate: existing.endDate, + activityName: existing.activityName, + isGroupUnblock: true, + customDomains: ["reddit.com"], + startDate: existing.startDate + ) + ] + + h.timedUnblock.updateGroupSelection( + groupId: group.id, + selection: TokenFixtures.selection(apps: [1, 2]), + customDomains: ["reddit.com"], + screenTimeService: h.screenTime + ) + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["reddit.com"]) + + h.passTime(to: h.at(10, 5)) + try h.unblockGroupTimed(group, .thirtyMinutes) + h.store.timedUnblocks.removeAll() + + h.timedUnblock.updateGroupSelection( + groupId: group.id, + selection: TokenFixtures.selection(apps: [1, 2]), + customDomains: ["reddit.com"], + screenTimeService: h.screenTime + ) + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func emptyingMainSelectionWithoutMainTimedUnblockCancelsGroupTimersAndLiftsAppDeletion() throws { + let h = BlockingHarness(mainApps: [1, 2]) + h.settings.blockAllPreventsAppDelete = true + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.appDeletionBlocked) + + h.settings.blockAllPreventsAppDelete = false + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: []) + #expect(h.timedUnblock.activeUnblocks.isEmpty) + #expect(h.blocked.isEmpty) + #expect(!h.appDeletionBlocked) + } + + @Test func clearBlockedClearsMaterializedPermanentDomainScheduleAfterBlockAllMovedBaseline() throws { + let h = BlockingHarness(mainApps: [1], customDomains: ["reddit.com"], startingAt: 8, constrainSchedules: true) + h.blockAll() + + let permanent = try h.addSchedule([], domains: ["reddit.com"], from: (9, 0), minutes: 15, block: true, timed: false) + h.wake(at: h.at(9, 5)) + #expect(h.blockedDomains == ["reddit.com"]) + + h.passTime(to: h.at(9, 30)) + permanent.startHour = 11 + try h.save(permanent) + let preserved = try #require(h.store.loadManualBlockState()?.customDomains.scheduleEntries["reddit.com"]) + #expect(preserved.isBlocked) + + h.passTime(to: h.at(9, 45)) + h.setCustomDomainsEnabled(false) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 50)) + h.setCustomDomainsEnabled(true) + #expect(h.blockedDomains.isEmpty) + } + + @Test func wideningPermanentScheduleInsideRegistrationWindowPreservesManualUnblockAndWaitsForNextStart() throws { + let h = BlockingHarness( + mainApps: [1, 2], + customDomains: ["reddit.com"], + startingAt: 8, + constrainSchedules: true + ) + h.settings.enableCustomDomains = false + h.scheduleService.mirrorCustomDomainsEnabled(false) + + let permanent = try h.addSchedule( + [1], + domains: ["reddit.com"], + from: (9, 0), + minutes: 15, + block: true, + timed: false + ) + + h.wake(at: h.at(9, 1)) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 5)) + h.screenTime.unblock(selection: TokenFixtures.selection(apps: [1])) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(9, 10)) + h.setCustomDomainsEnabled(true) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 12)) + permanent.selection = TokenFixtures.selection(apps: [1, 2]) + try h.save(permanent) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains.isEmpty) + + h.wake(at: h.at(9, 5, dayOffset: 1)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func removingAndRestoringTargetDuringActiveTimedScheduleRestoresCoverageWhilePreservingManualUnblock() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["reddit.com", "news.com"], startingAt: 9) + _ = try h.addSchedule([1, 2], domains: ["reddit.com", "news.com"], from: (9, 0), minutes: 120, block: true) + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["reddit.com", "news.com"]) + + h.passTime(to: h.at(9, 10)) + h.screenTime.unblock(selection: TokenFixtures.selection(apps: [2]), customDomains: ["news.com"]) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains == ["reddit.com"]) + + h.passTime(to: h.at(9, 15)) + try h.unblockAllTimed(.fifteenMinutes) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 20)) + h.updateMain(domains: ["news.com"]) + + h.wake(at: h.at(9, 35)) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + h.passTime(to: h.at(9, 40)) + h.updateMain(domains: ["reddit.com", "news.com"]) + #expect(h.blockedDomains == ["reddit.com"]) + + h.passTime(to: h.at(9, 45)) + h.updateMain(apps: [2]) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(9, 50)) + h.updateMain(apps: [1, 2]) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains == ["reddit.com"]) + } + + @Test func emptyingMainSelectionPreservesSeparatelyEnabledAppDeletionProtection() throws { + let h = BlockingHarness(mainApps: [1, 2]) + h.settings.blockAllPreventsAppDelete = true + + h.screenTime.enablePreventAppDelete() + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(9, 0)) + h.updateMain(apps: []) + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10, 0)) + h.main.selection = TokenFixtures.selection(apps: [1, 2]) + h.blockAll() + try h.unblockAllTimed(.thirtyMinutes) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: []) + h.wake(at: h.at(10, 35)) + #expect(h.appDeletionBlocked) + } + + @Test func disablingCustomDomainsDuringWebsiteOnlyTimerPreservesNewerStandaloneAppDeletion() throws { + let h = BlockingHarness(mainApps: [], customDomains: ["reddit.com"]) + h.settings.blockAllPreventsAppDelete = true + h.blockAll() + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(!h.appDeletionBlocked) + + h.passTime(to: h.at(10, 5)) + h.screenTime.enablePreventAppDelete() + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10, 10)) + h.setCustomDomainsEnabled(false) + #expect(!h.timedUnblock.isMainUnblockActive) + #expect(h.appDeletionBlocked) + + h.wake(at: h.at(10, 35)) + #expect(h.appDeletionBlocked) + } + + @Test func scheduleExpirationCallsOnExpirationWhenClockCrossesDeadlineDuringReconcile() throws { + let deadline = Date(timeIntervalSinceReferenceDate: 1_000_000) + var now = deadline.addingTimeInterval(-1000) + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let shields = InMemoryShieldStore(startBlocked: false) + let screenTime = ScreenTimeService( + defaults: UserDefaults(suiteName: "exp-\(UUID().uuidString)")!, + shield: shields, + sharedStore: store, + activityCenter: activity, + clock: { now } + ) + screenTime.blockAll( + selection: TokenFixtures.selection(apps: [1]), + customDomains: [], + blockAllPreventsAppDelete: false + ) + store.timedUnblocks = try [ + TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: deadline, + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + startDate: deadline.addingTimeInterval(-900) + ) + ] + now = deadline.addingTimeInterval(-10) + screenTime.reconcile() + #expect(shields.currentShields().applications.isEmpty) + + let ticks = [ + deadline.addingTimeInterval(-10), + deadline.addingTimeInterval(-5), + deadline.addingTimeInterval(-1), + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(1), + ] + var tickIndex = 0 + var expirations = 0 + var dtoPresentDuringExpiration = false + let service = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { + now = ticks[min(tickIndex, ticks.count - 1)] + tickIndex += 1 + return now + }, + onExpiration: { + expirations += 1 + dtoPresentDuringExpiration = !store.timedUnblocks.isEmpty + return screenTime.reconcile() + } + ) + + service.reconcile(screenTimeService: screenTime) + + #expect(!service.isMainUnblockActive) + #expect(dtoPresentDuringExpiration) + #expect(store.timedUnblocks.isEmpty) + #expect(expirations == 1) + #expect(shields.currentShields().applications == TokenFixtures.selection(apps: [1]).applicationTokens) + } + + @Test func permanentScheduleWithFutureActivationNeverEmitsFutureClaimAcrossDSTSpringForward() throws { + var chicago = Calendar(identifier: .gregorian) + chicago.timeZone = try #require(TimeZone(identifier: "America/Chicago")) + + let satStart = try #require( + chicago.date(from: DateComponents(year: 2026, month: 3, day: 7, hour: 10, minute: 0)) + ) + let futureActivation = satStart.addingTimeInterval(TimeInterval(1440 * 60)) + let sunBeforeActivation = try #require( + chicago.date(from: DateComponents(year: 2026, month: 3, day: 8, hour: 10, minute: 5)) + ) + let sunManualUnblock = try #require( + chicago.date(from: DateComponents(year: 2026, month: 3, day: 8, hour: 10, minute: 10)) + ) + let sunAfterActivation = try #require( + chicago.date(from: DateComponents(year: 2026, month: 3, day: 8, hour: 11, minute: 5)) + ) + let sunLaterUnblock = try #require( + chicago.date(from: DateComponents(year: 2026, month: 3, day: 8, hour: 11, minute: 10)) + ) + + let selection = TokenFixtures.selection(apps: [1, 2]) + let dto = ScheduleDTO( + id: UUID(), + name: "Daily", + selectionData: try selection.toData(), + startHour: 10, + startMinute: 0, + durationMinutes: 1440, + weekdays: Set(1...7), + shouldBlock: true, + isTimed: false, + customDomains: [], + isEnabled: true, + activatedAt: futureActivation + ) + + var manual = ManualBlockState() + func plan(at date: Date) -> ShieldPlan { + ShieldResolver.plan( + manual: manual, + enabledSchedules: [dto], + timedUnblocks: [], + customDomainsEnabled: false, + at: date, + calendar: chicago + ) + } + + manual.block(selection, customDomains: [], at: satStart) + #expect(plan(at: sunBeforeActivation).applications == selection.applicationTokens) + + manual.unblock(selection, customDomains: [], at: sunManualUnblock) + #expect(plan(at: sunManualUnblock).applications.isEmpty) + #expect(plan(at: sunAfterActivation).applications == selection.applicationTokens) + + manual.unblock(selection, customDomains: [], at: sunLaterUnblock) + #expect(plan(at: sunLaterUnblock).applications.isEmpty) + } + + @Test(arguments: [true, false]) + func disablingCustomDomainsWhileBlockedWebsiteOnlyRespectsAppDeletionOwnership(blockAllOwned: Bool) { + let h = BlockingHarness(mainApps: [], customDomains: ["reddit.com"], startingAt: 10) + h.settings.blockAllPreventsAppDelete = blockAllOwned + h.blockAll() + if blockAllOwned { + h.settings.blockAllPreventsAppDelete = false + } else { + h.passTime(to: h.at(10, 2)) + h.screenTime.enablePreventAppDelete() + } + #expect(h.blockedDomains == ["reddit.com"]) + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10, 5)) + h.setCustomDomainsEnabled(false) + #expect(h.blockedDomains.isEmpty) + #expect(h.appDeletionBlocked == !blockAllOwned) + } + + @Test func editingEnabledPermanentScheduleStartTimeNeverFiresRetroactivelyAndFiresFutureStartOnTime() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 8) + let schedule = try h.addSchedule([1], from: (10, 0), minutes: 60, block: true, timed: false) + h.wake(at: h.at(10, 5)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(10, 20)) + h.unblockGroupPermanently(h.group([1])) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(10, 30)) + schedule.startMinute = 15 + try h.save(schedule) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(11, 20)) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(11, 25)) + schedule.startHour = 11 + schedule.startMinute = 45 + try h.save(schedule) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(11, 46)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(11, 50)) + h.unblockGroupPermanently(h.group([1])) + h.wake(at: h.at(11, 46, dayOffset: 1)) + #expect(h.blocked == h.apps(1)) + } + + @Test func syncAndPersistCapturesSingleDecisionTimeAcrossPermanentScheduleStart() throws { + let day = Calendar.current.startOfDay(for: Calendar.current.date(byAdding: .day, value: 1, to: .now)!) + let weekday = Calendar.current.component(.weekday, from: day) + let beforeStart = Calendar.current.date(bySettingHour: 8, minute: 59, second: 59, of: day)! + let afterStart = Calendar.current.date(bySettingHour: 9, minute: 0, second: 1, of: day)! + let atNineOhFive = Calendar.current.date(bySettingHour: 9, minute: 5, second: 0, of: day)! + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let shields = InMemoryShieldStore(startBlocked: false) + var screenTimeNow = Calendar.current.date(bySettingHour: 8, minute: 0, second: 0, of: day)! + let screenTime = ScreenTimeService( + defaults: UserDefaults(suiteName: "single-clock-\(UUID().uuidString)")!, + shield: shields, + sharedStore: store, + activityCenter: activity, + clock: { screenTimeNow } + ) + let schedule = BlockSchedule( + name: "Weekly", + selection: TokenFixtures.selection(apps: [1]), + startHour: 9, + startMinute: 0, + durationMinutes: 15, + weekdays: [weekday], + shouldBlock: true, + isTimed: false, + isEnabled: true + ) + var scheduleClockReadings = [screenTimeNow, beforeStart, afterStart] + var scheduleClockReads = 0 + let service = ScheduleService( + activityCenter: activity, + sharedStore: store, + clock: { + scheduleClockReads += 1 + let next = scheduleClockReadings.first ?? afterStart + if scheduleClockReadings.count > 1 { + scheduleClockReadings.removeFirst() + } + return next + } + ) + try service.syncAndPersist(schedule, allSchedules: [schedule], screenTimeService: screenTime) + + scheduleClockReads = 0 + screenTimeNow = beforeStart + schedule.selection = TokenFixtures.selection(apps: [1, 2]) + try service.syncAndPersist(schedule, allSchedules: [schedule], screenTimeService: screenTime) + #expect(scheduleClockReads == 1) + + screenTimeNow = atNineOhFive + screenTime.reconcile() + #expect(shields.currentShields().applications == TokenFixtures.selection(apps: [1, 2]).applicationTokens) + } + + @Test(arguments: [false, true]) + func cancellingMainTimerAfterDisablingAppDeleteSettingRespectsSavedOwnership(websiteOnly: Bool) throws { + let h = BlockingHarness( + mainApps: websiteOnly ? [] : [1], + customDomains: websiteOnly ? ["reddit.com"] : [], + startingAt: 10 + ) + h.settings.blockAllPreventsAppDelete = true + h.blockAll() + #expect(h.appDeletionBlocked) + + h.settings.blockAllPreventsAppDelete = false + h.passTime(to: h.at(10, 5)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.appDeletionBlocked) + + h.passTime(to: h.at(10, 10)) + if websiteOnly { + h.setCustomDomainsEnabled(false) + } else { + h.updateMain(apps: []) + } + #expect(!h.timedUnblock.isMainUnblockActive) + #expect(!h.appDeletionBlocked) + + h.wake(at: h.at(10, 40)) + #expect(!h.appDeletionBlocked) + } + + @Test func expiredTimedUnblockDTOIsRetainedAndKeepsHeartbeatUntilReconciliationSucceeds() throws { + let deadline = Date(timeIntervalSinceReferenceDate: 1_000_000) + let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + + let screenTime = FakeScreenTimeService() + screenTime.reconcileResult = false + let (reconcileActivity, reconcileStore, reconcileService) = try makeTickingTimedUnblock( + deadline: deadline, + ticks: [ + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(1), + ], + onExpiration: { true } + ) + reconcileService.reconcile(screenTimeService: screenTime) + #expect(!reconcileService.isMainUnblockActive) + #expect(reconcileStore.timedUnblocks.count == 1) + #expect(reconcileActivity.registeredSchedule(for: heartbeat) != nil) + + screenTime.reconcileResult = true + reconcileService.reconcile(screenTimeService: screenTime) + #expect(reconcileStore.timedUnblocks.isEmpty) + #expect(reconcileActivity.registeredSchedule(for: heartbeat) == nil) + + let backwardClockScreenTime = FakeScreenTimeService() + backwardClockScreenTime.reconcileResult = false + let (backwardActivity, backwardStore, backwardService) = try makeTickingTimedUnblock( + deadline: deadline, + ticks: [ + deadline.addingTimeInterval(-10), + deadline.addingTimeInterval(-5), + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(-30), + deadline.addingTimeInterval(-30), + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(-30), + deadline.addingTimeInterval(1), + ], + onExpiration: { true } + ) + backwardService.reconcile(screenTimeService: backwardClockScreenTime) + #expect(!backwardService.isMainUnblockActive) + #expect(backwardClockScreenTime.reconcileDates == [deadline.addingTimeInterval(1)]) + #expect(backwardStore.timedUnblocks.count == 1) + #expect(backwardActivity.registeredSchedule(for: heartbeat) != nil) + + backwardClockScreenTime.reconcileResult = true + backwardService.reconcile(screenTimeService: backwardClockScreenTime) + #expect( + backwardClockScreenTime.reconcileDates == [ + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(1), + ] + ) + #expect(backwardStore.timedUnblocks.isEmpty) + #expect(backwardActivity.registeredSchedule(for: heartbeat) == nil) + + let (expireActivity, expireStore, expireService) = try makeTickingTimedUnblock( + deadline: deadline, + ticks: [ + deadline.addingTimeInterval(-10), + deadline.addingTimeInterval(-5), + deadline.addingTimeInterval(-1), + deadline.addingTimeInterval(1), + deadline.addingTimeInterval(1), + ], + onExpiration: { false } + ) + expireService.reconcile(screenTimeService: screenTime) + #expect(!expireService.isMainUnblockActive) + #expect(expireStore.timedUnblocks.count == 1) + #expect(expireActivity.registeredSchedule(for: heartbeat) != nil) + + expireService.reconcile(screenTimeService: screenTime) + #expect(expireStore.timedUnblocks.isEmpty) + #expect(expireActivity.registeredSchedule(for: heartbeat) == nil) + } + + @Test(arguments: [[11, 2], [11, 12]]) + func tokenRotationDuringMainSelectionEditNeverUnblocksManualOrScheduledBlocks(rotatedApps: [UInt8]) throws { + let h = BlockingHarness( + mainApps: [1, 2], + customDomains: ["a.com", "b.com"], + startingAt: 9, + constrainSchedules: true + ) + let schedule = try h.addSchedule([1], domains: ["a.com", "b.com"], from: (9, 0), minutes: 120, block: true) + let other = try h.addSchedule([2], from: (14, 0), minutes: 60, block: true) + h.blockAll() + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["a.com", "b.com"]) + + h.passTime(to: h.at(9, 30)) + h.updateMain(apps: rotatedApps, domains: ["a.com"]) + + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["a.com"]) + let dtoAfterEdit = try #require(h.store.schedules.first { $0.id == schedule.id }) + #expect(try FamilyActivitySelection.fromData(dtoAfterEdit.selectionData) == TokenFixtures.selection(apps: [1])) + #expect(dtoAfterEdit.customDomains == ["a.com"]) + + try h.toggle(other) + try h.delete(other) + h.setCustomDomainsEnabled(false) + h.openApp(at: h.at(9, 45)) + + let dtoAfterSyncs = try #require(h.store.schedules.first { $0.id == schedule.id }) + #expect(try FamilyActivitySelection.fromData(dtoAfterSyncs.selectionData) == TokenFixtures.selection(apps: [1])) + #expect(dtoAfterSyncs.customDomains.isEmpty) + + h.unblockAllPermanently() + #expect(h.blocked.isEmpty) + h.wake(at: h.at(9, 30, dayOffset: 1)) + #expect(h.blocked == h.apps(1)) + + h.updateMain(apps: [], domains: []) + let dtoAfterEmpty = try #require(h.store.schedules.first { $0.id == schedule.id }) + #expect(try FamilyActivitySelection.fromData(dtoAfterEmpty.selectionData).isEmpty) + #expect(h.blocked.isEmpty) + + let manualOnly = BlockingHarness(mainApps: [1, 2], customDomains: ["a.com"], startingAt: 9) + manualOnly.blockAll() + manualOnly.updateMain(apps: rotatedApps, domains: ["a.com"]) + #expect(manualOnly.blocked == manualOnly.apps(1, 2)) + manualOnly.updateMain(apps: [], domains: ["a.com"]) + #expect(manualOnly.blocked.isEmpty) + #expect(manualOnly.blockedDomains == ["a.com"]) + } + + @Test func tokenRotationDuringGroupTimedUnblockPreservesTimerAndReblocksAtExpiry() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["a.com"], startingAt: 9) + let group = h.group([1]) + h.blockGroup(group) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(10, 0)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.blocked.isEmpty) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: [11, 12], domains: ["a.com"]) + + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(1)) + + h.passTime(to: h.at(11, 0)) + try h.unblockGroupTimed(group, .thirtyMinutes) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + h.passTime(to: h.at(11, 5)) + h.updateMain(apps: [], domains: ["a.com"]) + #expect(!h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked.isEmpty) + } + + @Test func tokenRotationDuringMainTimedUnblockRemovesUncheckedAppAndReblocksKeptRotatedApps() throws { + let h = BlockingHarness(mainApps: [1, 2, 3], startingAt: 9) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: [11, 12]) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked == h.apps(11, 12)) + } + + @Test func previousRemovalStaysRemovedIfRemainingTokensLaterRotate() throws { + let h = BlockingHarness(mainApps: [1, 2, 3], startingAt: 9, constrainSchedules: true) + let schedule = try h.addSchedule([1, 2, 3], from: (10, 0), minutes: 60, block: true) + + h.passTime(to: h.at(9, 10)) + h.updateMain(apps: [1]) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + + h.passTime(to: h.at(9, 20)) + h.updateMain(apps: [1, 2]) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1, 2]) + ) + + h.passTime(to: h.at(9, 30)) + h.updateMain(apps: [11, 12]) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1, 2]) + ) + + schedule.selection = TokenFixtures.selection(apps: [11]) + try h.save(schedule) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [11]) + ) + } + + @Test func corruptOrMissingScheduleDTOConstrainsStrictlyToMainSelection() throws { + let h = BlockingHarness(mainApps: [1], startingAt: 9, constrainSchedules: true) + let schedule = try h.addSchedule([1, 2], from: (10, 0), minutes: 60, block: true) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + + let existing = try #require(h.store.schedules.first) + h.store.schedules = [ + ScheduleDTO( + id: existing.id, + name: existing.name, + selectionData: Data([0xFF]), + startHour: existing.startHour, + startMinute: existing.startMinute, + durationMinutes: existing.durationMinutes, + weekdays: existing.weekdays, + shouldBlock: existing.shouldBlock, + isTimed: existing.isTimed, + customDomains: existing.customDomains, + isEnabled: existing.isEnabled, + activatedAt: existing.activatedAt + ) + ] + + h.openApp(at: h.at(9, 30)) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first { $0.id == schedule.id }?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + } + + @Test func emptyingAppsDuringMainTimedUnblockClearsPreRotationLeftovers() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["a.com"], startingAt: 8, constrainSchedules: true) + let schedule = try h.addSchedule([1, 2], domains: ["a.com"], from: (9, 0), minutes: 15, block: true, timed: false) + + h.passTime(to: h.at(8, 30)) + h.updateMain(apps: [11, 12], domains: ["a.com"]) + + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1, 2)) + #expect(h.blockedDomains == ["a.com"]) + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.thirtyMinutes) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(10, 2)) + try h.delete(schedule) + + h.passTime(to: h.at(10, 5)) + h.updateMain(apps: [], domains: ["a.com"]) + + h.wake(at: h.at(10, 35)) + #expect(h.blocked.isEmpty) + #expect(h.blockedDomains == ["a.com"]) + } + + @Test func tokenRotationDuringMainTimedUnblockPreservesPostTimerGroupBlockAndTimer() throws { + let h = BlockingHarness(mainApps: [1, 2], startingAt: 9) + let group = h.group([1]) + h.blockAll() + + h.passTime(to: h.at(10, 0)) + try h.unblockAllTimed(.oneHour) + + h.passTime(to: h.at(10, 5)) + h.blockGroup(group) + h.passTime(to: h.at(10, 6)) + try h.unblockGroupTimed(group, .fifteenMinutes) + #expect(h.blocked.isEmpty) + + h.passTime(to: h.at(10, 10)) + h.updateMain(apps: [11, 12]) + #expect(h.timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(h.blocked.isEmpty) + + h.wake(at: h.at(10, 25)) + #expect(h.blocked == h.apps(1)) + } + + @Test func emergencyUnblockPreservesNarrowedScheduleDTOAcrossRelaunchAndRotation() throws { + let h = BlockingHarness(mainApps: [1, 2, 3], startingAt: 9, constrainSchedules: true) + _ = try h.addSchedule([1, 2, 3], from: (10, 0), minutes: 60, block: true) + + h.passTime(to: h.at(9, 10)) + h.updateMain(apps: [1]) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + + h.emergencyUnblock() + h.openApp(at: h.at(9, 20)) + h.updateMain(apps: [11]) + #expect( + try FamilyActivitySelection.fromData(#require(h.store.schedules.first?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + } + + @Test func failedPermanentSchedulePreservationRetainsDTOAcrossAllWritesUntilPreservationSucceeds() throws { + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let screenTime = FakeScreenTimeService() + let day = Calendar.current.startOfDay(for: Calendar.current.date(byAdding: .day, value: 1, to: .now)!) + var now = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: day)! + let service = ScheduleService(activityCenter: activity, sharedStore: store, clock: { now }) + + let schedule = BlockSchedule( + name: "Work", + selection: TokenFixtures.selection(apps: [1]), + startHour: 9, + startMinute: 0, + durationMinutes: 15, + weekdays: Set(1...7), + shouldBlock: true, + isTimed: false, + isEnabled: true + ) + let other = BlockSchedule( + name: "Other", + selection: TokenFixtures.selection(apps: [2]), + startHour: 11, + startMinute: 0, + durationMinutes: 60, + weekdays: Set(1...7), + shouldBlock: true, + isTimed: true, + isEnabled: true + ) + try service.syncAndPersist(schedule, allSchedules: [schedule, other], screenTimeService: screenTime) + try service.syncAndPersist(other, allSchedules: [schedule, other], screenTimeService: screenTime) + let originalDTO = try #require(store.schedules.first { $0.id == schedule.id }) + let activityName = SharedConstants.scheduleActivityName(for: schedule.id) + + screenTime.preservePermanentScheduleResult = false + now = Calendar.current.date(bySettingHour: 9, minute: 35, second: 0, of: day)! + + #expect(throws: ScheduleRegistrationError.storageUnavailable) { + try service.toggleEnabled(schedule, allSchedules: [schedule, other], screenTimeService: screenTime) + } + #expect(schedule.isEnabled) + #expect(store.schedules.first { $0.id == schedule.id }?.isEnabled == true) + + schedule.startHour = 14 + #expect(throws: ScheduleRegistrationError.storageUnavailable) { + try service.syncAndPersist(schedule, allSchedules: [schedule, other], screenTimeService: screenTime) + } + #expect(store.schedules.first { $0.id == schedule.id }?.startHour == originalDTO.startHour) + #expect(store.schedules.first { $0.id == schedule.id }?.activatedAt == originalDTO.activatedAt) + #expect(activity.monitoredActivityNames.contains(activityName)) + + service.syncAllToSharedStore([other, schedule]) + #expect(store.schedules.first { $0.id == schedule.id }?.startHour == originalDTO.startHour) + #expect(store.schedules.first { $0.id == schedule.id }?.activatedAt == originalDTO.activatedAt) + + other.startHour = 12 + try service.syncAndPersist(other, allSchedules: [schedule, other], screenTimeService: screenTime) + #expect(store.schedules.first { $0.id == schedule.id }?.startHour == originalDTO.startHour) + + let main = SelectedApps(selection: TokenFixtures.selection(apps: [1, 2])) + schedule.startHour = 9 + schedule.selection = TokenFixtures.selection(apps: [1, 2]) + service.syncConstrained( + [schedule, other], + constrainedTo: main.effectiveConstraint(customDomainsEnabled: false), + screenTimeService: screenTime + ) + #expect( + try FamilyActivitySelection.fromData(#require(store.schedules.first { $0.id == schedule.id }?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + + #expect(throws: ScheduleRegistrationError.storageUnavailable) { + try service.remove(schedule, remaining: [other], screenTimeService: screenTime) + } + #expect(store.schedules.contains { $0.id == schedule.id }) + #expect(activity.monitoredActivityNames.contains(activityName)) + + service.syncAllToSharedStore([other]) + #expect(store.schedules.contains { $0.id == schedule.id }) + + try service.remove(other, remaining: [], screenTimeService: screenTime) + #expect(store.schedules.map(\.id) == [schedule.id]) + #expect(activity.monitoredActivityNames.contains(activityName)) + + let timedUnblock = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { now }, + onExpiration: { screenTime.reconcile() } + ) + let settings = Settings() + BlockActions.updateMainSelection( + from: TokenFixtures.selection(apps: [1, 2]), + oldCustomDomains: [], + to: FamilyActivitySelection(), + newCustomDomains: [], + schedules: [], + settings: settings, + screenTimeService: screenTime, + timedUnblockService: timedUnblock, + scheduleService: service + ) + #expect(store.schedules.map(\.id) == [schedule.id]) + + screenTime.preservePermanentScheduleResult = true + BlockActions.updateMainSelection( + from: TokenFixtures.selection(apps: [1, 2]), + oldCustomDomains: [], + to: FamilyActivitySelection(), + newCustomDomains: [], + schedules: [], + settings: settings, + screenTimeService: screenTime, + timedUnblockService: timedUnblock, + scheduleService: service + ) + #expect(store.schedules.isEmpty) + #expect(!activity.monitoredActivityNames.contains(activityName)) + } + + @Test func disableAllStopsOrphanedScheduleActivities() throws { + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let screenTime = FakeScreenTimeService() + let service = ScheduleService(activityCenter: activity, sharedStore: store) + let orphanName = SharedConstants.scheduleActivityName(for: UUID()) + activity.monitoredActivityNames.insert(orphanName) + activity.monitoredActivityNames.insert(SharedConstants.usageLimitsActivityName) + + service.disableAll([], screenTimeService: screenTime) + + #expect(!activity.monitoredActivityNames.contains(orphanName)) + #expect(activity.monitoredActivityNames.contains(SharedConstants.usageLimitsActivityName)) + } + + @Test func deferredTimerCleanupPreservesTimersAndHeartbeatWhenReconciliationFails() throws { + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + var now = base + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let screenTime = FakeScreenTimeService() + let timed = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { now }, + onExpiration: { screenTime.reconcile() } + ) + let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + + try timed.startMain( + duration: .fifteenMinutes, + selection: FamilyActivitySelection(), + customDomains: ["example.com"], + screenTimeService: screenTime, + blockAllPreventsAppDelete: true + ) + #expect(timed.isMainUnblockActive) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + + screenTime.reconcileResult = false + timed.handleCustomDomainsDisabled(screenTimeService: screenTime) + #expect(timed.isMainUnblockActive) + #expect(store.timedUnblocks.count == 1) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + + screenTime.reconcileResult = true + timed.handleCustomDomainsDisabled(screenTimeService: screenTime) + #expect(!timed.isMainUnblockActive) + #expect(store.timedUnblocks.isEmpty) + #expect(activity.registeredSchedule(for: heartbeat) == nil) + + try timed.startMain( + duration: .fifteenMinutes, + selection: TokenFixtures.selection(apps: [1]), + customDomains: [], + screenTimeService: screenTime + ) + screenTime.reconcileResult = false + timed.updateMainSelection( + TokenFixtures.selection(apps: [1, 2]), + from: TokenFixtures.selection(apps: [1]), + screenTimeService: screenTime + ) + #expect( + try FamilyActivitySelection.fromData(#require(store.timedUnblocks.first?.selectionData)) + == TokenFixtures.selection(apps: [1]) + ) + + timed.updateMainSelection( + FamilyActivitySelection(), + from: TokenFixtures.selection(apps: [1]), + screenTimeService: screenTime + ) + #expect(timed.isMainUnblockActive) + #expect(store.timedUnblocks.count == 1) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + + screenTime.reconcileResult = true + timed.updateMainSelection( + FamilyActivitySelection(), + from: TokenFixtures.selection(apps: [1]), + screenTimeService: screenTime + ) + #expect(!timed.isMainUnblockActive) + #expect(store.timedUnblocks.isEmpty) + #expect(activity.registeredSchedule(for: heartbeat) == nil) + + let groupID = UUID() + try timed.startGroup( + duration: .fifteenMinutes, + groupId: groupID, + selection: TokenFixtures.selection(apps: [1]), + screenTimeService: screenTime + ) + screenTime.reconcileResult = false + timed.updateGroupSelection( + groupId: groupID, + selection: FamilyActivitySelection(), + screenTimeService: screenTime + ) + #expect(!timed.isGroupUnblockActive(groupId: groupID)) + #expect(store.timedUnblocks.count == 1) + #expect(store.timedUnblocks.first?.endDate == now) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + + now = base.addingTimeInterval(60) + let shields = InMemoryShieldStore() + var manual = ManualBlockState() + manual.blockAll(TokenFixtures.selection(apps: [1]), customDomains: [], at: base.addingTimeInterval(-60)) + store.saveManualBlockState(manual) + let plan = ShieldReconciler.reconcileMonitor( + sharedStore: store, + shields: shields, + activityCenter: activity, + at: now + ) + #expect(plan != nil) + #expect(shields.currentShields().applications == TokenFixtures.selection(apps: [1]).applicationTokens) + #expect(store.timedUnblocks.isEmpty) + #expect(activity.registeredSchedule(for: heartbeat) == nil) + } + + @Test func monitorReconcileRetiresExpiredTimersUpdatesHeartbeatAndPreservesReusedID() throws { + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let shields = InMemoryShieldStore() + let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + + var manual = ManualBlockState() + manual.blockAll(TokenFixtures.selection(apps: [1]), customDomains: [], at: base.addingTimeInterval(-3600)) + store.saveManualBlockState(manual) + + let expiredMain = try TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: base.addingTimeInterval(-60), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + startDate: base.addingTimeInterval(-960) + ) + store.timedUnblocks = [expiredMain] + activity.syncHeartbeat(sharedStore: store, at: base) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + + let replacement = try TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: base.addingTimeInterval(900), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + startDate: base + ) + store.timedUnblocks = [replacement] + #expect(!store.removeTimedUnblocks(matching: [expiredMain])) + #expect(store.timedUnblocks == [replacement]) + + store.timedUnblocks = [expiredMain] + let plan = ShieldReconciler.reconcileMonitor( + sharedStore: store, + shields: shields, + activityCenter: activity, + at: base + ) + #expect(plan != nil) + #expect(shields.currentShields().applications == TokenFixtures.selection(apps: [1]).applicationTokens) + #expect(store.timedUnblocks.isEmpty) + #expect(activity.registeredSchedule(for: heartbeat) == nil) + } + + @Test func exactMainStartDateManualBlockIsPreservedOnUnconfirmedRemoval() throws { + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + let store = FakeSharedStore() + let shields = InMemoryShieldStore() + let activity = FakeDeviceActivityCenter() + let screenTime = ScreenTimeService( + defaults: UserDefaults(suiteName: "exact-boundary-\(UUID().uuidString)") ?? .standard, + shield: shields, + sharedStore: store, + activityCenter: activity, + clock: { base } + ) + + var manual = ManualBlockState() + manual.block(TokenFixtures.selection(apps: [1]), customDomains: [], at: base) + manual.block(TokenFixtures.selection(apps: [2]), customDomains: [], at: base.addingTimeInterval(-1)) + store.saveManualBlockState(manual) + + screenTime.updateMainList( + from: TokenFixtures.selection(apps: [1, 2]), + customDomains: [], + to: TokenFixtures.selection(apps: [11, 12]), + customDomains: [], + addedBlockedAsOf: base.addingTimeInterval(-1), + unconfirmedRemovalBefore: base + ) + + let updated = try #require(store.loadManualBlockState()) + let app1 = try #require(TokenFixtures.selection(apps: [1]).applicationTokens.first) + let app2 = try #require(TokenFixtures.selection(apps: [2]).applicationTokens.first) + #expect(updated.applications.entry(for: app1).isBlocked) + #expect(!updated.applications.entry(for: app2).isBlocked) + } + + @Test func blockActionsRejectsMainRemovalAndCustomDomainDisableWhenCleanupFails() throws { + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let screenTime = FakeScreenTimeService() + let scheduleService = ScheduleService(activityCenter: activity, sharedStore: store, clock: { base }) + let timed = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { base }, + onExpiration: { screenTime.reconcile() } + ) + let settings = Settings() + settings.enableCustomDomains = true + scheduleService.mirrorCustomDomainsEnabled(true) + + let schedule = BlockSchedule( + name: "Work", + selection: TokenFixtures.selection(apps: [1]), + startHour: 9, + startMinute: 0, + durationMinutes: 60, + weekdays: Set(1...7), + shouldBlock: true, + isTimed: true, + isEnabled: true, + customDomains: ["example.com"] + ) + let main = SelectedApps(selection: TokenFixtures.selection(apps: [1]), customDomains: ["example.com"]) + try scheduleService.syncAndPersist( + schedule, + allSchedules: [schedule], + screenTimeService: screenTime, + constrainedTo: main.effectiveConstraint(customDomainsEnabled: true) + ) + try timed.startMain( + duration: .fifteenMinutes, + selection: FamilyActivitySelection(), + customDomains: ["example.com"], + screenTimeService: screenTime, + blockAllPreventsAppDelete: true + ) + + screenTime.reconcileResult = false + let disabledOK = BlockActions.setCustomDomainsEnabled( + false, + settings: settings, + schedules: [schedule], + mainSelection: SelectedApps(selection: FamilyActivitySelection(), customDomains: ["example.com"]), + screenTimeService: screenTime, + timedUnblockService: timed, + scheduleService: scheduleService + ) + #expect(!disabledOK) + #expect(settings.enableCustomDomains) + #expect(store.isCustomDomainsEnabled()) + #expect(store.schedules.first?.customDomains == ["example.com"]) + #expect(timed.isMainUnblockActive) + + let mainRemovedOK = BlockActions.updateMainSelection( + from: TokenFixtures.selection(apps: [1]), + oldCustomDomains: ["example.com"], + to: FamilyActivitySelection(), + newCustomDomains: [], + schedules: [schedule], + settings: settings, + screenTimeService: screenTime, + timedUnblockService: timed, + scheduleService: scheduleService + ) + #expect(!mainRemovedOK) + #expect(store.schedules.first?.customDomains == ["example.com"]) + #expect(timed.isMainUnblockActive) + + screenTime.reconcileResult = true + let disabledRetryOK = BlockActions.setCustomDomainsEnabled( + false, + settings: settings, + schedules: [schedule], + mainSelection: SelectedApps(selection: FamilyActivitySelection(), customDomains: ["example.com"]), + screenTimeService: screenTime, + timedUnblockService: timed, + scheduleService: scheduleService + ) + #expect(disabledRetryOK) + #expect(!settings.enableCustomDomains) + #expect(!store.isCustomDomainsEnabled()) + #expect(store.schedules.first?.customDomains.isEmpty == true) + #expect(!timed.isMainUnblockActive) + } + + @Test func sharedFileLockSkipsReconciliationWhenLockCannotOpen() throws { + let missingDir = FileManager.default.temporaryDirectory + .appending(path: "missing-\(UUID().uuidString)") + .appending(path: "shields.lock") + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + let store = FakeSharedStore() + let shields = InMemoryShieldStore() + let activity = FakeDeviceActivityCenter() + let heartbeat = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + + let expiredMain = try TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: base.addingTimeInterval(-60), + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + startDate: base.addingTimeInterval(-960) + ) + store.timedUnblocks = [expiredMain] + activity.syncHeartbeat(sharedStore: store, at: base) + + let skipped = ShieldReconciler.reconcileMonitor( + sharedStore: store, + shields: shields, + activityCenter: activity, + at: base, + lockURL: missingDir + ) + #expect(skipped == nil) + #expect(store.timedUnblocks == [expiredMain]) + #expect(activity.registeredSchedule(for: heartbeat) != nil) + } + + @Test func setCustomDomainsEnabledRejectsEnablementWhenPermanentSchedulePreservationFails() throws { + let day = Calendar.current.startOfDay(for: Calendar.current.date(byAdding: .day, value: 1, to: .now)!) + let now = Calendar.current.date(bySettingHour: 10, minute: 0, second: 0, of: day)! + let store = FakeSharedStore() + let activity = FakeDeviceActivityCenter() + let screenTime = FakeScreenTimeService() + let scheduleService = ScheduleService(activityCenter: activity, sharedStore: store, clock: { now }) + let timed = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { now }, + onExpiration: { screenTime.reconcile() } + ) + let settings = Settings() + settings.enableCustomDomains = false + scheduleService.mirrorCustomDomainsEnabled(false) + + let main = SelectedApps(selection: TokenFixtures.selection(apps: [1]), customDomains: ["example.com"]) + let schedule = BlockSchedule( + name: "Work", + selection: TokenFixtures.selection(apps: [1]), + startHour: 9, + startMinute: 0, + durationMinutes: 15, + weekdays: Set(1...7), + shouldBlock: true, + isTimed: false, + isEnabled: true, + customDomains: ["example.com"] + ) + try scheduleService.syncAndPersist( + schedule, + allSchedules: [schedule], + screenTimeService: screenTime, + constrainedTo: main.effectiveConstraint(customDomainsEnabled: false) + ) + #expect(store.schedules.first?.customDomains.isEmpty == true) + + screenTime.preservePermanentScheduleResult = false + let enabledWhileLocked = BlockActions.setCustomDomainsEnabled( + true, + settings: settings, + schedules: [schedule], + mainSelection: main, + screenTimeService: screenTime, + timedUnblockService: timed, + scheduleService: scheduleService + ) + #expect(!enabledWhileLocked) + #expect(!settings.enableCustomDomains) + #expect(!store.isCustomDomainsEnabled()) + #expect(store.schedules.first?.customDomains.isEmpty == true) + + screenTime.preservePermanentScheduleResult = true + let enabledAfterRecovery = BlockActions.setCustomDomainsEnabled( + true, + settings: settings, + schedules: [schedule], + mainSelection: main, + screenTimeService: screenTime, + timedUnblockService: timed, + scheduleService: scheduleService + ) + #expect(enabledAfterRecovery) + #expect(settings.enableCustomDomains) + #expect(store.isCustomDomainsEnabled()) + #expect(store.schedules.first?.customDomains == ["example.com"]) + } + + @Test func cancelGroupPreservesLegacyMigrationAndPermanentUnblockFailureKeepsTimer() throws { + let base = Date(timeIntervalSinceReferenceDate: 800_000_000) + let store = FakeSharedStore() + let shields = InMemoryShieldStore() + let activity = FakeDeviceActivityCenter() + let screenTime = ScreenTimeService( + defaults: UserDefaults(suiteName: "legacy-cancel-\(UUID().uuidString)") ?? .standard, + shield: shields, + sharedStore: store, + activityCenter: activity, + clock: { base } + ) + let groupID = UUID() + let groupTimer = try TimedUnblockDTO( + id: groupID.uuidString, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: base.addingTimeInterval(900), + activityName: SharedConstants.groupTimedUnblockActivityName(for: groupID), + isGroupUnblock: true, + startDate: base.addingTimeInterval(-60) + ) + store.timedUnblocks = [groupTimer] + let timed = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { base }, + onExpirationAt: { screenTime.reconcile(at: $0) } + ) + #expect(timed.isGroupUnblockActive(groupId: groupID)) + + timed.cancelGroup(groupId: groupID, screenTimeService: screenTime) + + #expect(!timed.isGroupUnblockActive(groupId: groupID)) + #expect(store.timedUnblocks.isEmpty) + #expect(shields.currentShields().applications == TokenFixtures.selection(apps: [1]).applicationTokens) + + let fakeScreenTime = FakeScreenTimeService() + let fakeStore = FakeSharedStore() + let fakeActivity = FakeDeviceActivityCenter() + let fakeTimed = TimedUnblockService( + activityCenter: fakeActivity, + sharedStore: fakeStore, + clock: { base }, + onExpiration: { fakeScreenTime.reconcile() } + ) + try fakeTimed.startMain( + duration: .fifteenMinutes, + selection: TokenFixtures.selection(apps: [1]), + screenTimeService: fakeScreenTime + ) + fakeScreenTime.reconcileResult = false + let settings = Settings() + let grant = try #require( + UnblockGrant( + .all(SelectedApps(selection: TokenFixtures.selection(apps: [1]))), + proof: KeyProof(keyGroupID: nil) + ) + ) + #expect(throws: TimedUnblockStorageError.unavailable) { + try BlockActions.unblock( + grant, + for: .permanent, + settings: settings, + screenTimeService: fakeScreenTime, + timedUnblockService: fakeTimed + ) + } + #expect(fakeTimed.isMainUnblockActive) + #expect(fakeStore.timedUnblocks.count == 1) + + fakeScreenTime.reconcileResult = true + try BlockActions.unblock( + grant, + for: .permanent, + settings: settings, + screenTimeService: fakeScreenTime, + timedUnblockService: fakeTimed + ) + #expect(!fakeTimed.isMainUnblockActive) + #expect(fakeStore.timedUnblocks.isEmpty) + } + + @Test func atomicMainUpdatePreservesPermanentScheduleAndClearsRemovedTargetInOneTransaction() throws { + let h = BlockingHarness(mainApps: [1, 2], customDomains: ["other.com"], startingAt: 8, constrainSchedules: true) + let schedule = try h.addSchedule([1, 2], domains: ["example.com"], from: (9, 0), minutes: 15, block: true, timed: false) + h.wake(at: h.at(9, 5)) + #expect(h.blocked == h.apps(1, 2)) + + h.passTime(to: h.at(10, 0)) + #expect(h.updateMain(apps: [1], domains: ["other.com", "example.com"])) + #expect(h.blocked == h.apps(1)) + #expect(h.blockedDomains.isEmpty) + + let updatedDTO = try #require(h.store.schedules.first { $0.id == schedule.id }) + #expect(try FamilyActivitySelection.fromData(updatedDTO.selectionData) == TokenFixtures.selection(apps: [1])) + #expect(updatedDTO.customDomains == ["example.com"]) + #expect(try #require(updatedDTO.activatedAt) > h.at(9, 15)) + } + + private func makeTickingTimedUnblock( + deadline: Date, + ticks: [Date], + onExpiration: @escaping @MainActor @Sendable () -> Bool + ) throws -> (FakeDeviceActivityCenter, FakeSharedStore, TimedUnblockService) { + let activity = FakeDeviceActivityCenter() + let store = FakeSharedStore() + store.timedUnblocks = try [ + TimedUnblockDTO( + id: TimedUnblockService.mainID, + selectionData: TokenFixtures.selection(apps: [1]).toData(), + endDate: deadline, + activityName: SharedConstants.mainTimedUnblockActivityName, + isGroupUnblock: false, + startDate: deadline.addingTimeInterval(-900) + ) + ] + var tickIndex = 0 + let service = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { + let value = ticks[min(tickIndex, ticks.count - 1)] + tickIndex += 1 + return value + }, + onExpiration: onExpiration + ) + return (activity, store, service) + } +} diff --git a/NormalTests/Services/ScheduleServiceTests.swift b/NormalTests/Services/ScheduleServiceTests.swift index ef34085..3f5849b 100644 --- a/NormalTests/Services/ScheduleServiceTests.swift +++ b/NormalTests/Services/ScheduleServiceTests.swift @@ -64,13 +64,13 @@ struct ScheduleServiceTests { #expect(throws: (any Error).self) { try service.sync(makeSchedule()) } } - @Test func removeStopsMonitoringPersistsRemainingAndReconciles() { + @Test func removeStopsMonitoringPersistsRemainingAndReconciles() throws { let (service, activity, store) = makeService() let screenTime = FakeScreenTimeService() let removed = makeSchedule() let kept = makeSchedule() - service.remove(removed, remaining: [kept], screenTimeService: screenTime) + try service.remove(removed, remaining: [kept], screenTimeService: screenTime) #expect(activity.stopCalls.last == [DeviceActivityName(SharedConstants.scheduleActivityName(for: removed.id))]) #expect(store.schedules.map(\.id) == [kept.id]) diff --git a/NormalTests/Services/TimedUnblockServiceTests.swift b/NormalTests/Services/TimedUnblockServiceTests.swift index e091129..683c1bf 100644 --- a/NormalTests/Services/TimedUnblockServiceTests.swift +++ b/NormalTests/Services/TimedUnblockServiceTests.swift @@ -17,7 +17,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: activity, sharedStore: store, - onExpiration: {} + onExpiration: { true } ) return (service, activity, store) } @@ -352,7 +352,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: activity, sharedStore: store, - onExpiration: {} + onExpiration: { true } ) #expect(service.isMainUnblockActive) @@ -376,7 +376,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: FakeDeviceActivityCenter(), sharedStore: store, - onExpiration: {} + onExpiration: { true } ) #expect(!service.isMainUnblockActive) @@ -429,7 +429,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: FakeDeviceActivityCenter(), sharedStore: store, - onExpiration: {} + onExpiration: { true } ) service.reconcile(screenTimeService: screenTime) @@ -455,7 +455,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: FakeDeviceActivityCenter(), sharedStore: store, - onExpiration: {} + onExpiration: { true } ) service.reconcile(screenTimeService: screenTime) @@ -488,7 +488,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: FakeDeviceActivityCenter(), sharedStore: store, - onExpiration: {} + onExpiration: { true } ) service.reconcile(screenTimeService: screenTime) @@ -514,7 +514,7 @@ struct TimedUnblockServiceTests { let service = TimedUnblockService( activityCenter: FakeDeviceActivityCenter(), sharedStore: store, - onExpiration: {} + onExpiration: { true } ) service.reconcile(screenTimeService: screenTime) @@ -728,22 +728,23 @@ struct TimedUnblockServiceTests { } @Test func editingGroupDomainsDuringUnblockUpdatesReblockPayload() throws { + // Group timed-unblock starts while the group blocks reddit.com. let (service, _, store) = makeService() let screenTime = FakeScreenTimeService() let groupId = UUID() - // Group timed-unblock starts while the group blocks reddit.com. + let selection = TokenFixtures.selection(apps: [1]) try service.startGroup( duration: .fifteenMinutes, groupId: groupId, - selection: FamilyActivitySelection(), + selection: selection, customDomains: ["reddit.com"], screenTimeService: screenTime ) let endDate = service.groupUnblockEndDate(groupId: groupId) // User edits the group mid-unblock and removes the domain. - service.updateGroupSelection(groupId: groupId, selection: FamilyActivitySelection(), customDomains: []) + service.updateGroupSelection(groupId: groupId, selection: selection, customDomains: []) let dto = store.timedUnblocks.first { $0.id == groupId.uuidString } #expect(dto?.customDomains == [], "Reblock payload reflects the removed domain") diff --git a/NormalTests/Services/UnblockTargetTests.swift b/NormalTests/Services/UnblockTargetTests.swift index d03efac..0fc13b3 100644 --- a/NormalTests/Services/UnblockTargetTests.swift +++ b/NormalTests/Services/UnblockTargetTests.swift @@ -11,7 +11,7 @@ struct UnblockTargetTests { private let service: TimedUnblockService init() { - service = TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: {}) + service = TimedUnblockService(activityCenter: activity, sharedStore: store, onExpiration: { true }) } private func grant(_ target: UnblockTarget) throws -> UnblockGrant { diff --git a/NormalTests/Shared/DTOBackCompatTests.swift b/NormalTests/Shared/DTOBackCompatTests.swift index 76d861e..69d6c8e 100644 --- a/NormalTests/Shared/DTOBackCompatTests.swift +++ b/NormalTests/Shared/DTOBackCompatTests.swift @@ -120,6 +120,37 @@ struct DTOBackCompatTests { #expect(decoded.customDomains == [], "Absent key decodes to an empty list") } + private struct LegacyManualLayer: Codable { + struct StoredEntry: Codable { + let token: Token + let entry: ManualEntry + } + + let baseline: ManualEntry + let entries: [StoredEntry] + } + + @Test func manualLayerDecodesLegacyBlobWithoutScheduleEntriesAndRoundTripsPopulatedEntries() throws { + let date = Date(timeIntervalSince1970: 1_000) + let legacy = LegacyManualLayer( + baseline: ManualEntry(isBlocked: false, date: .distantPast), + entries: [.init(token: "reddit.com", entry: ManualEntry(isBlocked: true, date: date))] + ) + let blob = try PropertyListEncoder().encode(legacy) + + let decoded = try PropertyListDecoder().decode(ManualLayer.self, from: blob) + #expect(decoded.entries == ["reddit.com": ManualEntry(isBlocked: true, date: date)]) + #expect(decoded.scheduleEntries.isEmpty) + + var populated = decoded + populated.setScheduleIfNewer(["news.com"], blocked: false, at: date.addingTimeInterval(60)) + let roundTripped = try PropertyListDecoder().decode( + ManualLayer.self, + from: PropertyListEncoder().encode(populated) + ) + #expect(roundTripped == populated) + } + @Test func roundTripPreservesCustomDomains() throws { let dto = ScheduleDTO( id: UUID(), @@ -137,4 +168,21 @@ struct DTOBackCompatTests { let decoded = try PropertyListDecoder().decode(ScheduleDTO.self, from: blob) #expect(decoded.customDomains == ["reddit.com", "news.com"]) } + + @Test func manualBlockStateDecodesLegacyBlobWithoutAppDeletionOwnershipAndFailsClosed() throws { + let date = Date(timeIntervalSince1970: 1_000) + var legacy = ManualBlockState() + legacy.setAppDeletionBlocked(true, ownedByBlockAll: false, at: date) + let data = try PropertyListEncoder().encode(legacy) + var raw = try #require(try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any]) + raw.removeValue(forKey: "appDeletionOwnedByBlockAll") + let stripped = try PropertyListSerialization.data(fromPropertyList: raw, format: .binary, options: 0) + + var decoded = try PropertyListDecoder().decode(ManualBlockState.self, from: stripped) + #expect(decoded.appDeletionBlocked == ManualEntry(isBlocked: true, date: date)) + #expect(decoded.appDeletionOwnedByBlockAll == nil) + + decoded.clearBlockAllOwnedAppDeletion(at: date.addingTimeInterval(60)) + #expect(decoded.appDeletionBlocked == ManualEntry(isBlocked: true, date: date)) + } } diff --git a/NormalTests/TestSupport/BlockingHarness.swift b/NormalTests/TestSupport/BlockingHarness.swift index 5519faa..9ba8a71 100644 --- a/NormalTests/TestSupport/BlockingHarness.swift +++ b/NormalTests/TestSupport/BlockingHarness.swift @@ -27,9 +27,16 @@ final class BlockingHarness { let usageLimits: UsageLimitService let settings = Settings() let main: SelectedApps + let constrainSchedules: Bool private(set) var schedules: [BlockSchedule] = [] - init(mainApps: [UInt8] = [1, 2, 3], customDomains: [String] = [], startingAt hour: Int = 8) { + init( + mainApps: [UInt8] = [1, 2, 3], + customDomains: [String] = [], + startingAt hour: Int = 8, + constrainSchedules: Bool = false + ) { + self.constrainSchedules = constrainSchedules let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: .now)! day = Calendar.current.startOfDay(for: tomorrow) let clock = Clock(Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: day)!) @@ -47,7 +54,7 @@ final class BlockingHarness { activityCenter: activity, sharedStore: store, clock: { clock.now }, - onExpiration: {} + onExpiration: { true } ) usageLimits = UsageLimitService( activityCenter: activity, @@ -98,10 +105,14 @@ final class BlockingHarness { screenTime.reconcile() } + private var activeConstraint: SelectionConstraint? { + constrainSchedules ? main.effectiveConstraint(customDomainsEnabled: settings.enableCustomDomains) : nil + } + func openApp(at date: Date) { clock.now = date timedUnblock.reconcile(screenTimeService: screenTime) - scheduleService.registerAll(schedules, screenTimeService: screenTime) + scheduleService.registerAll(schedules, screenTimeService: screenTime, constrainedTo: activeConstraint) } func blockAll() { @@ -191,16 +202,72 @@ final class BlockingHarness { customDomains: domains ) schedules.append(schedule) - try scheduleService.syncAndPersist(schedule, allSchedules: schedules, screenTimeService: screenTime) + try save(schedule) return schedule } + func save(_ schedule: BlockSchedule) throws { + try scheduleService.syncAndPersist( + schedule, + allSchedules: schedules, + screenTimeService: screenTime, + constrainedTo: activeConstraint + ) + } + + @discardableResult + func updateMain(apps: [UInt8]? = nil, domains: [String]? = nil) -> Bool { + let oldSelection = main.selection + let oldDomains = main.customDomains + let newSelection = apps.map { TokenFixtures.selection(apps: $0) } ?? oldSelection + let newDomains = domains ?? oldDomains + guard + BlockActions.updateMainSelection( + from: oldSelection, + oldCustomDomains: oldDomains, + to: newSelection, + newCustomDomains: newDomains, + schedules: schedules, + settings: settings, + screenTimeService: screenTime, + timedUnblockService: timedUnblock, + scheduleService: scheduleService + ) + else { return false } + main.selection = newSelection + main.customDomains = newDomains + return true + } + + func setCustomDomainsEnabled(_ enabled: Bool) { + BlockActions.setCustomDomainsEnabled( + enabled, + settings: settings, + schedules: schedules, + mainSelection: main, + screenTimeService: screenTime, + timedUnblockService: timedUnblock, + scheduleService: scheduleService + ) + } + func toggle(_ schedule: BlockSchedule) throws { - try scheduleService.toggleEnabled(schedule, allSchedules: schedules, screenTimeService: screenTime) + try scheduleService.toggleEnabled( + schedule, + allSchedules: schedules, + screenTimeService: screenTime, + constrainedTo: activeConstraint + ) } - func delete(_ schedule: BlockSchedule) { - schedules.removeAll { $0.id == schedule.id } - scheduleService.remove(schedule, remaining: schedules, screenTimeService: screenTime) + func delete(_ schedule: BlockSchedule) throws { + let remaining = schedules.filter { $0.id != schedule.id } + try scheduleService.remove( + schedule, + remaining: remaining, + screenTimeService: screenTime, + constrainedTo: activeConstraint + ) + schedules = remaining } } diff --git a/NormalTests/TestSupport/FakeScreenTimeService.swift b/NormalTests/TestSupport/FakeScreenTimeService.swift index 4100c0a..43653cb 100644 --- a/NormalTests/TestSupport/FakeScreenTimeService.swift +++ b/NormalTests/TestSupport/FakeScreenTimeService.swift @@ -24,6 +24,10 @@ final class FakeScreenTimeService: ScreenTimeProviding { var unblockSelection: FamilyActivitySelection? var unblockCustomDomains: [String]? var reconcileCallCount = 0 + var reconcileDates: [Date?] = [] + var reconcileResult = true + var reconcileResults: [Bool] = [] + var preservePermanentScheduleResult = true var enablePreventAppDeleteCalled = false var disablePreventAppDeleteCalled = false var notifyUpdateCallCount = 0 @@ -82,12 +86,14 @@ final class FakeScreenTimeService: ScreenTimeProviding { } } - func unblockAll(blockAllPreventsAppDelete: Bool) { + @discardableResult + func unblockAll(blockAllPreventsAppDelete: Bool) -> Bool { unblockAllCalled = true unblockAllPreventsAppDelete = blockAllPreventsAppDelete if blockAllPreventsAppDelete { disablePreventAppDeleteCalled = true } + return reconcileResult } func removeAllRestrictions() { @@ -101,32 +107,80 @@ final class FakeScreenTimeService: ScreenTimeProviding { blockCustomDomains = customDomains } - func unblock(selection: FamilyActivitySelection, customDomains: [String] = []) { + @discardableResult + func unblock(selection: FamilyActivitySelection, customDomains: [String] = []) -> Bool { unblockCalled = true unblockSelection = selection unblockCustomDomains = customDomains + return reconcileResult } + @discardableResult func updateMainList( from _: FamilyActivitySelection, customDomains _: [String], to _: FamilyActivitySelection, customDomains _: [String], - addedBlockedAsOf _: Date - ) {} + addedBlockedAsOf _: Date, + unconfirmedRemovalBefore _: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at _: Date? + ) -> Bool { + guard preservingPermanentSchedules.isEmpty || preservePermanentScheduleResult else { + return false + } + return reconcileResult + } - func reconcile() { + @discardableResult + func unblockRemovedFromMain( + from _: FamilyActivitySelection, + customDomains _: [String], + to _: FamilyActivitySelection, + customDomains _: [String], + clearAppDeletion _: Bool, + appDeletionCutoff _: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at _: Date? + ) -> Bool { + guard preservingPermanentSchedules.isEmpty || preservePermanentScheduleResult else { + return false + } + return reconcileResult + } + + @discardableResult + func clearCustomDomains( + clearAppDeletion _: Bool, + appDeletionCutoff _: Date?, + preservingPermanentSchedules: [ScheduleDTO], + at _: Date? + ) -> Bool { + guard preservingPermanentSchedules.isEmpty || preservePermanentScheduleResult else { + return false + } + return reconcileResult + } + + @discardableResult + func preservePermanentSchedule(_: ScheduleDTO, at _: Date) -> Bool { + preservePermanentScheduleResult + } + + @discardableResult + func reconcile(preservingPermanentSchedules: [ScheduleDTO], at date: Date?) -> Bool { reconcileCallCount += 1 + reconcileDates.append(date) + guard preservingPermanentSchedules.isEmpty || preservePermanentScheduleResult else { + return false + } + return reconcileResults.isEmpty ? reconcileResult : reconcileResults.removeFirst() } func activeShieldCount() -> Int { stubActiveShieldCount } - func hasActiveCustomDomainFilter() -> Bool { - false - } - func blockStatus(selection _: FamilyActivitySelection?, customDomains _: [String]? = nil) -> BlockStatus { stubBlockStatus } diff --git a/NormalTests/TestSupport/StatefulScreenTimeSpy.swift b/NormalTests/TestSupport/StatefulScreenTimeSpy.swift index 88d8693..e5fab73 100644 --- a/NormalTests/TestSupport/StatefulScreenTimeSpy.swift +++ b/NormalTests/TestSupport/StatefulScreenTimeSpy.swift @@ -62,12 +62,14 @@ final class StatefulScreenTimeSpy: ScreenTimeProviding { checkInvariant() } - func unblockAll(blockAllPreventsAppDelete: Bool) { + @discardableResult + func unblockAll(blockAllPreventsAppDelete: Bool) -> Bool { shieldActive = false if blockAllPreventsAppDelete { appDeleteDisabled = false } checkInvariant() + return true } func removeAllRestrictions() { @@ -81,30 +83,71 @@ final class StatefulScreenTimeSpy: ScreenTimeProviding { checkInvariant() } - func unblock(selection _: FamilyActivitySelection, customDomains _: [String] = []) { + @discardableResult + func unblock(selection _: FamilyActivitySelection, customDomains _: [String] = []) -> Bool { checkInvariant() + return true } + @discardableResult func updateMainList( from _: FamilyActivitySelection, customDomains _: [String], to _: FamilyActivitySelection, customDomains _: [String], - addedBlockedAsOf _: Date - ) {} + addedBlockedAsOf _: Date, + unconfirmedRemovalBefore _: Date?, + preservingPermanentSchedules _: [ScheduleDTO], + at _: Date? + ) -> Bool { + true + } + + @discardableResult + func unblockRemovedFromMain( + from _: FamilyActivitySelection, + customDomains _: [String], + to _: FamilyActivitySelection, + customDomains _: [String], + clearAppDeletion: Bool, + appDeletionCutoff _: Date?, + preservingPermanentSchedules _: [ScheduleDTO], + at _: Date? + ) -> Bool { + if clearAppDeletion { + appDeleteDisabled = false + } + return true + } - func reconcile() { + @discardableResult + func clearCustomDomains( + clearAppDeletion: Bool, + appDeletionCutoff _: Date?, + preservingPermanentSchedules _: [ScheduleDTO], + at _: Date? + ) -> Bool { + if clearAppDeletion { + appDeleteDisabled = false + } + return true + } + + @discardableResult + func preservePermanentSchedule(_: ScheduleDTO, at _: Date) -> Bool { + true + } + + @discardableResult + func reconcile(preservingPermanentSchedules _: [ScheduleDTO], at _: Date?) -> Bool { checkInvariant() + return true } func activeShieldCount() -> Int { shieldActive ? 1 : 0 } - func hasActiveCustomDomainFilter() -> Bool { - false - } - func blockStatus(selection _: FamilyActivitySelection?, customDomains _: [String]? = nil) -> BlockStatus { shieldActive ? .all : .none } diff --git a/Shared/DailyLimitMonitoring.swift b/Shared/DailyLimitMonitoring.swift index dea1c7c..2df42c2 100644 --- a/Shared/DailyLimitMonitoring.swift +++ b/Shared/DailyLimitMonitoring.swift @@ -35,6 +35,14 @@ extension DeviceActivityCenter: DeviceActivityProviding { } extension DeviceActivitySchedule { + static var heartbeat: DeviceActivitySchedule { + DeviceActivitySchedule( + intervalStart: DateComponents(minute: 0, second: 0), + intervalEnd: DateComponents(minute: 30, second: 0), + repeats: true + ) + } + func hasSameWindow(as other: DeviceActivitySchedule) -> Bool { repeats == other.repeats && Self.time(intervalStart) == Self.time(other.intervalStart) @@ -46,6 +54,56 @@ extension DeviceActivitySchedule { } } +extension DeviceActivityProviding { + func syncHeartbeat(sharedStore: any SharedStoreProviding, at date: Date) { + let name = DeviceActivityName(SharedConstants.reblockHeartbeatActivityName) + let monitored = monitoredActivityNames + let dailyLimitsNeeded = + monitored.contains(SharedConstants.usageLimitsActivityName) + || DailyLimitMonitoring.eventSpecs( + for: sharedStore.loadUsageLimits(), + period: sharedStore.usagePeriod, + on: date + ).contains(where: \.isArmable) + let needed = + sharedStore.loadSchedules().contains { $0.isEffectivelyEnabled(monitoredActivities: monitored) } + || dailyLimitsNeeded + || !sharedStore.loadTimedUnblocks().isEmpty + let heartbeat = DeviceActivitySchedule.heartbeat + let current = registeredSchedule(for: name) + if needed { + guard current?.hasSameWindow(as: heartbeat) != true else { return } + try? startMonitoring(name, during: heartbeat, events: [:]) + } else if current != nil || monitored.contains(name.rawValue) { + stopMonitoring([name]) + } + } +} + +extension ShieldReconciler { + @discardableResult + static func reconcileMonitor( + sharedStore: some SharedStoreProviding, + shields: some ShieldApplying, + activityCenter: any DeviceActivityProviding, + at date: Date = .now, + lockURL: URL? = nil + ) -> ShieldPlan? { + guard + let plan = reconcile( + sharedStore: sharedStore, + shields: shields, + monitoredActivities: activityCenter.monitoredActivityNames, + at: date, + lockURL: lockURL, + pruneExpiredTimedUnblocks: true + ) + else { return nil } + activityCenter.syncHeartbeat(sharedStore: sharedStore, at: date) + return plan + } +} + enum DailyLimitMonitoring { private static let maxReconcilePasses = 3 diff --git a/Shared/SharedDTO.swift b/Shared/SharedDTO.swift index 2e70cf1..125ef53 100644 --- a/Shared/SharedDTO.swift +++ b/Shared/SharedDTO.swift @@ -1,7 +1,7 @@ import FamilyControls import Foundation -nonisolated struct TimedUnblockDTO: Codable, Sendable, Identifiable { +nonisolated struct TimedUnblockDTO: Codable, Equatable, Sendable, Identifiable { let id: String let selectionData: Data let endDate: Date @@ -103,6 +103,16 @@ nonisolated extension ScheduleDTO { calendar: calendar ) } + + func latestStart(atOrBefore date: Date, calendar: Calendar = .current) -> Date? { + ScheduleWindow.latestStart( + atOrBefore: date, + startHour: startHour, + startMinute: startMinute, + weekdays: weekdays, + calendar: calendar + ) + } } nonisolated extension FamilyActivitySelection { @@ -164,6 +174,25 @@ nonisolated enum ScheduleWindow { return nil } + static func latestStart( + atOrBefore date: Date, + startHour: Int, + startMinute: Int, + weekdays: Set, + calendar: Calendar = .current + ) -> Date? { + let startOfToday = calendar.startOfDay(for: date) + for dayOffset in 0...7 { + guard let day = calendar.date(byAdding: .day, value: -dayOffset, to: startOfToday), + let start = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: day) + else { continue } + if start <= date, weekdays.contains(calendar.component(.weekday, from: start)) { + return start + } + } + return nil + } + private static func end( of day: Date, startHour: Int, diff --git a/Shared/SharedStoreProviding.swift b/Shared/SharedStoreProviding.swift index 6e18234..5c2f88e 100644 --- a/Shared/SharedStoreProviding.swift +++ b/Shared/SharedStoreProviding.swift @@ -86,6 +86,20 @@ extension SharedStoreProviding { return limits.filter { states[$0.id] == .reached } } + @discardableResult + func removeTimedUnblocks(matching expired: [TimedUnblockDTO]) -> Bool { + guard !expired.isEmpty else { return false } + let expiredByID = Dictionary(expired.map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest }) + let current = loadTimedUnblocks() + let kept = current.filter { stored in + guard let candidate = expiredByID[stored.id] else { return true } + return stored != candidate + } + guard kept.count != current.count else { return false } + saveTimedUnblocks(kept) + return true + } + private func mutateUsageDayState(_ transform: (UsageDayStateDTO) -> UsageDayStateDTO) { let current = loadUsageDayState() let updated = transform(current) diff --git a/Shared/ShieldReconciler.swift b/Shared/ShieldReconciler.swift index 6880a94..2643618 100644 --- a/Shared/ShieldReconciler.swift +++ b/Shared/ShieldReconciler.swift @@ -16,12 +16,10 @@ nonisolated enum SharedFileLock { static func withLock(at url: URL? = nil, _ body: () throws -> T) rethrows -> T? { guard let path = (url ?? defaultURL)?.path(percentEncoded: false) else { return try body() } let descriptor = open(path, O_CREAT | O_RDWR, 0o644) - guard descriptor >= 0 else { - return errno == EPERM || errno == EACCES ? nil : try body() - } + guard descriptor >= 0 else { return nil } defer { close(descriptor) } while flock(descriptor, LOCK_EX) != 0 { - guard errno == EINTR else { return try body() } + guard errno == EINTR else { return nil } } defer { flock(descriptor, LOCK_UN) } return try body() @@ -36,6 +34,7 @@ nonisolated enum ShieldReconciler { monitoredActivities: Set, at date: Date = .now, lockURL: URL? = nil, + pruneExpiredTimedUnblocks: Bool = false, update: (inout ManualBlockState) -> Void = { _ in } ) -> ShieldPlan? { SharedFileLock.withLock(at: lockURL) { @@ -72,6 +71,10 @@ nonisolated enum ShieldReconciler { if plan.differs(from: current) { shields.apply(plan) } + if pruneExpiredTimedUnblocks { + let expired = timedUnblocks.filter { $0.endDate <= date } + sharedStore.removeTimedUnblocks(matching: expired) + } return plan } } diff --git a/Shared/ShieldResolver.swift b/Shared/ShieldResolver.swift index 505c0f4..db4a91b 100644 --- a/Shared/ShieldResolver.swift +++ b/Shared/ShieldResolver.swift @@ -5,6 +5,10 @@ import ManagedSettings nonisolated struct ManualEntry: Codable, Equatable { let isBlocked: Bool let date: Date + + func supersedes(_ other: ManualEntry) -> Bool { + date > other.date || (date == other.date && isBlocked) + } } nonisolated struct ManualLayer: Codable, Equatable { @@ -16,10 +20,12 @@ nonisolated struct ManualLayer: Codable, Equatable { private enum CodingKeys: String, CodingKey { case baseline case entries + case scheduleEntries } private(set) var baseline = ManualEntry(isBlocked: false, date: .distantPast) private(set) var entries: [Token: ManualEntry] = [:] + private(set) var scheduleEntries: [Token: ManualEntry] = [:] init() {} @@ -28,12 +34,23 @@ nonisolated struct ManualLayer: Codable, Equatable { baseline = try container.decode(ManualEntry.self, forKey: .baseline) let stored = try container.decode([StoredEntry].self, forKey: .entries) entries = Dictionary(stored.map { ($0.token, $0.entry) }, uniquingKeysWith: { _, latest in latest }) + let storedSchedule = try container.decodeIfPresent([StoredEntry].self, forKey: .scheduleEntries) ?? [] + scheduleEntries = Dictionary( + storedSchedule.map { ($0.token, $0.entry) }, + uniquingKeysWith: { _, latest in latest } + ) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(baseline, forKey: .baseline) try container.encode(entries.map { StoredEntry(token: $0.key, entry: $0.value) }, forKey: .entries) + if !scheduleEntries.isEmpty { + try container.encode( + scheduleEntries.map { StoredEntry(token: $0.key, entry: $0.value) }, + forKey: .scheduleEntries + ) + } } var blockedTokens: Set { @@ -45,16 +62,65 @@ nonisolated struct ManualLayer: Codable, Equatable { } mutating func set(_ tokens: some Sequence, blocked: Bool, at date: Date) { + let next = ManualEntry(isBlocked: blocked, date: date) + for token in tokens { + entries[token] = next + if let preserved = scheduleEntries[token], next.supersedes(preserved) { + scheduleEntries.removeValue(forKey: token) + } + } + } + + mutating func setScheduleIfNewer(_ tokens: some Sequence, blocked: Bool, at date: Date) { + let next = ManualEntry(isBlocked: blocked, date: date) for token in tokens { - entries[token] = ManualEntry(isBlocked: blocked, date: date) + if let current = scheduleEntries[token] { + if next.supersedes(current) { + scheduleEntries[token] = next + } + } else { + scheduleEntries[token] = next + } } } mutating func reset(blocking tokens: some Sequence, at date: Date) { baseline = ManualEntry(isBlocked: false, date: date) entries = [:] + scheduleEntries = [:] set(tokens, blocked: true, at: date) } + + mutating func clearBlocked() { + if baseline.isBlocked { + baseline = ManualEntry(isBlocked: false, date: .distantPast) + } + if baseline.date == .distantPast { + entries = entries.filter { !$0.value.isBlocked } + } else { + for (token, entry) in entries where entry.isBlocked { + entries[token] = ManualEntry(isBlocked: false, date: .distantPast) + } + } + scheduleEntries = scheduleEntries.filter { !$0.value.isBlocked } + } + + mutating func clearBlocked(_ tokens: some Sequence, before cutoff: Date? = nil) { + for token in tokens { + if let entry = entries[token], entry.isBlocked, cutoff.map({ entry.date < $0 }) ?? true { + if baseline.date == .distantPast, !baseline.isBlocked { + entries.removeValue(forKey: token) + } else { + entries[token] = ManualEntry(isBlocked: false, date: .distantPast) + } + } else if entries[token] == nil, baseline.isBlocked, cutoff.map({ baseline.date < $0 }) ?? true { + entries[token] = ManualEntry(isBlocked: false, date: .distantPast) + } + if let preserved = scheduleEntries[token], preserved.isBlocked, cutoff.map({ preserved.date < $0 }) ?? true { + scheduleEntries.removeValue(forKey: token) + } + } + } } nonisolated struct ManualBlockState: Codable, Equatable { @@ -63,6 +129,7 @@ nonisolated struct ManualBlockState: Codable, Equatable { var categories = ManualLayer() var customDomains = ManualLayer() var appDeletionBlocked: ManualEntry? + var appDeletionOwnedByBlockAll: Bool? var migratedAt: Date? mutating func blockAll(_ selection: FamilyActivitySelection, customDomains domains: [String], at date: Date) { @@ -72,8 +139,24 @@ nonisolated struct ManualBlockState: Codable, Equatable { customDomains.reset(blocking: domains.compactMap(DomainNormalizer.normalize), at: date) } - mutating func setAppDeletionBlocked(_ blocked: Bool, at date: Date) { + mutating func setAppDeletionBlocked(_ blocked: Bool, ownedByBlockAll: Bool = false, at date: Date) { + if blocked, ownedByBlockAll, appDeletionBlocked?.isBlocked == true, appDeletionOwnedByBlockAll != true { + return + } appDeletionBlocked = ManualEntry(isBlocked: blocked, date: date) + appDeletionOwnedByBlockAll = blocked ? ownedByBlockAll : nil + } + + mutating func clearBlockAllOwnedAppDeletion(at date: Date, ifNotNewerThan cutoff: Date? = nil) { + guard let entry = appDeletionBlocked, + entry.isBlocked, + appDeletionOwnedByBlockAll == true + else { return } + if let cutoff, entry.date > cutoff { + return + } + appDeletionBlocked = ManualEntry(isBlocked: false, date: date) + appDeletionOwnedByBlockAll = nil } mutating func unblockAll(at date: Date) { @@ -88,6 +171,13 @@ nonisolated struct ManualBlockState: Codable, Equatable { set(selection, customDomains: domains, blocked: false, at: date) } + mutating func clearBlocked(_ selection: FamilyActivitySelection, customDomains domains: [String]) { + applications.clearBlocked(selection.applicationTokens) + webDomains.clearBlocked(selection.webDomainTokens) + categories.clearBlocked(selection.categoryTokens) + customDomains.clearBlocked(domains.compactMap(DomainNormalizer.normalize)) + } + private mutating func set( _ selection: FamilyActivitySelection, customDomains domains: [String], @@ -213,9 +303,13 @@ nonisolated enum ShieldResolver { !$0.isGroupUnblock && $0.blockAllPreventsAppDelete == true } if let deny = current.denyAppRemoval { - state.setAppDeletionBlocked(deny || mainUnblockLiftsAppDeletion, at: .distantPast) + state.setAppDeletionBlocked( + deny || mainUnblockLiftsAppDeletion, + ownedByBlockAll: mainUnblockLiftsAppDeletion && !deny, + at: .distantPast + ) } else if mainUnblockLiftsAppDeletion { - state.setAppDeletionBlocked(true, at: .distantPast) + state.setAppDeletionBlocked(true, ownedByBlockAll: true, at: .distantPast) } return state } @@ -233,10 +327,41 @@ nonisolated enum ShieldResolver { return entry.date > startDate(of: liftingUnblock) ? entry.isBlocked : false } - private static func startDate(of unblock: TimedUnblockDTO) -> Date { + static func startDate(of unblock: TimedUnblockDTO) -> Date { unblock.startDate ?? unblock.endDate.addingTimeInterval(-maxTimedUnblockDuration) } + static func materializePermanentSchedule( + _ schedule: ScheduleDTO, + into manual: inout ManualBlockState, + at date: Date, + calendar: Calendar = .current + ) { + guard !schedule.isTimed, + let activeClaim = claim(for: schedule, migratedAt: manual.migratedAt, at: date, calendar: calendar) + else { return } + manual.applications.setScheduleIfNewer( + activeClaim.selection.applicationTokens, + blocked: activeClaim.isBlocked, + at: activeClaim.date + ) + manual.webDomains.setScheduleIfNewer( + activeClaim.selection.webDomainTokens, + blocked: activeClaim.isBlocked, + at: activeClaim.date + ) + manual.categories.setScheduleIfNewer( + activeClaim.selection.categoryTokens, + blocked: activeClaim.isBlocked, + at: activeClaim.date + ) + manual.customDomains.setScheduleIfNewer( + activeClaim.customDomains, + blocked: activeClaim.isBlocked, + at: activeClaim.date + ) + } + private static func claim( for schedule: ScheduleDTO, migratedAt: Date?, @@ -249,7 +374,9 @@ nonisolated enum ShieldResolver { : schedule.latestStart(atOrBefore: date, calendar: calendar) let activation = schedule.activatedAt ?? (schedule.isTimed ? nil : migratedAt) ?? .distantPast guard let start, - schedule.isTimed || start.addingTimeInterval(TimeInterval(schedule.durationMinutes * 60)) > activation, + schedule.isTimed + || (activation <= date + && start.addingTimeInterval(TimeInterval(schedule.durationMinutes * 60)) > activation), let selection = try? FamilyActivitySelection.fromData(schedule.selectionData) else { return nil } return Claim( @@ -282,6 +409,7 @@ nonisolated enum ShieldResolver { _ tokens: KeyPath> ) -> Set { var candidates = Set(manual.entries.keys) + candidates.formUnion(manual.scheduleEntries.keys) for claim in claims { candidates.formUnion(claim[keyPath: tokens]) } @@ -289,27 +417,16 @@ nonisolated enum ShieldResolver { let covering = claims.filter { $0.coversEverything || $0[keyPath: tokens].contains(token) } let timedUnblocks = covering.filter(\.isTimedUnblock) var winner = manual.entry(for: token) + if timedUnblocks.isEmpty, let preserved = manual.scheduleEntries[token], preserved.supersedes(winner) { + winner = preserved + } for claim in timedUnblocks.isEmpty ? covering : timedUnblocks { - if claim.date > winner.date || (claim.date == winner.date && claim.isBlocked) { - winner = ManualEntry(isBlocked: claim.isBlocked, date: claim.date) + let candidate = ManualEntry(isBlocked: claim.isBlocked, date: claim.date) + if candidate.supersedes(winner) { + winner = candidate } } return winner.isBlocked } } } - -nonisolated extension ScheduleDTO { - func latestStart(atOrBefore date: Date, calendar: Calendar = .current) -> Date? { - let startOfToday = calendar.startOfDay(for: date) - for dayOffset in 0...7 { - guard let day = calendar.date(byAdding: .day, value: -dayOffset, to: startOfToday), - let start = calendar.date(bySettingHour: startHour, minute: startMinute, second: 0, of: day) - else { continue } - if start <= date, weekdays.contains(calendar.component(.weekday, from: start)) { - return start - } - } - return nil - } -}