diff --git a/app/UzzyCore/Alerts.swift b/app/UzzyCore/Alerts.swift index 480f7e0..2d15546 100644 --- a/app/UzzyCore/Alerts.swift +++ b/app/UzzyCore/Alerts.swift @@ -99,6 +99,37 @@ struct AlertQuota: Sendable, Equatable { var isLimited: Bool { usedPercent >= 100 } + + /// The name of the model, group or bag a named limit covers, or `nil` + /// for a limit on the whole account, such as the 5-hour or weekly one. + var scope: String? { + if case .limit(let name, _) = period { name } else { nil } + } + + /// Whether `other`, another quota of the same reading, still stops this + /// one from being used: it is at 100% and covers this quota's scope. + /// A limit on the whole account covers every scope; a named limit only + /// its own name. + func isBlocked(by other: AlertQuota) -> Bool { + other.period != period && other.isLimited && (other.scope == nil || other.scope == scope) + } + + /// The earliest reset, among the limited `quotas`, after which a quota + /// can be used again: a limited quota whose reset comes before another + /// limited quota blocking it would still be blocked then. `nil` when no + /// such reset is known. + static func earliestUsableReset(of quotas: [AlertQuota]) -> Date? { + let limited = quotas.filter(\.isLimited) + return limited.compactMap { quota -> Date? in + guard let reset = quota.resetDate else { return nil } + let outlasted = limited.contains { other in + guard quota.isBlocked(by: other) else { return false } + guard let otherReset = other.resetDate else { return true } + return otherReset.timeIntervalSince(reset) > QuotaReading.resetAgreement + } + return outlasted ? nil : reset + }.min() + } } /// Decides which alerts a fresh reading fires, and remembers which ones @@ -156,7 +187,11 @@ struct AlertTracker { } ?? false // A reset that passed without a new reading confirms nothing. if window.awaitsReset, quota.reset != .pendingConfirmation, !quota.isLimited || advanced { - alerts.append(.limitReset(provider, period: quota.period)) + // Another limit at 100% still stops the provider from being + // used, so its reset is the one that fires. + if !quotas.contains(where: quota.isBlocked(by:)) { + alerts.append(.limitReset(provider, period: quota.period)) + } window.awaitsReset = false } if advanced { diff --git a/app/UzzyCore/UsageCore.swift b/app/UzzyCore/UsageCore.swift index 7e337ab..4363593 100644 --- a/app/UzzyCore/UsageCore.swift +++ b/app/UzzyCore/UsageCore.swift @@ -277,11 +277,13 @@ public final class UsageCore { } /// A limited quota with a known reset is queried once right after it, - /// instead of at the next tick, so its reset is confirmed promptly. Only - /// while background refresh and reset alerts are on. + /// instead of at the next tick, so its reset is confirmed promptly. A + /// reset another limit at 100% outlasts confirms nothing worth telling, + /// so it is not queried early. Only while background refresh and reset + /// alerts are on. private func scheduleResetVerification(for provider: Provider, quotas: [AlertQuota]) { guard backgroundRefresh.isOn, alerts.limitReset, - let resetAt = quotas.filter(\.isLimited).compactMap(\.resetDate).min() + let resetAt = AlertQuota.earliestUsableReset(of: quotas) else { setResetVerification(nil, for: provider) return diff --git a/app/UzzyCoreTests/UsageAlertTests.swift b/app/UzzyCoreTests/UsageAlertTests.swift index fadacd7..d032750 100644 --- a/app/UzzyCoreTests/UsageAlertTests.swift +++ b/app/UzzyCoreTests/UsageAlertTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -import UzzyCore +@testable import UzzyCore /// Keeps the alerts a core fires. @MainActor @@ -377,4 +377,185 @@ struct UsageAlertTests { clock.now().addingTimeInterval(interval), ]) } + + // MARK: - Overlapping limits + + /// A weekly reset three days after the first reading, long after the + /// 5-hour one. + let weeklyResetAt = Samples.readingMoment.addingTimeInterval(3 * 86_400) + let nextWeeklyResetAt = Samples.readingMoment.addingTimeInterval(10 * 86_400) + + /// Codex answers with a 5-hour window and a weekly one. + func answer(fiveHours: Double, fiveHoursReset: Date, weekly: Double, weeklyReset: Date) async { + let windows = #""" + {"primary_window": {"used_percent": \#(fiveHours), "limit_window_seconds": 18000, "reset_at": \#(fiveHoursReset.timeIntervalSince1970)}, + "secondary_window": {"used_percent": \#(weekly), "limit_window_seconds": 604800, "reset_at": \#(weeklyReset.timeIntervalSince1970)}} + """# + await transport.answer(with: .codex(rateLimit: windows), for: .codex) + } + + /// Reaches both the 5-hour and the weekly limit on the first tick, 15 + /// minutes in, with the 5-hour reset at 20 minutes. + func reachBothLimits() async { + await answer(fiveHours: 50, fiveHoursReset: resetAt, weekly: 90, weeklyReset: weeklyResetAt) + core.panelOpened() + await core.queriesFinished() + core.panelClosed() + + await answer(fiveHours: 100, fiveHoursReset: resetAt, weekly: 100, weeklyReset: weeklyResetAt) + clock.advance(by: interval) + await core.queriesFinished() + #expect(recorder.alerts == [ + .limitReached(.codex, period: .fiveHours, reset: resetAt), + .limitReached(.codex, period: .weekly, reset: weeklyResetAt), + ]) + } + + /// The provider is still unusable until the weekly limit resets, so only + /// that reset fires. + @Test func aResetWhileTheWeeklyLimitStaysReachedFiresNothing() async { + await reachBothLimits() + + await answer(fiveHours: 3, fiveHoursReset: nextResetAt, weekly: 100, weeklyReset: weeklyResetAt) + clock.advance(by: interval) + await core.queriesFinished() + #expect(recorder.alerts.count == 2) + + await answer(fiveHours: 5, fiveHoursReset: nextResetAt, weekly: 1, weeklyReset: nextWeeklyResetAt) + clock.advance(by: interval) + await core.queriesFinished() + #expect(recorder.alerts.count == 3) + #expect(recorder.alerts.last == .limitReset(.codex, period: .weekly)) + } + + @Test func bothLimitsScheduleOneQueryRightAfterTheWeeklyReset() async { + await reachBothLimits() + + #expect(clock.scheduledDeadlines == [ + clock.now().addingTimeInterval(interval), + weeklyResetAt.addingTimeInterval(UsageCore.resetVerificationDelay), + ]) + } +} + +/// Which reset fires when several limits of one provider overlap: only the +/// one after which the provider can be used again. +@Suite +struct AlertTrackerOverlapTests { + let fiveHoursReset = Samples.readingMoment.addingTimeInterval(2 * 3_600) + let nextFiveHoursReset = Samples.readingMoment.addingTimeInterval(7 * 3_600) + let weeklyReset = Samples.readingMoment.addingTimeInterval(3 * 86_400) + + func quota(_ period: QuotaPeriod, used: Double, reset: Date?) -> AlertQuota { + AlertQuota(period: period, usedPercent: used, reset: reset.map(Reset.at) ?? .unknown) + } + + /// The alerts of a second reading, `after`, of the same account as the + /// baseline reading, `before`. + func alerts(_ provider: Provider, before: [AlertQuota], after: [AlertQuota]) -> [UsageAlert] { + var tracker = AlertTracker(threshold: AlertSettings.defaultThreshold) + _ = tracker.observe(provider, accountID: "account", quotas: before) + return tracker.observe(provider, accountID: "account", quotas: after) + } + + @Test func aGroupsWeeklyLimitBlocksItsOwnGroupsReset() { + let fiveHours = QuotaPeriod.limit("Gemini", .fiveHours) + let weekly = QuotaPeriod.limit("Gemini", .weekly) + + let fired = alerts( + .antigravity, + before: [quota(fiveHours, used: 100, reset: fiveHoursReset), quota(weekly, used: 100, reset: weeklyReset)], + after: [quota(fiveHours, used: 0, reset: nextFiveHoursReset), quota(weekly, used: 100, reset: weeklyReset)] + ) + + #expect(fired == []) + } + + @Test func anotherGroupsWeeklyLimitDoesNotBlockTheReset() { + let fiveHours = QuotaPeriod.limit("Gemini", .fiveHours) + let weekly = QuotaPeriod.limit("Gemini", .weekly) + let otherWeekly = QuotaPeriod.limit("Claude and GPT", .weekly) + + let fired = alerts( + .antigravity, + before: [ + quota(fiveHours, used: 100, reset: fiveHoursReset), + quota(weekly, used: 40, reset: weeklyReset), + quota(otherWeekly, used: 100, reset: weeklyReset), + ], + after: [ + quota(fiveHours, used: 0, reset: nextFiveHoursReset), + quota(weekly, used: 40, reset: weeklyReset), + quota(otherWeekly, used: 100, reset: weeklyReset), + ] + ) + + #expect(fired == [.limitReset(.antigravity, period: fiveHours)]) + } + + @Test func aNamedLimitDoesNotBlockTheAccountsReset() { + let named = QuotaPeriod.limit("GPT-5.3-Codex-Spark", .weekly) + + let fired = alerts( + .codex, + before: [quota(.fiveHours, used: 100, reset: fiveHoursReset), quota(named, used: 100, reset: weeklyReset)], + after: [quota(.fiveHours, used: 2, reset: nextFiveHoursReset), quota(named, used: 100, reset: weeklyReset)] + ) + + #expect(fired == [.limitReset(.codex, period: .fiveHours)]) + } + + @Test func theAccountsWeeklyLimitBlocksANamedLimitsReset() { + let named = QuotaPeriod.limit("GPT-5.3-Codex-Spark", .fiveHours) + + let fired = alerts( + .codex, + before: [quota(named, used: 100, reset: fiveHoursReset), quota(.weekly, used: 100, reset: weeklyReset)], + after: [quota(named, used: 2, reset: nextFiveHoursReset), quota(.weekly, used: 100, reset: weeklyReset)] + ) + + #expect(fired == []) + } + + /// A new window already at 100% confirms the reset, but a blocking limit + /// still holds it back; the new window's limit reached fires as usual. + @Test func aNewWindowAlreadyAtTheLimitIsBlockedToo() { + let fired = alerts( + .claude, + before: [quota(.fiveHours, used: 100, reset: fiveHoursReset), quota(.weekly, used: 100, reset: weeklyReset)], + after: [quota(.fiveHours, used: 100, reset: nextFiveHoursReset), quota(.weekly, used: 100, reset: weeklyReset)] + ) + + #expect(fired == [.limitReached(.claude, period: .fiveHours, reset: nextFiveHoursReset)]) + } + + @Test func theEarliestUsableResetSkipsAResetALaterLimitOutlasts() { + let quotas = [quota(.fiveHours, used: 100, reset: fiveHoursReset), quota(.weekly, used: 100, reset: weeklyReset)] + + #expect(AlertQuota.earliestUsableReset(of: quotas) == weeklyReset) + } + + @Test func aBlockingLimitWithoutAKnownResetLeavesNoUsableReset() { + let quotas = [quota(.fiveHours, used: 100, reset: fiveHoursReset), quota(.weekly, used: 100, reset: nil)] + + #expect(AlertQuota.earliestUsableReset(of: quotas) == nil) + } + + @Test func limitsResettingTogetherShareTheirReset() { + let quotas = [ + quota(.fiveHours, used: 100, reset: weeklyReset), + quota(.weekly, used: 100, reset: weeklyReset.addingTimeInterval(30)), + ] + + #expect(AlertQuota.earliestUsableReset(of: quotas) == weeklyReset) + } + + @Test func anotherGroupsLimitLeavesTheEarlierResetUsable() { + let quotas = [ + quota(.limit("Gemini", .fiveHours), used: 100, reset: fiveHoursReset), + quota(.limit("Claude and GPT", .weekly), used: 100, reset: weeklyReset), + ] + + #expect(AlertQuota.earliestUsableReset(of: quotas) == fiveHoursReset) + } }