From e34940a8753ffe36330f72b48a433909aa72637b Mon Sep 17 00:00:00 2001 From: ykisana Date: Wed, 18 Nov 2026 18:53:44 -0600 Subject: [PATCH] fix: re-arm daily limits iOS drops and show when they can't start - Register daily limits again when iOS no longer lists their activity, the way schedules already do. An unchanged set used to return early, so the limits stayed off until the next day's first open or an edit. - When iOS refuses to start them (its 20 schedules-and-timers cap or another error), say so on Max Daily Limits and Status instead of only logging it. - Debug builds log when limits register, and whether the monitor kept or dropped each threshold and why. --- Normal/Resources/Localizable.xcstrings | 8 ++ Normal/Services/UsageLimitService.swift | 41 +++++++- Normal/Views/Home/StatusDetailView.swift | 15 ++- Normal/Views/Usage/UsageView.swift | 8 +- NormalMonitor/NormalMonitor.swift | 11 ++- .../Services/UsageLimitServiceTests.swift | 95 +++++++++++++++++++ 6 files changed, 170 insertions(+), 8 deletions(-) diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index c16fd60..413d253 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -610,6 +610,14 @@ "comment" : "A section header for custom website domain blocking.", "isCommentAutoGenerated" : true }, + "Daily limits are off: iOS couldn't start them. Normal tries again each time you open it." : { + "comment" : "Shown on Max Daily Limits and Status when iOS refused to start monitoring daily limits for a reason other than the activity limit.", + "isCommentAutoGenerated" : true + }, + "Daily limits are off: iOS only tracks 20 schedules and timers at once. Turn off a schedule and they'll start the next time you open Normal." : { + "comment" : "Shown on Max Daily Limits and Status when iOS refused to start monitoring daily limits because 20 schedules and timers are already registered.", + "isCommentAutoGenerated" : true + }, "Default" : { "comment" : "A label displayed next to a timed unblock duration that is set as the user's default.", "isCommentAutoGenerated" : true diff --git a/Normal/Services/UsageLimitService.swift b/Normal/Services/UsageLimitService.swift index 0af7169..c96f39f 100644 --- a/Normal/Services/UsageLimitService.swift +++ b/Normal/Services/UsageLimitService.swift @@ -18,6 +18,8 @@ final class UsageLimitService { private(set) var resetAnchor: Date? + private(set) var registrationFailure: UsageLimitRegistrationFailure? + /// Minutes of usage before a limit is hit that `eventWillReachThresholdWarning` fires. static let warningMinutes = SharedConstants.usageLimitWarningMinutes @@ -59,14 +61,19 @@ final class UsageLimitService { let specs = Self.eventSpecs(for: dtos, period: config.period, on: date).filter(\.isArmable) let fingerprint = Self.fingerprint(for: dtos, period: config.period, on: date) - guard fingerprint != sharedStore.loadUsageRegistration() else { return } - let activityName = DeviceActivityName(SharedConstants.usageLimitsActivityName) + let isMonitored = activityCenter.monitoredActivityNames.contains(activityName.rawValue) + if fingerprint == sharedStore.loadUsageRegistration() { + guard !specs.isEmpty, !isMonitored else { return } + CallbackLog.record("app usage limits: iOS no longer lists the activity, registering again") + } + activityCenter.stopMonitoring([activityName]) sharedStore.saveUsageRegistration(nil) guard !specs.isEmpty else { sharedStore.saveUsageRegistration(fingerprint) + registrationFailure = nil notifyUpdate() return } @@ -81,10 +88,14 @@ final class UsageLimitService { events: specs.reduce(into: [:]) { $0[$1.name] = $1.event } ) sharedStore.saveUsageRegistration(fingerprint) + registrationFailure = nil + CallbackLog.record("app usage limits: registered \(specs.map { "\($0.minutes) min" }.joined(separator: ", "))") } catch { // Every limit shares one activity, so a throw here disables all of // them. Leave the fingerprint cleared so the next launch retries. + registrationFailure = UsageLimitRegistrationFailure(error) logger.error("Usage limit monitoring failed: \(error.localizedDescription, privacy: .public)") + CallbackLog.record("app usage limits: startMonitoring failed: \(error)") } notifyUpdate() } @@ -219,3 +230,29 @@ final class UsageLimitService { ) } } + +enum UsageLimitRegistrationFailure: Equatable { + case tooManyActivities + case failed + + init(_ error: any Error) { + switch error { + case DeviceActivityCenter.MonitoringError.excessiveActivities: + self = .tooManyActivities + default: + self = .failed + } + } + + var message: String { + switch self { + case .tooManyActivities: + String( + localized: + "Daily limits are off: iOS only tracks 20 schedules and timers at once. Turn off a schedule and they'll start the next time you open Normal." + ) + case .failed: + String(localized: "Daily limits are off: iOS couldn't start them. Normal tries again each time you open it.") + } + } +} diff --git a/Normal/Views/Home/StatusDetailView.swift b/Normal/Views/Home/StatusDetailView.swift index 0350ee2..4bb328c 100644 --- a/Normal/Views/Home/StatusDetailView.swift +++ b/Normal/Views/Home/StatusDetailView.swift @@ -60,20 +60,25 @@ struct StatusDetailView: View { private var limitsSection: some View { let states = usageLimitService.states(for: limits) + let failure = usageLimitService.registrationFailure let isPaused = usageLimitService.isDayOverridden() let reset = usageLimitService.nextReset().formatted(date: .omitted, time: .shortened) return Section { ForEach(limits) { limit in - limitRow(limit, state: states[limit.id] ?? .under, isPaused: isPaused) + limitRow(limit, state: states[limit.id] ?? .under, isOff: failure != nil, isPaused: isPaused) } } header: { Text("Max Daily Limits") } footer: { - Text(isPaused ? "Paused by emergency unblock until \(reset)." : "Resets at \(reset).") + if let failure { + Text(failure.message) + } else { + Text(isPaused ? "Paused by emergency unblock until \(reset)." : "Resets at \(reset).") + } } } - private func limitRow(_ limit: UsageLimit, state: UsageLimitState, isPaused: Bool) -> some View { + private func limitRow(_ limit: UsageLimit, state: UsageLimitState, isOff: Bool, isPaused: Bool) -> some View { HStack { VStack(alignment: .leading, spacing: DS.Spacing.xs) { SelectionIconsView(tokens: limit.selection.allTokens, limit: 5) @@ -82,7 +87,9 @@ struct StatusDetailView: View { .foregroundStyle(.secondary) } Spacer() - if isPaused { + if isOff { + StatusBadge(title: "Off", systemImage: "exclamationmark.triangle.fill", tint: .red) + } else if isPaused { StatusBadge(title: "Paused", systemImage: "pause.circle.fill", tint: .secondary) } else { StatusBadge(title: state.label, systemImage: state.icon, tint: state.color) diff --git a/Normal/Views/Usage/UsageView.swift b/Normal/Views/Usage/UsageView.swift index 890b68e..c772998 100644 --- a/Normal/Views/Usage/UsageView.swift +++ b/Normal/Views/Usage/UsageView.swift @@ -43,7 +43,13 @@ struct UsageView: View { @ViewBuilder private var noticeSection: some View { - if !limits.isEmpty, usageLimitService.isDayOverridden() { + if !limits.isEmpty, let failure = usageLimitService.registrationFailure { + Section { + MessageView(text: Text(failure.message), color: .red) + .standaloneListRow() + .accessibilityIdentifier("usage.registrationFailure") + } + } else if !limits.isEmpty, usageLimitService.isDayOverridden() { let reset = usageLimitService.nextReset().formatted(date: .omitted, time: .shortened) Section { MessageView(text: Text("Paused by emergency unblock until \(reset)."), color: .orange) diff --git a/NormalMonitor/NormalMonitor.swift b/NormalMonitor/NormalMonitor.swift index bf0a819..9d4157c 100644 --- a/NormalMonitor/NormalMonitor.swift +++ b/NormalMonitor/NormalMonitor.swift @@ -30,6 +30,7 @@ final class NormalMonitor: DeviceActivityMonitor { if let limit = credibleUsageLimit(eventName: event.rawValue, minutes: \.minutesPerDay) { sharedStore.recordUsageState(.reached, for: limit.id) limitStore.syncDailyLimits(from: sharedStore) + CallbackLog.record("monitor usage limit \(limit.minutesPerDay) min: reached") } reconcile("eventDidReachThreshold", activity: event.rawValue) } @@ -43,6 +44,7 @@ final class NormalMonitor: DeviceActivityMonitor { minutes: { $0.minutesPerDay - SharedConstants.usageLimitWarningMinutes } ) { sharedStore.recordUsageState(.warning, for: limit.id) + CallbackLog.record("monitor usage limit \(limit.minutesPerDay) min: warning") } reconcile("eventWillReachThresholdWarning", activity: event.rawValue) } @@ -76,9 +78,16 @@ final class NormalMonitor: DeviceActivityMonitor { if let start = sharedStore.loadUsageLimitsIntervalStart(), Date.now.timeIntervalSince(start) < Self.thresholdGraceSeconds { + CallbackLog.record( + "monitor usage limit \(limit.minutesPerDay) min: dropped, " + + "\(Date.now.timeIntervalSince(start).formatted(.number.precision(.fractionLength(1)))) s after the interval started" + ) + return nil + } + guard sharedStore.usagePeriod.couldHaveMetered(minutes: minutes(limit), by: .now) else { + CallbackLog.record("monitor usage limit \(limit.minutesPerDay) min: dropped, too soon after the reset") return nil } - guard sharedStore.usagePeriod.couldHaveMetered(minutes: minutes(limit), by: .now) else { return nil } return limit } diff --git a/NormalTests/Services/UsageLimitServiceTests.swift b/NormalTests/Services/UsageLimitServiceTests.swift index 8d57535..82595e2 100644 --- a/NormalTests/Services/UsageLimitServiceTests.swift +++ b/NormalTests/Services/UsageLimitServiceTests.swift @@ -205,6 +205,101 @@ struct UsageLimitServiceTests { #expect(h.center.stopCalls.count == stopsAfterFirst) } + @Test func reRegisteringAnUnchangedArmedSetDoesNotTouchMonitoring() { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60) + + h.service.registerAll([limit], config: config, on: day) + h.service.registerAll([limit], config: config, on: day) + + #expect(h.center.startCalls.count == 1) + #expect(h.center.stopCalls.count == 1) + } + + @Test func anUnchangedSetIsRegisteredAgainWhenIOSNoLongerListsIt() { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60) + h.service.registerAll([limit], config: config, on: day) + h.center.stopMonitoring([usageActivity]) + + h.service.registerAll([limit], config: config, on: day) + + #expect(h.center.startCalls.count == 2) + #expect(h.center.monitoredActivityNames.contains(usageActivity.rawValue)) + } + + @Test func tooManyActivitiesIsReportedUntilRegistrationSucceeds() { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60) + h.center.startError = DeviceActivityCenter.MonitoringError.excessiveActivities + + h.service.registerAll([limit], config: config, on: day) + #expect(h.service.registrationFailure == .tooManyActivities) + + h.center.startError = nil + h.service.registerAll([limit], config: config, on: day) + #expect(h.service.registrationFailure == nil) + #expect(h.center.monitoredActivityNames.contains(usageActivity.rawValue)) + } + + @Test func aLimitAddedWhenSchedulesFillEverySlotIsReportedUntilOneIsFreed() { + let center = FakeDeviceActivityCenter() + center.activityLimit = 20 + let store = FakeSharedStore() + let schedules = ScheduleService(activityCenter: center, sharedStore: store, clock: { day }) + let limits = UsageLimitService( + activityCenter: center, + sharedStore: store, + ledger: InMemoryUsageLimitLedger(date: nil), + limitShield: InMemoryDailyLimitShield() + ) + let nineteen = (0..<19).map { _ in + BlockSchedule( + name: "Work", + selection: FamilyActivitySelection(), + startHour: 9, startMinute: 0, + durationMinutes: 60, + weekdays: [2, 3, 4, 5, 6], + shouldBlock: true, + isTimed: true, + isEnabled: true + ) + } + schedules.registerAll(nineteen, screenTimeService: FakeScreenTimeService()) + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 30, createdAt: day) + + limits.registerAll([limit], config: config, on: day) + #expect(!center.monitoredActivityNames.contains(usageActivity.rawValue)) + #expect(limits.registrationFailure == .tooManyActivities) + + nineteen[0].isEnabled = false + schedules.registerAll(nineteen, screenTimeService: FakeScreenTimeService()) + limits.registerAll([limit], config: config, on: day) + #expect(center.monitoredActivityNames.contains(usageActivity.rawValue)) + #expect(limits.registrationFailure == nil) + } + + @Test func otherRegistrationErrorsAreReportedAsFailed() { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60) + h.center.startError = DeviceActivityCenter.MonitoringError.unauthorized + + h.service.registerAll([limit], config: config, on: day) + + #expect(h.service.registrationFailure == .failed) + } + + @Test func removingEveryLimitClearsARegistrationFailure() { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60) + h.center.startError = DeviceActivityCenter.MonitoringError.excessiveActivities + h.service.registerAll([limit], config: config, on: day) + + h.service.registerAll([], config: config, on: day) + + #expect(h.service.registrationFailure == nil) + } + @Test func changingALimitReRegisters() { let h = makeService() let limit = UsageLimit(minutesPerDay: 60)