diff --git a/CHANGELOG.md b/CHANGELOG.md index ad6597e0..dc11b5c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ - **The Capacity Dock gauge can report the short usage window instead of the weekly one, without expanding the dock.** The resting rail shows one number per provider, and that number was always the weekly (else monthly) billing window. Clicking the provider already resting in the rail now switches its gauge to the provider's short rolling window — Claude's 5-hour limit, Codex's 5-hour or daily window, any `Hourly`, `Daily` or session row an adapter reports — and clicking again switches back. The choice is stored per provider under `CodeBurnCapacityDockGlanceWindows`, so Claude can sit on its 5-hour window while Codex stays weekly, and it survives relaunch. A per-model row such as `Weekly · Opus` is never read as a short window, a provider that reports only one window keeps the plain click-to-pin behaviour, and a stored horizon the provider stops reporting falls back to the window it does report rather than blanking the gauge to `--`. The rail's geometry is untouched, VoiceOver and keyboard users get the switch as a named action on the provider cell with the window named in the cell's value, and Escape or a click outside still unpins the dock. (#1243) ### Changed -- **The Capacity Dock card no longer prints a pace verdict under each quota window.** The "On pace" / "Lasts until reset" caption from #1314 added a third line to every window cell and made the card read as clutter; the cells are back to percent, label and countdown, up to three windows share one row again with a fourth wrapping to a second, and the pace math still feeds the tooltip and the agent-tab card. +- **The Capacity Dock card and the popover quota rows no longer print a pace verdict under each window.** The "On pace" / "Lasts until reset" caption from #1314 added a third line to every window cell and made the card read as clutter; the cells are back to percent, label and countdown, up to three windows share one row again with a fourth wrapping to a second, and the pace math still feeds the tooltip and the agent-tab card. ### Fixed - **Shared and MCP-redacted payloads no longer carry git branch names or the working directory of a session.** Two identities were riding along in `current`: the `topSessions` rows added in #1316 carry `projectKey`, a dash-encoded absolute path such as `-Users--Projects-`, which `redactProjectNames` left verbatim even when an MCP client asked not to see project names, and the per-branch rows added in #788 carry the raw branch, which both `sanitizeForSharing` and the MCP pass let through, so a branch such as `exp/extraction-arms` reached a shared payload as typed. The MCP pass now hashes `projectKey` with the same salted pseudonym it already applies to `topProjects[].id`, hashes the drill-through `sessionId` on both `topSessions` and `topProjects[].sessionDetails` (a Codex id embeds the rollout timestamp the pass blanks out of `date`), and gives each distinct branch a stable `branch-xxxxxx` pseudonym, keeping the cost, calls and session counts untouched; a `null` branch stays null, because unbranched spend is not a name. Sharing drops the per-branch block outright, the way it already drops the project and session rows, since a pseudonymized branch tells a peer device nothing anyway. Nothing changes for the local menubar, the desktop app or the web dashboard, which read the unsanitized payload, and nothing changes for an MCP caller that passes `include_project_names: true` — it still gets every name as recorded. (#1325, #1321) diff --git a/mac/Sources/CodeBurnMenubar/Data/QuotaPacePresentation.swift b/mac/Sources/CodeBurnMenubar/Data/QuotaPacePresentation.swift index d98e4c34..39012bc2 100644 --- a/mac/Sources/CodeBurnMenubar/Data/QuotaPacePresentation.swift +++ b/mac/Sources/CodeBurnMenubar/Data/QuotaPacePresentation.swift @@ -1,231 +1,13 @@ import Foundation -/// Turns a quota window into the one-line pace caption the Capacity Dock's -/// window columns and the agent-tab quota hover card both draw (#1215): the -/// whole-window average interpretation `QuotaPace` defends (#726 phase 1), -/// rendered as "on pace", a deficit/reserve stage, an estimated exhaustion, -/// or the explicit exhausted state. Deliberately text-only: the math lives in -/// `QuotaPace`, the wording lives here, so both stay testable without a view. -/// -/// Honesty rules this type enforces: -/// - The caption describes the AVERAGE pace across the whole elapsed window, -/// never a measured recent rate. The hover/accessibility text says so. -/// - Only validated window durations are used. A window without -/// `windowSeconds` gets no estimate — the label ("Weekly") is not a length. -/// - `Window.percent` is a 0...1 fraction; `QuotaPace` consumes 0...100. -/// This is the one place the unit crosses, and it is tested. Anything -/// outside 0...1 (negative, >1, NaN, infinity) is rejected, not clamped. -/// - A projection is valid only while the sample that produced the window is -/// inside `QuotaSummary`'s ten-minute freshness horizon. A connected -/// account can still carry an old loaded sample while a refresh is pending; -/// that sample must not become a forecast. -/// - The estimate is an ETA measured from `now` ("est. out in 3h 20m"), never -/// a lead before reset, and every countdown is computed against the passed -/// `now`, never a hidden wall clock, so fixtures stay deterministic. -/// - Stale, failed, loading or disconnected quota data gets nothing. A reset -/// in the past, or further out than one full window (clock/data skew), and -/// non-finite reset timestamps are refused before any branch. +/// Countdown wording shared by the Capacity Dock, the popover quota rows and +/// the reset notices, plus Claude's fixed window lengths. enum QuotaPacePresentation { /// Claude's rate-limit windows are fixed lengths (the same values the /// plan popover projects with), so they are validated durations. static let claudeFiveHourSeconds = 5 * 3600 static let claudeSevenDaySeconds = 7 * 24 * 3600 - /// What a window column draws in its reserved pace slot. The slot itself - /// stays empty when no `Line` is defensible. - struct Line: Equatable { - enum Kind: Equatable { - /// Projected from the whole-window average. - case estimate - /// The window is at exactly 100% and has not reset yet. - case exhausted - } - - /// Visual weight for the caption: muted for a healthy pace, amber for - /// a deficit or projected overflow, red once the limit is reached. - enum Tone: Equatable { - case neutral - case warning - case danger - } - - let kind: Kind - let tone: Tone - /// Compact caption for the column, e.g. "est. out in 3h 20m". - let text: String - /// Hover/accessibility text carrying the full honest reading. - let helpText: String - } - - /// The caption for one window, or nil when nothing defensible remains. - static func line( - for window: QuotaSummary.Window, - connection: QuotaSummary.Connection, - now: Date = Date() - ) -> Line? { - // Last-known or in-flight data cannot back a projection. - guard connection == .connected else { return nil } - // A connected summary can still be an old loaded sample while a - // refresh is pending. Keep the pace caption honest by tying it to the - // same injected `now` used by the calculation and by the tests. - guard window.isFresh(at: now) else { return nil } - guard let windowSeconds = window.windowSeconds, windowSeconds > 0 else { return nil } - guard let resetsAt = window.resetsAt else { return nil } - // `percent` arrives as a fraction; the pace math consumes percent. - // Reject non-finite or out-of-range samples before either branch: a - // negative fraction clamped to zero would invent a healthy forecast, - // and >1 is not a "100% used" signal, it is a broken sample. - guard window.percent.isFinite, window.percent >= 0, window.percent <= 1 else { return nil } - let usedPercent = window.percent * 100 - - // Reset in the past, or further out than one full window, or a - // non-finite timestamp: clock/data skew. Guard both branches — an - // "exhausted" window whose reset is months away is impossible data, - // not a limit that is actually reached. - let remaining = resetsAt.timeIntervalSince(now) - guard remaining.isFinite else { return nil } - guard remaining > 0, remaining <= TimeInterval(windowSeconds) else { return nil } - - if usedPercent >= 100 { - return Line( - kind: .exhausted, - tone: .danger, - text: L("Limit reached"), - helpText: L( - "This window's limit is fully used. It resets in %@.", - countdownLabel(seconds: remaining) - ) - ) - } - - guard let result = QuotaPace.evaluate( - usedPercent: usedPercent, - resetsAt: resetsAt, - windowSeconds: windowSeconds, - now: now - ) else { return nil } - let tone: Line.Tone = result.willOverflow || result.deltaPercent > 2 ? .warning : .neutral - return Line( - kind: .estimate, - tone: tone, - text: caption(for: result, windowSeconds: windowSeconds, now: now), - helpText: helpText( - result: result, - windowSeconds: windowSeconds, - now: now, - resetsAt: resetsAt - ) - ) - } - - /// One line per displayed window, in report order. Distinct scope windows - /// that merely share a duration (Claude's Weekly vs Weekly · Opus vs - /// Weekly · Sonnet, or Codex's extra per-model limits) each keep their own - /// caption — they report different usage and different exhaustion risk. - /// Only a genuinely identical duplicate window (same label, percent, - /// reset and duration) is suppressed. - static func lines( - for windows: [QuotaSummary.Window], - connection: QuotaSummary.Connection, - now: Date = Date() - ) -> [Line?] { - var seen: [QuotaSummary.Window] = [] - return windows.map { window in - guard !seen.contains(window) else { return nil } - seen.append(window) - return line(for: window, connection: connection, now: now) - } - } - - /// Whether the panel must reserve a pace slot under the window columns. - /// Deliberately independent of both wall-clock time and connection state: - /// the slot is reserved whenever a displayed window carries a validated - /// duration and a reset date, even while the caption itself is empty (a - /// window younger than 3%, a stale sample, a refresh in flight). Reserving - /// on shape alone keeps the computed panel height from changing under the - /// pointer every time a refresh or a freshness horizon flips the caption. - static func reservesLine(for windows: [QuotaSummary.Window]) -> Bool { - windows.contains { window in - guard let seconds = window.windowSeconds, seconds > 0 else { return false } - return window.resetsAt != nil - } - } - - /// Compact caption, phrased as the plain "am I going to make it?" answer - /// #1287 argued for rather than as a projection the reader has to decode: - /// a window that lands at or under the limit reads "Lasts until reset", - /// one that does not reads "Runs out in ". The projected - /// percentage it came from stays in `helpText`, where there is room for - /// the reasoning. On windows at or under - /// `QuotaPace.etaSuppressionMaxSeconds` there is no defensible ETA at all - /// — a linear read of a short window cries wolf after one burst — so - /// those keep the on-pace / deficit / reserve stage instead (#726). - static func caption(for result: QuotaPace.Result, windowSeconds: Int, now: Date = Date()) -> String { - let compact = TimeInterval(windowSeconds) <= QuotaPace.etaSuppressionMaxSeconds - if compact { - if abs(result.deltaPercent) <= 2 { return L("On pace") } - // Same two keys the Plan tab's stage caption uses, so a stage never - // reads one way in the dock and another in the popover. - if result.deltaPercent > 0 { - return L("%@%% in deficit", String(Int(result.deltaPercent.rounded()))) - } - return L("%@%% in reserve", String(Int(-result.deltaPercent.rounded()))) - } - guard result.willOverflow else { return L("Lasts until reset") } - // A long overflowing window always yields an ETA (a projection over - // 100% implies a positive rate), but if that ever stopped holding, - // saying it lasts would be the one wrong answer. - guard let hitsLimitAt = result.hitsLimitAt else { return L("Won't last until reset") } - return L("Runs out in %@", countdownLabel(from: now, to: hitsLimitAt)) - } - - private static func helpText( - result: QuotaPace.Result, - windowSeconds: Int, - now: Date, - resetsAt: Date - ) -> String { - let basis = L( - "Estimated from the average pace across this whole %@ window so far — not a measured recent rate.", - windowLengthLabel(seconds: windowSeconds) - ) - let projected = Int(result.projectedPercent.rounded()) - let projectionSentence: String - if result.willOverflow, let hitsLimitAt = result.hitsLimitAt { - projectionSentence = L( - "At that pace the limit is reached in %@, before the reset in %@.", - countdownLabel(from: now, to: hitsLimitAt), - countdownLabel(from: now, to: resetsAt) - ) - } else if abs(result.deltaPercent) <= 2 { - projectionSentence = L("Projected %lld%% used by the reset — on pace.", projected) - } else if result.deltaPercent > 0 { - projectionSentence = L( - "Projected %d%% used by the reset, %.0f%% ahead of the pace the elapsed window implies.", - projected, result.deltaPercent - ) - } else { - projectionSentence = L( - "Projected %d%% used by the reset, %.0f%% of the window still in reserve.", - projected, -result.deltaPercent - ) - } - return basis + " " + projectionSentence - } - - /// Human label for a validated duration: the two lengths Claude and Codex - /// actually report, else a plain hours/days rendering of the number. - private static func windowLengthLabel(seconds: Int) -> String { - switch seconds { - case claudeFiveHourSeconds: return L("5-hour") - case claudeSevenDaySeconds: return L("7-day") - default: - let hours = seconds / 3600 - if hours >= 24, seconds % 86400 == 0 { return L("%lld-day", hours / 24) } - return L("%lld-hour", hours) - } - } - /// "2d 3h" / "3h 20m" / "45m" / "<1m", mirroring the window column's own /// countdown shape. Computed against the passed dates, never a hidden /// wall clock, so fixtures stay deterministic. diff --git a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings index 6e302813..4e57275a 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/en.lproj/Localizable.strings @@ -650,21 +650,8 @@ "Follows System Settings > Language & Region unless you pick one here." = "Follows System Settings > Language & Region unless you pick one here."; /* MARK: Quota pace captions (#1267) */ -"Limit reached" = "Limit reached"; -"This window's limit is fully used. It resets in %@." = "This window's limit is fully used. It resets in %@."; "On pace" = "On pace"; -"Lasts until reset" = "Lasts until reset"; -"Won't last until reset" = "Won't last until reset"; -"Runs out in %@" = "Runs out in %@"; -"Estimated from the average pace across this whole %@ window so far — not a measured recent rate." = "Estimated from the average pace across this whole %@ window so far — not a measured recent rate."; -"At that pace the limit is reached in %@, before the reset in %@." = "At that pace the limit is reached in %@, before the reset in %@."; -"Projected %lld%% used by the reset — on pace." = "Projected %lld%% used by the reset — on pace."; -"Projected %d%% used by the reset, %.0f%% ahead of the pace the elapsed window implies." = "Projected %d%% used by the reset, %.0f%% ahead of the pace the elapsed window implies."; -"Projected %d%% used by the reset, %.0f%% of the window still in reserve." = "Projected %d%% used by the reset, %.0f%% of the window still in reserve."; "5-hour" = "5-hour"; -"7-day" = "7-day"; -"%lld-day" = "%lld-day"; -"%lld-hour" = "%lld-hour"; "<1m" = "<1m"; /* MARK: Early quota reset (#725) */ diff --git a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings index 7bad5a92..2404faee 100644 --- a/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings +++ b/mac/Sources/CodeBurnMenubar/Resources/zh-Hans.lproj/Localizable.strings @@ -642,21 +642,8 @@ "Follows System Settings > Language & Region unless you pick one here." = "除非在此处选择,否则将跟随“系统设置 > 语言与地区”。"; /* MARK: Quota pace captions (#1267) */ -"Limit reached" = "限额已用尽"; -"This window's limit is fully used. It resets in %@." = "该窗口的限额已全部用完,将在 %@后重置。"; "On pace" = "符合节奏"; -"Lasts until reset" = "可支撑到重置"; -"Won't last until reset" = "撑不到重置"; -"Runs out in %@" = "%@后耗尽"; -"Estimated from the average pace across this whole %@ window so far — not a measured recent rate." = "根据整个 %@窗口至今的平均速度估算,而非最近实测的速率。"; -"At that pace the limit is reached in %@, before the reset in %@." = "按此速度,限额将在 %@后用尽,早于 %@后的重置。"; -"Projected %lld%% used by the reset — on pace." = "预计到重置时将用掉 %lld%% — 符合节奏。"; -"Projected %d%% used by the reset, %.0f%% ahead of the pace the elapsed window implies." = "预计到重置时将用掉 %d%%,比已过窗口所对应的节奏超出 %.0f%%。"; -"Projected %d%% used by the reset, %.0f%% of the window still in reserve." = "预计到重置时将用掉 %d%%,该窗口还有 %.0f%% 的结余。"; "5-hour" = "5 小时"; -"7-day" = "7 天"; -"%lld-day" = "%lld 天"; -"%lld-hour" = "%lld 小时"; "<1m" = "<1 分"; /* MARK: Early quota reset (#725) */ diff --git a/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift b/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift index c0dd48ad..3eed7530 100644 --- a/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift +++ b/mac/Sources/CodeBurnMenubar/Views/AgentTabStrip.swift @@ -378,14 +378,7 @@ private struct QuotaDetailPopover: View { } private var rowsCard: some View { - // Resolve every window's pace caption once, against this summary's - // connection and freshness, so the card and the Capacity Dock cannot - // disagree about a window and an exact duplicate is captioned once. - let paceLines = QuotaPacePresentation.lines( - for: quota.details, - connection: quota.connection - ) - return VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 6) { HStack(spacing: 6) { Text(L("%@ usage", quota.providerFilter.displayLabel)) .font(.system(size: 11, weight: .semibold)) @@ -418,7 +411,7 @@ private struct QuotaDetailPopover: View { } } ForEach(Array(quota.details.enumerated()), id: \.offset) { index, w in - QuotaDetailRow(window: w, paceLine: paceLines[index]) + QuotaDetailRow(window: w) } // What this Mac has seen of the provider's own reset timing, next to // the pace captions. Derived from the snapshots already on disk. @@ -465,15 +458,7 @@ private struct QuotaDetailPopover: View { private struct QuotaDetailRow: View { let window: QuotaSummary.Window - /// Whether this window lasts to its reset, already resolved against the - /// summary's connection and sample freshness by `QuotaPacePresentation`. - /// Nil means the row says nothing at all: this card is fitted, so a silent - /// caption collapses rather than leaving a gap — unlike the Capacity Dock, - /// whose frame is computed and therefore reserves the slot either way. - let paceLine: QuotaPacePresentation.Line? - /// The label column's width. The caption hangs under the bar, so it is - /// indented past the label by this plus the row's own spacing. private static let labelWidth: CGFloat = 92 private static let rowSpacing: CGFloat = 8 @@ -502,28 +487,6 @@ private struct QuotaDetailRow: View { .frame(width: 50, alignment: .trailing) } } - if let paceLine { - Text(paceLine.text) - .font(.system(size: 9.5, weight: .medium)) - .foregroundStyle(paceTint) - .lineLimit(1) - .padding(.leading, Self.labelWidth + Self.rowSpacing) - .help(paceLine.helpText) - .accessibilityLabel(paceLine.text) - .accessibilityHint(paceLine.helpText) - } - } - } - - /// Muted while the pace is healthy, amber for a deficit or a projected - /// overflow, red once the limit is actually reached — the same three - /// tones the dock's caption uses, so one surface cannot look calmer than - /// the other about the same window. - private var paceTint: AnyShapeStyle { - switch paceLine?.tone { - case .danger: return AnyShapeStyle(Color.red.opacity(0.92)) - case .warning: return AnyShapeStyle(Color.orange) - default: return AnyShapeStyle(.tertiary) } } diff --git a/mac/Tests/CodeBurnMenubarTests/CapacityDockPacePresentationTests.swift b/mac/Tests/CodeBurnMenubarTests/CapacityDockPacePresentationTests.swift deleted file mode 100644 index 8431ce0e..00000000 --- a/mac/Tests/CodeBurnMenubarTests/CapacityDockPacePresentationTests.swift +++ /dev/null @@ -1,329 +0,0 @@ -import Foundation -import Testing -@testable import CodeBurnMenubar - -/// Fixtures for the Capacity Dock pace caption. These drive the production -/// `QuotaPacePresentation` path that the window columns render, not helper -/// arithmetic: every assertion names the exact caption string the view will -/// draw, which is also what pins the fraction/percent unit crossing. -private struct Fixture { - let now = Date(timeIntervalSince1970: 1_800_000_000) - let week = 7 * 24 * 3600 - let fiveHours = 5 * 3600 - - /// resetsAt such that `fraction` of the window has elapsed at `now`. - func resets(afterElapsedFraction fraction: Double, windowSeconds: Int) -> Date { - now.addingTimeInterval(TimeInterval(windowSeconds) * (1 - fraction)) - } - - func window( - _ label: String, - _ percent: Double, - resetsAt: Date, - windowSeconds: Int - ) -> QuotaSummary.Window { - QuotaSummary.Window( - label: label, - percent: percent, - resetsAt: resetsAt, - windowSeconds: windowSeconds, - fetchedAt: now - ) - } - - func line( - percent: Double, - elapsedFraction: Double, - windowSeconds: Int, - connection: QuotaSummary.Connection = .connected - ) -> QuotaPacePresentation.Line? { - QuotaPacePresentation.line( - for: window("Weekly", percent, resetsAt: resets(afterElapsedFraction: elapsedFraction, windowSeconds: windowSeconds), windowSeconds: windowSeconds), - connection: connection, - now: now - ) - } -} - -@Suite("Capacity Dock quota pace caption") -struct CapacityDockPacePresentationTests { - private let f = Fixture() - - @Test("A window fraction is consumed as percent, not as a raw 0..1 value") - func fractionBecomesPercent() { - // 0.5 fraction at halfway through the week is 50% used — on pace. - // Read as a raw 0..1 value it would be 0.5% used, which projects to 1% - // at reset; the help text is where that number is still visible. - let line = f.line(percent: 0.5, elapsedFraction: 0.5, windowSeconds: f.week) - #expect(line?.kind == .estimate) - #expect(line?.text == "Lasts until reset") - #expect(line?.helpText.contains("Projected 100% used by the reset") == true) - #expect(line?.tone == .neutral) - } - - @Test("Ahead of pace with a projected overflow names an exhaustion ETA from now") - func deficitProjectsEarlyExhaustion() { - // used 60%, expected 40% -> projected 150%; the limit is hit 44h 48m - // from `now`, while the reset itself is still 4d 4h away. - let line = f.line(percent: 0.6, elapsedFraction: 0.4, windowSeconds: f.week) - #expect(line?.kind == .estimate) - #expect(line?.text == "Runs out in 1d 20h") - #expect(line?.tone == .warning) - #expect(!(line?.text.contains("early") ?? false)) - } - - @Test("The ETA is now-to-limit, which differs from now-to-reset") - func etaIsNowToLimitNotLeadBeforeReset() { - let hitsLimitAt = f.now.addingTimeInterval(44 * 3600 + 48 * 60) // 44h 48m - let resetsAt = f.resets(afterElapsedFraction: 0.4, windowSeconds: f.week) - let nowToLimit = QuotaPacePresentation.countdownLabel(from: f.now, to: hitsLimitAt) - let nowToReset = QuotaPacePresentation.countdownLabel(from: f.now, to: resetsAt) - // The two intervals differ, so the caption must state the ETA from now, - // not a "lead before reset" that would come out as reset-minus-limit. - #expect(nowToLimit == "1d 20h") - #expect(nowToReset == "4d 4h") - #expect(nowToLimit != nowToReset) - } - - @Test("Behind pace stays in reserve with a projection, no alarm") - func reserveStaysNeutral() { - let line = f.line(percent: 0.2, elapsedFraction: 0.5, windowSeconds: f.week) - #expect(line?.text == "Lasts until reset") - #expect(line?.helpText.contains("30% of the window still in reserve") == true) - #expect(line?.tone == .neutral) - } - - @Test("A window younger than 3% elapsed gets no estimate") - func earlyWindowIsSilent() { - #expect(f.line(percent: 0.5, elapsedFraction: 0.01, windowSeconds: f.week) == nil) - } - - @Test("No usage yet reads as a zero projection, not as zero-signal") - func noUsageYet() { - let line = f.line(percent: 0.0, elapsedFraction: 0.5, windowSeconds: f.week) - #expect(line?.text == "Lasts until reset") - #expect(line?.helpText.contains("Projected 0% used by the reset") == true) - #expect(line?.tone == .neutral) - } - - @Test("A fully used window is exhausted, and a past reset is stale") - func exhaustedState() { - let reached = f.line(percent: 1.0, elapsedFraction: 0.5, windowSeconds: f.week) - #expect(reached?.kind == .exhausted) - #expect(reached?.text == "Limit reached") - #expect(reached?.tone == .danger) - let window = f.window( - "Weekly", 1.0, - resetsAt: f.now.addingTimeInterval(-100), - windowSeconds: f.week - ) - #expect(QuotaPacePresentation.line(for: window, connection: .connected, now: f.now) == nil) - } - - @Test("Short windows show stage only, never a burst ETA") - func shortWindowSuppressesETA() { - let line = f.line(percent: 0.9, elapsedFraction: 0.5, windowSeconds: f.fiveHours) - #expect(line?.kind == .estimate) - #expect(line?.text == "40% in deficit") - #expect(line?.tone == .warning) - // Neither the long-window verdict nor an ETA may appear here. - #expect(!(line?.text.contains("Runs out") ?? false)) - #expect(!(line?.text.contains("until reset") ?? false)) - } - - @Test("The on-pace band is two points wide in each direction") - func onPaceBandEdges() { - // Nothing else pins this width, so widening it would silently turn a - // real deficit into "On pace" on every short window. - #expect(f.line(percent: 0.515, elapsedFraction: 0.5, windowSeconds: f.fiveHours)?.text == "On pace") - #expect(f.line(percent: 0.485, elapsedFraction: 0.5, windowSeconds: f.fiveHours)?.text == "On pace") - #expect(f.line(percent: 0.53, elapsedFraction: 0.5, windowSeconds: f.fiveHours)?.text == "3% in deficit") - #expect(f.line(percent: 0.47, elapsedFraction: 0.5, windowSeconds: f.fiveHours)?.text == "3% in reserve") - } - - @Test("Six hours exactly is still a short window; one second more is not") - func etaSuppressionBoundary() { - let sixHours = 6 * 3600 - #expect(f.line(percent: 0.9, elapsedFraction: 0.5, windowSeconds: sixHours)?.text == "40% in deficit") - let justOver = f.line(percent: 0.9, elapsedFraction: 0.5, windowSeconds: sixHours + 1) - #expect(justOver?.text.hasPrefix("Runs out in") == true) - } - - @Test("Stale, failed and disconnected data get nothing") - func nonConnectedDataIsSilent() { - for connection: QuotaSummary.Connection in [.stale, .loading, .transientFailure, .disconnected] { - #expect(f.line(percent: 0.6, elapsedFraction: 0.4, windowSeconds: f.week, connection: connection) == nil) - } - } - - @Test("An old connected sample gets no pace caption") - func oldConnectedSampleIsSilent() { - let old = f.window( - "Weekly", - 0.6, - resetsAt: f.resets(afterElapsedFraction: 0.4, windowSeconds: f.week), - windowSeconds: f.week - ) - let stale = QuotaSummary.Window( - label: old.label, - percent: old.percent, - resetsAt: old.resetsAt, - windowSeconds: old.windowSeconds, - fetchedAt: f.now.addingTimeInterval(-QuotaSummary.freshnessThreshold - 1) - ) - #expect(QuotaPacePresentation.line(for: stale, connection: .connected, now: f.now) == nil) - } - - @Test("Negative, over-one, non-finite and missing metadata get nothing") - func invalidInputsAreSilent() { - // A negative fraction must be rejected, not clamped into a healthy 0%. - #expect(f.line(percent: -0.1, elapsedFraction: 0.5, windowSeconds: f.week) == nil) - // Over 100% is not a "limit reached" signal — it is a broken sample. - #expect(f.line(percent: 1.2, elapsedFraction: 0.5, windowSeconds: f.week) == nil) - #expect(f.line(percent: .nan, elapsedFraction: 0.5, windowSeconds: f.week) == nil) - #expect(f.line(percent: .infinity, elapsedFraction: 0.5, windowSeconds: f.week) == nil) - #expect(f.line(percent: 0.5, elapsedFraction: 0.5, windowSeconds: 0) == nil) - #expect(f.line(percent: 0.5, elapsedFraction: 0.5, windowSeconds: -100) == nil) - - let noDuration = QuotaSummary.Window( - label: "Weekly", - percent: 0.5, - resetsAt: f.resets(afterElapsedFraction: 0.5, windowSeconds: f.week), - windowSeconds: nil, - fetchedAt: f.now - ) - #expect(QuotaPacePresentation.line(for: noDuration, connection: .connected, now: f.now) == nil) - - let noReset = QuotaSummary.Window( - label: "Weekly", - percent: 0.5, - resetsAt: nil, - windowSeconds: f.week, - fetchedAt: f.now - ) - #expect(QuotaPacePresentation.line(for: noReset, connection: .connected, now: f.now) == nil) - } - - @Test("Clock skew in either direction gets nothing") - func clockSkewIsSilent() { - let tooFar = f.window("Weekly", 0.5, resetsAt: f.now.addingTimeInterval(TimeInterval(f.week + 100)), windowSeconds: f.week) - #expect(QuotaPacePresentation.line(for: tooFar, connection: .connected, now: f.now) == nil) - let elapsed = f.window("Weekly", 0.5, resetsAt: f.now.addingTimeInterval(-1), windowSeconds: f.week) - #expect(QuotaPacePresentation.line(for: elapsed, connection: .connected, now: f.now) == nil) - } - - @Test("An impossible exhausted window (reset far past the duration) is rejected") - func impossibleExhaustedIsSilent() { - // 100% used, but the reset is thirty days out on a weekly window: - // that is clock/data skew, not an actually-exhausted limit. - let window = f.window("Weekly", 1.0, resetsAt: f.now.addingTimeInterval(30 * 24 * 3600), windowSeconds: f.week) - #expect(QuotaPacePresentation.line(for: window, connection: .connected, now: f.now) == nil) - } - - @Test("A non-finite reset timestamp is rejected before any branch") - func nonFiniteResetIsSilent() { - let window = f.window("Weekly", 1.0, resetsAt: Date(timeIntervalSinceReferenceDate: .infinity), windowSeconds: f.week) - #expect(QuotaPacePresentation.line(for: window, connection: .connected, now: f.now) == nil) - } - - @Test("A mislabeled duration is used as given, not re-inferred from the label") - func durationIsUsedAsGiven() { - let thirtyDays = 30 * 24 * 3600 - let window = f.window( - "Weekly", 0.9, - resetsAt: f.now.addingTimeInterval(2 * 24 * 3600), - windowSeconds: thirtyDays - ) - let line = QuotaPacePresentation.line(for: window, connection: .connected, now: f.now) - #expect(line?.kind == .estimate) - #expect(line?.text == "Lasts until reset") - #expect(line?.helpText.contains("Projected 96% used by the reset") == true) - } - - @Test("A monthly cycle whose label reads Weekly paces against the month, not 7 days") - func grokBuildMonthlyCycleLabeledWeekly() { - // Grok Build picks its window label from the distance to the reset, so - // a monthly cycle sitting in the 4-12 day band is labeled "Weekly". - // Deriving the length from that label — the round trip #1287 used — - // paces a month's budget against 7 days. - let month = 30 * 24 * 3600 - let resetsAt = f.now.addingTimeInterval(6 * 24 * 3600) // inside the band - let window = f.window("Weekly", 0.72, resetsAt: resetsAt, windowSeconds: month) - - // 24 of 30 days elapsed at 72% used projects to 90%: it lasts. - let line = QuotaPacePresentation.line(for: window, connection: .connected, now: f.now) - #expect(line?.text == "Lasts until reset") - #expect(line?.tone == .neutral) - #expect(line?.helpText.contains("30-day window") == true) - - // The same sample against the label-inferred 7-day window is 1 of 7 - // days elapsed, which projects past 500% and would print an alarming - // run-out ETA on a healthy account. That is the reading the real - // `windowSeconds` must never produce. - let asWeekly = QuotaPace.evaluate( - usedPercent: 72, - resetsAt: resetsAt, - windowSeconds: 7 * 24 * 3600, - now: f.now - ) - #expect(asWeekly?.willOverflow == true) - #expect(line?.text != QuotaPacePresentation.caption( - for: asWeekly!, - windowSeconds: 7 * 24 * 3600, - now: f.now - )) - - // And with no duration metadata at all, the label stays a label: the - // caption is silent rather than falling back to inferring "Weekly". - let noDuration = QuotaSummary.Window( - label: window.label, - percent: window.percent, - resetsAt: resetsAt, - windowSeconds: nil, - fetchedAt: f.now - ) - #expect(QuotaPacePresentation.line(for: noDuration, connection: .connected, now: f.now) == nil) - } - - @Test("Distinct scopes sharing a duration each keep their own caption") - func distinctScopesAreNotSuppressed() { - // A healthy aggregate Weekly and an exhausted Weekly · Opus share the - // same 7-day duration; the healthy window must not hide the exhausted - // one. - let weekly = f.window("Weekly", 0.5, resetsAt: f.resets(afterElapsedFraction: 0.5, windowSeconds: f.week), windowSeconds: f.week) - let opus = f.window("Weekly · Opus", 1.0, resetsAt: f.resets(afterElapsedFraction: 0.5, windowSeconds: f.week), windowSeconds: f.week) - let lines = QuotaPacePresentation.lines(for: [weekly, opus], connection: .connected, now: f.now) - #expect(lines[0]?.text == "Lasts until reset") - #expect(lines[1]?.text == "Limit reached") - } - - @Test("Same-duration windows with different reset dates both keep captions") - func sameDurationDifferentResets() { - let a = f.window("Limit A", 0.5, resetsAt: f.now.addingTimeInterval(3 * 24 * 3600), windowSeconds: f.week) - let b = f.window("Limit B", 0.9, resetsAt: f.now.addingTimeInterval(2 * 24 * 3600), windowSeconds: f.week) - let lines = QuotaPacePresentation.lines(for: [a, b], connection: .connected, now: f.now) - #expect(lines[0] != nil) - #expect(lines[1] != nil) - } - - @Test("Only a genuinely identical duplicate window is suppressed") - func exactDuplicatesAreSuppressed() { - let resetsAt = f.resets(afterElapsedFraction: 0.5, windowSeconds: f.week) - let a = f.window("Weekly", 0.5, resetsAt: resetsAt, windowSeconds: f.week) - let duplicate = f.window("Weekly", 0.5, resetsAt: resetsAt, windowSeconds: f.week) - let lines = QuotaPacePresentation.lines(for: [a, duplicate], connection: .connected, now: f.now) - #expect(lines[0] != nil) - #expect(lines[1] == nil) - } - - @Test("The panel reserves a slot on metadata, independent of time and connection") - func reservationIsMetadataOnly() { - let resetsAt = f.now.addingTimeInterval(3 * 24 * 3600) - let eligible = [QuotaSummary.Window(label: "Weekly", percent: 0.5, resetsAt: resetsAt, windowSeconds: f.week, fetchedAt: f.now)] - let noDuration = [QuotaSummary.Window(label: "Weekly", percent: 0.5, resetsAt: resetsAt, fetchedAt: f.now)] - let noReset = [QuotaSummary.Window(label: "Weekly", percent: 0.5, resetsAt: nil, windowSeconds: f.week, fetchedAt: f.now)] - #expect(QuotaPacePresentation.reservesLine(for: eligible)) - #expect(!QuotaPacePresentation.reservesLine(for: noDuration)) - #expect(!QuotaPacePresentation.reservesLine(for: noReset)) - } -}