test(menubar): assert the en and zh-Hans catalogs cannot drift apart

A translation catalog rots in ways the compiler cannot see: a key added to a
view but not to zh-Hans shows English in a Chinese UI, a dropped key shows a
raw identifier, and a format specifier that disagrees between the tables is a
wrong number or a crash inside String(format:).

LocalizationCatalogTests reads both tables out of the resource bundle, the same
files L(_:) resolves at runtime, and asserts: the key sets are equal in both
directions; no value is blank; en repeats its key verbatim, which is what makes
the English fallback correct; argument specifiers match in count and order,
because String(format:) binds them positionally; literal `%%` counts match,
while allowing `%%` to move where Chinese word order demands it; no key is only
specifiers, which would leave a translator nothing to work with; and the shipped
localizations agree with L10n.supportedLocalizations, so Package.swift, the two
packaging scripts' CFBundleLocalizations and the Swift constant cannot drift.

Four cases then resolve representative presentation strings in both locales and
check that the English one equals what the presentation struct returns, which is
the link proving the struct reads the catalog rather than a stale hardcoded
string, and that a substituted product name survives translation.

The specifier test caught one bad key while being written: the Capacity Dock
connect button's accessibility label was `L("%@ %@", title, providerName)`,
which has no translatable content at all. It is plain interpolation now, and
both halves were already localized on their own.

CHANGELOG and mac/README document the user-visible part: the language follows
the system, overridable per app in System Settings, plus what adding a third
language requires.

Closes #1219
This commit is contained in:
ozymandiashh 2026-09-11 17:34:34 +03:00 • committed by iamtoruk
parent 9eebfda627
commit a03cc5ff3f
3 changed files with 269 additions and 0 deletions

View file

@ -6,6 +6,7 @@
- **CodeBurn tells you when OpenAI banks a limit reset on your Codex account.** These grants — the "banked" or "goodwill" resets that restore a rate-limit window early — are sometimes announced and sometimes not, and until now the only way to notice one was to go looking. The reset-credit inventory CodeBurn already reads on every Codex quota refresh is now compared against the previous reading: a credit seen for the first time posts one notification naming what was granted, when it landed and how many you have available to use. The first reading after connecting is a baseline, not news; a credit that disappears because you spent it says nothing; a failed fetch or a malformed payload is treated as no opinion rather than as an empty account, so reconnecting does not re-announce what you were already told; and the fired event is persisted next to the existing quota snapshots, so a relaunch does not repeat it. Settings → Notifications gains a switch for it, on by default. The count and the most recent grant also appear in the Codex Plan tab, in the agent-tab quota hover card, and as a `Limit resets · …` line in `codeburn quota` (text and `--format json`), worded identically on both sides. No new endpoint, no new polling loop and no new data source: this reads fields off a response already fetched on the existing cadence, per the rule #702/#724 established. CodeBurn never spends a credit — this is a notice only. (#725)
### Added (macOS)
- **The macOS menubar app speaks Simplified Chinese, and follows your system language to decide.** Every user-facing string in the popover, the Capacity Dock, the status-item menu, the update alerts and all of Settings now resolves through a `Localizable.strings` catalog shipped for `en` and `zh-Hans` with no third-party library: 533 keys, whose key *is* the English copy, so an untranslated string degrades to correct English rather than a visible identifier. AppKit picks the table from the user's preferred languages, and `CFBundleLocalizations` in both packaging scripts puts CodeBurn under System Settings > Language & Region so the language can be overridden for this app alone. Enum raw values that double as persistence or cache keys (`Period`, `MenubarScope`, `InsightMode`, `AccentPreset`, `ProviderFilter`) keep their raw value and gained a separate display label, so nothing a user has saved changes meaning. Three display-only date formatters that were pinned to `en_US_POSIX` with fixed patterns now follow the locale, and the calendar popover's weekday row comes from the locale's own symbols, so a Chinese UI reads `2026年9月` and `一 二 三` rather than `September 2026` and `Mo Tu We`. Provider, model and plan names, units, currency codes, shell commands and anything the `codeburn` CLI itself produces stay verbatim in every locale. Adding a language is now one more `.lproj`; a test fails the build if the two tables disagree on keys, leave a value blank, or disagree on format specifiers. This covers the menubar half of #1219 only, not the CLI output or the web dashboard. (#1219)
- **The menubar tells you when a vendor resets your quota early, and what that provider's early resets have looked like.** Vendors sometimes reset a usage window ahead of schedule as a goodwill gesture; CodeBurn showed the new percentage but never said it had happened, so the free capacity went unused. Two signals now catch it on the refresh lifecycle that already runs, with no new polling: a reset time that jumps to a new cycle while the stored one still had time to run, and usage emptying (a fall of at least 40 points landing at or under 10%) while the advertised reset time stands still. A system notification through the existing notifier names the provider, the window and the lead, worded for the signal that saw it ("Claude's weekly limit reset 18h early. You're back to 100%." when the cycle rolled over, "Claude cleared your weekly usage 18h before its reset. You're back to 100%." when the counter emptied but the reset time held), the Capacity Dock carries a band saying the same for twelve hours, and the quota hover card gains this Mac's own pattern from the 30 days of snapshots already on disk ("Last 3 weekly resets came ~18h early"), derived from the stored reset times with no network and no external feed. One goodwill reset is one notification per provider however many windows it empties, and a reset already announced is never announced again — after a relaunch, or when the vendor briefly serves the old cycle back. It stays silent on a normal scheduled reset, a plan change, clock or timestamp skew, a window appearing or disappearing between fetches, a window's first observation, a reconnect after a terminal failure or a fresh bootstrap, and a window whose length the adapter does not validate; a missing or malformed stored reading is no opinion rather than an event. Settings → General → Notifications turns the notification off, default on, and with it off the dock band still appears. Claude is the provider wired up today, because it is the one whose quota readings are persisted. (#725)
- **The Capacity Dock shows today's cache-read tokens and tells you whether each quota window will last to its reset.** The Today section gains a provider-scoped cache-read figure beside input, output and calls; a known zero prints as `0` while missing or incomplete historical accounting stays unknown rather than becoming a fabricated zero, and because cache reads were already priced into the burned figure this adds visibility without changing any total. Each quota window then gets one line under it: `Lasts until reset`, `Runs out in 2d 8h`, or — on windows of six hours or less, where one burst would make a linear ETA cry wolf — the pace stage the Plan tab uses (`On pace`, `40% in deficit`, `30% in reserve`). The same line appears under each bar in the agent-tab quota hover card. The projection runs against the window length the provider adapter reports, never a length guessed from the display label, so a monthly cycle whose label happens to read `Weekly` is still paced against its month; it stays silent early in a window, on an exhausted window, without a reset time or a validated duration, and on stale, disconnected or older-than-ten-minute data. Four quota windows move to a two-column grid so scope labels, reset times and captions stay readable, and the dock reserves the caption's height whether or not a column has one so the bubble cannot resize under the pointer. Status snapshot revision 7 invalidates older cached payloads without purging daily history, and no extra polling is introduced. (#1267)
- **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)

View file

@ -8,6 +8,26 @@ Native Swift + SwiftUI menubar app. The codeburn menubar surface.
- Swift 6.0+ toolchain (bundled with Xcode 16 or standalone)
- `codeburn` CLI installed globally (`npm install -g codeburn`)
## Language
The app ships English and Simplified Chinese (`zh-Hans`) and follows your system
language: no setting inside CodeBurn, because macOS already owns this choice. To
use a different language for CodeBurn than for the rest of the system, open
System Settings > General > Language & Region, scroll to Applications, and add
CodeBurn Menubar there.
Strings live in `Sources/CodeBurnMenubar/Resources/<locale>.lproj/Localizable.strings`
and are reached through `L(_:)` / `L(_:_:)` (see `Localization.swift`). The key
*is* the English copy, so an untranslated string shows correct English rather
than an identifier, and `en.lproj` is an identity table.
To add a language, copy `en.lproj` to `<locale>.lproj`, translate the values,
then add the locale in three places that must stay in step: `.process` in
`Package.swift`, `CFBundleLocalizations` in both `Scripts/package-app.sh` and
`Scripts/build-local.sh`, and `L10n.supportedLocalizations`.
`LocalizationCatalogTests` fails if they disagree, if a key is missing from
either table, if a value is blank, or if the format specifiers do not match.
## Install (end users)
One command:
@ -82,6 +102,9 @@ mac/
├── Sources/CodeBurnMenubar/
│ ├── CodeBurnApp.swift @main + MenuBarExtra scene
│ ├── AppStore.swift @Observable store + enums
│ ├── Localization.swift L(_:) lookups against the module bundle
│ ├── Resources/en.lproj/ Localizable.strings (identity table)
│ ├── Resources/zh-Hans.lproj/ Localizable.strings (简体中文)
│ ├── Data/MenubarPayload.swift Codable payload types + placeholder
│ ├── Theme/Theme.swift Design tokens (warm terracotta palette)
│ └── Views/MenuBarContent.swift Popover layout + footer action bar

View file

@ -0,0 +1,245 @@
import Foundation
import Testing
@testable import CodeBurnMenubar
/// Guards the `Localizable.strings` catalogs (#1219).
///
/// A translation catalog rots silently: a key added to a view but not to
/// `zh-Hans` shows English in a Chinese UI, a dropped key shows a raw
/// identifier, and a format specifier that disagrees between the two tables is
/// a wrong number or a crash inside `String(format:)` — none of which the
/// compiler can see. These tests are the only thing standing between a new
/// string and that class of bug.
@Suite("Localization catalogs")
struct LocalizationCatalogTests {
// MARK: - Loading
/// Reads one locale's table straight out of the resource bundle: the same
/// file `L(_:)` resolves at runtime.
static func table(_ localization: String) throws -> [String: String] {
let path = L10n.bundle.path(
forResource: L10n.table,
ofType: "strings",
inDirectory: nil,
forLocalization: localization
)
let resolved = try #require(
path,
"no Localizable.strings for this localization; is Resources/<locale>.lproj declared in Package.swift?"
)
let parsed = NSDictionary(contentsOfFile: resolved) as? [String: String]
return try #require(
parsed,
"table is not a string/string plist — usually a stray quote or a missing semicolon"
)
}
/// Specifier occurrences in order, `%%` included.
static func specifiers(in value: String) -> [String] {
var found: [String] = []
var rest = Substring(value)
while let percent = rest.firstIndex(of: "%") {
var cursor = rest.index(after: percent)
guard cursor < rest.endIndex else { break }
if rest[cursor] == "%" {
found.append("%%")
rest = rest[rest.index(after: cursor)...]
continue
}
// Flags, width and precision, then any length modifier, then the verb.
var token = "%"
while cursor < rest.endIndex, "0123456789.+- #'".contains(rest[cursor]) {
token.append(rest[cursor])
cursor = rest.index(after: cursor)
}
while cursor < rest.endIndex, "lhqLzjt".contains(rest[cursor]) {
token.append(rest[cursor])
cursor = rest.index(after: cursor)
}
if cursor < rest.endIndex {
token.append(rest[cursor])
cursor = rest.index(after: cursor)
}
found.append(token)
rest = rest[cursor...]
}
return found
}
/// The specifiers that consume an argument. `String(format:)` binds these
/// positionally, so their order is part of the contract between locales.
static func arguments(in value: String) -> [String] {
specifiers(in: value).filter { $0 != "%%" }
}
static func literalPercentCount(in value: String) -> Int {
specifiers(in: value).filter { $0 == "%%" }.count
}
/// Formats `key` out of one locale's table, the way `L(_:_:)` does for
/// whichever locale AppKit picks at runtime.
static func localized(_ key: String, _ localization: String, _ arguments: CVarArg...) throws -> String {
let format = try #require(table(localization)[key], "missing key in this localization")
return String(format: format, arguments: arguments)
}
// MARK: - Coverage
@Test("every shipped localization has a table, and they agree with Package.swift")
func shippedLocalizationsMatchTheManifest() throws {
let declared = Set(L10n.supportedLocalizations.map { $0.lowercased() })
// NSBundle lowercases what it reports, so compare case-insensitively.
let onDisk = Set(L10n.bundle.localizations.map { $0.lowercased() })
#expect(
declared == onDisk,
"L10n.supportedLocalizations and the bundle disagree; Package.swift, both packaging scripts' CFBundleLocalizations, and L10n have to move together"
)
for localization in L10n.supportedLocalizations {
let entries = try Self.table(localization)
#expect(!entries.isEmpty)
}
}
@Test("en and zh-Hans cover exactly the same keys")
func keySetsMatch() throws {
let en = try Self.table("en")
let zh = try Self.table("zh-Hans")
let untranslated = Set(en.keys).subtracting(zh.keys).sorted()
#expect(
untranslated.isEmpty,
"these en keys have no zh-Hans entry: \(untranslated.prefix(10))"
)
let orphaned = Set(zh.keys).subtracting(en.keys).sorted()
#expect(
orphaned.isEmpty,
"these zh-Hans keys are not in en, so nothing ever reaches them: \(orphaned.prefix(10))"
)
}
@Test("no entry is blank in either locale")
func noEmptyValues() throws {
for localization in ["en", "zh-Hans"] {
let blank = try Self.table(localization)
.filter { $0.value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
.keys
.sorted()
#expect(blank.isEmpty, "blank values render as nothing at all: \(blank.prefix(10))")
}
}
@Test("en is an identity table, so a missing translation degrades to English")
func englishIsIdentity() throws {
let mismatched = try Self.table("en").filter { $0.key != $0.value }.keys.sorted()
#expect(
mismatched.isEmpty,
"en entries must repeat their key verbatim — L(_:) falls back to the key, so drift means two different English strings for one key: \(mismatched.prefix(10))"
)
}
// MARK: - Format specifiers
@Test("argument specifiers match in count and order across locales")
func argumentSpecifierParity() throws {
let en = try Self.table("en")
let zh = try Self.table("zh-Hans")
for key in en.keys.sorted() {
guard let english = en[key], let chinese = zh[key] else { continue }
let expected = Self.arguments(in: english)
let actual = Self.arguments(in: chinese)
#expect(
expected == actual,
"specifier mismatch for \(key.debugDescription): en \(expected) vs zh-Hans \(actual). String(format:) binds positionally, so a reorder or a dropped specifier is a wrong value or a crash."
)
}
}
@Test("literal percent signs survive translation")
func literalPercentParity() throws {
let en = try Self.table("en")
let zh = try Self.table("zh-Hans")
for key in en.keys.sorted() {
guard let english = en[key], let chinese = zh[key] else { continue }
// Unlike the argument specifiers above, `%%` may move: Chinese word
// order puts the time before the verb in "%@ · %@ 达到 100%%".
let expected = Self.literalPercentCount(in: english)
let actual = Self.literalPercentCount(in: chinese)
#expect(
expected == actual,
"\(key.debugDescription) has \(expected) literal percent sign(s) in en but \(actual) in zh-Hans"
)
}
}
@Test("a key is never only specifiers, which would leave nothing to translate")
func keysCarryContext() throws {
for key in try Self.table("en").keys {
let stripped = Self.specifiers(in: key)
.reduce(key) { $0.replacingOccurrences(of: $1, with: "") }
.trimmingCharacters(in: .whitespacesAndNewlines)
#expect(
!stripped.isEmpty,
"\(key.debugDescription) is only specifiers and spaces; a translator has no sentence to work with"
)
}
}
// MARK: - Representative presentation strings
@Test("session-count copy resolves in both locales")
func sessionCountResolves() throws {
let english = try Self.localized("%lld sessions", "en", 3)
let chinese = try Self.localized("%lld sessions", "zh-Hans", 3)
#expect(english == "3 sessions")
#expect(chinese == "3 个会话")
let lowerBound = try Self.localized("At least %lld sessions", "zh-Hans", 12)
#expect(lowerBound == "至少 12 个会话")
// The test process runs under en, so the presentation struct itself must
// agree with the en table. That is the link proving the struct reads the
// catalog rather than a stale hardcoded string.
#expect(SessionCountLabel.text(sessions: 3, basis: "identity") == english)
let unavailable = try Self.localized("Session count unavailable", "en")
#expect(SessionCountLabel.combinedText == unavailable)
}
@Test("provider reconnect copy resolves in both locales, keeping the product name")
func reconnectCopyResolves() throws {
let presentation = ProviderReconnectPresentation(provider: .claude)
let englishTitle = try Self.localized("Reconnect %@", "en", "Claude")
#expect(presentation.title == englishTitle)
let chineseTitle = try Self.localized("Reconnect %@", "zh-Hans", "Claude")
#expect(chineseTitle == "重新连接 Claude")
// Product names are never translated, and the substitution must carry through.
#expect(chineseTitle.contains("Claude"))
let chineseInstruction = try Self.localized(
"Open Claude Code in your terminal and type `/login`, then click Reconnect.",
"zh-Hans"
)
#expect(chineseInstruction.contains("Claude Code"))
#expect(chineseInstruction.contains("/login"))
}
@Test("percent-bearing quota copy formats correctly in both locales")
func quotaCopyResolves() throws {
let englishOverLimit = try Self.localized("%@ over limit (%lld%%)", "en", "Claude", 105)
#expect(englishOverLimit == "Claude over limit (105%)")
let chineseOverLimit = try Self.localized("%@ over limit (%lld%%)", "zh-Hans", "Claude", 105)
#expect(chineseOverLimit == "Claude 已超限(105%)")
let countdown = try Self.localized("%lldh %lldm", "zh-Hans", 2, 11)
#expect(countdown == "2 小时 11 分")
let cacheHit = try Self.localized("%@%% cache hit", "zh-Hans", "87")
#expect(cacheHit == "缓存命中 87%")
}
}