From e4cc0feeccec90dc3ceeb70e84992814c1019f87 Mon Sep 17 00:00:00 2001 From: ykisana Date: Wed, 18 Nov 2026 20:19:41 -0600 Subject: [PATCH] fix: count a new daily limit from when it's set on its first day A limit added after its apps were already used counted the whole day. If they were already past it, the threshold fired as the limit was registered, the monitor dropped it as a likely false fire, and the limit never blocked that day. New limits now count only usage after they're registered on the day they're created (includesPastActivity: false). From the next reset they count the whole day as before, so re-registering can't refund time. Limits saved before this change keep counting the whole day. --- Normal/Models/UsageLimit.swift | 4 +- Normal/Resources/Localizable.xcstrings | 14 ++++- Normal/Services/UsageLimitService.swift | 20 +++++-- Normal/Views/Usage/UsageLimitEditor.swift | 4 ++ Normal/Views/Usage/UsageLimitsGuideView.swift | 2 +- NormalTests/Models/StoreUpgradeTests.swift | 1 + .../Services/UsageLimitServiceTests.swift | 55 +++++++++++++++++-- NormalTests/Shared/UsageDTOTests.swift | 11 ++++ Shared/UsageDTO.swift | 6 ++ 9 files changed, 104 insertions(+), 13 deletions(-) diff --git a/Normal/Models/UsageLimit.swift b/Normal/Models/UsageLimit.swift index df81386..d6e26c6 100644 --- a/Normal/Models/UsageLimit.swift +++ b/Normal/Models/UsageLimit.swift @@ -15,6 +15,7 @@ final class UsageLimit: Identifiable { var minutesPerDay: Int var sortIndex: Int = 0 var lockAnchor: Date? + var createdAt: Date? /// Shortest allowance we offer. `DeviceActivity` thresholds below a few /// minutes fire unreliably, so the picker never goes lower. @@ -32,6 +33,7 @@ final class UsageLimit: Identifiable { self.minutesPerDay = minutesPerDay self.sortIndex = sortIndex lockAnchor = createdAt + self.createdAt = createdAt } func lockState(now: Date = .now) -> UsageLimitLockState { @@ -54,6 +56,6 @@ final class UsageLimit: Identifiable { /// without the app running. func toDTO() -> UsageLimitDTO? { guard let data = try? selection.toData() else { return nil } - return UsageLimitDTO(id: id, selectionData: data, minutesPerDay: minutesPerDay) + return UsageLimitDTO(id: id, selectionData: data, minutesPerDay: minutesPerDay, createdAt: createdAt) } } diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index 237279e..c16fd60 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -294,6 +294,18 @@ } } }, + "After %@ of combined use, these stay blocked until %@, even if unblocked with a key. Today, only time after you save counts." : { + "comment" : "Explains a new daily limit, which only counts usage after it's saved on its first day. The arguments are the time per day and the reset time.", + "isCommentAutoGenerated" : true, + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "After %1$@ of combined use, these stay blocked until %2$@, even if unblocked with a key. Today, only time after you save counts." + } + } + } + }, "After saving, you have 10 minutes to adjust this limit. Then raising or deleting it is allowed once every 7 days." : { }, @@ -516,7 +528,7 @@ "comment" : "A section header for categories in the app picker.", "isCommentAutoGenerated" : true }, - "Choose how much time they get each day. Time you've already used today counts." : { + "Choose how much time they get each day. On the day you add a limit, only time after that counts." : { "comment" : "How it works section of the usage limits guide.", "isCommentAutoGenerated" : true }, diff --git a/Normal/Services/UsageLimitService.swift b/Normal/Services/UsageLimitService.swift index 2f1e587..0af7169 100644 --- a/Normal/Services/UsageLimitService.swift +++ b/Normal/Services/UsageLimitService.swift @@ -57,7 +57,7 @@ final class UsageLimitService { sharedStore.saveUsageLimitConfig(config) syncShields(on: date) - let specs = Self.eventSpecs(for: dtos).filter(\.isArmable) + 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 } @@ -98,6 +98,7 @@ final class UsageLimitService { let eventName: String let minutes: Int let selection: FamilyActivitySelection + let includesPastActivity: Bool var name: DeviceActivityEvent.Name { DeviceActivityEvent.Name(eventName) @@ -115,9 +116,10 @@ final class UsageLimitService { categories: selection.categoryTokens, webDomains: selection.webDomainTokens, threshold: DateComponents(minute: minutes), - // Accounts for usage already spent earlier in the interval, so - // re-registering mid-day cannot refund an allowance. - includesPastActivity: true + // A limit counts from when it's created on its first day. After + // that it counts the whole interval, so re-registering mid-day + // cannot refund an allowance. + includesPastActivity: includesPastActivity ) } } @@ -125,7 +127,7 @@ final class UsageLimitService { /// Drops only limits whose selection cannot be decoded; whether a spec is /// worth arming is `EventSpec.isArmable`, kept separate so the naming and /// threshold rules stay checkable without real `ManagedSettings` tokens. - static func eventSpecs(for dtos: [UsageLimitDTO]) -> [EventSpec] { + static func eventSpecs(for dtos: [UsageLimitDTO], period: UsagePeriod, on date: Date) -> [EventSpec] { dtos.compactMap { dto in guard let selection = try? FamilyActivitySelection.fromData(dto.selectionData) else { return nil } @@ -133,7 +135,8 @@ final class UsageLimitService { id: dto.id, eventName: SharedConstants.usageLimitEventName(for: dto.id), minutes: dto.minutesPerDay, - selection: selection + selection: selection, + includesPastActivity: period.countsPastActivity(createdAt: dto.createdAt, on: date) ) } } @@ -159,6 +162,11 @@ final class UsageLimitService { return sharedStore.usageStates(for: limits.map(\.id), on: date) } + func countsTimeUsedEarlierToday(by limit: UsageLimit?, on date: Date = .now) -> Bool { + guard let limit else { return false } + return sharedStore.usagePeriod.countsPastActivity(createdAt: limit.createdAt, on: date) + } + func nextReset(after date: Date = .now) -> Date { _ = lastUpdate return sharedStore.usagePeriod.nextReset(after: date) diff --git a/Normal/Views/Usage/UsageLimitEditor.swift b/Normal/Views/Usage/UsageLimitEditor.swift index b2c2876..6b25133 100644 --- a/Normal/Views/Usage/UsageLimitEditor.swift +++ b/Normal/Views/Usage/UsageLimitEditor.swift @@ -209,6 +209,10 @@ struct UsageLimitEditor: View { private var explanation: LocalizedStringKey { let reset = usageLimitService.nextReset().formatted(date: .omitted, time: .shortened) + guard usageLimitService.countsTimeUsedEarlierToday(by: existing) else { + return + "After \(DurationFormat.spelled(minutes: minutes)) of combined use, these stay blocked until \(reset), even if unblocked with a key. Today, only time after you save counts." + } return "After \(DurationFormat.spelled(minutes: minutes)) of combined use, these stay blocked until \(reset), even if unblocked with a key. Time already used today counts; if you're already past it, the limit starts at the next reset." } diff --git a/Normal/Views/Usage/UsageLimitsGuideView.swift b/Normal/Views/Usage/UsageLimitsGuideView.swift index 7ab1475..0eca773 100644 --- a/Normal/Views/Usage/UsageLimitsGuideView.swift +++ b/Normal/Views/Usage/UsageLimitsGuideView.swift @@ -20,7 +20,7 @@ struct UsageLimitsGuideView: View { Section("How It Works") { FeatureRow( systemImage: "square.grid.2x2.fill", text: "Pick apps, websites, or categories. You can group multiple apps in a single limit.") - FeatureRow(systemImage: "timer", text: "Choose how much time they get each day. Time you've already used today counts.") + FeatureRow(systemImage: "timer", text: "Choose how much time they get each day. On the day you add a limit, only time after that counts.") FeatureRow( systemImage: "lock.fill", text: "When the time runs out, they stay blocked until the reset. Only Emergency Unblock lifts them early.", tint: .red) diff --git a/NormalTests/Models/StoreUpgradeTests.swift b/NormalTests/Models/StoreUpgradeTests.swift index 6657286..d12203d 100644 --- a/NormalTests/Models/StoreUpgradeTests.swift +++ b/NormalTests/Models/StoreUpgradeTests.swift @@ -435,5 +435,6 @@ struct StoreUpgradeTests { #expect(limit.selection == TokenFixtures.selection(apps: [4])) #expect(limit.minutesPerDay == 45) #expect(limit.lockAnchor == Self.updated) + #expect(limit.createdAt == nil) } } diff --git a/NormalTests/Services/UsageLimitServiceTests.swift b/NormalTests/Services/UsageLimitServiceTests.swift index 0caa40e..8d57535 100644 --- a/NormalTests/Services/UsageLimitServiceTests.swift +++ b/NormalTests/Services/UsageLimitServiceTests.swift @@ -54,7 +54,7 @@ struct UsageLimitServiceTests { let first = try dto(minutes: 60) let second = try dto(minutes: 20) - let specs = UsageLimitService.eventSpecs(for: [first, second]) + let specs = UsageLimitService.eventSpecs(for: [first, second], period: config.period, on: day) #expect(specs.count == 2) #expect(specs.map(\.minutes).sorted() == [20, 60]) @@ -63,7 +63,7 @@ struct UsageLimitServiceTests { @Test func eventNamesRoundTripBackToTheirLimit() throws { let limit = try dto(minutes: 60) - let spec = try #require(UsageLimitService.eventSpecs(for: [limit]).first) + let spec = try #require(UsageLimitService.eventSpecs(for: [limit], period: config.period, on: day).first) #expect(spec.eventName == SharedConstants.usageLimitEventName(for: limit.id)) #expect(SharedConstants.usageLimitID(fromEventName: spec.eventName) == limit.id) @@ -73,7 +73,7 @@ struct UsageLimitServiceTests { /// armed — otherwise the threshold never fires and the limit looks active /// while doing nothing. @Test func aLimitWithAnEmptySelectionIsNotArmable() throws { - let spec = try #require(try UsageLimitService.eventSpecs(for: [dto(minutes: 60)]).first) + let spec = try #require(try UsageLimitService.eventSpecs(for: [dto(minutes: 60)], period: config.period, on: day).first) #expect(spec.isArmable == false) } @@ -85,7 +85,54 @@ struct UsageLimitServiceTests { minutesPerDay: 60 ) - #expect(UsageLimitService.eventSpecs(for: [broken]).isEmpty) + #expect(UsageLimitService.eventSpecs(for: [broken], period: config.period, on: day).isEmpty) + } + + @Test func aLimitCreatedTodayCountsOnlyTimeAfterItIsRegistered() throws { + var limit = try dto(minutes: 60) + limit.createdAt = day + + let spec = try #require(UsageLimitService.eventSpecs(for: [limit], period: config.period, on: day).first) + + #expect(spec.includesPastActivity == false) + #expect(spec.event.includesPastActivity == false) + } + + @Test func aLimitCreatedBeforeTodaysResetCountsTheWholeDay() throws { + var limit = try dto(minutes: 60) + limit.createdAt = day - .days(1) + + let spec = try #require(UsageLimitService.eventSpecs(for: [limit], period: config.period, on: day).first) + + #expect(spec.includesPastActivity) + #expect(spec.event.includesPastActivity) + } + + @Test func aLimitSavedBeforeCreationDatesExistedCountsTheWholeDay() throws { + let spec = try #require(try UsageLimitService.eventSpecs(for: [dto(minutes: 60)], period: config.period, on: day).first) + + #expect(spec.includesPastActivity) + } + + @Test func aNewLimitCountsTheWholeDayFromTheNextDaysRegistration() throws { + let h = makeService() + let limit = UsageLimit(selection: TokenFixtures.selection(apps: [1]), minutesPerDay: 60, createdAt: day) + + h.service.registerAll([limit], config: config, on: day) + h.service.registerAll([limit], config: config, on: day + .days(1)) + + let flags = h.center.startCalls.compactMap { $0.events.values.first?.includesPastActivity } + #expect(flags == [false, true]) + } + + @Test func theEditorSaysWhetherTimeUsedEarlierTodayCounts() { + let h = makeService() + let createdToday = UsageLimit(minutesPerDay: 60, createdAt: day) + let createdYesterday = UsageLimit(minutesPerDay: 60, createdAt: day - .days(1)) + + #expect(h.service.countsTimeUsedEarlierToday(by: nil, on: day) == false) + #expect(h.service.countsTimeUsedEarlierToday(by: createdToday, on: day) == false) + #expect(h.service.countsTimeUsedEarlierToday(by: createdYesterday, on: day)) } // MARK: - The daily schedule diff --git a/NormalTests/Shared/UsageDTOTests.swift b/NormalTests/Shared/UsageDTOTests.swift index 6ed4efe..14d3ffb 100644 --- a/NormalTests/Shared/UsageDTOTests.swift +++ b/NormalTests/Shared/UsageDTOTests.swift @@ -301,6 +301,17 @@ struct UsageDTOTests { #expect(nyPeriod.couldHaveMetered(minutes: 5, by: date("2026-03-14T15:00:00-04:00"))) } + @Test func onlyLimitsCreatedBeforeTheCurrentResetCountPastActivity() { + let period = newYorkPeriod(resetAt: 4) + let now = date("2026-03-14T12:00:00-04:00") + + #expect(period.countsPastActivity(createdAt: nil, on: now)) + #expect(period.countsPastActivity(createdAt: date("2026-03-14T03:59:00-04:00"), on: now)) + #expect(period.countsPastActivity(createdAt: date("2026-03-14T04:00:00-04:00"), on: now) == false) + #expect(period.countsPastActivity(createdAt: date("2026-03-14T11:00:00-04:00"), on: now) == false) + #expect(period.countsPastActivity(createdAt: date("2026-03-14T11:00:00-04:00"), on: date("2026-03-15T04:00:00-04:00"))) + } + @Test func plausibilityIsMeasuredFromTheTopOfTheResetHour() { let period = newYorkPeriod(resetAt: 4, 30) diff --git a/Shared/UsageDTO.swift b/Shared/UsageDTO.swift index 2efce21..7fac876 100644 --- a/Shared/UsageDTO.swift +++ b/Shared/UsageDTO.swift @@ -34,6 +34,7 @@ nonisolated struct UsageLimitDTO: Codable, Sendable, Identifiable { let id: UUID let selectionData: Data let minutesPerDay: Int + var createdAt: Date? = nil } nonisolated struct UsageLimitConfig: Codable, Sendable, Equatable { @@ -164,6 +165,11 @@ nonisolated struct UsagePeriod: Equatable, Sendable { return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) } + func countsPastActivity(createdAt: Date?, on date: Date) -> Bool { + guard let createdAt else { return true } + return createdAt < start(containing: date) + } + func couldHaveMetered(minutes: Int, by date: Date) -> Bool { let start = start(containing: date) let hourStart = calendar.dateInterval(of: .hour, for: start)?.start ?? start