From 153df14ffac894b286e6e3d6b9c37e6a8dd09977 Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Sun, 13 Sep 2026 13:49:03 -0700 Subject: [PATCH] menubar: retire older instances at launch A second copy of the app stacks a second Capacity Dock on the screen edge. At launch the app now terminates instances of its own bundle identifier that launched strictly before it, so two simultaneous launches cannot quit each other, and forces out one that ignores the polite terminate after a few seconds. --- CHANGELOG.md | 1 + mac/Sources/CodeBurnMenubar/CodeBurnApp.swift | 1 + .../CodeBurnMenubar/SingleInstanceGuard.swift | 56 +++++++++++++++++++ .../SingleInstanceGuardTests.swift | 44 +++++++++++++++ 4 files changed, 102 insertions(+) create mode 100644 mac/Sources/CodeBurnMenubar/SingleInstanceGuard.swift create mode 100644 mac/Tests/CodeBurnMenubarTests/SingleInstanceGuardTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 49b59bbb..3730fb3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - **Kimi Code sessions now show up in the live-sessions block.** A Kimi session whose `agents/*/wire.jsonl` was written inside the liveness window is reported as `kimicode`, with its project, the model of its last request and the activity of its sub-agents folded in. ### Added (macOS) +- **Launching the menubar app replaces the copy already running instead of stacking a second Capacity Dock on the screen edge.** At launch it terminates only *strictly older* instances of its own bundle identifier, so two simultaneous launches cannot quit each other and leave none, and an older copy that ignores the polite quit is forced out a few seconds later. - **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: 628 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; Settings > General > Language overrides it for CodeBurn alone by writing `AppleLanguages` into the app's own preferences domain, which is the same key `CFBundleLocalizations` makes System Settings > Language & Region > Applications write, so the two surfaces are one setting rather than two. 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 short symbols clipped to two units, so a Chinese UI reads `2026年9月` and `周一 周二` while English keeps `Mo Tu We`. That locale move is the one place English output changes: `EEE MMM d` reads `Sat, Sep 12` in en_US and `Sat 12 Sep` in en_GB, and `MMM d` reads `12 Sep` in en_GB. 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, and a second test reads `mac/Sources` itself and fails when a user-facing literal never reaches the catalog at all — the drift a catalog-versus-catalog diff cannot see, because both tables stay in perfect agreement while a bare `Text("…")` ships English to a zh-Hans user. 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) diff --git a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift index ebd6a4e2..03fc965d 100644 --- a/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift +++ b/mac/Sources/CodeBurnMenubar/CodeBurnApp.swift @@ -130,6 +130,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate, NSM } func applicationDidFinishLaunching(_ notification: Notification) { + SingleInstanceGuard.retireOlderInstances() ProcessInfo.processInfo.automaticTerminationSupportEnabled = false ProcessInfo.processInfo.disableSuddenTermination() // Deliberately NO app-lifetime beginActivity here. A permanent diff --git a/mac/Sources/CodeBurnMenubar/SingleInstanceGuard.swift b/mac/Sources/CodeBurnMenubar/SingleInstanceGuard.swift new file mode 100644 index 00000000..02e20d05 --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/SingleInstanceGuard.swift @@ -0,0 +1,56 @@ +import AppKit + +/// Retires copies of the app that were already running when this one launched. +/// +/// A second copy is not a harmless duplicate the way a second text editor is: +/// the Capacity Dock is a window pinned to a screen edge, so a second instance +/// stacks a second dock on top of the first. A build in `.build`, a staged +/// release and `/Applications` are separate bundle paths, so the system starts +/// each as its own process rather than activating the one already up. +/// +/// The newcomer wins deliberately — quitting the *new* copy would be the wrong +/// way round while developing. Only *strictly* older instances are asked to go, +/// which is what keeps two simultaneous launches from terminating each other +/// and leaving none. +enum SingleInstanceGuard { + /// Grace period before an instance that ignored `terminate()` is killed. + private static let forceTerminateDelay: Duration = .seconds(3) + + static func pidsToTerminate( + running: [(pid: pid_t, launchDate: Date?)], + ownPID: pid_t, + ownLaunchDate: Date + ) -> [pid_t] { + running + .filter { $0.pid != ownPID && ($0.launchDate ?? .distantPast) < ownLaunchDate } + .map(\.pid) + } + + @MainActor + static func retireOlderInstances() { + guard let identifier = Bundle.main.bundleIdentifier else { return } + let running = NSRunningApplication.runningApplications(withBundleIdentifier: identifier) + let doomed = pidsToTerminate( + running: running.map { (pid: $0.processIdentifier, launchDate: $0.launchDate) }, + ownPID: ProcessInfo.processInfo.processIdentifier, + ownLaunchDate: NSRunningApplication.current.launchDate ?? Date() + ) + let victims = running.filter { doomed.contains($0.processIdentifier) } + guard !victims.isEmpty else { return } + + for victim in victims { + NSLog("CodeBurn: retiring older instance (pid %d)", victim.processIdentifier) + // A polite terminate lets the older copy tear its dock windows down + // and release its status item; forceTerminate is only for a copy + // that never answers. + if !victim.terminate() { victim.forceTerminate() } + } + Task { @MainActor in + try? await Task.sleep(for: forceTerminateDelay) + for victim in victims where !victim.isTerminated { + NSLog("CodeBurn: older instance (pid %d) ignored terminate - forcing", victim.processIdentifier) + victim.forceTerminate() + } + } + } +} diff --git a/mac/Tests/CodeBurnMenubarTests/SingleInstanceGuardTests.swift b/mac/Tests/CodeBurnMenubarTests/SingleInstanceGuardTests.swift new file mode 100644 index 00000000..781ff3db --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/SingleInstanceGuardTests.swift @@ -0,0 +1,44 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Single instance guard") +struct SingleInstanceGuardTests { + private let now = Date(timeIntervalSince1970: 1_000_000) + + @Test("strictly older instances are retired, same-age and newer ones are not") + func retiresOnlyOlder() { + let pids = SingleInstanceGuard.pidsToTerminate( + running: [ + (pid: 10, launchDate: now.addingTimeInterval(-60)), + (pid: 11, launchDate: now), + (pid: 12, launchDate: now.addingTimeInterval(60)), + // No launch date reported: treated as older, since a copy that + // predates ours is the only way to lose that field in practice. + (pid: 13, launchDate: nil), + (pid: 99, launchDate: now), + ], + ownPID: 99, + ownLaunchDate: now + ) + #expect(pids == [10, 13]) + } + + @Test("our own process is never retired, however its launch date reads") + func neverRetiresSelf() { + #expect( + SingleInstanceGuard.pidsToTerminate( + running: [(pid: 99, launchDate: now.addingTimeInterval(-60))], + ownPID: 99, + ownLaunchDate: now + ).isEmpty + ) + } + + @Test("two simultaneous launches cannot terminate each other") + func simultaneousLaunchesSurvive() { + let both: [(pid: pid_t, launchDate: Date?)] = [(pid: 1, launchDate: now), (pid: 2, launchDate: now)] + #expect(SingleInstanceGuard.pidsToTerminate(running: both, ownPID: 1, ownLaunchDate: now).isEmpty) + #expect(SingleInstanceGuard.pidsToTerminate(running: both, ownPID: 2, ownLaunchDate: now).isEmpty) + } +}