diff --git a/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaReset.swift b/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaReset.swift new file mode 100644 index 00000000..6c27f84c --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaReset.swift @@ -0,0 +1,346 @@ +import Foundation + +/// User preference for early-quota-reset notifications. Absent key is true, +/// matching `UpdateNotificationPreference`: existing installs get the alert +/// without visiting Settings first. +enum EarlyQuotaResetPreference { + static let defaultsKey = "codeburn.quota.earlyResetNotificationsEnabled" + + static func isEnabled(defaults: UserDefaults = .standard) -> Bool { + defaults.object(forKey: defaultsKey) as? Bool ?? true + } +} + +/// One reading of a fixed-cycle quota window, in the snapshot store's units. +struct EarlyQuotaResetReading: Codable, Equatable, Sendable { + /// Used share of the window, 0...100 — the `SubscriptionSnapshot` scale, + /// not `QuotaSummary.Window.percent`'s 0...1 fraction. + let percent: Double + let resetsAt: Date + let observedAt: Date + + /// A reading this build can reason about. Anything else is "no opinion". + var isWellFormed: Bool { + percent.isFinite && percent >= 0 && percent <= 100 + && resetsAt.timeIntervalSince1970.isFinite + && observedAt.timeIntervalSince1970.isFinite + } +} + +/// A vendor reset a quota window before its scheduled time. +struct EarlyQuotaResetEvent: Codable, Equatable, Sendable { + enum Signal: String, Codable, Sendable { + /// The advertised reset time jumped to a new cycle before the old one ended. + case resetMovedForward + /// Usage fell to near-empty while the advertised reset time stood still. + case usageDropped + } + + let providerID: String + let providerName: String + let windowKey: String + /// Lower-case noun phrase for copy, e.g. "weekly limit". + let windowName: String + let signal: Signal + /// When the cycle that was cut short had been scheduled to reset. + let scheduledResetAt: Date + let detectedAt: Date + let percentBefore: Double + let percentAfter: Double + + /// How long before its schedule the reset landed, measured to the fetch + /// that saw it. The true reset happened at or before `detectedAt`, so this + /// can understate the lead by one refresh interval, never overstate it. + var earlyBySeconds: TimeInterval { scheduledResetAt.timeIntervalSince(detectedAt) } + + /// Coalescing key: one event per provider window per cut-short cycle, + /// whichever signal saw it first. + var identity: String { + "\(providerID)|\(windowKey)|\(Int(scheduledResetAt.timeIntervalSince1970.rounded()))" + } + + var notificationTitle: String { "\(providerName) quota reset early" } + + var notificationBody: String { + let remaining = Int((100 - percentAfter).rounded()) + return "\(providerName)'s \(windowName) reset " + + "\(EarlyQuotaResetFormat.lead(seconds: earlyBySeconds)) early. " + + "You're back to \(remaining)%." + } + + /// The Capacity Dock band, e.g. "Weekly limit reset 18h early". + var noticeText: String { + "\(EarlyQuotaResetFormat.capitalizedFirst(windowName)) reset " + + "\(EarlyQuotaResetFormat.lead(seconds: earlyBySeconds)) early" + } + + var noticeHelpText: String { + let remaining = Int((100 - percentAfter).rounded()) + return "\(providerName) reset this \(windowName) " + + "\(EarlyQuotaResetFormat.lead(seconds: earlyBySeconds)) before its scheduled time. " + + "\(remaining)% of it was available when CodeBurn noticed." + } +} + +/// Decides whether two consecutive readings of the same window are an early +/// reset. Pure: every clock value comes from the readings themselves. +/// +/// The detector assumes a fixed-cycle window with a validated duration (Claude's +/// 5-hour and 7-day limits). A rolling window's reset time creeps forward on +/// every fetch, which is exactly what signal 1 must not read as a new cycle, so +/// callers must not pass rolling windows and a window without a duration gets +/// no opinion. +enum EarlyQuotaResetDetector { + /// Anything within this of a boundary is clock or timestamp noise, not a + /// reset: vendors jitter `resets_at` by seconds between fetches, and local + /// and vendor clocks disagree by a little. + static let skewTolerance: TimeInterval = 10 * 60 + + /// A new cycle's reset time can sit up to this much earlier than a full + /// window after our previous observation, because vendors round window + /// starts. Wider than `skewTolerance` so rounding never hides a real reset. + static let cycleAnchorTolerance: TimeInterval = 60 * 60 + + /// Signal 2 threshold. Inside one cycle, reported usage only rises; it moves + /// down by rounding noise of a point or two. A goodwill reset zeroes the + /// window, so we require both a fall of at least 40 points and a landing at + /// or under 10% — enough slack for a refresh interval of real use after the + /// reset, and far outside rounding noise. A smaller drop that does not land + /// near empty is not "you have your capacity back". + static let minimumPercentDrop: Double = 40 + static let maximumPercentAfterDrop: Double = 10 + + struct Context: Equatable, Sendable { + let providerID: String + let providerName: String + let windowKey: String + let windowName: String + /// Validated cycle length. Nil means unknown, and unknown means silent. + let windowSeconds: Int? + /// Plan label at the previous successful fetch, and now. A different plan + /// changes capacity legitimately, so it is never an early reset. + let previousPlanLabel: String? + let currentPlanLabel: String? + /// False when the provider is coming back from a disconnect, a terminal + /// failure or a fresh bootstrap: the previous reading predates the gap and + /// anything could have happened since. + let baselineIsTrusted: Bool + } + + static func detect( + previous: EarlyQuotaResetReading?, + current: EarlyQuotaResetReading?, + context: Context + ) -> EarlyQuotaResetEvent? { + // First observation or a window that just appeared: no baseline. + // A window that disappeared: nothing to announce. + guard let previous, let current else { return nil } + guard previous.isWellFormed, current.isWellFormed else { return nil } + guard context.baselineIsTrusted else { return nil } + guard context.previousPlanLabel == context.currentPlanLabel else { return nil } + guard let seconds = context.windowSeconds, seconds > 0 else { return nil } + let window = TimeInterval(seconds) + + let now = current.observedAt + // Clock went backwards between fetches. + guard now >= previous.observedAt else { return nil } + // Same discipline as `QuotaPace`: a reset in the past, or further out + // than one full window, is clock or data skew. Say nothing. + let currentRemaining = current.resetsAt.timeIntervalSince(now) + guard currentRemaining > 0, currentRemaining <= window + skewTolerance else { return nil } + let lead = previous.resetsAt.timeIntervalSince(now) + guard lead <= window + skewTolerance else { return nil } + // The stored reset has passed, or is about to: a scheduled reset. This is + // the common case and must stay silent. + guard lead >= skewTolerance else { return nil } + + let jump = current.resetsAt.timeIntervalSince(previous.resetsAt) + + // Signal 1: a new cycle began while the old one still had time left. + if jump >= skewTolerance { + // A new fixed cycle starts no earlier than our last look at the old + // one, so it cannot reset sooner than a window after that look. A + // reset time that merely creeps forward is not a new cycle. + let anchoredToNewCycle = current.resetsAt + >= previous.observedAt.addingTimeInterval(window - cycleAnchorTolerance) + guard anchoredToNewCycle else { return nil } + // A reset that gives nothing back is not free capacity. + guard current.percent < previous.percent else { return nil } + return event(.resetMovedForward, previous: previous, current: current, context: context) + } + + // Signal 2: the reset time held still but usage emptied. A backwards + // move of the reset time is neither signal. + guard abs(jump) < skewTolerance else { return nil } + guard previous.percent - current.percent >= minimumPercentDrop, + current.percent <= maximumPercentAfterDrop else { return nil } + return event(.usageDropped, previous: previous, current: current, context: context) + } + + private static func event( + _ signal: EarlyQuotaResetEvent.Signal, + previous: EarlyQuotaResetReading, + current: EarlyQuotaResetReading, + context: Context + ) -> EarlyQuotaResetEvent { + EarlyQuotaResetEvent( + providerID: context.providerID, + providerName: context.providerName, + windowKey: context.windowKey, + windowName: context.windowName, + signal: signal, + scheduledResetAt: previous.resetsAt, + detectedAt: current.observedAt, + percentBefore: previous.percent, + percentAfter: current.percent + ) + } +} + +/// How long the Capacity Dock keeps an early-reset band on screen. +enum EarlyQuotaResetNotice { + static let visibleSeconds: TimeInterval = 12 * 3600 + + static func isVisible(_ event: EarlyQuotaResetEvent, now: Date) -> Bool { + let age = now.timeIntervalSince(event.detectedAt) + // A detection stamped in the future is skew, not a fresh event. + guard age.isFinite, age >= -EarlyQuotaResetDetector.skewTolerance else { return false } + return age <= visibleSeconds + } +} + +/// A user's own record of early resets for one window, derived from the +/// 30 days of snapshots already on disk. Local only. +enum EarlyQuotaResetHistory { + /// Leads shorter than this are not claimed as a pattern: window starts are + /// rounded by vendors, so a sub-hour gap is not evidence of anything. + static let minimumLeadSeconds: TimeInterval = 60 * 60 + + struct Summary: Equatable, Sendable { + let windowKey: String + let windowName: String + /// Consecutive cycle transitions the store can see for this window. + let observedResets: Int + let earlyResets: Int + /// Median lead across the early resets. + let typicalEarlyBySeconds: TimeInterval + + /// Hover-card caption, e.g. "Last 3 weekly resets came ~18h early". + var caption: String { + let noun = windowName.hasSuffix(" limit") + ? String(windowName.dropLast(" limit".count)) + : windowName + let lead = EarlyQuotaResetFormat.approximateLead(seconds: typicalEarlyBySeconds) + if earlyResets == 1 && observedResets == 1 { + return "Last \(noun) reset came ~\(lead) early" + } + if earlyResets == observedResets { + return "Last \(earlyResets) \(noun) resets came ~\(lead) early" + } + return "\(earlyResets) of the last \(observedResets) \(noun) resets came ~\(lead) early" + } + } + + /// The store keeps one entry per window cycle holding the cycle's highest + /// reading, so the moment a new cycle was first seen is not recoverable from + /// `capturedAt`. The reset times are: a fixed window that starts at moment t + /// resets at t + window, so a cycle that followed an early reset ends sooner + /// than a full window after the previous cycle's scheduled end. The lead is + /// `previous.resetsAt + window - next.resetsAt`. + /// + /// Short windows (at or under `QuotaPace.etaSuppressionMaxSeconds`) get no + /// summary, for the same reason they get no pace ETA: rounding of their start + /// times is a large share of the window. + static func summarize( + snapshots: [SubscriptionSnapshot], + windowKey: String, + windowName: String, + windowSeconds: Int? + ) -> Summary? { + guard let seconds = windowSeconds, seconds > 0 else { return nil } + let window = TimeInterval(seconds) + guard window > QuotaPace.etaSuppressionMaxSeconds else { return nil } + + let resets = snapshots + .filter { $0.windowKey == windowKey } + .map(\.resetsAt) + .filter { $0.timeIntervalSince1970.isFinite } + .sorted() + // Jittered timestamps of one cycle collapse to that cycle's latest. + var cycles: [Date] = [] + for reset in resets { + if let last = cycles.last, + reset.timeIntervalSince(last) < EarlyQuotaResetDetector.skewTolerance { + cycles[cycles.count - 1] = reset + } else { + cycles.append(reset) + } + } + guard cycles.count >= 2 else { return nil } + + var observed = 0 + var leads: [TimeInterval] = [] + for (earlier, later) in zip(cycles, cycles.dropFirst()) { + let gap = later.timeIntervalSince(earlier) + // A gap longer than a window means cycles went unobserved (app closed, + // idle between short windows); that pair says nothing about timing. + guard gap <= window + EarlyQuotaResetDetector.cycleAnchorTolerance else { continue } + observed += 1 + let lead = window - gap + if lead >= minimumLeadSeconds { leads.append(lead) } + } + guard !leads.isEmpty else { return nil } + return Summary( + windowKey: windowKey, + windowName: windowName, + observedResets: observed, + earlyResets: leads.count, + typicalEarlyBySeconds: median(leads) + ) + } + + private static func median(_ values: [TimeInterval]) -> TimeInterval { + let sorted = values.sorted() + let mid = sorted.count / 2 + return sorted.count % 2 == 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid] + } +} + +/// Window names and lead formatting shared by the notification, the dock band +/// and the history caption. +enum EarlyQuotaResetFormat { + /// Copy names for the Claude windows the snapshot store records. + static func claudeWindowName(forKey key: String) -> String { + switch key { + case "five_hour": "5-hour limit" + case "seven_day": "weekly limit" + case "seven_day_opus": "Opus weekly limit" + case "seven_day_sonnet": "Sonnet weekly limit" + default: key + } + } + + /// "2d 3h", "18h", "40m" — precise enough for a single event. + static func lead(seconds: TimeInterval) -> String { + let minutes = Int(max(0, seconds) / 60) + let hours = minutes / 60 + if hours >= 24 { + let rest = hours % 24 + return rest == 0 ? "\(hours / 24)d" : "\(hours / 24)d \(rest)h" + } + if hours >= 1 { return "\(hours)h" } + return "\(max(minutes, 1))m" + } + + /// "18h", "2d" — rounded, for a pattern that is only ever approximate. + static func approximateLead(seconds: TimeInterval) -> String { + let hours = Int((max(0, seconds) / 3600).rounded()) + if hours >= 48 { return "\(Int((seconds / 86400).rounded()))d" } + return "\(max(hours, 1))h" + } + + static func capitalizedFirst(_ text: String) -> String { + guard let first = text.first else { return text } + return first.uppercased() + text.dropFirst() + } +} diff --git a/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaResetMonitor.swift b/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaResetMonitor.swift new file mode 100644 index 00000000..2495f35d --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/Data/EarlyQuotaResetMonitor.swift @@ -0,0 +1,180 @@ +import Foundation + +/// Runs `EarlyQuotaResetDetector` over each successful quota fetch, remembers +/// what it has already announced, and posts through the same notifier the +/// update check uses. It adds no polling: the caller invokes it from the +/// existing refresh lifecycle. +/// +/// State lives in `UserDefaults`, one JSON record per provider: +/// - the readings from the previous successful fetch only, so a window that +/// was absent last time has no baseline and a baseline is never older than +/// one fetch. The snapshot store keeps each cycle's highest reading instead, +/// which is right for "what did the cycle end at" and wrong for "what did the +/// last fetch say": read as a baseline, it would re-announce a usage-drop +/// reset on every later fetch of the same cycle; +/// - the plan label seen at that fetch; +/// - the scheduled reset time of every announcement already made, matched with +/// the detector's own skew tolerance, so a vendor that briefly serves the old +/// cycle again — possibly from a replica whose timestamp differs by a minute +/// or two — cannot announce the same reset twice, across relaunches included; +/// - the latest event, for the Capacity Dock band. +@MainActor +final class EarlyQuotaResetMonitor { + struct Observation: Equatable { + let windowKey: String + let windowName: String + let windowSeconds: Int? + /// Nil when the window was not in this fetch. + let reading: EarlyQuotaResetReading? + } + + struct ProviderState: Codable, Equatable { + var planLabel: String? + var windows: [String: EarlyQuotaResetReading] + /// Scheduled reset times already announced, per window key. + var announced: [String: [Date]] + var latestEvent: EarlyQuotaResetEvent? + } + + /// Announcements older than the snapshot store's horizon are dropped. + static let firedRetentionSeconds: TimeInterval = 30 * 24 * 3600 + static let defaultsKeyPrefix = "codeburn.quota.earlyReset.state." + + private let defaults: UserDefaults + private let makeNotifier: () -> any UpdateNotifier + private var notifier: (any UpdateNotifier)? + + init( + defaults: UserDefaults = .standard, + makeNotifier: @escaping () -> any UpdateNotifier = { SystemUpdateNotifier() } + ) { + self.defaults = defaults + self.makeNotifier = makeNotifier + } + + /// Evaluates one successful fetch and returns the event it announced, if + /// any. At most one notification per provider per fetch: a goodwill reset + /// that empties several windows at once is one event, named after the + /// longest window. Every window's identity is still recorded so a later + /// fetch cannot announce the others. + @discardableResult + func record( + providerID: String, + providerName: String, + planLabel: String?, + baselineIsTrusted: Bool, + observations: [Observation], + now: Date = Date() + ) async -> EarlyQuotaResetEvent? { + let stored = loadState(providerID: providerID) + var announced = stored?.announced ?? [:] + + var fresh: [(event: EarlyQuotaResetEvent, windowSeconds: Int)] = [] + if let stored { + for observation in observations { + let context = EarlyQuotaResetDetector.Context( + providerID: providerID, + providerName: providerName, + windowKey: observation.windowKey, + windowName: observation.windowName, + windowSeconds: observation.windowSeconds, + previousPlanLabel: stored.planLabel, + currentPlanLabel: planLabel, + baselineIsTrusted: baselineIsTrusted + ) + guard let event = EarlyQuotaResetDetector.detect( + previous: stored.windows[observation.windowKey], + current: observation.reading, + context: context + ) else { continue } + guard !Self.wasAnnounced(event, in: announced) else { continue } + announced[event.windowKey, default: []].append(event.scheduledResetAt) + fresh.append((event, observation.windowSeconds ?? 0)) + } + } + + let headline = fresh.max { lhs, rhs in + lhs.windowSeconds != rhs.windowSeconds + ? lhs.windowSeconds < rhs.windowSeconds + : lhs.event.earlyBySeconds < rhs.event.earlyBySeconds + }?.event + + var windows: [String: EarlyQuotaResetReading] = [:] + for observation in observations { + if let reading = observation.reading { windows[observation.windowKey] = reading } + } + let cutoff = now.addingTimeInterval(-Self.firedRetentionSeconds) + saveState( + ProviderState( + planLabel: planLabel, + windows: windows, + announced: announced + .mapValues { $0.filter { $0 >= cutoff } } + .filter { !$0.value.isEmpty }, + latestEvent: headline ?? stored?.latestEvent + ), + providerID: providerID + ) + + guard let headline else { return nil } + // Persisted before delivery: an event is one-shot even when the user has + // notifications off or denied, and the dock band still shows it. + await post(headline) + return headline + } + + /// The latest announced event for the dock band, while it is still recent. + func visibleEvent(providerID: String, now: Date = Date()) -> EarlyQuotaResetEvent? { + guard let event = loadState(providerID: providerID)?.latestEvent else { return nil } + return EarlyQuotaResetNotice.isVisible(event, now: now) ? event : nil + } + + /// Called on user disconnect so a reconnect, possibly to another account, + /// starts without a baseline. + func forget(providerID: String) { + defaults.removeObject(forKey: Self.defaultsKeyPrefix + providerID) + } + + /// Whether this cut-short cycle has already been announced. Compared with the + /// detector's skew tolerance rather than exactly: the same cycle can come back + /// from the vendor with a slightly different reset timestamp, and that is the + /// same event, not a second one. + private static func wasAnnounced( + _ event: EarlyQuotaResetEvent, + in announced: [String: [Date]] + ) -> Bool { + guard let times = announced[event.windowKey] else { return false } + // Inclusive: at exactly the tolerance, not announcing twice is the safer + // side of the boundary. + return times.contains { + abs($0.timeIntervalSince(event.scheduledResetAt)) <= EarlyQuotaResetDetector.skewTolerance + } + } + + private func post(_ event: EarlyQuotaResetEvent) async { + guard EarlyQuotaResetPreference.isEnabled(defaults: defaults) else { return } + let notifier = notifier ?? makeNotifier() + self.notifier = notifier + guard await notifier.requestAuthorizationIfNeeded() else { return } + notifier.post( + title: event.notificationTitle, + body: event.notificationBody, + identifier: "EarlyQuotaReset.\(event.identity)" + ) + } + + /// A missing or undecodable record is "no opinion": no baseline, no event. + private func loadState(providerID: String) -> ProviderState? { + guard let data = defaults.data(forKey: Self.defaultsKeyPrefix + providerID) else { return nil } + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + return try? decoder.decode(ProviderState.self, from: data) + } + + private func saveState(_ state: ProviderState, providerID: String) { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .secondsSince1970 + guard let data = try? encoder.encode(state) else { return } + defaults.set(data, forKey: Self.defaultsKeyPrefix + providerID) + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/EarlyQuotaResetTests.swift b/mac/Tests/CodeBurnMenubarTests/EarlyQuotaResetTests.swift new file mode 100644 index 00000000..2a4d5430 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/EarlyQuotaResetTests.swift @@ -0,0 +1,645 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +private let now = Date(timeIntervalSince1970: 1_800_000_000) +private let week: TimeInterval = 7 * 24 * 3600 +private let fiveHours: TimeInterval = 5 * 3600 +private let weekSeconds = 7 * 24 * 3600 + +private func reading( + percent: Double, + resetsIn: TimeInterval, + observedAgo: TimeInterval = 0 +) -> EarlyQuotaResetReading { + EarlyQuotaResetReading( + percent: percent, + resetsAt: now.addingTimeInterval(resetsIn), + observedAt: now.addingTimeInterval(-observedAgo) + ) +} + +private func context( + windowSeconds: Int? = weekSeconds, + previousPlanLabel: String? = "Max 20x", + currentPlanLabel: String? = "Max 20x", + baselineIsTrusted: Bool = true +) -> EarlyQuotaResetDetector.Context { + EarlyQuotaResetDetector.Context( + providerID: "claude", + providerName: "Claude", + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: windowSeconds, + previousPlanLabel: previousPlanLabel, + currentPlanLabel: currentPlanLabel, + baselineIsTrusted: baselineIsTrusted + ) +} + +/// The stored cycle still has 18 hours to run. +private let beforeEarlyReset = reading(percent: 80, resetsIn: 18 * 3600, observedAgo: 300) +/// A new cycle, anchored a full window after the previous look at the old one. +private let afterEarlyReset = reading(percent: 0, resetsIn: week) + +@Suite("Early quota reset detection") +struct EarlyQuotaResetDetectorTests { + @Test("A reset time that jumps to a new cycle before the old one ended is an early reset") + func resetTimeJumpIsDetected() { + let event = EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, current: afterEarlyReset, context: context() + ) + #expect(event?.signal == .resetMovedForward) + #expect(event?.earlyBySeconds == 18 * 3600) + #expect(event?.percentBefore == 80) + #expect(event?.percentAfter == 0) + #expect(event?.notificationBody == "Claude's weekly limit reset 18h early. You're back to 100%.") + #expect(event?.noticeText == "Weekly limit reset 18h early") + } + + @Test("Usage emptying while the reset time stands still is an early reset") + func percentDropIsDetected() { + let event = EarlyQuotaResetDetector.detect( + previous: reading(percent: 92, resetsIn: 18 * 3600, observedAgo: 300), + current: reading(percent: 1, resetsIn: 18 * 3600), + context: context() + ) + #expect(event?.signal == .usageDropped) + #expect(event?.earlyBySeconds == 18 * 3600) + } + + @Test("Both signals describe the same cut-short cycle, so they coalesce to one identity") + func signalsShareAnIdentity() { + let jumped = EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, current: afterEarlyReset, context: context() + ) + let dropped = EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, + current: reading(percent: 1, resetsIn: 18 * 3600), + context: context() + ) + #expect(jumped?.identity == dropped?.identity) + } + + // MARK: - Must not false-positive + + @Test("A normal scheduled reset stays silent") + func scheduledResetIsSilent() { + // The stored cycle's reset has passed: this is the common case. + let event = EarlyQuotaResetDetector.detect( + previous: reading(percent: 96, resetsIn: -60, observedAgo: 300), + current: reading(percent: 0, resetsIn: week), + context: context() + ) + #expect(event == nil) + } + + @Test("A plan change stays silent") + func planChangeIsSilent() { + let event = EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, + current: afterEarlyReset, + context: context(previousPlanLabel: "Pro", currentPlanLabel: "Max 20x") + ) + #expect(event == nil) + } + + @Test("Clock skew stays silent") + func clockSkewIsSilent() { + // A reset already in the past. + #expect(EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, + current: reading(percent: 0, resetsIn: -3600), + context: context() + ) == nil) + // A reset further out than one whole window. + #expect(EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, + current: reading(percent: 0, resetsIn: week + 2 * 3600), + context: context() + ) == nil) + // The clock went backwards between the two fetches. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 80, resetsIn: 18 * 3600, observedAgo: -600), + current: afterEarlyReset, + context: context() + ) == nil) + // A stored reset further out than a window is stale or skewed state. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 80, resetsIn: week + 2 * 3600, observedAgo: 300), + current: afterEarlyReset, + context: context() + ) == nil) + } + + @Test("A window appearing or disappearing between fetches stays silent") + func windowComingAndGoingIsSilent() { + #expect(EarlyQuotaResetDetector.detect( + previous: nil, current: afterEarlyReset, context: context() + ) == nil) + #expect(EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, current: nil, context: context() + ) == nil) + } + + @Test("The first ever observation of a window stays silent") + func firstObservationIsSilent() { + #expect(EarlyQuotaResetDetector.detect( + previous: nil, current: afterEarlyReset, context: context() + ) == nil) + } + + @Test("A provider reconnecting after a failure stays silent") + func reconnectIsSilent() { + let event = EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, + current: afterEarlyReset, + context: context(baselineIsTrusted: false) + ) + #expect(event == nil) + #expect(SubscriptionLoadState.terminalFailure(reason: nil).earlyResetBaselineIsTrusted == false) + #expect(SubscriptionLoadState.bootstrapping.earlyResetBaselineIsTrusted == false) + #expect(SubscriptionLoadState.noCredentials.earlyResetBaselineIsTrusted == false) + #expect(SubscriptionLoadState.notBootstrapped.earlyResetBaselineIsTrusted == false) + #expect(SubscriptionLoadState.loaded.earlyResetBaselineIsTrusted) + #expect(SubscriptionLoadState.dormant.earlyResetBaselineIsTrusted) + } + + @Test("A malformed stored snapshot is no opinion, never an event") + func malformedBaselineIsSilent() { + for percent in [150.0, -1.0, Double.nan] { + #expect(EarlyQuotaResetDetector.detect( + previous: EarlyQuotaResetReading( + percent: percent, + resetsAt: now.addingTimeInterval(18 * 3600), + observedAt: now.addingTimeInterval(-300) + ), + current: afterEarlyReset, + context: context() + ) == nil) + } + } + + @Test("A window with no validated duration stays silent") + func unknownDurationIsSilent() { + #expect(EarlyQuotaResetDetector.detect( + previous: beforeEarlyReset, current: afterEarlyReset, context: context(windowSeconds: nil) + ) == nil) + } + + @Test("Rounding noise and partial drops are not a reset") + func smallMovesAreSilent() { + // A percent that dips by rounding. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 80, resetsIn: 18 * 3600, observedAgo: 300), + current: reading(percent: 79, resetsIn: 18 * 3600), + context: context() + ) == nil) + // A big fall that does not land near empty: not "your capacity is back". + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 95, resetsIn: 18 * 3600, observedAgo: 300), + current: reading(percent: 40, resetsIn: 18 * 3600), + context: context() + ) == nil) + } + + @Test("A stored reset further out than one whole window is skew, on either signal") + func staleBaselineIsSilent() { + // Signal 2's shape: the reset time effectively holds still and usage + // empties, with the current reset just inside the horizon while the + // stored one sits beyond it. A baseline that claims this cycle is due + // further out than the window is long cannot say when it was due at all. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 92, resetsIn: week + 1000, observedAgo: 300), + current: reading(percent: 1, resetsIn: week + 500), + context: context() + ) == nil) + // And the plain case: a current reset beyond one whole window. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 92, resetsIn: week + 2 * 3600, observedAgo: 300), + current: reading(percent: 1, resetsIn: week + 2 * 3600), + context: context() + ) == nil) + } + + @Test("A small drop to near-empty is noise, not a reset") + func smallDropToNearEmptyIsSilent() { + // A lightly-used window shedding a few points (rolling decay, a vendor + // recount) lands near empty without any capacity having been given back. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 20, resetsIn: 18 * 3600, observedAgo: 300), + current: reading(percent: 8, resetsIn: 18 * 3600), + context: context() + ) == nil) + } + + @Test("A reset time that only creeps forward is not a new cycle") + func rollingCreepIsSilent() { + // A rolling window's reset time advances with the clock; the new value is + // nowhere near a full window after the previous observation. + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 80, resetsIn: 18 * 3600, observedAgo: 300), + current: reading(percent: 0, resetsIn: 18 * 3600 + 1800), + context: context() + ) == nil) + } + + @Test("A reset time moving backwards is neither signal") + func backwardsResetIsSilent() { + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 80, resetsIn: 30 * 3600, observedAgo: 300), + current: reading(percent: 0, resetsIn: 18 * 3600), + context: context() + ) == nil) + } + + @Test("A new cycle that gives nothing back is not announced") + func noCapacityReturnedIsSilent() { + #expect(EarlyQuotaResetDetector.detect( + previous: reading(percent: 0, resetsIn: 18 * 3600, observedAgo: 300), + current: afterEarlyReset, + context: context() + ) == nil) + } +} + +@Suite("Early quota reset history") +struct EarlyQuotaResetHistoryTests { + private func snapshots(resetOffsets: [TimeInterval], windowKey: String = "seven_day") -> [SubscriptionSnapshot] { + resetOffsets.map { offset in + SubscriptionSnapshot( + windowKey: windowKey, + percent: 50, + resetsAt: now.addingTimeInterval(offset), + capturedAt: now.addingTimeInterval(offset - 3600), + effectiveTokens: nil + ) + } + } + + @Test("Three consecutive weekly cycles that each landed 18h early read as a pattern") + func consistentEarlyResets() { + let early: TimeInterval = 18 * 3600 + // Each cycle ends a window after the previous reset, minus the lead. + var offsets: [TimeInterval] = [-3 * week] + for _ in 0..<3 { offsets.append(offsets.last! + week - early) } + let summary = EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: offsets), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) + #expect(summary?.earlyResets == 3) + #expect(summary?.observedResets == 3) + #expect(summary?.typicalEarlyBySeconds == early) + #expect(summary?.caption == "Last 3 weekly resets came ~18h early") + } + + @Test("Cycles that ran to schedule produce no summary") + func onScheduleResetsHaveNoPattern() { + let offsets: [TimeInterval] = [-3 * week, -2 * week, -week, 0] + #expect(EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: offsets), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) == nil) + } + + @Test("A mixed record says how many of the observed resets were early") + func mixedRecord() { + let early: TimeInterval = 12 * 3600 + let offsets: [TimeInterval] = [ + -3 * week, + -3 * week + week - early, + -3 * week + 2 * week - early, + -3 * week + 3 * week - early * 2, + ] + let summary = EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: offsets), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) + #expect(summary?.observedResets == 3) + #expect(summary?.earlyResets == 2) + #expect(summary?.caption == "2 of the last 3 weekly resets came ~12h early") + } + + @Test("Short windows get no pattern, the same discipline the pace ETA uses") + func shortWindowsHaveNoPattern() { + let offsets: [TimeInterval] = [0, fiveHours - 2 * 3600, 2 * (fiveHours - 2 * 3600)] + #expect(EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: offsets, windowKey: "five_hour"), + windowKey: "five_hour", + windowName: "5-hour limit", + windowSeconds: 5 * 3600 + ) == nil) + } + + @Test("A single observed cycle is not a pattern") + func oneCycleHasNoPattern() { + #expect(EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: [0]), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) == nil) + } + + @Test("Cycles the store never saw are not read as timing evidence") + func unobservedCyclesAreSkipped() { + // A gap of three windows: the app was closed. That pair says nothing. + #expect(EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: [-4 * week, -week]), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) == nil) + } + + @Test("A gap in the record is not counted among the resets the summary speaks for") + func unobservedCyclesAreNotCounted() { + let early: TimeInterval = 18 * 3600 + let first = -5 * week + // Three windows pass unobserved, then one cycle that landed early. + let resumed = first + 3 * week + let summary = EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: [first, resumed, resumed + week - early]), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) + #expect(summary?.observedResets == 1) + #expect(summary?.earlyResets == 1) + #expect(summary?.caption == "Last weekly reset came ~18h early") + } + + @Test("Jittered reset timestamps inside one cycle collapse to that cycle") + func jitterIsCollapsed() { + let early: TimeInterval = 18 * 3600 + let first = -2 * week + let second = first + week - early + let offsets: [TimeInterval] = [first, first + 90, second, second + 120] + let summary = EarlyQuotaResetHistory.summarize( + snapshots: snapshots(resetOffsets: offsets), + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds + ) + #expect(summary?.observedResets == 1) + #expect(summary?.earlyResets == 1) + #expect(summary?.caption == "Last weekly reset came ~18h early") + } +} + +@Suite("Early quota reset notifications") +@MainActor +struct EarlyQuotaResetMonitorTests { + @Test("An early reset notifies once, naming the provider and the lead") + func notifiesOnce() async throws { + try await withIsolatedMonitor { monitor, notifier, _ in + await seedBaseline(monitor) + let event = await monitor.record( + providerID: "claude", + providerName: "Claude", + planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(event?.signal == .resetMovedForward) + #expect(notifier.posts.count == 1) + #expect(notifier.posts.first?.title == "Claude quota reset early") + #expect(notifier.posts.first?.body == "Claude's weekly limit reset 18h early. You're back to 100%.") + } + } + + @Test("Several windows resetting in one fetch are one notification, named after the longest") + func coalescesAcrossWindows() async throws { + try await withIsolatedMonitor { monitor, notifier, _ in + await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [ + weeklyObservation(beforeEarlyReset), + fiveHourObservation(reading(percent: 70, resetsIn: 3 * 3600, observedAgo: 300)), + ], + now: now.addingTimeInterval(-300) + ) + let event = await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [ + weeklyObservation(afterEarlyReset), + fiveHourObservation(reading(percent: 0, resetsIn: fiveHours)), + ], + now: now + ) + #expect(notifier.posts.count == 1) + #expect(event?.windowKey == "seven_day") + } + } + + @Test("The same event is not announced again after a relaunch or a vendor flip-flop") + func doesNotRepeatAcrossRelaunch() async throws { + try await withIsolatedMonitor { monitor, notifier, defaults in + await seedBaseline(monitor) + await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(notifier.posts.count == 1) + + // Relaunch over the same defaults, and the vendor briefly serves the + // old cycle again before the new one. + let relaunched = EarlyQuotaResetMonitor(defaults: defaults, makeNotifier: { notifier }) + await relaunched.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(reading(percent: 80, resetsIn: 18 * 3600 - 600))], + now: now.addingTimeInterval(600) + ) + await relaunched.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(reading(percent: 0, resetsIn: week))], + now: now.addingTimeInterval(1200) + ) + #expect(notifier.posts.count == 1) + } + } + + @Test("Toggle off posts nothing and never asks for authorization, but the dock still shows it") + func toggleOffStaysSilent() async throws { + try await withIsolatedMonitor { monitor, notifier, defaults in + defaults.set(false, forKey: EarlyQuotaResetPreference.defaultsKey) + await seedBaseline(monitor) + let event = await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(event != nil) + #expect(notifier.posts.isEmpty) + #expect(notifier.authorizationRequests == 0) + #expect(monitor.visibleEvent(providerID: "claude", now: now) != nil) + } + } + + @Test("Denied authorization posts nothing") + func deniedAuthorizationPostsNothing() async throws { + try await withIsolatedMonitor { monitor, notifier, _ in + notifier.authorized = false + await seedBaseline(monitor) + await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(notifier.posts.isEmpty) + #expect(notifier.authorizationRequests == 1) + } + } + + @Test("The first fetch only seeds a baseline") + func firstFetchIsSilent() async throws { + try await withIsolatedMonitor { monitor, notifier, _ in + let event = await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(event == nil) + #expect(notifier.posts.isEmpty) + } + } + + @Test("Disconnecting drops the baseline so a reconnect cannot fire on stale state") + func forgetClearsState() async throws { + try await withIsolatedMonitor { monitor, notifier, _ in + await seedBaseline(monitor) + monitor.forget(providerID: "claude") + await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + #expect(notifier.posts.isEmpty) + #expect(monitor.visibleEvent(providerID: "claude", now: now) == nil) + } + } + + @Test("The dock band is bounded in time") + func noticeExpires() async throws { + try await withIsolatedMonitor { monitor, _, _ in + await seedBaseline(monitor) + await monitor.record( + providerID: "claude", providerName: "Claude", planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(afterEarlyReset)], + now: now + ) + let stillVisible = EarlyQuotaResetNotice.visibleSeconds - 60 + #expect(monitor.visibleEvent(providerID: "claude", now: now.addingTimeInterval(stillVisible)) != nil) + #expect(monitor.visibleEvent( + providerID: "claude", + now: now.addingTimeInterval(EarlyQuotaResetNotice.visibleSeconds + 60) + ) == nil) + } + } +} + +@Suite("Capacity Dock early reset band") +struct EarlyQuotaResetDockTests { + @Test("The band is a notice the computed panel height reserves") + func bandIsReserved() { + let quota = QuotaSummary( + providerFilter: .claude, + connection: .connected, + primary: nil, + details: [QuotaSummary.Window(label: "Weekly", percent: 0.2, resetsAt: now)], + planLabel: "Max 20x", + footerLines: [] + ) + func height(_ hasBand: Bool) -> CGFloat { + CapacityDockMetrics.detailHeight( + quota: quota, + sessionCount: 1, + hasToday: true, + tailEdge: .right, + scale: 1, + hasEarlyResetNotice: hasBand + ) + } + #expect(height(true) == height(false) + CapacityDockGlance.noticeHeight) + } +} + +// MARK: - Helpers + +private func weeklyObservation(_ reading: EarlyQuotaResetReading?) -> EarlyQuotaResetMonitor.Observation { + EarlyQuotaResetMonitor.Observation( + windowKey: "seven_day", + windowName: "weekly limit", + windowSeconds: weekSeconds, + reading: reading + ) +} + +private func fiveHourObservation(_ reading: EarlyQuotaResetReading?) -> EarlyQuotaResetMonitor.Observation { + EarlyQuotaResetMonitor.Observation( + windowKey: "five_hour", + windowName: "5-hour limit", + windowSeconds: 5 * 3600, + reading: reading + ) +} + +@MainActor +private func seedBaseline(_ monitor: EarlyQuotaResetMonitor) async { + await monitor.record( + providerID: "claude", + providerName: "Claude", + planLabel: "Max 20x", + baselineIsTrusted: true, + observations: [weeklyObservation(beforeEarlyReset)], + now: now.addingTimeInterval(-300) + ) +} + +@MainActor +private func withIsolatedMonitor( + _ body: @MainActor (EarlyQuotaResetMonitor, RecordingEarlyResetNotifier, UserDefaults) async throws -> Void +) async throws { + let suiteName = "codeburn.quota.earlyReset.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let notifier = RecordingEarlyResetNotifier() + let monitor = EarlyQuotaResetMonitor(defaults: defaults, makeNotifier: { notifier }) + try await body(monitor, notifier, defaults) +} + +@MainActor +private final class RecordingEarlyResetNotifier: UpdateNotifier { + var authorized = true + var authorizationRequests = 0 + var posts: [(title: String, body: String, identifier: String)] = [] + + func requestAuthorizationIfNeeded() async -> Bool { + authorizationRequests += 1 + return authorized + } + + func post(title: String, body: String, identifier: String) { + posts.append((title, body, identifier)) + } +}