Merge pull request #1353 from getagentseal/fix/dock-drop-pace-caption

menubar: drop the pace caption from the Capacity Dock window cells
This commit is contained in:
Resham Joshi 2026-09-13 22:48:07 +03:00 • committed by GitHub
commit a498332bcf
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 27 additions and 766 deletions

View file

@ -12,6 +12,9 @@
- **The macOS menubar item can show a second line.** Settings → General → Display gains a "Second row" switch, off by default, and a picker for what that line shows: quota remaining with its reset countdown for whichever connected provider is nearest its limit, today's all-provider cost, today's total tokens, or the number of running sessions. Both lines render as one attributed title at 9pt with their line height clamped to 10pt, so the pair fits the standard 22pt menu bar, and the second line hides itself whenever its metric has no data yet, leaving the existing single-row figure exactly as it was. This is a deliberately small first slice of the multi-row layout request: no layout editor, no presets, no live preview, no per-item provider or period scoping. The setting persists as `CodeBurnMenubarSecondRowEnabled` and `CodeBurnMenubarSecondRowMetric` in the app's own defaults domain alongside the existing menubar period, scope and metric keys. (#1252)
- **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 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-<user>-Projects-<repo>`, 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)
- **A pull request row now opens the sessions that produced it.** Every other aggregate in the app drills through — a day bar, a model name, a task category, a project — but the Pull requests section only ever expanded and collapsed: the PR selection builder and the drill-through callback were threaded through the section four component levels deep and nothing ever called either, so the one report that names actual shipped work had no way into the sessions behind it. An expanded PR row now carries a `View sessions for this pull request →` control above its work breakdown, the same affordance a project row in Spend already offers; it selects the PR by its URL — the aggregation key the by-PR report is built on — and lands in Sessions with the chip applied and each session's per-turn contribution reconciled against its full cost. The control is its own click target rather than the row, so clicking it or pressing Enter on it never costs the expansion, and a legacy row with no per-turn detail offers it too. Two smaller items from the same review: the sessions list's return-to-the-first-page reset wrote internal state the app does not read while it owns the pagination depth, so revealing another 120 rows and then changing the sort or removing a chip left you deep inside a list that had just been reordered — the reset now rides the same commit as the change that caused it, and the depth a Back/Forward restore brings back is left alone. And the investigation chips were keyed by the label they display, which truncates a session id to 12 characters and a project to its last path segment: two chips that read alike collided into one React key, warned about it, and risked reconciling or removing the wrong one — they are now keyed by the full provider+id and project+branch identity the selection is deduplicated by. (#1317)

View file

@ -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 <now-to-limit>". 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.

View file

@ -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) */

View file

@ -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) */

View file

@ -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)
}
}

View file

@ -154,27 +154,10 @@ enum CapacityDockGlance {
/// The old zero-spacing HStack let intrinsic Text widths bleed across columns.
static let windowsColumnGap: CGFloat = 8
static let windowsRowGap: CGFloat = 6
/// One 9.5pt pace caption under the reset line, with its 2pt gap. Reserved
/// whenever connected data carries a window with validated duration, even
/// while the caption itself is still empty — the slot must not appear and
/// disappear with wall-clock time under an open panel.
static let paceLineHeight: CGFloat = 12
static let paceLineGap: CGFloat = 2
/// 8 top + one secondary line + 16 bottom.
static let windowsEmptyHeight: CGFloat = 37
/// Whether the windows row carries pace slots: connected data with at
/// least one displayed window holding validated duration metadata.
static func drawsPace(_ quota: QuotaSummary) -> Bool {
guard drawsWindows(quota) else { return false }
let shown = windows(quota)
guard !shown.isEmpty else { return false }
return QuotaPacePresentation.reservesLine(for: shown)
}
/// The windows row's height for this quota: the plain row, or the row with
/// the pace slot every column reserves. Must stay in step with
/// `windowColumn`, which draws the slot under every column when this fires.
/// The windows row's height for this quota.
static func windowsHeight(for quota: QuotaSummary) -> CGFloat {
let shown = windows(quota)
guard !shown.isEmpty else { return windowsEmptyHeight }
@ -185,12 +168,10 @@ enum CapacityDockGlance {
).rounded()
}
/// One or two windows stay on one compact row. Three and four windows use
/// two columns and enough row height for every percentage, reset, and pace
/// caption. This is shared by `detailHeight` and the actual SwiftUI grid.
/// Up to three windows share one compact row; a fourth starts a second row. This is shared by `detailHeight` and the actual SwiftUI grid.
static func windowColumnCount(for windowCount: Int) -> Int {
guard windowCount > 0 else { return 0 }
return min(windowCount, 2)
return min(windowCount, 3)
}
static func windowRowCount(for windowCount: Int) -> Int {
@ -199,18 +180,13 @@ enum CapacityDockGlance {
return (windowCount + columns - 1) / columns
}
static func windowRowHeight(hasPaceSlot: Bool) -> CGFloat {
windowContentHeight + (hasPaceSlot ? paceLineGap + paceLineHeight : 0)
}
/// Height of the grid alone, excluding this section's top and bottom pads.
static func windowsGridHeight(for quota: QuotaSummary) -> CGFloat {
let count = windows(quota).count
guard count > 0 else { return 0 }
let rows = windowRowCount(for: count)
let rowHeight = windowRowHeight(hasPaceSlot: drawsPace(quota))
return (
CGFloat(rows) * rowHeight
CGFloat(rows) * windowContentHeight
+ CGFloat(max(0, rows - 1)) * windowsRowGap
).rounded()
}
@ -1152,32 +1128,18 @@ struct CapacityDockDetailView: View {
}
/// One cell per quota window, in the order the provider reported them.
/// One or two windows stay on a compact row. Three or four windows use a
/// two-column grid whose cell width comes from the actual content geometry,
/// including its inter-column gap. When the panel reserved pace slots
/// (`drawsPace`), every cell draws the slot — empty where its window has no
/// defensible caption — so rows stay aligned with the height the panel
/// reserved.
/// Up to three windows share a compact row; four use two rows. Cell width
/// comes from the actual content geometry, including its inter-column gap.
@ViewBuilder
private func windowsSection(_ quota: QuotaSummary) -> some View {
let s = model.detailScale
let windows = CapacityDockGlance.windows(quota)
let hasPaceSlot = CapacityDockGlance.drawsPace(quota)
let paceLines = QuotaPacePresentation.lines(
for: windows,
connection: quota.connection
)
Group {
if windows.isEmpty {
budgetLine()
.frame(height: CapacityDockGlance.captionLine * s)
} else {
windowGrid(
windows,
paceLines: paceLines,
hasPaceSlot: hasPaceSlot,
scale: s
)
windowGrid(windows, scale: s)
.frame(height: CapacityDockGlance.windowsGridHeight(for: quota) * s)
}
}
@ -1190,8 +1152,6 @@ struct CapacityDockDetailView: View {
@ViewBuilder
private func windowGrid(
_ windows: [QuotaSummary.Window],
paceLines: [QuotaPacePresentation.Line?],
hasPaceSlot: Bool,
scale: CGFloat
) -> some View {
let columnCount = CapacityDockGlance.windowColumnCount(for: windows.count)
@ -1206,7 +1166,7 @@ struct CapacityDockDetailView: View {
(geometry.size.width - columnSpacing * CGFloat(max(0, columnCount - 1)))
/ CGFloat(max(columnCount, 1))
)
VStack(spacing: windows.count > 2 ? CapacityDockGlance.windowsRowGap * scale : 0) {
VStack(spacing: rowCount > 1 ? CapacityDockGlance.windowsRowGap * scale : 0) {
ForEach(0..<rowCount, id: \.self) { row in
HStack(spacing: columnSpacing) {
ForEach(0..<columnCount, id: \.self) { column in
@ -1216,8 +1176,6 @@ struct CapacityDockDetailView: View {
windows[index],
width: columnWidth,
alignment: alignment,
paceLine: hasPaceSlot ? paceLines[index] : nil,
hasPaceSlot: hasPaceSlot,
scale: scale
)
} else {
@ -1241,8 +1199,6 @@ struct CapacityDockDetailView: View {
_ window: QuotaSummary.Window,
width: CGFloat,
alignment: HorizontalAlignment,
paceLine: QuotaPacePresentation.Line?,
hasPaceSlot: Bool,
scale: CGFloat
) -> some View {
VStack(alignment: alignment, spacing: 0) {
@ -1282,15 +1238,6 @@ struct CapacityDockDetailView: View {
)
.padding(.top, 2 * scale)
.accessibilityLabel(L("Resets %@", window.resetsInLabel))
if hasPaceSlot {
paceCaption(paceLine)
.frame(
width: width,
height: CapacityDockGlance.paceLineHeight * scale,
alignment: alignment == .leading ? .leading : .center
)
.padding(.top, CapacityDockGlance.paceLineGap * scale)
}
}
.frame(
width: width,
@ -1298,34 +1245,6 @@ struct CapacityDockDetailView: View {
)
}
/// The whole-window-average pace reading under one quota window. An absent
/// caption leaves its reserved slot empty: no estimate is the honest state
/// for a too-young window, and inventing one is not.
@ViewBuilder
private func paceCaption(_ line: QuotaPacePresentation.Line?) -> some View {
if let line {
let color: Color = switch line.tone {
case .danger: .red.opacity(0.92)
case .warning: .orange.opacity(0.9)
case .neutral: Color.capacityDockText.opacity(0.45)
}
Text(line.text)
.font(.system(size: 9.5, weight: .medium))
.monospacedDigit()
.foregroundStyle(color)
.lineLimit(1)
.minimumScaleFactor(0.8)
// The full caption remains in the tooltip/accessibility tree;
// middle truncation retains both the estimate kind and its
// useful endpoint when a future caption grows longer.
.truncationMode(.middle)
.help(line.helpText)
.accessibilityElement(children: .ignore)
.accessibilityLabel(line.text)
.accessibilityHint(line.helpText)
}
}
/// No quota window exists for this provider, so money is the capacity.
@ViewBuilder
private func budgetLine() -> some View {

View file

@ -85,55 +85,7 @@ struct CapacityDockGlanceTests {
#expect(CapacityDockGlance.windows(quota([])).isEmpty)
}
@Test("Pace slots reserve height for any window with a validated duration")
func paceSlotReservedByDuration() {
let resetsAt = Date().addingTimeInterval(3 * 24 * 3600)
let withoutDuration = [window("5-hour", 0.2, resetsAt: resetsAt), window("Weekly", 0.5, resetsAt: resetsAt)]
let withDuration = [
window("5-hour", 0.2, resetsAt: resetsAt, windowSeconds: QuotaPacePresentation.claudeFiveHourSeconds),
window("Weekly", 0.5, resetsAt: resetsAt, windowSeconds: QuotaPacePresentation.claudeSevenDaySeconds),
]
#expect(!CapacityDockGlance.drawsPace(quota(withoutDuration)))
#expect(CapacityDockGlance.drawsPace(quota(withDuration)))
// Missing duration still draws the plain row.
#expect(CapacityDockGlance.windowsHeight(for: quota(withoutDuration)) == CapacityDockGlance.windowsHeight)
let step = CapacityDockGlance.paceLineGap + CapacityDockGlance.paceLineHeight
#expect(CapacityDockGlance.windowsHeight(for: quota(withDuration)) == CapacityDockGlance.windowsHeight + step)
// Stale and loading data carry the durations but no defensible
// estimate. The slot stays reserved anyway: it is the caption that
// goes quiet, and the panel must not resize under the pointer every
// time a refresh starts or a sample ages out.
for connection in [QuotaSummary.Connection.stale, .loading] {
#expect(CapacityDockGlance.drawsPace(quota(withDuration, connection: connection)))
#expect(
CapacityDockGlance.windowsHeight(for: quota(withDuration, connection: connection))
== CapacityDockGlance.windowsHeight(for: quota(withDuration))
)
}
// The computed panel height reflects the reserved slot.
func detailHeight(_ windows: [QuotaSummary.Window], connection: QuotaSummary.Connection) -> CGFloat {
CapacityDockMetrics.detailHeight(
quota: quota(windows, connection: connection),
sessionCount: nil,
hasToday: false,
tailEdge: .right,
scale: 1
)
}
#expect(detailHeight(withDuration, connection: .connected) - detailHeight(withoutDuration, connection: .connected) == step)
for scale in [0.9, 1.0, 1.15, 1.25, 1.4] {
let h = CapacityDockMetrics.detailHeight(
quota: quota(withDuration),
sessionCount: 2,
hasToday: true,
tailEdge: .bottom,
scale: CGFloat(scale)
)
#expect(h == h.rounded())
}
}
@Test("Three or four windows use two constrained columns and two rows")
@Test("Up to three windows share one row; a fourth wraps to a second")
func multiWindowGridGeometry() {
let plainThree = quota([
window("5-hour", 0.2),
@ -148,15 +100,15 @@ struct CapacityDockGlanceTests {
])
#expect(CapacityDockGlance.windowColumnCount(for: 1) == 1)
#expect(CapacityDockGlance.windowColumnCount(for: 2) == 2)
#expect(CapacityDockGlance.windowColumnCount(for: 3) == 2)
#expect(CapacityDockGlance.windowColumnCount(for: 4) == 2)
#expect(CapacityDockGlance.windowColumnCount(for: 3) == 3)
#expect(CapacityDockGlance.windowColumnCount(for: 4) == 3)
#expect(CapacityDockGlance.windowRowCount(for: 1) == 1)
#expect(CapacityDockGlance.windowRowCount(for: 2) == 1)
#expect(CapacityDockGlance.windowRowCount(for: 3) == 2)
#expect(CapacityDockGlance.windowRowCount(for: 3) == 1)
#expect(CapacityDockGlance.windowRowCount(for: 4) == 2)
#expect(abs(CapacityDockGlance.windowsGridHeight(for: plainThree) - (2 * 53 + 6)) < 0.001)
#expect(abs(CapacityDockGlance.windowsHeight(for: plainThree) - (8 + 2 * 53 + 6 + 16)) < 0.001)
#expect(CapacityDockGlance.windowsHeight(for: plainFour) == CapacityDockGlance.windowsHeight(for: plainThree))
#expect(CapacityDockGlance.windowsHeight(for: plainThree) == CapacityDockGlance.windowsHeight)
#expect(abs(CapacityDockGlance.windowsGridHeight(for: plainFour) - (2 * 53 + 6)) < 0.001)
#expect(abs(CapacityDockGlance.windowsHeight(for: plainFour) - (8 + 2 * 53 + 6 + 16)) < 0.001)
// One and two windows retain the original compact one-row geometry.
#expect(CapacityDockGlance.windowsHeight(for: quota([window("Weekly", 0.5)])) == CapacityDockGlance.windowsHeight)
#expect(CapacityDockGlance.windowsHeight(for: quota([window("5-hour", 0.2), window("Weekly", 0.5)])) == CapacityDockGlance.windowsHeight)
@ -290,8 +242,8 @@ struct CapacityDockGlanceTests {
+ CapacityDockGlance.todayHeight
+ CapacityDockGlance.windowsHeight(for: quota(three))
)
// 44 header + 83 sessions + 97 today + 136 two-row windows grid.
#expect(full == 360)
// 44 header + 83 sessions + 97 today + 77 one-row windows grid.
#expect(full == 301)
// The panel opens and closes on the same 16pt inset it uses sideways.
let headerParts: CGFloat = CapacityDockGlance.contentInset + 20 + 8
#expect(CapacityDockGlance.headerHeight == headerParts)
@ -320,13 +272,10 @@ struct CapacityDockGlanceTests {
height(1, hasToday: true, windows: []) - full
== CapacityDockGlance.windowsEmptyHeight - CapacityDockGlance.windowsHeight(for: quota(three))
)
// One and two columns stay on the compact row; three windows need the
// Up to three windows share the compact row; a fourth needs the
// second grid row so every scope remains visible.
#expect(height(1, hasToday: true, windows: [three[0]]) < full)
#expect(
height(1, hasToday: true, windows: [three[0], three[1]])
== height(1, hasToday: true, windows: [three[0]])
)
#expect(height(1, hasToday: true, windows: [three[0]]) == full)
#expect(height(1, hasToday: true, windows: three + [window("Sonnet", 0.5)]) > full)
}
@Test("A vertical tail adds its allowance to the panel height")

View file

@ -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))
}
}