feat(menubar): optional second row in the macOS menu bar item

The menu bar item could show one figure, so seeing subscription quota and
today's local usage at the same time meant opening the popover. This adds an
optional second line, off by default, configured from the existing
Settings > General > Display section: a "Second row" toggle plus a picker for
what it shows. All four metrics are figures the app already computes for the
popover, so nothing here adds a fetch or a refresh cadence: quota remaining
with its reset countdown for whichever connected provider is nearest its limit
(the same provider the flame already tints for), today's all-provider cost,
today's total tokens, or running sessions.

The rows are one attributed title. A paragraph style clamps text line height
but not an attachment, so the inline flame at the text's own point size dragged
the title to 24pt and AppKit clipped the second line away; the flame is
requested at 8pt and seated back inside the line, which puts every row
combination at exactly 20pt inside the standard 22pt menu bar, centred with 1pt
of slack above and below. Measured with NSAttributedString.boundingRect and
asserted in the tests, since those four numbers only work together.

With the setting off, or whenever the chosen metric has no data yet (no
connected provider with a quota window, no today payload, a CLI that predates
the liveSessions block), the title falls back to the previous single-row
composition unchanged: same font, same attributes, no paragraph style. The row
formatting is a pure type over the row settings and a plain-value payload
snapshot, so it is covered without an AppStore or a status item.

This is a deliberately reduced slice of the request. Not included: the layout
editor, presets, live preview, a third row, multiple items or aligned columns
per row, per-item provider/period/scope, optional labels, decimal precision,
reordering and text size. Keeping the formatter pure leaves room for those
later without touching the rendering path.

Closes #1252
This commit is contained in:
ozymandiashh 2026-09-11 17:13:03 +03:00 • committed by iamtoruk
parent ef86348673
commit 016b8edaef
7 changed files with 826 additions and 14 deletions

View file

@ -85,6 +85,20 @@ final class AppStore {
var displayMetric: DisplayMetric = DisplayMetric(rawValue: UserDefaults.standard.string(forKey: "CodeBurnDisplayMetric") ?? "") ?? .cost {
didSet { UserDefaults.standard.set(displayMetric.rawValue, forKey: "CodeBurnDisplayMetric") }
}
/// Optional second menu-bar line. Off by default, so the status item keeps
/// rendering exactly the historical single-row title until asked otherwise.
var menubarSecondRowEnabled: Bool = MenubarRowPreferences.load().isSecondRowEnabled {
didSet { MenubarRowPreferences.setSecondRowEnabled(menubarSecondRowEnabled) }
}
var menubarSecondRowMetric: MenubarSecondRowMetric = MenubarRowPreferences.load().secondRowMetric {
didSet { MenubarRowPreferences.setSecondRowMetric(menubarSecondRowMetric) }
}
var menubarRowSettings: MenubarRowSettings {
MenubarRowSettings(
isSecondRowEnabled: menubarSecondRowEnabled,
secondRowMetric: menubarSecondRowMetric
)
}
var dailyBudget: Double = UserDefaults.standard.double(forKey: "CodeBurnDailyBudget") {
didSet { UserDefaults.standard.set(dailyBudget, forKey: "CodeBurnDailyBudget") }
}
@ -2033,6 +2047,54 @@ final class AppStore {
return todayPayload?.current
}
/// Connected providers that report a headline quota window, as plain values.
/// Bounded on purpose: the six adapters with a native quota path, plus the
/// CodeBurn-owned adapters whose summary has already been fetched. Nothing
/// here starts a fetch, so the menu-bar title stays a pure read.
var menubarQuotaCandidates: [MenubarQuotaCandidate] {
var candidates: [MenubarQuotaCandidate] = []
var seen: Set<String> = []
func append(label: String, summary: QuotaSummary?) {
guard let summary,
summary.connection == .connected || summary.connection == .stale,
let window = summary.headlineWindow,
window.percent.isFinite,
seen.insert(label).inserted else { return }
candidates.append(
MenubarQuotaCandidate(
label: label,
percentUsed: window.percent,
resetsAt: window.resetsAt
)
)
}
for provider in CapacityDockPreferences.supportedProviders {
guard let filter = provider.legacyFilter else { continue }
append(label: provider.displayName, summary: quotaSummary(for: filter))
}
for (id, summary) in capacityDockProviderSummaries {
guard let provider = CapacityDockProvider(rawValue: id) else { continue }
append(label: provider.displayName, summary: summary)
}
return candidates
}
/// Plain-value snapshot the second menu-bar row formats. Reads only figures
/// the app already keeps for the popover.
var menubarRowSnapshot: MenubarRowSnapshot {
let today = capacityDockToday
return MenubarRowSnapshot(
quota: MenubarQuotaRowSelection.primary(from: menubarQuotaCandidates),
todayCost: today?.cost,
todayTotalTokens: today.map { $0.inputTokens + $0.outputTokens },
activeSessionCount: menubarPayload?.liveSessions?.sessions.count,
currencySymbol: CurrencyState.shared.symbol,
currencyRate: CurrencyState.shared.rate
)
}
/// Today's totals for ONE provider's glance card. The card is provider
/// scoped, so the machine-wide `capacityDockToday` block is the wrong number
/// in it; `providerDetails` carries the per-provider row.

View file

@ -989,6 +989,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
// currency switch instead of waiting for the next 30s payload tick.
_ = self.store.currency
_ = self.store.displayMetric
// Second-row settings: the title has to re-render the moment the
// toggle or its metric changes, not on the next payload tick.
_ = self.store.menubarSecondRowEnabled
_ = self.store.menubarSecondRowMetric
_ = self.store.dailyBudget
_ = self.store.dailyTokenBudget
// Read the derived flag so the flame re-tints when today's usage
@ -1247,8 +1251,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
/// menubar text point size. With no tint it stays a template image so the system
/// auto-adapts to the menu bar; a tint returns a recolored non-template copy for
/// the budget/quota warning states.
private static func menubarFlameImage(tint: NSColor?) -> NSImage? {
let config = NSImage.SymbolConfiguration(pointSize: menubarTitleFontSize, weight: .medium)
private static func menubarFlameImage(
tint: NSColor?,
pointSize: CGFloat = menubarTitleFontSize
) -> NSImage? {
let config = NSImage.SymbolConfiguration(pointSize: pointSize, weight: .medium)
guard let symbol = NSImage(systemSymbolName: "flame.fill", accessibilityDescription: "CodeBurn")?
.withSymbolConfiguration(config) else { return nil }
guard let tint else {
@ -1265,6 +1272,35 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
return recolored
}
/// Typography for one rendering of the status-item title. `singleRow` holds
/// the historical constants, so the off state of the second-row setting
/// produces exactly the string this app has always rendered.
private struct MenubarTitleStyle {
let fontSize: CGFloat
let attachmentPointSize: CGFloat
let baselineOffset: CGFloat
let attachmentVerticalOffset: CGFloat
static let singleRow = MenubarTitleStyle(
fontSize: menubarTitleFontSize,
attachmentPointSize: menubarTitleFontSize,
baselineOffset: -1.0,
attachmentVerticalOffset: -3
)
static let twoRow = MenubarTitleStyle(
fontSize: MenubarRowTypography.twoRowFontSize,
attachmentPointSize: MenubarRowTypography.twoRowAttachmentPointSize,
baselineOffset: MenubarRowTypography.twoRowBaselineOffset,
attachmentVerticalOffset: MenubarRowTypography.twoRowAttachmentVerticalOffset
)
}
/// The button cell's single-line state as AppKit handed it to us, captured
/// before the two-row path ever touches it so turning the second row back
/// off restores the original rendering rather than a guessed default.
private var defaultTitleUsesSingleLineMode: Bool?
private var defaultTitleWraps: Bool?
private func refreshStatusButton() {
guard let button = statusItem.button else { return }
// Skip while the popover is anchored to this button. Rewriting the
@ -1279,7 +1315,55 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
button.image = nil
button.imagePosition = .noImage
let font = NSFont.monospacedDigitSystemFont(ofSize: menubarTitleFontSize, weight: .regular)
// nil whenever the setting is off or the chosen metric has no data, in
// which case the title falls back to the single-row composition.
let secondRow = MenubarRowFormatter.secondRow(
settings: store.menubarRowSettings,
snapshot: store.menubarRowSnapshot
)
applyTitleLineMode(to: button, multiline: secondRow != nil)
button.attributedTitle = composeStatusTitle(
style: secondRow == nil ? .singleRow : .twoRow,
secondRow: secondRow
)
let menubarPeriod = store.menubarPeriod
if let shortfall = store.menubarBadgeDeviceShortfall {
button.toolTip = "CodeBurn \(menubarPeriod.menubarMetricLabel) · \(shortfall.reachable) of \(shortfall.total) devices reporting"
} else {
button.toolTip = "CodeBurn \(menubarPeriod.menubarMetricLabel)"
}
persistBadgeStatusFile()
}
/// A multi-line attributed title only renders once the cell stops forcing a
/// single line. Both states are applied explicitly so toggling the setting
/// at runtime never leaves the cell in the other mode.
private func applyTitleLineMode(to button: NSStatusBarButton, multiline: Bool) {
guard let cell = button.cell else { return }
if defaultTitleUsesSingleLineMode == nil {
defaultTitleUsesSingleLineMode = cell.usesSingleLineMode
defaultTitleWraps = cell.wraps
}
if multiline {
cell.usesSingleLineMode = false
cell.wraps = true
} else {
cell.usesSingleLineMode = defaultTitleUsesSingleLineMode ?? false
cell.wraps = defaultTitleWraps ?? false
}
}
/// Composes the status-item title. With `secondRow` nil this is the original
/// single-row string, byte for byte; with a second row it renders the same
/// first line at the two-row point size and appends the extra line under a
/// paragraph style that clamps both lines into the menu bar's height.
private func composeStatusTitle(
style: MenubarTitleStyle,
secondRow: String?
) -> NSAttributedString {
let font = NSFont.monospacedDigitSystemFont(ofSize: style.fontSize, weight: .regular)
// Tint the flame based on the worst-affected connected provider's quota.
// Normal (<70%) keeps the template (auto white-on-dark / black-on-light);
// warning/critical/danger override with a fixed palette color so the
@ -1289,12 +1373,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
if tint == nil, store.isOverDailyBudget {
tint = NSColor.systemYellow
}
let flame = Self.menubarFlameImage(tint: tint)
let flame = Self.menubarFlameImage(tint: tint, pointSize: style.attachmentPointSize)
let attachment = NSTextAttachment()
attachment.image = flame
if let size = flame?.size {
attachment.bounds = CGRect(x: 0, y: -3, width: size.width, height: size.height)
attachment.bounds = CGRect(
x: 0,
y: style.attachmentVerticalOffset,
width: size.width,
height: size.height
)
}
let menubarPeriod = store.menubarPeriod
@ -1334,7 +1423,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
: " " + (cost?.asCompactCurrency() ?? fallback) + suffix
}
var textAttrs: [NSAttributedString.Key: Any] = [.font: font, .baselineOffset: -1.0]
var textAttrs: [NSAttributedString.Key: Any] = [.font: font, .baselineOffset: style.baselineOffset]
if !hasPayload {
textAttrs[.foregroundColor] = NSColor.secondaryLabelColor
}
@ -1347,21 +1436,38 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM
let marker = " · \(shortfall.reachable)/\(shortfall.total)"
let markerAttrs: [NSAttributedString.Key: Any] = [
.font: font,
.baselineOffset: -1.0,
.baselineOffset: style.baselineOffset,
.foregroundColor: NSColor.secondaryLabelColor,
]
composed.append(NSAttributedString(string: marker, attributes: markerAttrs))
}
}
button.attributedTitle = composed
if let shortfall = store.menubarBadgeDeviceShortfall {
button.toolTip = "CodeBurn \(menubarPeriod.menubarMetricLabel) · \(shortfall.reachable) of \(shortfall.total) devices reporting"
} else {
button.toolTip = "CodeBurn \(menubarPeriod.menubarMetricLabel)"
}
guard let secondRow else { return composed }
persistBadgeStatusFile()
var secondRowAttrs: [NSAttributedString.Key: Any] = [.font: font]
if style.baselineOffset != 0 {
secondRowAttrs[.baselineOffset] = style.baselineOffset
}
composed.append(NSAttributedString(string: "\n" + secondRow, attributes: secondRowAttrs))
// Centre both lines against each other and clamp their height: the
// status item is only as tall as the menu bar, and an unclamped 9pt
// line box (with its natural leading) pushes the pair past 22pt, which
// AppKit resolves by clipping the second line away.
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
paragraph.lineBreakMode = .byClipping
paragraph.lineSpacing = 0
paragraph.paragraphSpacing = 0
paragraph.minimumLineHeight = MenubarRowTypography.twoRowLineHeight
paragraph.maximumLineHeight = MenubarRowTypography.twoRowLineHeight
composed.addAttribute(
.paragraphStyle,
value: paragraph,
range: NSRange(location: 0, length: composed.length)
)
return composed
}
private var lastWrittenBadgeGenerated: String?

View file

@ -0,0 +1,246 @@
import Foundation
import CoreGraphics
/// What the optional second menu-bar row shows. Every case is a figure the app
/// already computes for the popover — the second row only re-renders it, so no
/// case can introduce a new fetch or a new refresh cadence.
enum MenubarSecondRowMetric: String, CaseIterable, Identifiable, Sendable {
/// Quota remaining plus reset countdown for the primary connected provider.
case quotaRemaining
/// Today's all-provider cost.
case todayCost
/// Today's all-provider input + output tokens.
case todayTokens
/// Sessions the CLI reported as live in its liveness window.
case activeSessions
var id: String { rawValue }
/// Settings picker label.
var settingsLabel: String {
switch self {
case .quotaRemaining: "Quota remaining"
case .todayCost: "Today's cost"
case .todayTokens: "Today's tokens"
case .activeSessions: "Active sessions"
}
}
}
/// The persisted row configuration. The first row is never configurable here:
/// it stays the existing Metric/Period/Scope badge, so an off setting leaves
/// the historical single-row title untouched.
struct MenubarRowSettings: Equatable, Sendable {
var isSecondRowEnabled: Bool
var secondRowMetric: MenubarSecondRowMetric
static let `default` = MenubarRowSettings(
isSecondRowEnabled: false,
secondRowMetric: .quotaRemaining
)
init(
isSecondRowEnabled: Bool = false,
secondRowMetric: MenubarSecondRowMetric = .quotaRemaining
) {
self.isSecondRowEnabled = isSecondRowEnabled
self.secondRowMetric = secondRowMetric
}
}
/// UserDefaults storage for the row settings, in the same shape as the other
/// menubar preferences (`CodeBurnMenubarPeriod`, `CodeBurnMenubarScope`,
/// `CodeBurnDisplayMetric`): a string-keyed value in the app's own domain, read
/// through a small loader so an unknown stored value degrades to the default
/// rather than failing.
enum MenubarRowPreferences {
static let secondRowEnabledKey = "CodeBurnMenubarSecondRowEnabled"
static let secondRowMetricKey = "CodeBurnMenubarSecondRowMetric"
static func load(defaults: UserDefaults = .standard) -> MenubarRowSettings {
MenubarRowSettings(
isSecondRowEnabled: defaults.bool(forKey: secondRowEnabledKey),
secondRowMetric: defaults.string(forKey: secondRowMetricKey)
.flatMap(MenubarSecondRowMetric.init(rawValue:))
?? MenubarRowSettings.default.secondRowMetric
)
}
static func setSecondRowEnabled(_ enabled: Bool, defaults: UserDefaults = .standard) {
defaults.set(enabled, forKey: secondRowEnabledKey)
}
static func setSecondRowMetric(
_ metric: MenubarSecondRowMetric,
defaults: UserDefaults = .standard
) {
defaults.set(metric.rawValue, forKey: secondRowMetricKey)
}
}
/// One connected provider's headline quota window, reduced to plain values so
/// the row selection and formatting stay testable without an AppStore.
struct MenubarQuotaCandidate: Equatable, Sendable {
let label: String
/// Fraction of the window consumed, 0...1.
let percentUsed: Double
let resetsAt: Date?
}
enum MenubarQuotaRowSelection {
/// The "primary" connected provider for the second row: the one nearest its
/// limit, which is the same provider the menu-bar flame already tints for.
/// Ties break on label so the row does not flip between equal providers
/// from one refresh to the next.
static func primary(from candidates: [MenubarQuotaCandidate]) -> MenubarQuotaCandidate? {
candidates
.sorted { lhs, rhs in
if lhs.percentUsed != rhs.percentUsed { return lhs.percentUsed > rhs.percentUsed }
return lhs.label < rhs.label
}
.first
}
}
/// Everything the second row can read, captured as plain values. A nil field
/// means "no data" for that metric and makes the row degrade to one line; it
/// never renders as a zero.
struct MenubarRowSnapshot: Equatable, Sendable {
var quota: MenubarQuotaCandidate?
var todayCost: Double?
var todayTotalTokens: Int?
/// Nil when the payload carries no live-session block at all (a CLI that
/// predates it), which is unknown rather than "nothing running".
var activeSessionCount: Int?
var currencySymbol: String
var currencyRate: Double
init(
quota: MenubarQuotaCandidate? = nil,
todayCost: Double? = nil,
todayTotalTokens: Int? = nil,
activeSessionCount: Int? = nil,
currencySymbol: String = "$",
currencyRate: Double = 1
) {
self.quota = quota
self.todayCost = todayCost
self.todayTotalTokens = todayTotalTokens
self.activeSessionCount = activeSessionCount
self.currencySymbol = currencySymbol
self.currencyRate = currencyRate
}
}
/// Pure composition of the menu-bar rows. Returns one string when the second
/// row is off or its metric has no data, two when it has something to say.
enum MenubarRowFormatter {
static func rows(
firstRow: String,
settings: MenubarRowSettings,
snapshot: MenubarRowSnapshot,
now: Date = Date()
) -> [String] {
guard let second = secondRow(settings: settings, snapshot: snapshot, now: now) else {
return [firstRow]
}
return [firstRow, second]
}
/// The second row's text, or nil when the setting is off or the chosen
/// metric has no data yet.
static func secondRow(
settings: MenubarRowSettings,
snapshot: MenubarRowSnapshot,
now: Date = Date()
) -> String? {
guard settings.isSecondRowEnabled else { return nil }
switch settings.secondRowMetric {
case .quotaRemaining:
return quotaRow(snapshot.quota, now: now)
case .todayCost:
guard let cost = snapshot.todayCost, cost.isFinite else { return nil }
let converted = cost * snapshot.currencyRate
return String(format: "\(snapshot.currencySymbol)%.2f today", converted)
case .todayTokens:
guard let tokens = snapshot.todayTotalTokens else { return nil }
return "\(compactTokens(Double(tokens))) tok today"
case .activeSessions:
guard let count = snapshot.activeSessionCount else { return nil }
// Live sessions are identity-derived, so the exact phrasing applies.
return SessionCountLabel.compact(sessions: count, basis: "identity")
}
}
/// "Claude 42% left · 3h 12m". The countdown is dropped when the provider
/// reports no reset instant; the whole row is dropped when there is no
/// usable percentage.
private static func quotaRow(_ quota: MenubarQuotaCandidate?, now: Date) -> String? {
guard let quota, quota.percentUsed.isFinite else { return nil }
let remaining = min(max(1 - quota.percentUsed, 0), 1)
let percent = Int((remaining * 100).rounded())
var row = quota.label.isEmpty ? "\(percent)% left" : "\(quota.label) \(percent)% left"
if let countdown = resetCountdown(quota.resetsAt, now: now) {
row += " · \(countdown)"
}
return row
}
/// Same shape as the popover's quota rows (`QuotaSummary.Window.resetsInLabel`),
/// with an injectable clock so the row is testable.
static func resetCountdown(_ resetsAt: Date?, now: Date) -> String? {
guard let resetsAt else { return nil }
let seconds = max(0, resetsAt.timeIntervalSince(now))
if seconds < 60 { return "now" }
let minutes = Int(seconds / 60)
let hours = minutes / 60
let days = hours / 24
if days > 0 { return "\(days)d \(hours % 24)h" }
if hours > 0 { return "\(hours)h \(minutes % 60)m" }
return "\(minutes)m"
}
/// Menu-bar token shorthand, matching `Double.asCompactTokens()`. Kept here
/// so the formatter stays free of the main actor.
static func compactTokens(_ n: Double) -> String {
if n >= 1_000_000_000 { return String(format: "%.1fB", n / 1_000_000_000) }
if n >= 1_000_000 { return String(format: "%.1fM", n / 1_000_000) }
if n >= 1_000 { return String(format: "%.0fK", n / 1_000) }
return String(format: "%.0f", n)
}
}
/// Geometry for the two-line title. The menu bar is 22pt on every standard
/// display (`NSStatusBar.system.thickness`), so the two lines get 10pt each and
/// the remaining 2pt is the slack AppKit's button cell centres the block in.
///
/// The inline flame has to shrink too, and by more than the text does: a
/// paragraph style clamps *text* line height but not an attachment, so a flame
/// whose image is taller than the clamp drags line one — and the whole title —
/// past the menu bar. These numbers were measured with
/// `NSAttributedString.boundingRect` over every first-row and second-row
/// combination the app renders; all of them come out at exactly
/// `twoRowMeasuredHeight`. Raising the font size, the line height or the flame's
/// point size breaks that, so change them together and re-measure.
enum MenubarRowTypography {
/// The historical single-row text size, for reference in tests.
static let singleRowFontSize: CGFloat = 13
static let twoRowFontSize: CGFloat = 9
static let twoRowLineHeight: CGFloat = 10
static let standardMenuBarThickness: CGFloat = 22
static let twoRowBaselineOffset: CGFloat = 0
/// 8pt renders a 10pt-tall flame, which the -3pt offset seats inside the
/// clamped first line instead of pushing it taller.
static let twoRowAttachmentPointSize: CGFloat = 8
static let twoRowAttachmentVerticalOffset: CGFloat = -3
static var twoRowTextHeight: CGFloat { twoRowLineHeight * 2 }
/// The height AppKit actually lays the two rows out at.
static let twoRowMeasuredHeight: CGFloat = 20
/// True when both clamped lines fit inside a menu bar of this thickness.
static func fitsMenuBar(thickness: CGFloat = standardMenuBarThickness) -> Bool {
thickness > 0 && twoRowMeasuredHeight <= thickness
}
}

View file

@ -457,6 +457,26 @@ private struct GeneralSettingsTab: View {
}
}
.pickerStyle(.menu)
// Optional second menu-bar line. Off by default, so the status
// item keeps its existing single-row figure untouched.
Toggle("Second row", isOn: Binding(
get: { store.menubarSecondRowEnabled },
set: { store.menubarSecondRowEnabled = $0 }
))
if store.menubarSecondRowEnabled {
Picker("Second row shows", selection: Binding(
get: { store.menubarSecondRowMetric },
set: { store.menubarSecondRowMetric = $0 }
)) {
ForEach(MenubarSecondRowMetric.allCases) { metric in
Text(metric.settingsLabel).tag(metric)
}
}
.pickerStyle(.menu)
Text("Adds a smaller second line under the menubar figure. Quota remaining tracks whichever connected provider is nearest its limit. The line hides itself while the chosen metric has no data.")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
Picker("Accent", selection: Binding(
get: { store.accentPreset },
set: { store.accentPreset = $0 }