Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Normal/Models/UsageLimit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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)
}
}
14 changes: 13 additions & 1 deletion Normal/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -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." : {

},
Expand Down Expand Up @@ -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
},
Expand Down
20 changes: 14 additions & 6 deletions Normal/Services/UsageLimitService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down Expand Up @@ -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)
Expand All @@ -115,25 +116,27 @@ 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
)
}
}

/// 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 }
return EventSpec(
id: dto.id,
eventName: SharedConstants.usageLimitEventName(for: dto.id),
minutes: dto.minutesPerDay,
selection: selection
selection: selection,
includesPastActivity: period.countsPastActivity(createdAt: dto.createdAt, on: date)
)
}
}
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions Normal/Views/Usage/UsageLimitEditor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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."
}
Expand Down
2 changes: 1 addition & 1 deletion Normal/Views/Usage/UsageLimitsGuideView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions NormalTests/Models/StoreUpgradeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
55 changes: 51 additions & 4 deletions NormalTests/Services/UsageLimitServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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)
Expand All @@ -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)
}
Expand All @@ -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
Expand Down
11 changes: 11 additions & 0 deletions NormalTests/Shared/UsageDTOTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
6 changes: 6 additions & 0 deletions Shared/UsageDTO.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down