Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): macOS 菜单栏余量与用量面板 (#5805)

Chris Zhang0152a20edaf6
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index d7e740e641..880d0fe112 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -936,6 +936,8 @@ const MACOS_VOICE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
const MACOS_AGENT_ISLAND_HELPER_DEPLOYMENT_TARGET = 'macos14.0';
const MACOS_COMPUTER_PERMISSION_GUIDE_HELPER_DEPLOYMENT_TARGET = 'macos13.0';
const MACOS_SESSION_DRAG_RELEASE_HELPER_DEPLOYMENT_TARGET = 'macos10.15';
+// Swift Charts and the macOS 14 SwiftUI animation APIs.
+const MACOS_MENUBAR_HELPER_DEPLOYMENT_TARGET = 'macos14.0';
const MACOS_XBOX_GAMEPAD_HELPER_DEPLOYMENT_TARGET = 'macos11.0';
const MACOS_REMOTE_DESKTOP_INPUT_DEPLOYMENT_TARGET = 'macos10.15';
@@ -1627,6 +1629,39 @@ function buildMacSessionDragReleaseHelper(platform: ForgePlatform, arch: ForgeAr
);
}
+function buildMacMenubarHelper(platform: ForgePlatform, arch: ForgeArch): void {
+ if (process.platform !== 'darwin' || !isMacForgePlatform(platform)) return;
+ const srcDir = path.join(__dirname, 'native', 'menubar');
+ const src = path.join(srcDir, 'macos-menubar-helper.swift');
+ const destDir = path.join(__dirname, 'resources', 'tools', 'menubar');
+ const dest = path.join(destDir, 'xdt-macos-menubar-helper');
+ const assets = ['wordmark-light.png', 'wordmark-dark.png'];
+ if (!fs.existsSync(src)) {
+ throw new Error(`[forge] macOS menu bar helper source missing at ${src}`);
+ }
+ for (const asset of assets) {
+ if (!fs.existsSync(path.join(srcDir, asset))) {
+ throw new Error(`[forge] macOS menu bar helper asset missing: ${asset}`);
+ }
+ }
+ fs.mkdirSync(destDir, { recursive: true });
+ buildSwiftHelperForForgeArch(
+ src,
+ dest,
+ arch,
+ MACOS_MENUBAR_HELPER_DEPLOYMENT_TARGET,
+ // The helper uses @main, which requires library parsing mode.
+ ['-O', '-parse-as-library'],
+ 'menu bar helper',
+ );
+ for (const asset of assets) fs.copyFileSync(path.join(srcDir, asset), path.join(destDir, asset));
+ fs.chmodSync(dest, 0o755);
+ const sizeMb = (fs.statSync(dest).size / (1024 * 1024)).toFixed(2);
+ console.log(
+ `[forge:prePackage] macOS menu bar helper (${swiftArchLabel(arch, MACOS_MENUBAR_HELPER_DEPLOYMENT_TARGET)}) -> ${dest} (${sizeMb} MB)`,
+ );
+}
+
// MakerNSIS is Windows-only (native dependency), conditionally require to
// avoid import errors on macOS / Linux.
const makers: ForgeConfig['makers'] = [
@@ -1938,6 +1973,7 @@ const config: ForgeConfig = {
buildMacAgentIslandHelper(platform, arch);
buildMacComputerPermissionGuideHelper(platform, arch);
buildMacSessionDragReleaseHelper(platform, arch);
+ buildMacMenubarHelper(platform, arch);
buildRemoteDesktopInput(platform, arch);
},
// packaged dir 产出后、makers 跑之前签内部 .exe。这样 NSIS 包出来的
diff --git a/apps/desktop/native/menubar/macos-menubar-helper.swift b/apps/desktop/native/menubar/macos-menubar-helper.swift
new file mode 100644
index 0000000000..a9bcdafa56
--- /dev/null
+++ b/apps/desktop/native/menubar/macos-menubar-helper.swift
@@ -0,0 +1,2927 @@
+// Cindy menu bar quota helper (macOS).
+//
+// Main (TypeScript) owns data, product wording and settings; it sends a complete view
+// model as newline-delimited JSON on stdin. This process owns the NSStatusItem, the panel
+// window and the SwiftUI pages, and reports user intent back on stdout.
+//
+// Built with `-parse-as-library` so SwiftUI state behaves normally (the top-level script
+// mode used by the Agent Island helper drops `@State` initial values).
+
+import AppKit
+import Charts
+import Combine
+import SwiftUI
+
+// MARK: - Protocol
+
+struct MBSettings: Codable, Equatable {
+ var enabled: Bool
+ var order: [String]
+ var hidden: [String]
+ var shown: [String]
+ var statusText: String
+ var lowAlert: Bool
+ var privacy: Bool
+ var scope: String
+}
+
+struct MBCell: Decodable, Identifiable, Equatable {
+ let id: String
+ let kind: String
+ let logoSvg: String
+ let name: String
+ let value: String?
+ let valueUnit: String?
+ let valueLabel: String?
+ let level: String
+ let fill: Double?
+ let reserve: Bool
+ let emphasized: Bool
+ let when: String
+ let whenLevel: String
+ let accessibilityLabel: String
+}
+
+struct MBRing: Decodable, Equatable {
+ let fraction: Double
+ let color: String
+}
+
+struct MBFact: Decodable, Equatable, Hashable {
+ let label: String
+ let value: String
+ let sub: String
+}
+
+struct MBAction: Decodable, Equatable {
+ let kind: String
+ let providerId: String?
+}
+
+struct MBLegend: Decodable, Equatable, Hashable {
+ let label: String
+ let color: String
+}
+
+struct MBDetail: Decodable, Equatable {
+ let id: String
+ let logoSvg: String
+ let title: String
+ let plan: String
+ let rings: [MBRing]
+ let bigValue: String
+ let bigUnit: String?
+ let bigColor: String?
+ let bigCompact: Bool
+ let bigCaption: String
+ let legend: [MBLegend]
+ let sayPrimary: String
+ let saySecondary: String?
+ let facts: [MBFact]
+ let actionLabel: String
+ let action: MBAction
+}
+
+struct MBTask: Decodable, Identifiable, Equatable {
+ var id: String { sessionId }
+ let sessionId: String
+ let title: String
+ let harness: String
+ let logoSvg: String
+ let value: Double
+ let tokens: Double
+ let running: Bool
+ let startedAtMs: Double?
+ let idleStatus: String
+ let meta: String
+}
+
+struct MBModelUsage: Decodable, Equatable {
+ let name: String
+ let harness: String
+ let money: Double
+ let tokens: Double
+}
+
+struct MBDaily: Decodable, Equatable {
+ let money: [Double]
+ let paid: Double
+ let tokens: [Double]
+}
+
+struct MBScopeData: Decodable, Equatable {
+ let daily: [MBDaily]
+ let models: [String: [MBModelUsage]]
+ let note: String
+}
+
+struct MBUsage: Decodable, Equatable {
+ let days: [String]
+ let scopes: [String: MBScopeData]
+}
+
+struct MBManageRow: Decodable, Identifiable, Equatable {
+ let id: String
+ let logoSvg: String
+ let title: String
+ let subtitle: String
+ let value: String
+ let hidden: Bool
+}
+
+struct MBView: Decodable, Equatable {
+ let locale: String
+ let moneySymbol: String
+ let strings: [String: String]
+ let statusTextByMode: [String: String?]
+ let updatedAtMs: Double?
+ let headlinePrimary: String
+ let headlineSecondary: String?
+ let sources: [MBCell]
+ let details: [String: MBDetail]
+ let taskSummary: String
+ let tasks: [MBTask]
+ let usage: MBUsage
+ let manage: [MBManageRow]
+ let settings: MBSettings
+ /// "sign-in" until the user signs in or skips sign-in; nothing was read.
+ let gate: String?
+}
+
+struct MBIncoming: Decodable {
+ let type: String
+ let view: MBView?
+}
+
+enum Bridge {
+ private static let lock = NSLock()
+
+ static func emit(_ payload: [String: Any]) {
+ lock.lock()
+ defer { lock.unlock() }
+ guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else {
+ FileHandle.standardError.write(Data("menubar: could not encode event\n".utf8))
+ return
+ }
+ FileHandle.standardOutput.write(data)
+ FileHandle.standardOutput.write(Data([0x0a]))
+ }
+
+ static func emitSettings(_ patch: [String: Any]) {
+ emit(["type": "settings", "patch": patch])
+ }
+}
+
+// MARK: - Palette
+
+enum Palette {
+ private static func hex(_ value: UInt32, _ alpha: CGFloat = 1) -> NSColor {
+ NSColor(
+ srgbRed: CGFloat((value >> 16) & 0xFF) / 255,
+ green: CGFloat((value >> 8) & 0xFF) / 255,
+ blue: CGFloat(value & 0xFF) / 255,
+ alpha: alpha
+ )
+ }
+
+ private static func dynamic(_ light: NSColor, _ dark: NSColor) -> Color {
+ Color(nsColor: NSColor(name: nil) { appearance in
+ appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light
+ })
+ }
+
+ static let ink = dynamic(hex(0x0B0B0B), hex(0xF5F5F4))
+ static let ink2 = dynamic(NSColor(white: 0, alpha: 0.52), NSColor(white: 1, alpha: 0.58))
+ static let ink3 = dynamic(NSColor(white: 0, alpha: 0.32), NSColor(white: 1, alpha: 0.36))
+ static let ink4 = dynamic(NSColor(white: 0, alpha: 0.14), NSColor(white: 1, alpha: 0.16))
+ static let ink5 = dynamic(NSColor(white: 0, alpha: 0.06), NSColor(white: 1, alpha: 0.07))
+ static let line = dynamic(NSColor(white: 0, alpha: 0.08), NSColor(white: 1, alpha: 0.08))
+ static let tile = dynamic(NSColor(white: 1, alpha: 0.62), NSColor(white: 1, alpha: 0.06))
+ static let edge = dynamic(NSColor(white: 1, alpha: 0.75), NSColor(white: 1, alpha: 0.16))
+ static let fill = dynamic(hex(0x111111), hex(0xF5F5F4))
+ /// Text on an `ink` pill.
+ static let onInk = dynamic(hex(0xFFFFFF), hex(0x111111))
+ static let warn = Color(nsColor: hex(0xEA6B17))
+ static let error = Color(nsColor: hex(0xD91F37))
+ static let focus = Color(nsColor: hex(0x417CDD))
+ static let claude = Color(nsColor: hex(0xD97757))
+ static let claude2 = Color(nsColor: hex(0xE8A184))
+ static let claude3 = Color(nsColor: hex(0xF2C9B6))
+ static let codex = Color(nsColor: hex(0x7A9DFF))
+ static let pi = dynamic(hex(0x14B8A6), hex(0x2DD4BF))
+
+ static func named(_ name: String?) -> Color {
+ switch name {
+ case "ink2": return ink2
+ case "ink3": return ink3
+ case "fill": return fill
+ case "warn": return warn
+ case "error": return error
+ case "claude": return claude
+ case "claude2": return claude2
+ case "claude3": return claude3
+ case "codex": return codex
+ case "pi": return pi
+ default: return ink
+ }
+ }
+
+ static func level(_ level: String) -> Color? {
+ switch level {
+ case "warn": return warn
+ case "error": return error
+ default: return nil
+ }
+ }
+
+ static func harness(_ harness: String) -> Color {
+ switch harness {
+ case "claude-code": return claude
+ case "pi": return pi
+ default: return codex
+ }
+ }
+}
+
+/// The open/fill curve shared by tubes, rings, page slides and the panel width.
+enum Motion {
+ static let fill = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.5)
+ static let page = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.5)
+ static let quick = Animation.easeOut(duration: 0.2)
+}
+
+// MARK: - Formatting
+
+enum Fmt {
+ /// Currency symbol of the usage ledger ($ on Global, ¥ in mainland China); set by main.
+ @MainActor static var symbol = "$"
+
+ @MainActor static func money(_ value: Double) -> String {
+ if value >= 10_000 { return symbol + String(format: "%.1fk", value / 1000) }
+ if value >= 100 { return symbol + grouped(value.rounded()) }
+ return symbol + String(format: "%.2f", value)
+ }
+
+ static func tokens(_ value: Double) -> String {
+ let millions = value / 1_000_000
+ if millions >= 1000 { return String(format: "%.1fB", millions / 1000) }
+ if millions >= 1 { return "\(Int(millions.rounded()))M" }
+ if value >= 1000 { return "\(Int((value / 1000).rounded()))K" }
+ return "\(Int(max(0, value).rounded()))"
+ }
+
+ static func grouped(_ value: Double) -> String {
+ let formatter = NumberFormatter()
+ formatter.numberStyle = .decimal
+ formatter.locale = Locale(identifier: "en_US")
+ formatter.maximumFractionDigits = 0
+ return formatter.string(from: NSNumber(value: value)) ?? String(Int(value))
+ }
+
+ static func clock(_ seconds: Double) -> String {
+ let total = max(0, Int(seconds))
+ return "\(total / 60):" + String(format: "%02d", total % 60)
+ }
+
+ static func template(_ template: String, _ values: [String: String]) -> String {
+ var output = template
+ for (key, value) in values {
+ output = output.replacingOccurrences(of: "{{\(key)}}", with: value)
+ }
+ return output
+ }
+
+ private static var dayCache: [String: Date] = [:]
+
+ static func day(_ iso: String) -> Date {
+ if let cached = dayCache[iso] { return cached }
+ var components = DateComponents()
+ let parts = iso.split(separator: "-").compactMap { Int($0) }
+ if parts.count == 3 {
+ components.year = parts[0]
+ components.month = parts[1]
+ components.day = parts[2]
+ components.hour = 12
+ }
+ let date = Calendar.current.date(from: components) ?? Date()
+ dayCache[iso] = date
+ return date
+ }
+
+ static func monthDay(_ date: Date, locale: String) -> String {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: locale)
+ formatter.setLocalizedDateFormatFromTemplate("MMMd")
+ return formatter.string(from: date)
+ }
+
+ static func weekday(_ date: Date, locale: String) -> String {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: locale)
+ formatter.setLocalizedDateFormatFromTemplate("EEE")
+ return formatter.string(from: date)
+ }
+
+ static func clockTime(_ date: Date, locale: String) -> String {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: locale)
+ formatter.setLocalizedDateFormatFromTemplate("MMMd EEE HH:mm")
+ return formatter.string(from: date)
+ }
+}
+
+// MARK: - Logos
+
+enum Logos {
+ private static var cache: [String: NSImage] = [:]
+
+ /// Main sends this instead of the Cindy mark's long path; see `MENUBAR_CINDY_LOGO`.
+ static let cindySentinel = "cindy:mark"
+
+ static func image(_ svg: String) -> NSImage? {
+ if let cached = cache[svg] { return cached }
+ let source = svg == cindySentinel
+ ? "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"#000\" fill-rule=\"evenodd\" d=\"\(cindyMarkPath)\"/></svg>"
+ : svg
+ guard let data = source.data(using: .utf8), let image = NSImage(data: data) else { return nil }
+ image.isTemplate = true
+ cache[svg] = image
+ return image
+ }
+
+ /// Cindy "A" mark on an 18 pt canvas with 14 pt ink, the menu bar size from the brand kit.
+ /// The mark is fitted to 17pt of the 18pt canvas (its path bounds are x 2.4–21.5,
+ /// y 1.2–22 in a 24-unit box) so it matches the optical size of other menu bar extras.
+ static let statusIcon: NSImage? = {
+ let svg = """
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"><path fill="#000" fill-rule="evenodd" transform="translate(-0.765 -0.445) scale(0.8157)" d="\(cindyMarkPath)"/></svg>
+ """
+ guard let data = svg.data(using: .utf8), let image = NSImage(data: data) else { return nil }
+ image.isTemplate = true
+ image.size = NSSize(width: 18, height: 18)
+ image.accessibilityDescription = "Cindy"
+ return image
+ }()
+}
+
+struct LogoView: View {
+ let svg: String
+ var size: CGFloat = 13
+ var color: Color = Palette.ink
+
+ var body: some View {
+ if let image = Logos.image(svg) {
+ Image(nsImage: image)
+ .renderingMode(.template)
+ .resizable()
+ .interpolation(.high)
+ .aspectRatio(contentMode: .fit)
+ .frame(width: size, height: size)
+ .foregroundStyle(color)
+ } else {
+ Color.clear.frame(width: size, height: size)
+ }
+ }
+}
+
+// MARK: - Store
+
+enum Page: Equatable {
+ case main
+ case detail(String)
+ case wide
+ case manage
+}
+
+enum WideList: String {
+ case models
+ case tasks
+}
+
+@MainActor
+final class MenubarStore: ObservableObject {
+ @Published var view: MBView?
+ @Published var page: Page = .main
+ /// Bumped every time the panel opens; tubes and rings replay their fill from zero.
+ @Published var fillToken = 0
+ @Published var refreshing = false
+ @Published var wideRange = 30
+ @Published var wideMoney = true
+ @Published var wideScope = "all"
+ @Published var wideList: WideList = .models
+ /// Manage list order while the user drags, before main echoes the saved settings back.
+ @Published var draftOrder: [String]?
+ @Published var mainContentHeight: CGFloat = 0
+ /// Width of the narrow pages; follows the number of tubes so a few don't sit in a wide panel.
+ @Published var narrowWidth: CGFloat = StatusController.narrowWidth
+ /// Natural height of the open detail page; the panel grows to fit it when main is shorter.
+ @Published var detailContentHeight: CGFloat = 0
+ /// Natural height of the manage page; the panel takes it instead of the main page's height.
+ @Published var manageContentHeight: CGFloat = 0
+ @Published var shakeId: String?
+
+ var strings: [String: String] { view?.strings ?? [:] }
+
+ func s(_ key: String) -> String { strings[key] ?? key }
+
+ /// Fills `{{name}}` placeholders. A count in `n` picks the `_one` / `_other` variant when
+ /// main sent one, so languages with singular forms read naturally.
+ func s(_ key: String, _ values: [String: String]) -> String {
+ var resolved = key
+ if let n = values["n"], let count = Int(n) {
+ let variant = "\(key)_\(count == 1 ? "one" : "other")"
+ if strings[variant] != nil { resolved = variant }
+ }
+ return Fmt.template(s(resolved), values)
+ }
+
+ var locale: String { view?.locale ?? "en" }
+
+ func apply(_ next: MBView) {
+ let firstView = view == nil
+ Fmt.symbol = next.moneySymbol
+ view = next
+ if refreshing { refreshing = false }
+ if let draft = draftOrder, draft == next.settings.order || draftMatches(next) {
+ draftOrder = nil
+ }
+ if firstView { wideScope = next.settings.scope }
+ if case .detail(let id) = page, next.details[id] == nil { page = .main }
+ if next.gate != nil, page == .wide { page = .main }
+ let width = Self.narrowWidth(tubes: next.gate == nil ? next.sources.filter { $0.fill != nil }.count : 0)
+ if width != narrowWidth { narrowWidth = width }
+ }
+
+ /// Five or more tubes use the full 404pt; fewer give width back, down to 340pt, which still
+ /// fits the captions, task rows and the month card.
+ static func narrowWidth(tubes: Int) -> CGFloat {
+ switch tubes {
+ case ...2: return 340
+ case 3: return 356
+ case 4: return 380
+ default: return StatusController.narrowWidth
+ }
+ }
+
+ private func draftMatches(_ next: MBView) -> Bool {
+ guard let draft = draftOrder else { return false }
+ return next.manage.map(\.id) == draft
+ }
+
+ func go(_ next: Page) {
+ if next == .wide, let view { wideScope = view.settings.scope }
+ withAnimation(Motion.page) { page = next }
+ }
+
+ func refresh() {
+ guard !refreshing else { return }
+ refreshing = true
+ Bridge.emit(["type": "refresh"])
+ DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [weak self] in
+ self?.refreshing = false
+ }
+ }
+
+ var manageRows: [MBManageRow] {
+ guard let view else { return [] }
+ guard let draft = draftOrder else { return view.manage }
+ let byId = Dictionary(uniqueKeysWithValues: view.manage.map { ($0.id, $0) })
+ return draft.compactMap { byId[$0] }
+ }
+
+ /// Live reorder while dragging: the dragged row takes the slot of the row it enters, so
+ /// entering the next row down moves it down by one (and up likewise).
+ func move(_ id: String, into target: String) {
+ var order = manageRows.map(\.id)
+ guard let from = order.firstIndex(of: id), let to = order.firstIndex(of: target), from != to else { return }
+ order.remove(at: from)
+ order.insert(id, at: to)
+ withAnimation(.spring(response: 0.3, dampingFraction: 0.86)) { draftOrder = order }
+ }
+
+ func moveBy(_ id: String, offset: Int) {
+ var order = manageRows.map(\.id)
+ guard let from = order.firstIndex(of: id) else { return }
+ let to = from + offset
+ guard to >= 0, to < order.count else { return }
+ order.swapAt(from, to)
+ withAnimation(.spring(response: 0.3, dampingFraction: 0.86)) { draftOrder = order }
+ commitOrder()
+ }
+
+ func commitOrder() {
+ guard let draft = draftOrder else { return }
+ Bridge.emitSettings(["order": draft])
+ }
+
+ func toggleHidden(_ row: MBManageRow) {
+ guard let view else { return }
+ var hidden = Set(view.settings.hidden)
+ var shown = Set(view.settings.shown)
+ if row.hidden {
+ hidden.remove(row.id)
+ shown.insert(row.id)
+ } else {
+ let visibleCount = view.manage.filter { !$0.hidden }.count
+ if visibleCount <= 1 {
+ shakeId = row.id
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in self?.shakeId = nil }
+ return
+ }
+ hidden.insert(row.id)
+ shown.remove(row.id)
+ }
+ Bridge.emitSettings(["hidden": Array(hidden).sorted(), "shown": Array(shown).sorted()])
+ }
+}
+
+// MARK: - Panel window
+
+final class MenubarPanel: NSPanel {
+ override var canBecomeKey: Bool { true }
+ override var canBecomeMain: Bool { false }
+}
+
+/// Rounded, frosted backing for the panel. Uses the system popover material so the panel
+/// reads like other menu bar extras in both appearances.
+final class PanelBackgroundView: NSVisualEffectView {
+ static let radius: CGFloat = 26
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ material = .popover
+ blendingMode = .behindWindow
+ state = .active
+ maskImage = PanelBackgroundView.mask(radius: PanelBackgroundView.radius)
+ }
+
+ required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+
+ static func mask(radius: CGFloat) -> NSImage {
+ let edge = radius * 2 + 1
+ let image = NSImage(size: NSSize(width: edge, height: edge), flipped: false) { rect in
+ NSColor.black.setFill()
+ NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill()
+ return true
+ }
+ image.capInsets = NSEdgeInsets(top: radius, left: radius, bottom: radius, right: radius)
+ image.resizingMode = .stretch
+ return image
+ }
+}
+
+@MainActor
+final class StatusController: NSObject, NSWindowDelegate {
+ static let narrowWidth: CGFloat = 404
+ static let wideWidth: CGFloat = 820
+ private static let screenGap: CGFloat = 6
+ private static let sideMargin: CGFloat = 12
+
+ let store: MenubarStore
+ private let statusItem: NSStatusItem
+ private var panel: MenubarPanel?
+ private var hosting: NSHostingView<PanelRoot>?
+ private var outsideMonitor: Any?
+ private var keyMonitor: Any?
+ private var cancellables = Set<AnyCancellable>()
+ private(set) var isOpen = false
+ private var closing = false
+ private var openRetries = 0
+ /** True while the open animation runs; a frame set directly then would be overwritten. */
+ private var openAnimating = false
+ /** When a press on the status item closed the panel; that click's own action is then ignored. */
+ private var closedByStatusPressAt: TimeInterval?
+
+ init(store: MenubarStore) {
+ self.store = store
+ statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
+ super.init()
+ if let button = statusItem.button {
+ button.image = Logos.statusIcon
+ button.imagePosition = .imageLeading
+ button.target = self
+ button.action = #selector(toggle)
+ button.sendAction(on: [.leftMouseUp, .rightMouseUp])
+ button.setAccessibilityLabel("Cindy")
+ }
+ store.$view
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in self?.updateStatusTitle() }
+ .store(in: &cancellables)
+ store.$page
+ .removeDuplicates()
+ .receive(on: RunLoop.main)
+ .sink { [weak self] page in self?.layoutPanel(for: page, animated: true) }
+ .store(in: &cancellables)
+ store.$mainContentHeight
+ .removeDuplicates()
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in
+ guard let self, self.isOpen, self.store.page != .wide else { return }
+ self.layoutPanel(for: self.store.page, animated: false)
+ }
+ .store(in: &cancellables)
+ store.$narrowWidth
+ .removeDuplicates()
+ .dropFirst()
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in
+ guard let self, self.isOpen, self.store.page != .wide else { return }
+ self.layoutPanel(for: self.store.page, animated: true)
+ }
+ .store(in: &cancellables)
+ store.$manageContentHeight
+ .removeDuplicates()
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in
+ guard let self, self.isOpen, self.store.page == .manage else { return }
+ self.layoutPanel(for: .manage, animated: true)
+ }
+ .store(in: &cancellables)
+ store.$detailContentHeight
+ .removeDuplicates()
+ .receive(on: RunLoop.main)
+ .sink { [weak self] _ in
+ guard let self, self.isOpen, case .detail = self.store.page else { return }
+ self.layoutPanel(for: self.store.page, animated: true)
+ }
+ .store(in: &cancellables)
+ }
+
+ private func updateStatusTitle() {
+ guard let button = statusItem.button else { return }
+ let mode = store.view?.settings.statusText ?? "icon"
+ let text = (store.view?.statusTextByMode[mode] ?? nil) ?? ""
+ if text.isEmpty {
+ button.attributedTitle = NSAttributedString(string: "")
+ button.imagePosition = .imageOnly
+ } else {
+ button.imagePosition = .imageLeading
+ button.attributedTitle = NSAttributedString(
+ string: " " + text,
+ attributes: [
+ .font: NSFont.monospacedDigitSystemFont(ofSize: 12.5, weight: .semibold),
+ .baselineOffset: 0,
+ ]
+ )
+ }
+ if let view = store.view {
+ button.setAccessibilityLabel(text.isEmpty ? "Cindy" : "Cindy, \(text)")
+ button.toolTip = view.headlinePrimary
+ }
+ }
+
+ @objc func toggle() {
+ if let at = closedByStatusPressAt {
+ closedByStatusPressAt = nil
+ if ProcessInfo.processInfo.systemUptime - at < 0.6 { return }
+ }
+ isOpen ? close() : open()
+ }
+
+ func open() {
+ guard !isOpen else { return }
+ // Right after launch the status item may not be placed in the menu bar yet; its rect is
+ // then empty or off every screen. Wait a few runloop turns before falling back.
+ if statusAnchor() == nil && openRetries < 20 {
+ openRetries += 1
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in self?.open() }
+ return
+ }
+ openRetries = 0
+ isOpen = true
+ closing = false
+ let panel = ensurePanel()
+ store.page = .main
+ store.fillToken += 1
+ layoutPanel(for: .main, animated: false)
+ let target = panel.frame
+ panel.setFrame(target.offsetBy(dx: 0, dy: 6), display: false)
+ panel.alphaValue = 0
+ panel.makeKeyAndOrderFront(nil)
+ openAnimating = true
+ NSAnimationContext.runAnimationGroup({ context in
+ context.duration = 0.22
+ context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1, 0.36, 1)
+ panel.animator().alphaValue = 1
+ panel.animator().setFrame(target, display: true)
+ }, completionHandler: { [weak self] in
+ Task { @MainActor in
+ guard let self else { return }
+ self.openAnimating = false
+ // Opening asks main for fresh data, which often lands mid-animation and changes the
+ // content height; settle on the latest frame once the animation is done.
+ if self.isOpen { self.layoutPanel(for: self.store.page, animated: false) }
+ }
+ })
+ statusItem.button?.highlight(true)
+ installMonitors()
+ Bridge.emit(["type": "panel", "open": true])
+ }
+
+ func close() {
+ guard isOpen, let panel else { return }
+ isOpen = false
+ closing = true
+ removeMonitors()
+ statusItem.button?.highlight(false)
+ NSAnimationContext.runAnimationGroup({ context in
+ context.duration = 0.16
+ context.timingFunction = CAMediaTimingFunction(name: .easeIn)
+ panel.animator().alphaValue = 0
+ }, completionHandler: { [weak self] in
+ Task { @MainActor in
+ guard let self, self.closing else { return }
+ panel.orderOut(nil)
+ self.closing = false
+ self.store.page = .main
+ self.store.draftOrder = nil
+ }
+ })
+ Bridge.emit(["type": "panel", "open": false])
+ }
+
+ private func ensurePanel() -> MenubarPanel {
+ if let panel { return panel }
+ let panel = MenubarPanel(
+ contentRect: NSRect(x: 0, y: 0, width: Self.narrowWidth, height: 600),
+ styleMask: [.borderless, .nonactivatingPanel, .fullSizeContentView],
+ backing: .buffered,
+ defer: false
+ )
+ panel.isFloatingPanel = true
+ panel.level = .popUpMenu
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .transient, .ignoresCycle]
+ panel.isOpaque = false
+ panel.backgroundColor = .clear
+ panel.hasShadow = true
+ panel.hidesOnDeactivate = false
+ panel.isMovable = false
+ panel.animationBehavior = .none
+ panel.delegate = self
+
+ let background = PanelBackgroundView(frame: panel.contentLayoutRect)
+ background.autoresizingMask = [.width, .height]
+ let hosting = NSHostingView(rootView: PanelRoot(store: store, controller: self))
+ hosting.translatesAutoresizingMaskIntoConstraints = true
+ hosting.autoresizingMask = [.width, .height]
+ hosting.frame = background.bounds
+ hosting.sizingOptions = []
+ background.addSubview(hosting)
+ panel.contentView = background
+ self.hosting = hosting
+ self.panel = panel
+ return panel
+ }
+
+ /// Keeps the panel's right edge under the status item (inside the screen) and its top just
+ /// below the menu bar; the wide page grows to the left like the prototype.
+ /// The status button's rect on screen, or nil while the item is not placed yet.
+ private func statusAnchor() -> (rect: NSRect, screen: NSScreen)? {
+ guard let button = statusItem.button, let buttonWindow = button.window else { return nil }
+ let rect = buttonWindow.convertToScreen(button.convert(button.bounds, to: nil))
+ guard rect.width > 0, rect.height > 0 else { return nil }
+ let center = NSPoint(x: rect.midX, y: rect.midY)
+ guard let screen = NSScreen.screens.first(where: { $0.frame.contains(center) }) else { return nil }
+ return (rect, screen)
+ }
+
+ private func targetFrame(for page: Page) -> NSRect? {
+ let buttonRect: NSRect
+ let screen: NSScreen
+ if let anchor = statusAnchor() {
+ buttonRect = anchor.rect
+ screen = anchor.screen
+ } else {
+ // Not placed: anchor to the top-right of the main screen, where status items live.
+ guard let main = NSScreen.main ?? NSScreen.screens.first else { return nil }
+ screen = main
+ let frame = main.frame
+ buttonRect = NSRect(x: frame.maxX - store.narrowWidth / 2 - Self.sideMargin, y: main.visibleFrame.maxY, width: 0, height: 0)
+ }
+ let visible = screen.visibleFrame
+ let top = min(buttonRect.minY, visible.maxY) - Self.screenGap
+ let maxHeight = max(320, top - visible.minY - Self.sideMargin)
+ let wide = page == .wide
+ let width = min(wide ? Self.wideWidth : store.narrowWidth, visible.width - Self.sideMargin * 2)
+ let right = min(visible.maxX - Self.sideMargin, buttonRect.midX + store.narrowWidth / 2)
+ let x = max(visible.minX + Self.sideMargin, right - width)
+ let height: CGFloat
+ if wide {
+ height = min(maxHeight, 806)
+ } else {
+ var natural = store.mainContentHeight > 0 ? store.mainContentHeight : 640
+ if case .detail = page { natural = max(natural, store.detailContentHeight) }
+ if page == .manage, store.manageContentHeight > 0 { natural = store.manageContentHeight }
+ height = min(maxHeight, natural)
+ }
+ return NSRect(x: x, y: top - height, width: width, height: height)
+ }
+
+ func layoutPanel(for page: Page, animated: Bool) {
+ guard let panel, isOpen, let target = targetFrame(for: page) else { return }
+ if panel.frame.equalTo(target) { return }
+ if openAnimating {
+ // Retarget the running open animation instead of being overwritten by it.
+ NSAnimationContext.runAnimationGroup { context in
+ context.duration = 0.18
+ context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1, 0.36, 1)
+ panel.animator().setFrame(target, display: true)
+ }
+ return
+ }
+ let widthChanged = abs(panel.frame.width - target.width) > 0.5
+ let heightChanged = abs(panel.frame.height - target.height) > 0.5
+ if animated && (widthChanged || heightChanged) && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
+ NSAnimationContext.runAnimationGroup { context in
+ // Width changes slide with the page; a height-only change just settles the bottom edge.
+ context.duration = widthChanged ? 0.55 : 0.25
+ context.timingFunction = CAMediaTimingFunction(controlPoints: 0.22, 1, 0.36, 1)
+ context.allowsImplicitAnimation = true
+ panel.animator().setFrame(target, display: true)
+ }
+ } else {
+ panel.setFrame(target, display: true)
+ }
+ }
+
+ private func installMonitors() {
+ removeMonitors()
+ outsideMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] _ in
+ Task { @MainActor in
+ guard let self else { return }
+ // The menu bar reports a press on our own status item here too, and a quick tap may
+ // never reach the item's action. Close on the press and let `toggle` skip that click.
+ if self.statusAnchor()?.rect.contains(NSEvent.mouseLocation) == true {
+ guard self.isOpen else { return }
+ self.close()
+ self.closedByStatusPressAt = ProcessInfo.processInfo.systemUptime
+ return
+ }
+ self.close()
+ }
+ }
+ keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { [weak self] event in
+ guard let self, self.isOpen else { return event }
+ return self.handleKey(event) ? nil : event
+ }
+ }
+
+ private func removeMonitors() {
+ if let outsideMonitor { NSEvent.removeMonitor(outsideMonitor) }
+ if let keyMonitor { NSEvent.removeMonitor(keyMonitor) }
+ outsideMonitor = nil
+ keyMonitor = nil
+ }
+
+ private func handleKey(_ event: NSEvent) -> Bool {
+ let command = event.modifierFlags.contains(.command)
+ let key = event.charactersIgnoringModifiers?.lowercased() ?? ""
+ if event.keyCode == 53 {
+ if store.page == .main { close() } else { store.go(.main) }
+ return true
+ }
+ guard command else { return false }
+ switch key {
+ case "r":
+ store.refresh()
+ case "o":
+ openApp()
+ case ",":
+ store.go(.manage)
+ case "w":
+ close()
+ default:
+ return false
+ }
+ return true
+ }
+
+ func openApp() {
+ Bridge.emit(["type": "open-app"])
+ close()
+ }
+
+ func emitAndClose(_ payload: [String: Any]) {
+ Bridge.emit(payload)
+ close()
+ }
+
+ func windowDidResignKey(_ notification: Notification) {
+ // A press on our own status item takes focus first; its click then toggles the panel
+ // closed. Closing here too would let that click reopen it.
+ if let event = NSApp.currentEvent,
+ event.type == .leftMouseDown || event.type == .rightMouseDown,
+ let buttonWindow = statusItem.button?.window,
+ event.window === buttonWindow {
+ return
+ }
+ // Clicking another app: behave like a menu.
+ if isOpen { close() }
+ }
+
+ /// Preview mode only: open without a click so screenshots show the panel.
+ func openForPreview(page: Page) {
+ open()
+ store.page = page
+ layoutPanel(for: page, animated: false)
+ }
+}
+
+// MARK: - Root
+
+struct PanelRoot: View {
+ @ObservedObject var store: MenubarStore
+ let controller: StatusController
+
+ var body: some View {
+ ZStack(alignment: .topTrailing) {
+ if let view = store.view {
+ pages(view)
+ } else {
+ ProgressView().controlSize(.small).frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
+ .overlay(
+ RoundedRectangle(cornerRadius: PanelBackgroundView.radius, style: .circular)
+ .strokeBorder(Palette.edge, lineWidth: 0.5)
+ .allowsHitTesting(false)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: PanelBackgroundView.radius, style: .circular))
+ .foregroundStyle(Palette.ink)
+ .environment(\.locale, Locale(identifier: store.locale))
+ }
+
+ @ViewBuilder
+ private func pages(_ view: MBView) -> some View {
+ ZStack(alignment: .topTrailing) {
+ if store.page == .main, view.gate != nil {
+ GatePage(store: store, controller: controller)
+ .frame(width: store.narrowWidth)
+ .transition(.asymmetric(
+ insertion: .offset(x: -store.narrowWidth * 0.3).combined(with: .opacity),
+ removal: .offset(x: -store.narrowWidth * 0.3).combined(with: .opacity)
+ ))
+ } else if store.page == .main {
+ MainPage(store: store, view: view, controller: controller)
+ .frame(width: store.narrowWidth)
+ .transition(.asymmetric(
+ insertion: .offset(x: -store.narrowWidth * 0.3).combined(with: .opacity),
+ removal: .offset(x: -store.narrowWidth * 0.3).combined(with: .opacity)
+ ))
+ }
+ if case .detail(let id) = store.page, let detail = view.details[id] {
+ DetailPage(store: store, detail: detail, controller: controller)
+ .frame(width: store.narrowWidth)
+ .transition(.move(edge: .trailing).combined(with: .opacity))
+ }
+ if store.page == .manage {
+ ManagePage(store: store, view: view, controller: controller)
+ .frame(width: store.narrowWidth)
+ .transition(.move(edge: .trailing).combined(with: .opacity))
+ }
+ if store.page == .wide {
+ WidePage(store: store, view: view, controller: controller)
+ .frame(width: StatusController.wideWidth)
+ .transition(.move(edge: .trailing).combined(with: .opacity))
+ }
+ }
+ }
+}
+
+// MARK: - Shared pieces
+
+struct IconButton: View {
+ let systemName: String
+ let label: String
+ var help: String? = nil
+ var rotation: Double = 0
+ let action: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ Button(action: action) {
+ Image(systemName: systemName)
+ .font(.system(size: 13, weight: .medium))
+ .rotationEffect(.degrees(rotation))
+ .frame(width: 32, height: 32)
+ .foregroundStyle(hovering ? Palette.ink : Palette.ink2)
+ .background(Circle().fill(hovering ? Palette.ink5 : .clear))
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in withAnimation(Motion.quick) { self.hovering = hovering } }
+ .help(help ?? label)
+ .accessibilityLabel(label)
+ }
+}
+
+struct InkPillButton: View {
+ let title: String
+ var shortcut: String? = nil
+ var height: CGFloat = 34
+ var fullWidth = false
+ var disabled = false
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 8) {
+ Text(title).font(.system(size: 12.5, weight: .semibold))
+ if let shortcut {
+ Text(shortcut).font(.system(size: 12.5, weight: .medium)).opacity(0.55)
+ }
+ }
+ .padding(.horizontal, 16)
+ .frame(height: height)
+ .frame(maxWidth: fullWidth ? .infinity : nil)
+ .foregroundStyle(Palette.onInk)
+ .background(Capsule().fill(Palette.ink))
+ .contentShape(Capsule())
+ }
+ .buttonStyle(PressScaleStyle())
+ .disabled(disabled)
+ .opacity(disabled ? 0.4 : 1)
+ }
+}
+
+struct PressScaleStyle: ButtonStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label
+ .scaleEffect(configuration.isPressed ? 0.97 : 1)
+ .animation(.easeOut(duration: 0.12), value: configuration.isPressed)
+ }
+}
+
+struct Tile<Content: View>: View {
+ var radius: CGFloat = 20
+ @ViewBuilder let content: Content
+
+ var body: some View {
+ content
+ .background(RoundedRectangle(cornerRadius: radius, style: .circular).fill(Palette.tile))
+ .overlay(RoundedRectangle(cornerRadius: radius, style: .circular).strokeBorder(Palette.line, lineWidth: 0.5))
+ }
+}
+
+/// Fixed bar above or below a scroll area; shows a hairline only while content runs under it.
+struct EdgeLine: View {
+ let visible: Bool
+ var body: some View {
+ Rectangle().fill(Palette.line).frame(height: 0.5).opacity(visible ? 1 : 0)
+ .animation(Motion.quick, value: visible)
+ }
+}
+
+private struct ScrollOffsetKey: PreferenceKey {
+ static var defaultValue: CGFloat = 0
+ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = nextValue() }
+}
+
+private struct ContentHeightKey: PreferenceKey {
+ static var defaultValue: CGFloat = 0
+ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) }
+}
+
+/// Scroll view that reports how far it is scrolled and how tall its content is.
+struct TrackedScroll<Content: View>: View {
+ @Binding var offset: CGFloat
+ @Binding var contentHeight: CGFloat
+ @ViewBuilder let content: Content
+ private let space = UUID().uuidString
+
+ var body: some View {
+ GeometryReader { outer in
+ ScrollView(.vertical, showsIndicators: false) {
+ content
+ .background(GeometryReader { inner in
+ Color.clear
+ .preference(key: ScrollOffsetKey.self, value: -inner.frame(in: .named(space)).minY)
+ .preference(key: ContentHeightKey.self, value: inner.size.height)
+ })
+ }
+ .coordinateSpace(name: space)
+ .onPreferenceChange(ScrollOffsetKey.self) { offset = $0 }
+ .onPreferenceChange(ContentHeightKey.self) { contentHeight = $0 }
+ .frame(height: outer.size.height)
+ }
+ }
+}
+
+// MARK: - Tube
+
+struct TubeView: View {
+ let fill: Double?
+ let level: String
+ let reserve: Bool
+ let emphasized: Bool
+ let index: Int
+ let fillToken: Int
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var shown = true
+
+ private static let height: CGFloat = 116
+ private static let inset: CGFloat = 3
+ private static let outerRadius: CGFloat = 15
+
+ var body: some View {
+ let wellHeight = Self.height - Self.inset * 2
+ let fraction = max(0, min(1, fill ?? 0))
+ let liquid = fraction > 0 ? max(3, fraction * wellHeight) : 0
+ ZStack {
+ if fill == nil {
+ RoundedRectangle(cornerRadius: Self.outerRadius, style: .circular)
+ .strokeBorder(Palette.ink4, style: StrokeStyle(lineWidth: 1.5, dash: [4, 3]))
+ } else {
+ RoundedRectangle(cornerRadius: Self.outerRadius, style: .circular).fill(Palette.ink5)
+ if reserve {
+ HatchPattern()
+ .stroke(Palette.ink4, lineWidth: 2)
+ .clipShape(RoundedRectangle(cornerRadius: Self.outerRadius - Self.inset, style: .circular))
+ .padding(Self.inset)
+ }
+ // Liquid lives in a well inset 3pt on every side; the well's rounded bottom shapes low
+ // levels, so the liquid never touches the tube wall and the top stays flat.
+ VStack(spacing: 0) {
+ Spacer(minLength: 0)
+ Rectangle()
+ .fill(Palette.level(level) ?? Palette.fill)
+ .frame(height: liquid)
+ .scaleEffect(x: 1, y: shown ? 1 : 0.001, anchor: .bottom)
+ }
+ .clipShape(RoundedRectangle(cornerRadius: Self.outerRadius - Self.inset, style: .circular))
+ .padding(Self.inset)
+ .animation(Motion.fill, value: liquid)
+ RoundedRectangle(cornerRadius: Self.outerRadius, style: .circular)
+ .strokeBorder(emphasized ? Palette.ink : Palette.ink4, lineWidth: emphasized ? 1.5 : 0.5)
+ }
+ }
+ .frame(maxWidth: 46)
+ .frame(height: Self.height)
+ .onChange(of: fillToken) { replay() }
+ .onAppear { replay() }
+ }
+
+ private func replay() {
+ guard !reduceMotion else { shown = true; return }
+ var transaction = Transaction()
+ transaction.disablesAnimations = true
+ withTransaction(transaction) { shown = false }
+ DispatchQueue.main.async {
+ withAnimation(Motion.fill.delay(Double(index) * 0.025)) { shown = true }
+ }
+ }
+}
+
+struct HatchPattern: Shape {
+ func path(in rect: CGRect) -> Path {
+ var path = Path()
+ let step: CGFloat = 7
+ var x = -rect.height
+ while x < rect.width {
+ path.move(to: CGPoint(x: x, y: rect.maxY))
+ path.addLine(to: CGPoint(x: x + rect.height, y: rect.minY))
+ x += step
+ }
+ return path
+ }
+}
+
+// MARK: - Main page
+
+struct MainPage: View {
+ @ObservedObject var store: MenubarStore
+ let view: MBView
+ let controller: StatusController
+ @State private var offset: CGFloat = 0
+ @State private var contentHeight: CGFloat = 0
+ @State private var topHeight: CGFloat = 0
+ @State private var footHeight: CGFloat = 0
+ @State private var viewportHeight: CGFloat = 0
+
+ var body: some View {
+ VStack(spacing: 0) {
+ topBar
+ .background(GeometryReader { g in Color.clear.onAppear { topHeight = g.size.height }.onChange(of: g.size.height) { _, h in topHeight = h } })
+ EdgeLine(visible: offset > 2)
+ TrackedScroll(offset: $offset, contentHeight: $contentHeight) {
+ content
+ }
+ .background(GeometryReader { g in Color.clear.onAppear { viewportHeight = g.size.height }.onChange(of: g.size.height) { _, h in viewportHeight = h } })
+ EdgeLine(visible: offset + viewportHeight < contentHeight - 2)
+ foot
+ .background(GeometryReader { g in Color.clear.onAppear { footHeight = g.size.height }.onChange(of: g.size.height) { _, h in footHeight = h } })
+ }
+ .onChange(of: contentHeight) { report() }
+ .onChange(of: topHeight) { report() }
+ .onChange(of: footHeight) { report() }
+ }
+
+ private func report() {
+ guard contentHeight > 0 else { return }
+ let natural = (topHeight + contentHeight + footHeight + 1).rounded(.up)
+ if abs(store.mainContentHeight - natural) > 0.5 { store.mainContentHeight = natural }
+ }
+
+ private var topBar: some View {
+ HStack(spacing: 0) {
+ Wordmark().frame(height: 15)
+ TimelineView(.periodic(from: .now, by: 15)) { context in
+ Text(updatedText(now: context.date))
+ .font(.system(size: 11.5))
+ .foregroundStyle(Palette.ink3)
+ .padding(.leading, 10)
+ }
+ Spacer(minLength: 0)
+ RefreshButton(store: store)
+ }
+ .padding(EdgeInsets(top: 22, leading: 22, bottom: 10, trailing: 22))
+ }
+
+ private func updatedText(now: Date) -> String {
+ guard let updated = view.updatedAtMs else { return "" }
+ let seconds = max(0, now.timeIntervalSince1970 - updated / 1000)
+ if seconds < 60 { return store.s("updatedJustNow") }
+ if seconds < 3600 { return store.s("updatedMinutes", ["n": String(Int(seconds / 60))]) }
+ if seconds < 86400 { return store.s("updatedHours", ["n": String(Int(seconds / 3600))]) }
+ return store.s("updatedDays", ["n": String(Int(seconds / 86400))])
+ }
+
+ private var content: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Headline(primary: view.headlinePrimary, secondary: view.headlineSecondary)
+ .padding(EdgeInsets(top: 20, leading: 24, bottom: 2, trailing: 24))
+
+ // Only sources with a level get a tube; the rest (not read yet, pay-as-you-go) are
+ // listed as quiet rows so an empty tube never stands in for missing data.
+ let measured = view.sources.filter { $0.fill != nil }
+ let unmeasured = view.sources.filter { $0.fill == nil }
+ if !measured.isEmpty {
+ Cells(store: store, cells: measured)
+ .padding(.horizontal, 22)
+ .padding(.top, 22)
+ }
+ if !unmeasured.isEmpty {
+ UnmeasuredSources(store: store, cells: unmeasured)
+ .padding(.horizontal, 14)
+ .padding(.top, measured.isEmpty ? 18 : 8)
+ }
+
+ Caption(title: store.s("tasks"), detail: view.taskSummary) {
+ TaskTotal(tasks: view.tasks, tokenUnit: store.s("tokenUnit"), showsTokens: store.narrowWidth >= 380)
+ }
+ .padding(EdgeInsets(top: 28, leading: 24, bottom: 12, trailing: 24))
+
+ TaskList(store: store, tasks: view.tasks, controller: controller)
+ .padding(.horizontal, 14)
+
+ MonthCard(store: store, view: view)
+ .padding(EdgeInsets(top: 12, leading: 16, bottom: 14, trailing: 16))
+ }
+ }
+
+ private var foot: some View {
+ HStack(spacing: 6) {
+ InkPillButton(title: store.s("openApp"), shortcut: "⌘O") { controller.openApp() }
+ Spacer(minLength: 0)
+ IconButton(systemName: "gearshape", label: store.s("settings"), help: store.s("settings") + " ⌘,") {
+ store.go(.manage)
+ }
+ }
+ .padding(EdgeInsets(top: 12, leading: 18, bottom: 18, trailing: 18))
+ }
+}
+
+/// Shown before the user signs in or skips sign-in: nothing has been read, so there is
+/// nothing to show but the way in.
+struct GatePage: View {
+ @ObservedObject var store: MenubarStore
+ let controller: StatusController
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Wordmark().frame(height: 15)
+ .padding(EdgeInsets(top: 22, leading: 22, bottom: 0, trailing: 22))
+
+ Image(systemName: "person.crop.circle")
+ .font(.system(size: 30, weight: .regular))
+ .foregroundStyle(Palette.ink3)
+ .accessibilityHidden(true)
+ .padding(EdgeInsets(top: 30, leading: 24, bottom: 14, trailing: 24))
+
+ Text(store.s("gateTitle"))
+ .font(.system(size: 22, weight: .semibold))
+ .tracking(-0.4)
+ .fixedSize(horizontal: false, vertical: true)
+ .accessibilityAddTraits(.isHeader)
+ .padding(.horizontal, 24)
+
+ Text(store.s("gateBody"))
+ .font(.system(size: 13))
+ .lineSpacing(3)
+ .foregroundStyle(Palette.ink3)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(EdgeInsets(top: 8, leading: 24, bottom: 0, trailing: 24))
+
+ HStack(spacing: 6) {
+ InkPillButton(title: store.s("openApp"), shortcut: "⌘O") { controller.openApp() }
+ Spacer(minLength: 0)
+ IconButton(systemName: "gearshape", label: store.s("settings"), help: store.s("settings") + " ⌘,") {
+ store.go(.manage)
+ }
+ }
+ .padding(EdgeInsets(top: 26, leading: 18, bottom: 18, trailing: 18))
+ }
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .fixedSize(horizontal: false, vertical: true)
+ .background(GeometryReader { g in
+ Color.clear
+ .onAppear { report(g.size.height) }
+ .onChange(of: g.size.height) { _, h in report(h) }
+ })
+ .frame(maxHeight: .infinity, alignment: .top)
+ }
+
+ private func report(_ height: CGFloat) {
+ let natural = (height + 1).rounded(.up)
+ if natural > 0, abs(store.mainContentHeight - natural) > 0.5 { store.mainContentHeight = natural }
+ }
+}
+
+struct Wordmark: View {
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ if let image = WordmarkAsset.image(dark: colorScheme == .dark) {
+ Image(nsImage: image)
+ .resizable()
+ .interpolation(.high)
+ .aspectRatio(contentMode: .fit)
+ .accessibilityLabel("Cindy")
+ } else {
+ Text("Cindy").font(.system(size: 15, weight: .bold)).foregroundStyle(Palette.ink)
+ }
+ }
+}
+
+/// The wordmark keeps its red ">" and dot, so it is a full-color pair, not a template image.
+enum WordmarkAsset {
+ private static let dir: String = ProcessInfo.processInfo.environment["CINDY_MENUBAR_ASSET_DIR"]
+ ?? (CommandLine.arguments.first.map { ($0 as NSString).deletingLastPathComponent } ?? "")
+ private static let light = NSImage(contentsOfFile: (dir as NSString).appendingPathComponent("wordmark-light.png"))
+ private static let dark = NSImage(contentsOfFile: (dir as NSString).appendingPathComponent("wordmark-dark.png"))
+
+ static func image(dark isDark: Bool) -> NSImage? {
+ isDark ? (dark ?? light) : (light ?? dark)
+ }
+}
+
+struct RefreshButton: View {
+ @ObservedObject var store: MenubarStore
+ @State private var angle: Double = 0
+
+ var body: some View {
+ IconButton(systemName: "arrow.clockwise", label: store.s("refresh"), help: store.s("refresh") + " ⌘R", rotation: angle) {
+ store.refresh()
+ }
+ .onChange(of: store.refreshing) { _, refreshing in
+ guard refreshing else { return }
+ withAnimation(.timingCurve(0.4, 0.1, 0.3, 1, duration: 0.9)) { angle += 360 }
+ }
+ }
+}
+
+struct Headline: View {
+ let primary: String
+ let secondary: String?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 3) {
+ Text(primary)
+ .font(.system(size: 26, weight: .semibold))
+ .tracking(-0.6)
+ .lineSpacing(2)
+ if let secondary {
+ Text(secondary)
+ .font(.system(size: 20, weight: .semibold))
+ .tracking(-0.4)
+ .foregroundStyle(Palette.ink3)
+ }
+ }
+ .fixedSize(horizontal: false, vertical: true)
+ .accessibilityElement(children: .combine)
+ .accessibilityAddTraits(.isHeader)
+ }
+}
+
+struct Caption<Trailing: View>: View {
+ let title: String
+ let detail: String
+ @ViewBuilder let trailing: Trailing
+
+ var body: some View {
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(title).font(.system(size: 13, weight: .semibold)).tracking(-0.1)
+ Text(detail).font(.system(size: 12)).foregroundStyle(Palette.ink3).monospacedDigit().lineLimit(1)
+ Spacer(minLength: 4)
+ trailing
+ }
+ }
+}
+
+struct Cells: View {
+ @ObservedObject var store: MenubarStore
+ let cells: [MBCell]
+
+ var body: some View {
+ HStack(alignment: .top, spacing: cells.count > 6 ? 6 : 10) {
+ ForEach(Array(cells.enumerated()), id: \.element.id) { index, cell in
+ CellView(cell: cell, index: index, fillToken: store.fillToken) {
+ store.go(.detail(cell.id))
+ }
+ }
+ }
+ }
+}
+
+/// Sources without a level: logo, name and why there is no tube, opening the detail page.
+struct UnmeasuredSources: View {
+ @ObservedObject var store: MenubarStore
+ let cells: [MBCell]
+
+ var body: some View {
+ VStack(spacing: 2) {
+ ForEach(cells) { cell in
+ UnmeasuredRow(cell: cell) { store.go(.detail(cell.id)) }
+ }
+ }
+ }
+}
+
+struct UnmeasuredRow: View {
+ let cell: MBCell
+ let action: () -> Void
+ @State private var hovering = false
+
+ private var status: String {
+ [cell.valueLabel, cell.when]
+ .compactMap { $0 }
+ .filter { !$0.isEmpty && $0 != "—" }
+ .joined(separator: " · ")
+ }
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 10) {
+ LogoView(svg: cell.logoSvg, size: 13)
+ .frame(width: 26, height: 26)
+ .background(RoundedRectangle(cornerRadius: 8, style: .circular).fill(Palette.ink5))
+ Text(cell.name)
+ .font(.system(size: 13, weight: .semibold))
+ .tracking(-0.1)
+ .lineLimit(1)
+ Spacer(minLength: 8)
+ Text(status)
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .lineLimit(1)
+ Image(systemName: "chevron.right")
+ .font(.system(size: 10, weight: .semibold))
+ .foregroundStyle(Palette.ink4)
+ }
+ .padding(EdgeInsets(top: 6, leading: 10, bottom: 6, trailing: 12))
+ .background(RoundedRectangle(cornerRadius: 12, style: .circular).fill(hovering ? Palette.ink5 : .clear))
+ .contentShape(RoundedRectangle(cornerRadius: 12, style: .circular))
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in withAnimation(.easeOut(duration: 0.15)) { self.hovering = hovering } }
+ .accessibilityLabel(cell.accessibilityLabel)
+ }
+}
+
+struct CellView: View {
+ let cell: MBCell
+ let index: Int
+ let fillToken: Int
+ let action: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ Button(action: action) {
+ VStack(spacing: 9) {
+ valueLabel.frame(height: 20)
+ TubeView(
+ fill: cell.kind == "payg" ? nil : cell.fill,
+ level: cell.level,
+ reserve: cell.reserve,
+ emphasized: cell.emphasized,
+ index: index,
+ fillToken: fillToken
+ )
+ VStack(spacing: 5) {
+ LogoView(svg: cell.logoSvg, size: 13)
+ Text(cell.name)
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.ink2)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ }
+ Text(cell.when)
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(Palette.level(cell.whenLevel) ?? Palette.ink2)
+ .lineLimit(1)
+ .frame(height: 15)
+ .padding(.top, -4)
+ }
+ .padding(.top, 6)
+ .padding(.bottom, 4)
+ .frame(maxWidth: .infinity)
+ .contentShape(Rectangle())
+ .offset(y: hovering ? -3 : 0)
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in
+ withAnimation(.timingCurve(0.22, 1, 0.36, 1, duration: 0.25)) { self.hovering = hovering }
+ }
+ .accessibilityLabel(cell.accessibilityLabel)
+ }
+
+ @ViewBuilder
+ private var valueLabel: some View {
+ if let value = cell.value {
+ HStack(alignment: .firstTextBaseline, spacing: 1) {
+ Text(value)
+ .font(.system(size: cell.kind == "balance" ? 13 : 15, weight: .semibold))
+ .tracking(cell.kind == "balance" ? -0.2 : -0.3)
+ if let unit = cell.valueUnit {
+ Text(unit).font(.system(size: 10, weight: .semibold)).foregroundStyle(Palette.ink3)
+ }
+ }
+ .monospacedDigit()
+ .foregroundStyle(Palette.level(cell.level) ?? Palette.ink)
+ } else if let label = cell.valueLabel {
+ Text(label)
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(Palette.ink2)
+ .padding(.top, 3)
+ }
+ }
+}
+
+// MARK: - Tasks
+
+struct TaskTotal: View {
+ let tasks: [MBTask]
+ let tokenUnit: String
+ /// A narrow panel keeps just the money; each task row still shows its tokens.
+ var showsTokens = true
+
+ var body: some View {
+ let money = tasks.reduce(0) { $0 + $1.value }
+ let tokens = tasks.reduce(0) { $0 + $1.tokens }
+ (Text(Fmt.money(money)).foregroundColor(Palette.ink).fontWeight(.semibold)
+ + Text(showsTokens ? " · \(Fmt.tokens(tokens)) \(tokenUnit)" : ""))
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .monospacedDigit()
+ .lineLimit(1)
+ }
+}
+
+struct TaskList: View {
+ @ObservedObject var store: MenubarStore
+ let tasks: [MBTask]
+ let controller: StatusController
+
+ var body: some View {
+ let sorted = tasks.sorted { $0.value > $1.value }
+ let total = max(0.0001, sorted.reduce(0) { $0 + $1.value })
+ let top = Array(sorted.prefix(3))
+ let rest = Array(sorted.dropFirst(3))
+ VStack(spacing: 2) {
+ if sorted.isEmpty {
+ Text(store.s("noTasksToday"))
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ }
+ ForEach(top) { task in
+ TaskRow(store: store, task: task, share: task.value / total) {
+ controller.emitAndClose(["type": "open-session", "sessionId": task.sessionId])
+ }
+ }
+ if !rest.isEmpty {
+ MoreRow(
+ label: store.s("moreTasks", ["n": String(rest.count)]),
+ value: Fmt.money(rest.reduce(0) { $0 + $1.value })
+ ) {
+ store.wideList = .tasks
+ store.go(.wide)
+ }
+ .padding(.horizontal, 10)
+ }
+ }
+ }
+}
+
+struct TaskRow: View {
+ @ObservedObject var store: MenubarStore
+ let task: MBTask
+ let share: Double
+ let action: () -> Void
+ @State private var hovering = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ var body: some View {
+ Button(action: action) {
+ HStack(alignment: .center, spacing: 11) {
+ TaskIcon(svg: task.logoSvg, running: task.running)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(task.title)
+ .font(.system(size: 13, weight: .semibold))
+ .tracking(-0.1)
+ .lineLimit(1)
+ metaLine
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ VStack(alignment: .trailing, spacing: 1) {
+ Text(Fmt.money(task.value))
+ .font(.system(size: 15, weight: .semibold))
+ .tracking(-0.3)
+ Text("\(Int((share * 100).rounded()))%")
+ .font(.system(size: 10.5, weight: .medium))
+ .foregroundStyle(Palette.ink3)
+ }
+ .monospacedDigit()
+ }
+ .padding(EdgeInsets(top: 9, leading: 10, bottom: 11, trailing: 10))
+ .background(alignment: .bottomLeading) { shareBar }
+ .background(RoundedRectangle(cornerRadius: 16, style: .circular).fill(hovering ? Palette.ink5 : .clear))
+ .contentShape(RoundedRectangle(cornerRadius: 16, style: .circular))
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in withAnimation(.easeOut(duration: 0.15)) { self.hovering = hovering } }
+ .help(task.title)
+ .accessibilityLabel("\(task.title), \(Fmt.money(task.value))")
+ }
+
+ private var shareBar: some View {
+ GeometryReader { geometry in
+ let width = geometry.size.width - 55 - 10
+ ZStack(alignment: .leading) {
+ Capsule().fill(Palette.ink5)
+ Capsule().fill(Palette.ink3).frame(width: max(4, width * share))
+ }
+ .frame(width: max(0, width), height: 2)
+ .offset(x: 55, y: geometry.size.height - 4 - 2)
+ }
+ }
+
+ @ViewBuilder
+ private var metaLine: some View {
+ if task.running, let started = task.startedAtMs {
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ HStack(spacing: 0) {
+ BreathingDot(animate: !reduceMotion)
+ .padding(.trailing, 5)
+ Text(store.s("running") + " " + Fmt.clock(context.date.timeIntervalSince1970 - started / 1000))
+ .fontWeight(.semibold)
+ .foregroundStyle(Palette.ink2)
+ Text(" · " + task.meta).foregroundStyle(Palette.ink3)
+ }
+ .font(.system(size: 11))
+ .monospacedDigit()
+ .lineLimit(1)
+ }
+ } else {
+ Text(task.idleStatus + " · " + task.meta)
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.ink3)
+ .monospacedDigit()
+ .lineLimit(1)
+ }
+ }
+}
+
+struct TaskIcon: View {
+ let svg: String
+ let running: Bool
+ @State private var pulse = false
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ var body: some View {
+ ZStack {
+ RoundedRectangle(cornerRadius: 12, style: .circular).fill(Palette.ink5)
+ LogoView(svg: svg, size: 15)
+ if running && !reduceMotion {
+ RoundedRectangle(cornerRadius: 14, style: .circular)
+ .strokeBorder(Palette.ink3, lineWidth: 1)
+ .padding(-3)
+ .scaleEffect(pulse ? 1.12 : 0.92)
+ .opacity(pulse ? 0 : 0.7)
+ .onAppear {
+ withAnimation(.easeOut(duration: 2.2).repeatForever(autoreverses: false)) { pulse = true }
+ }
+ }
+ }
+ .frame(width: 34, height: 34)
+ }
+}
+
+struct BreathingDot: View {
+ let animate: Bool
+ @State private var dim = false
+
+ var body: some View {
+ Circle()
+ .fill(Palette.ink2)
+ .frame(width: 6, height: 6)
+ .opacity(dim ? 0.2 : 1)
+ .onAppear {
+ guard animate else { return }
+ withAnimation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true)) { dim = true }
+ }
+ }
+}
+
+struct MoreRow: View {
+ let label: String
+ let value: String
+ let action: () -> Void
+ @State private var hovering = false
+
+ var body: some View {
+ Button(action: action) {
+ HStack {
+ Text(label)
+ Spacer()
+ Text(value + " ›").monospacedDigit()
+ }
+ .font(.system(size: 12))
+ .foregroundStyle(hovering ? Palette.ink : Palette.ink3)
+ .padding(.vertical, 6)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in withAnimation(Motion.quick) { self.hovering = hovering } }
+ }
+}
+
+// MARK: - Month card
+
+struct MonthCard: View {
+ @ObservedObject var store: MenubarStore
+ let view: MBView
+ @State private var hovering = false
+
+ var body: some View {
+ let scope = view.settings.scope
+ let data = view.usage.scopes[scope] ?? view.usage.scopes["all"]
+ let last = Array((data?.daily ?? []).suffix(30))
+ let days = Array(view.usage.days.suffix(30))
+ let total = last.reduce(0) { $0 + $1.money.reduce(0, +) }
+ Button {
+ store.wideList = .models
+ store.go(.wide)
+ } label: {
+ HStack(spacing: 14) {
+ VStack(alignment: .leading, spacing: 0) {
+ Text(store.s(scope == "local" ? "monthScopeLocal" : "monthScopeAll"))
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.ink3)
+ Text(Fmt.money(total))
+ .font(.system(size: 20, weight: .bold))
+ .tracking(-0.6)
+ .monospacedDigit()
+ }
+ UsageChart(days: days, daily: last, money: true, compact: true, selection: .constant(nil))
+ .frame(height: 34)
+ HStack(spacing: 5) {
+ Text(store.s("expand"))
+ Image(systemName: "arrow.up.right").font(.system(size: 9, weight: .semibold))
+ }
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(Palette.ink2)
+ }
+ .padding(EdgeInsets(top: 12, leading: 14, bottom: 12, trailing: 14))
+ .background(RoundedRectangle(cornerRadius: 18, style: .circular).fill(Palette.tile))
+ .overlay(RoundedRectangle(cornerRadius: 18, style: .circular).strokeBorder(Palette.line, lineWidth: 0.5))
+ .contentShape(RoundedRectangle(cornerRadius: 18, style: .circular))
+ .offset(y: hovering ? -1 : 0)
+ }
+ .buttonStyle(.plain)
+ .onHover { hovering in withAnimation(Motion.quick) { self.hovering = hovering } }
+ .accessibilityLabel(store.s("expandUsage"))
+ }
+}
+
+// MARK: - Usage chart (Swift Charts)
+
+struct UsagePoint: Identifiable {
+ let id: String
+ let date: Date
+ let harness: String
+ let value: Double
+}
+
+/// Harness stacking order, bottom to top: Codex, Claude Code, Pi.
+let harnessOrder: [(index: Int, key: String)] = [(1, "codex"), (0, "claude-code"), (2, "pi")]
+
+struct UsageChart: View {
+ let days: [String]
+ let daily: [MBDaily]
+ let money: Bool
+ let compact: Bool
+ @Binding var selection: Int?
+ var axisLabels: [(Int, String)] = []
+
+ var body: some View {
+ let count = min(days.count, daily.count)
+ let dates = days.suffix(count).map(Fmt.day)
+ let rows = Array(daily.suffix(count))
+ let points = harnessOrder.flatMap { harness in
+ (0..<count).map { i in
+ UsagePoint(
+ id: "\(harness.key)-\(i)",
+ date: dates[i],
+ harness: harness.key,
+ value: money ? rows[i].money[harness.index] : rows[i].tokens[harness.index]
+ )
+ }
+ }
+ let totals = (0..<count).map { i in
+ money ? rows[i].money.reduce(0, +) : rows[i].tokens.reduce(0, +)
+ }
+ let maxTotal = max(totals.max() ?? 0, 0.0001) * 1.08
+ Chart {
+ ForEach(points) { point in
+ AreaMark(
+ x: .value("Day", point.date),
+ y: .value("Value", point.value),
+ stacking: .standard
+ )
+ .foregroundStyle(by: .value("Harness", point.harness))
+ .interpolationMethod(.monotone)
+ }
+ ForEach(0..<count, id: \.self) { i in
+ LineMark(x: .value("Day", dates[i]), y: .value("Total", totals[i]), series: .value("Series", "total"))
+ .foregroundStyle(Palette.ink.opacity(0.55))
+ .lineStyle(StrokeStyle(lineWidth: compact ? 1 : 1.2))
+ .interpolationMethod(.monotone)
+ }
+ if let selection, selection < count {
+ RuleMark(x: .value("Day", dates[selection]))
+ .foregroundStyle(Palette.ink3)
+ .lineStyle(StrokeStyle(lineWidth: 1))
+ PointMark(x: .value("Day", dates[selection]), y: .value("Total", totals[selection]))
+ .symbol {
+ Circle()
+ .fill(Palette.ink)
+ .frame(width: 8, height: 8)
+ .overlay(Circle().stroke(Color(nsColor: .windowBackgroundColor), lineWidth: 2))
+ }
+ }
+ }
+ .chartForegroundStyleScale([
+ "codex": gradient(Palette.codex),
+ "claude-code": gradient(Palette.claude),
+ "pi": gradient(Palette.pi),
+ ])
+ .chartLegend(.hidden)
+ .chartYAxis(.hidden)
+ .chartYScale(domain: 0...maxTotal)
+ .chartXAxis {
+ if compact || axisLabels.isEmpty {
+ AxisMarks { _ in }
+ } else {
+ AxisMarks(values: axisLabels.map { dates[$0.0] }) { value in
+ AxisValueLabel(anchor: .top) {
+ if let date = value.as(Date.self), let label = axisLabels.first(where: { dates[$0.0] == date })?.1 {
+ Text(label).font(.system(size: 10.5)).foregroundStyle(Palette.ink3)
+ }
+ }
+ }
+ }
+ }
+ .chartPlotStyle { plot in plot.clipped(antialiased: true) }
+ .chartOverlay { proxy in
+ if !compact {
+ GeometryReader { geometry in
+ Rectangle()
+ .fill(Color.clear)
+ .contentShape(Rectangle())
+ .onContinuousHover { phase in
+ switch phase {
+ case .active(let location):
+ guard let plotFrame = proxy.plotFrame else { return }
+ let origin = geometry[plotFrame].origin
+ let x = location.x - origin.x
+ guard let date: Date = proxy.value(atX: x) else { return }
+ let index = nearestIndex(dates: dates, to: date)
+ if selection != index { selection = index }
+ case .ended:
+ selection = nil
+ }
+ }
+ }
+ }
+ }
+ .accessibilityHidden(compact)
+ }
+
+ private func gradient(_ color: Color) -> LinearGradient {
+ LinearGradient(colors: [color.opacity(0.95), color.opacity(0.55)], startPoint: .top, endPoint: .bottom)
+ }
+
+ private func nearestIndex(dates: [Date], to date: Date) -> Int {
+ var best = 0
+ var bestDistance = Double.greatestFiniteMagnitude
+ for (i, candidate) in dates.enumerated() {
+ let distance = abs(candidate.timeIntervalSince(date))
+ if distance < bestDistance {
+ best = i
+ bestDistance = distance
+ }
+ }
+ return best
+ }
+}
+
+// MARK: - Detail page
+
+struct RingArc: Shape {
+ var progress: Double
+ let lineWidth: CGFloat
+
+ var animatableData: Double {
+ get { progress }
+ set { progress = newValue }
+ }
+
+ /// The visible arc including both round caps spans exactly 0...progress of the circle:
+ /// the stroke starts half a line width after 12 o'clock and ends half a line width early.
+ /// A full ring uses butt caps so two round caps never meet; zero draws nothing.
+ func path(in rect: CGRect) -> Path {
+ let radius = min(rect.width, rect.height) / 2 - lineWidth / 2
+ let center = CGPoint(x: rect.midX, y: rect.midY)
+ guard progress > 0.0005, radius > 0 else { return Path() }
+ var arc = Path()
+ if progress >= 0.9995 {
+ arc.addArc(center: center, radius: radius, startAngle: .degrees(-90), endAngle: .degrees(270), clockwise: false)
+ return arc.strokedPath(StrokeStyle(lineWidth: lineWidth, lineCap: .butt))
+ }
+ let cap = Double(lineWidth / 2 / radius)
+ let start = -Double.pi / 2 + cap
+ let end = max(start + 0.0001, -Double.pi / 2 + 2 * Double.pi * progress - cap)
+ arc.addArc(center: center, radius: radius, startAngle: .radians(start), endAngle: .radians(end), clockwise: false)
+ return arc.strokedPath(StrokeStyle(lineWidth: lineWidth, lineCap: .round))
+ }
+}
+
+struct RingsView: View {
+ let rings: [MBRing]
+ let fillToken: Int
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var shown = true
+
+ var body: some View {
+ let lineWidth: CGFloat = rings.count > 1 ? 14 : 16
+ let gap: CGFloat = 4
+ ZStack {
+ ForEach(Array(rings.enumerated()), id: \.offset) { index, ring in
+ let inset = 4 + CGFloat(index) * (lineWidth + gap)
+ ZStack {
+ Circle()
+ .strokeBorder(Palette.ink5, lineWidth: lineWidth)
+ RingArc(progress: shown ? max(0, min(1, ring.fraction)) : 0, lineWidth: lineWidth)
+ .fill(Palette.named(ring.color))
+ .animation(Motion.fill.delay(Double(index) * 0.06), value: shown)
+ .animation(Motion.fill, value: ring.fraction)
+ }
+ .padding(inset)
+ }
+ }
+ .frame(width: 240, height: 240)
+ .onAppear { replay() }
+ .onChange(of: fillToken) { replay() }
+ }
+
+ private func replay() {
+ guard !reduceMotion else { shown = true; return }
+ var transaction = Transaction()
+ transaction.disablesAnimations = true
+ withTransaction(transaction) { shown = false }
+ DispatchQueue.main.async { shown = true }
+ }
+}
+
+struct DetailPage: View {
+ @ObservedObject var store: MenubarStore
+ let detail: MBDetail
+ let controller: StatusController
+
+ var body: some View {
+ ScrollView(.vertical, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 8) {
+ IconButton(systemName: "chevron.left", label: store.s("back")) { store.go(.main) }
+ LogoView(svg: detail.logoSvg, size: 15)
+ Text(detail.title).font(.system(size: 14, weight: .semibold))
+ Text(detail.plan).font(.system(size: 11, weight: .medium)).foregroundStyle(Palette.ink3)
+ Spacer(minLength: 0)
+ }
+ .padding(EdgeInsets(top: 18, leading: 18, bottom: 0, trailing: 18))
+
+ ZStack {
+ RingsView(rings: detail.rings, fillToken: store.fillToken)
+ VStack(spacing: 6) {
+ HStack(alignment: .firstTextBaseline, spacing: 2) {
+ Text(detail.bigValue)
+ .font(.system(size: detail.bigCompact ? 46 : 64, weight: .light))
+ .tracking(detail.bigCompact ? -2 : -3)
+ if let unit = detail.bigUnit {
+ Text(unit).font(.system(size: 22)).foregroundStyle(Palette.ink3)
+ }
+ }
+ .monospacedDigit()
+ .foregroundStyle(detail.bigColor.map(Palette.named) ?? Palette.ink)
+ Text(detail.bigCaption).font(.system(size: 12)).foregroundStyle(Palette.ink3)
+ }
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.top, 20)
+ .accessibilityElement(children: .combine)
+
+ if !detail.legend.isEmpty {
+ HStack(spacing: 16) {
+ ForEach(detail.legend, id: \.self) { item in
+ HStack(spacing: 6) {
+ Circle().fill(Palette.named(item.color)).frame(width: 8, height: 8)
+ Text(item.label)
+ }
+ }
+ }
+ .font(.system(size: 11.5))
+ .foregroundStyle(Palette.ink2)
+ .monospacedDigit()
+ .frame(maxWidth: .infinity)
+ .padding(.top, 14)
+ }
+
+ sayText
+ .font(.system(size: 19, weight: .semibold))
+ .tracking(-0.4)
+ .lineSpacing(3)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(EdgeInsets(top: 22, leading: 28, bottom: 0, trailing: 28))
+
+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)], spacing: 10) {
+ ForEach(detail.facts, id: \.self) { fact in
+ FactCard(fact: fact)
+ }
+ }
+ .padding(EdgeInsets(top: 22, leading: 22, bottom: 24, trailing: 22))
+
+ InkPillButton(title: detail.actionLabel, height: 40, fullWidth: true, disabled: detail.action.kind == "none") {
+ controller.emitAndClose(["type": "detail-action", "sourceId": detail.id])
+ }
+ .padding(EdgeInsets(top: 0, leading: 22, bottom: 24, trailing: 22))
+ }
+ .background(GeometryReader { inner in
+ Color.clear
+ .onAppear { report(inner.size.height) }
+ .onChange(of: inner.size.height) { _, height in report(height) }
+ })
+ }
+ }
+
+ private func report(_ height: CGFloat) {
+ let natural = (height + 1).rounded(.up)
+ if abs(store.detailContentHeight - natural) > 0.5 { store.detailContentHeight = natural }
+ }
+
+ private var sayText: Text {
+ var text = Text(detail.sayPrimary)
+ if let secondary = detail.saySecondary {
+ text = text + Text(secondary).foregroundColor(Palette.ink3)
+ }
+ return text
+ }
+}
+
+struct FactCard: View {
+ let fact: MBFact
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Text(fact.label).font(.system(size: 11)).foregroundStyle(Palette.ink3)
+ Text(fact.value)
+ .font(.system(size: fact.value.count > 14 ? 13 : 17, weight: .semibold))
+ .tracking(fact.value.count > 14 ? 0 : -0.4)
+ .monospacedDigit()
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ .padding(.top, fact.value.count > 14 ? 5 : 3)
+ Text(fact.sub).font(.system(size: 11)).foregroundStyle(Palette.ink3).lineLimit(1).padding(.top, 1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(EdgeInsets(top: 13, leading: 14, bottom: 13, trailing: 14))
+ .background(RoundedRectangle(cornerRadius: 16, style: .circular).fill(Palette.tile))
+ .overlay(RoundedRectangle(cornerRadius: 16, style: .circular).strokeBorder(Palette.line, lineWidth: 0.5))
+ }
+}
+
+// MARK: - Wide usage page
+
+struct WidePage: View {
+ @ObservedObject var store: MenubarStore
+ let view: MBView
+ let controller: StatusController
+ @State private var selection: Int?
+
+ private var scopeData: MBScopeData? { view.usage.scopes[store.wideScope] ?? view.usage.scopes["all"] }
+
+ var body: some View {
+ let data = scopeData
+ let range = store.wideRange
+ let allDays = view.usage.days
+ let days = Array(allDays.suffix(range))
+ let daily = Array((data?.daily ?? []).suffix(range))
+ let byHarness = harnessTotals(daily)
+ let total = byHarness.reduce(0, +)
+ HStack(alignment: .top, spacing: 0) {
+ sidebar(days: days, daily: daily, byHarness: byHarness, total: total, note: data?.note ?? "")
+ .frame(width: 260)
+ .frame(maxHeight: .infinity, alignment: .top)
+ .overlay(alignment: .trailing) { Rectangle().fill(Palette.line).frame(width: 0.5) }
+ ScrollView(.vertical, showsIndicators: false) {
+ VStack(alignment: .leading, spacing: 0) {
+ controls
+ UsageChart(
+ days: days,
+ daily: daily,
+ money: store.wideMoney,
+ compact: false,
+ selection: $selection,
+ axisLabels: axisLabels(days: days)
+ )
+ .frame(height: 306)
+ .padding(.top, 22)
+ Picker("", selection: $store.wideList) {
+ Text(store.s("listModels", ["n": String(range)])).tag(WideList.models)
+ Text(store.s("listTasks")).tag(WideList.tasks)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .fixedSize()
+ .padding(.top, 22)
+ if store.wideList == .models {
+ modelList(data?.models[String(range)] ?? [])
+ } else {
+ taskList
+ }
+ }
+ .padding(EdgeInsets(top: 20, leading: 24, bottom: 22, trailing: 24))
+ }
+ }
+ .onChange(of: store.wideRange) { selection = nil }
+ }
+
+ private func harnessTotals(_ daily: [MBDaily]) -> [Double] {
+ var totals = [0.0, 0.0, 0.0]
+ for day in daily {
+ for j in 0..<3 {
+ totals[j] += store.wideMoney ? day.money[j] : day.tokens[j]
+ }
+ }
+ return totals
+ }
+
+ private func format(_ value: Double) -> String {
+ store.wideMoney ? Fmt.money(value) : Fmt.tokens(value)
+ }
+
+ @ViewBuilder
+ private func sidebar(days: [String], daily: [MBDaily], byHarness: [Double], total: Double, note: String) -> some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 6) {
+ IconButton(systemName: "chevron.left", label: store.s("back")) { store.go(.main) }
+ Text(store.s("usageTitle")).font(.system(size: 14, weight: .bold))
+ }
+ if let selection, selection < daily.count {
+ selectedSummary(day: days[selection], row: daily[selection])
+ } else {
+ Text(format(total))
+ .font(.system(size: 52, weight: .semibold))
+ .tracking(-2.4)
+ .monospacedDigit()
+ .lineLimit(1)
+ .minimumScaleFactor(0.6)
+ .padding(.top, 26)
+ Text(store.s(store.wideMoney ? "wideCaptionMoney" : "wideCaptionTokens", ["n": String(store.wideRange)])
+ + "\n" + store.s(store.wideScope == "local" ? "scopeLocal" : "scopeAll"))
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .frame(minHeight: 36, alignment: .topLeading)
+ .padding(.top, 8)
+ }
+ subStats(daily: daily, total: total).padding(.top, 22)
+ harnessList(byHarness: byHarness, total: total).padding(.top, 28)
+ Spacer(minLength: 20)
+ Text(note)
+ .font(.system(size: 11))
+ .foregroundStyle(Palette.ink3)
+ .lineSpacing(4)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(EdgeInsets(top: 20, leading: 22, bottom: 22, trailing: 22))
+ }
+
+ @ViewBuilder
+ private func selectedSummary(day: String, row: MBDaily) -> some View {
+ let values = store.wideMoney ? row.money : row.tokens
+ Text(format(values.reduce(0, +)))
+ .font(.system(size: 52, weight: .semibold))
+ .tracking(-2.4)
+ .monospacedDigit()
+ .lineLimit(1)
+ .minimumScaleFactor(0.6)
+ .padding(.top, 26)
+ VStack(alignment: .leading, spacing: 2) {
+ let date = Fmt.day(day)
+ Text(Fmt.monthDay(date, locale: store.locale) + " " + Fmt.weekday(date, locale: store.locale))
+ .fontWeight(.semibold)
+ .foregroundStyle(Palette.ink)
+ let present = harnessOrder.filter { values[$0.index] > 0 }
+ if present.isEmpty {
+ Text(store.s("noUsage"))
+ }
+ ForEach(present, id: \.index) { harness in
+ HStack(spacing: 4) {
+ Circle().fill(Palette.harness(harness.key)).frame(width: 7, height: 7)
+ Text("\(store.s("harness." + harness.key)) \(format(values[harness.index]))")
+ }
+ }
+ }
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .monospacedDigit()
+ .frame(minHeight: 36, alignment: .topLeading)
+ .padding(.top, 8)
+ }
+
+ @ViewBuilder
+ private func subStats(daily: [MBDaily], total: Double) -> some View {
+ let range = Double(max(1, store.wideRange))
+ HStack(alignment: .top, spacing: 18) {
+ if store.wideMoney {
+ stat(store.s("dailyAverage"), Fmt.money(total / range))
+ stat(store.s("paid"), Fmt.money(daily.reduce(0) { $0 + $1.paid }))
+ stat(store.s("tokenUnitTitle"), Fmt.tokens(daily.reduce(0) { $0 + $1.tokens.reduce(0, +) }))
+ } else {
+ stat(store.s("dailyAverage"), Fmt.tokens(total / range))
+ stat(store.s("peakDay"), Fmt.tokens(daily.map { $0.tokens.reduce(0, +) }.max() ?? 0))
+ }
+ }
+ }
+
+ private func stat(_ label: String, _ value: String) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(label).font(.system(size: 11)).foregroundStyle(Palette.ink3)
+ Text(value).font(.system(size: 16, weight: .semibold)).tracking(-0.3).monospacedDigit()
+ }
+ }
+
+ @ViewBuilder
+ private func harnessList(byHarness: [Double], total: Double) -> some View {
+ VStack(alignment: .leading, spacing: 0) {
+ HarnessBar(values: harnessOrder.map { ($0.key, byHarness[$0.index]) })
+ .frame(height: 6)
+ .padding(.top, 10)
+ ForEach(harnessOrder, id: \.index) { harness in
+ HStack(spacing: 10) {
+ Circle().fill(Palette.harness(harness.key)).frame(width: 9, height: 9)
+ Text(store.s("harness." + harness.key)).frame(maxWidth: .infinity, alignment: .leading)
+ Text("\(Int((byHarness[harness.index] / max(total, 0.0001) * 100).rounded()))%")
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ Text(format(byHarness[harness.index]))
+ .fontWeight(.semibold)
+ .frame(width: 70, alignment: .trailing)
+ }
+ .font(.system(size: 13))
+ .monospacedDigit()
+ .padding(.vertical, 9)
+ }
+ }
+ }
+
+ private var controls: some View {
+ HStack(spacing: 8) {
+ Picker("", selection: $store.wideRange) {
+ Text(store.s("range7")).tag(7)
+ Text(store.s("range30")).tag(30)
+ Text(store.s("range90")).tag(90)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .fixedSize()
+ Picker("", selection: $store.wideMoney) {
+ Text(store.s("metricMoney")).tag(true)
+ Text(store.s("metricTokens")).tag(false)
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .fixedSize()
+ Picker("", selection: $store.wideScope) {
+ Text(store.s("scopeLocal")).tag("local")
+ Text(store.s("scopeAll")).tag("all")
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .fixedSize()
+ }
+ }
+
+ private func axisLabels(days: [String]) -> [(Int, String)] {
+ let every = store.wideRange == 7 ? 1 : store.wideRange == 30 ? 7 : 21
+ var labels: [(Int, String)] = []
+ for (i, day) in days.enumerated() where (days.count - 1 - i) % every == 0 {
+ let date = Fmt.day(day)
+ let label: String
+ if i == days.count - 1 {
+ label = store.s("today")
+ } else if store.wideRange == 7 {
+ label = Fmt.weekday(date, locale: store.locale)
+ } else {
+ label = Fmt.monthDay(date, locale: store.locale)
+ }
+ labels.append((i, label))
+ }
+ return labels
+ }
+
+ @ViewBuilder
+ private func modelList(_ models: [MBModelUsage]) -> some View {
+ let rows = models
+ .map { ($0, store.wideMoney ? $0.money : $0.tokens) }
+ .filter { $0.1 > 0 }
+ .sorted { $0.1 > $1.1 }
+ .prefix(8)
+ LazyVGrid(columns: [GridItem(.flexible(), spacing: 24), GridItem(.flexible(), spacing: 24)], alignment: .leading, spacing: 4) {
+ ForEach(Array(rows.enumerated()), id: \.offset) { index, row in
+ HStack(spacing: 10) {
+ Text("\(index + 1)").font(.system(size: 11)).foregroundStyle(Palette.ink3).frame(width: 16, alignment: .leading)
+ Circle().fill(Palette.harness(row.0.harness)).frame(width: 7, height: 7)
+ Text(row.0.name).lineLimit(1).truncationMode(.tail).frame(maxWidth: .infinity, alignment: .leading)
+ Text(format(row.1)).fontWeight(.semibold)
+ }
+ .font(.system(size: 12.5))
+ .monospacedDigit()
+ .padding(.vertical, 7)
+ .overlay(alignment: .bottom) { Rectangle().fill(Palette.line).frame(height: 0.5) }
+ }
+ }
+ .padding(.top, 22)
+ .animation(Motion.quick, value: store.wideMoney)
+ }
+
+ private var taskList: some View {
+ let tasks = view.tasks.sorted { $0.value > $1.value }
+ return VStack(spacing: 4) {
+ if tasks.isEmpty {
+ Text(store.s("noTasksToday")).font(.system(size: 12)).foregroundStyle(Palette.ink3).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ ForEach(Array(tasks.enumerated()), id: \.element.id) { index, task in
+ Button {
+ controller.emitAndClose(["type": "open-session", "sessionId": task.sessionId])
+ } label: {
+ WideTaskRow(store: store, index: index, task: task)
+ }
+ .buttonStyle(.plain)
+ .help(task.title)
+ }
+ }
+ .padding(.top, 22)
+ }
+}
+
+struct WideTaskRow: View {
+ @ObservedObject var store: MenubarStore
+ let index: Int
+ let task: MBTask
+
+ var body: some View {
+ HStack(spacing: 10) {
+ Text("\(index + 1)").font(.system(size: 11)).foregroundStyle(Palette.ink3).frame(width: 16, alignment: .leading)
+ Circle().fill(Palette.harness(task.harness)).frame(width: 7, height: 7)
+ HStack(spacing: 5) {
+ if task.running { BreathingDot(animate: true) }
+ Text(task.title).lineLimit(1).truncationMode(.tail)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ let status = task.running && task.startedAtMs != nil
+ ? store.s("running") + " " + Fmt.clock(context.date.timeIntervalSince1970 - (task.startedAtMs ?? 0) / 1000)
+ : task.idleStatus
+ Text(status + " · " + task.meta).font(.system(size: 11.5)).foregroundStyle(Palette.ink3).lineLimit(1)
+ }
+ Text(Fmt.money(task.value)).fontWeight(.semibold).frame(width: 64, alignment: .trailing)
+ }
+ .font(.system(size: 12.5))
+ .monospacedDigit()
+ .padding(.vertical, 7)
+ .contentShape(Rectangle())
+ .overlay(alignment: .bottom) { Rectangle().fill(Palette.line).frame(height: 0.5) }
+ }
+}
+
+/// Capsule segments in harness order. Each segment is its own capsule, so rounding comes from
+/// a single shape per segment and tiny shares keep a readable minimum width.
+struct HarnessBar: View {
+ let values: [(String, Double)]
+
+ var body: some View {
+ GeometryReader { geometry in
+ let present = values.filter { $0.1 > 0 }
+ let total = max(present.reduce(0) { $0 + $1.1 }, 0.0001)
+ let gaps = CGFloat(max(0, present.count - 1)) * 2
+ let available = max(0, geometry.size.width - gaps)
+ let minimum: CGFloat = 6
+ let raw = present.map { CGFloat($0.1 / total) * available }
+ let deficit = raw.reduce(0) { $0 + max(0, minimum - $1) }
+ let flexible = raw.reduce(0) { $0 + ($1 > minimum ? $1 : 0) }
+ HStack(spacing: 2) {
+ ForEach(Array(present.enumerated()), id: \.offset) { index, item in
+ let width = raw[index] <= minimum ? minimum : raw[index] - deficit * (raw[index] / max(flexible, 0.0001))
+ Capsule().fill(Palette.harness(item.0)).frame(width: max(minimum, width))
+ }
+ }
+ }
+ }
+}
+
+// MARK: - Manage page
+
+struct ManagePage: View {
+ @ObservedObject var store: MenubarStore
+ let view: MBView
+ let controller: StatusController
+ @State private var offset: CGFloat = 0
+ @State private var contentHeight: CGFloat = 0
+ @State private var headerHeight: CGFloat = 0
+ @State private var dragging: String?
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 6) {
+ IconButton(systemName: "chevron.left", label: store.s("back")) { store.go(.main) }
+ Text(store.s("manageTitle")).font(.system(size: 14, weight: .bold))
+ Spacer(minLength: 0)
+ Button { store.go(.main) } label: {
+ Text(store.s("done"))
+ .font(.system(size: 12.5, weight: .semibold))
+ .foregroundStyle(Palette.onInk)
+ .padding(.horizontal, 14)
+ .frame(height: 30)
+ .background(Capsule().fill(Palette.ink))
+ }
+ .buttonStyle(PressScaleStyle())
+ .keyboardShortcut(.defaultAction)
+ }
+ .padding(EdgeInsets(top: 18, leading: 18, bottom: 10, trailing: 18))
+ .background(GeometryReader { g in
+ Color.clear
+ .onAppear { headerHeight = g.size.height }
+ .onChange(of: g.size.height) { _, h in headerHeight = h }
+ })
+ EdgeLine(visible: offset > 2)
+ TrackedScroll(offset: $offset, contentHeight: $contentHeight) {
+ content
+ }
+ }
+ .onChange(of: contentHeight) { report() }
+ .onChange(of: headerHeight) { report() }
+ }
+
+ /// Sizes the panel to the whole page; it only scrolls when the screen is shorter.
+ private func report() {
+ guard contentHeight > 0 else { return }
+ let natural = (headerHeight + contentHeight + 1).rounded(.up)
+ if abs(store.manageContentHeight - natural) > 0.5 { store.manageContentHeight = natural }
+ }
+
+ private var content: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ VStack(alignment: .leading, spacing: 6) {
+ Text(store.s("manageHero"))
+ .font(.system(size: 24, weight: .semibold))
+ .tracking(-0.5)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(store.s("manageHeroSub"))
+ .font(.system(size: 14, weight: .medium))
+ .foregroundStyle(Palette.ink3)
+ .lineSpacing(3)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(EdgeInsets(top: 18, leading: 24, bottom: 0, trailing: 24))
+
+ section(store.s("sources"), store.s("sourcesShown", [
+ "a": String(view.manage.filter { !$0.hidden }.count),
+ "b": String(view.manage.count),
+ ]))
+ sourceList
+
+ section(store.s("statusIcon"), store.s("statusIconSub"))
+ StatusPreview(store: store, view: view)
+ .padding(.horizontal, 16)
+ Picker("", selection: Binding(
+ get: { view.settings.statusText },
+ set: { Bridge.emitSettings(["statusText": $0]) }
+ )) {
+ Text(store.s("statusIconMode.icon")).tag("icon")
+ Text(store.s("statusIconMode.lowest")).tag("lowest")
+ Text(store.s("statusIconMode.today")).tag("today")
+ Text(store.s("statusIconMode.task")).tag("task")
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .padding(EdgeInsets(top: 12, leading: 16, bottom: 0, trailing: 16))
+
+ section(store.s("other"), nil)
+ Tile {
+ VStack(spacing: 0) {
+ settingRow(store.s("lowAlert"), store.s("lowAlertSub")) {
+ Toggle("", isOn: Binding(get: { view.settings.lowAlert }, set: { Bridge.emitSettings(["lowAlert": $0]) }))
+ .toggleStyle(.switch).controlSize(.small).labelsHidden()
+ }
+ Divider().overlay(Palette.line)
+ settingRow(store.s("privacy"), store.s("privacySub")) {
+ Toggle("", isOn: Binding(get: { view.settings.privacy }, set: { Bridge.emitSettings(["privacy": $0]) }))
+ .toggleStyle(.switch).controlSize(.small).labelsHidden()
+ }
+ Divider().overlay(Palette.line)
+ settingRow(store.s("usageScope"), nil) {
+ Picker("", selection: Binding(get: { view.settings.scope }, set: { Bridge.emitSettings(["scope": $0]) })) {
+ Text(store.s("scopeLocal")).tag("local")
+ Text(store.s("scopeAll")).tag("all")
+ }
+ .pickerStyle(.segmented)
+ .labelsHidden()
+ .controlSize(.small)
+ .fixedSize()
+ }
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 2)
+ }
+ .padding(.horizontal, 16)
+
+ Button { controller.emitAndClose(["type": "open-provider-settings"]) } label: {
+ Text(store.s("manageFoot"))
+ .font(.system(size: 11.5))
+ .foregroundStyle(Palette.ink3)
+ .lineSpacing(4)
+ .multilineTextAlignment(.leading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .buttonStyle(.plain)
+ .padding(EdgeInsets(top: 20, leading: 24, bottom: 22, trailing: 24))
+ }
+ }
+
+ private func section(_ title: String, _ detail: String?) -> some View {
+ HStack(alignment: .firstTextBaseline) {
+ Text(title).font(.system(size: 13, weight: .semibold))
+ Spacer()
+ if let detail {
+ Text(detail).font(.system(size: 11.5)).foregroundStyle(Palette.ink3).monospacedDigit()
+ }
+ }
+ .padding(EdgeInsets(top: 26, leading: 24, bottom: 10, trailing: 24))
+ }
+
+ private func settingRow<Control: View>(_ title: String, _ sub: String?, @ViewBuilder control: () -> Control) -> some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(title).font(.system(size: 13))
+ if let sub {
+ Text(sub).font(.system(size: 11)).foregroundStyle(Palette.ink3).fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ control()
+ }
+ .padding(.vertical, 11)
+ }
+
+ private var sourceList: some View {
+ let rows = store.manageRows
+ return Tile {
+ VStack(spacing: 0) {
+ ForEach(Array(rows.enumerated()), id: \.element.id) { index, row in
+ ManageRow(
+ store: store,
+ row: row,
+ showDivider: index > 0,
+ dragging: dragging == row.id
+ )
+ .onDrag {
+ dragging = row.id
+ return NSItemProvider(object: row.id as NSString)
+ }
+ .onDrop(of: [.text], delegate: ReorderDropDelegate(target: row.id, store: store, dragging: $dragging))
+ }
+ }
+ .padding(4)
+ }
+ .padding(.horizontal, 16)
+ }
+}
+
+struct ReorderDropDelegate: DropDelegate {
+ let target: String
+ let store: MenubarStore
+ @Binding var dragging: String?
+
+ func dropEntered(info: DropInfo) {
+ guard let dragging, dragging != target else { return }
+ Task { @MainActor in store.move(dragging, into: target) }
+ }
+
+ func dropUpdated(info: DropInfo) -> DropProposal? { DropProposal(operation: .move) }
+
+ func performDrop(info: DropInfo) -> Bool {
+ Task { @MainActor in
+ store.commitOrder()
+ dragging = nil
+ }
+ return true
+ }
+
+ func dropExited(info: DropInfo) {}
+}
+
+struct ManageRow: View {
+ @ObservedObject var store: MenubarStore
+ let row: MBManageRow
+ let showDivider: Bool
+ let dragging: Bool
+ @State private var hovering = false
+ @State private var shake: CGFloat = 0
+
+ var body: some View {
+ HStack(spacing: 12) {
+ Image(systemName: "line.3.horizontal")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(Palette.ink3)
+ .frame(width: 16, height: 28)
+ .accessibilityHidden(true)
+ ZStack {
+ RoundedRectangle(cornerRadius: 10, style: .circular).fill(Palette.ink5)
+ LogoView(svg: row.logoSvg, size: 15)
+ }
+ .frame(width: 30, height: 30)
+ .opacity(row.hidden ? 0.4 : 1)
+ VStack(alignment: .leading, spacing: 0) {
+ Text(row.title).font(.system(size: 13, weight: .semibold)).lineLimit(1)
+ Text(row.subtitle).font(.system(size: 11)).foregroundStyle(Palette.ink3).lineLimit(1)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .opacity(row.hidden ? 0.4 : 1)
+ Text(row.value)
+ .font(.system(size: 12))
+ .foregroundStyle(Palette.ink3)
+ .monospacedDigit()
+ .padding(.trailing, 4)
+ Toggle("", isOn: Binding(get: { !row.hidden }, set: { _ in store.toggleHidden(row) }))
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ .labelsHidden()
+ .offset(x: shake)
+ .accessibilityLabel(store.s("showSource", ["name": row.title]))
+ }
+ .padding(EdgeInsets(top: 9, leading: 6, bottom: 9, trailing: 10))
+ .background(RoundedRectangle(cornerRadius: 16, style: .circular).fill(hovering ? Palette.ink5 : .clear))
+ .overlay(alignment: .top) {
+ if showDivider {
+ Rectangle().fill(Palette.line).frame(height: 0.5).padding(.leading, 58).padding(.trailing, 12)
+ }
+ }
+ .opacity(dragging ? 0.35 : 1)
+ .contentShape(Rectangle())
+ .onHover { hovering in withAnimation(.easeOut(duration: 0.15)) { self.hovering = hovering } }
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(row.title)
+ .accessibilityHint(store.s("reorderHint"))
+ .accessibilityAction(named: store.s("moveUp")) { store.moveBy(row.id, offset: -1) }
+ .accessibilityAction(named: store.s("moveDown")) { store.moveBy(row.id, offset: 1) }
+ .contextMenu {
+ Button(store.s("moveUp")) { store.moveBy(row.id, offset: -1) }
+ Button(store.s("moveDown")) { store.moveBy(row.id, offset: 1) }
+ }
+ .onChange(of: store.shakeId) { _, id in
+ guard id == row.id else { return }
+ withAnimation(.easeInOut(duration: 0.06).repeatCount(4, autoreverses: true)) { shake = 4 }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { withAnimation(.easeOut(duration: 0.05)) { shake = 0 } }
+ }
+ }
+}
+
+/// A slice of a menu bar over a wallpaper, showing exactly what the status item will look like.
+struct StatusPreview: View {
+ @ObservedObject var store: MenubarStore
+ let view: MBView
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ let text = (view.statusTextByMode[view.settings.statusText] ?? nil) ?? ""
+ let dark = colorScheme == .dark
+ ZStack(alignment: .topLeading) {
+ wallpaper(dark: dark)
+ HStack(spacing: 4) {
+ Spacer()
+ Image(systemName: "wifi").font(.system(size: 13, weight: .semibold)).opacity(0.5).padding(.horizontal, 8)
+ HStack(spacing: 6) {
+ if let icon = Logos.statusIcon {
+ Image(nsImage: icon).renderingMode(.template).resizable().frame(width: 18, height: 18)
+ }
+ if !text.isEmpty {
+ Text(text).font(.system(size: 12.5, weight: .semibold)).monospacedDigit()
+ }
+ }
+ .padding(.horizontal, 8)
+ .frame(height: 24)
+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(dark ? Color.white.opacity(0.18) : Color.black.opacity(0.11)))
+ TimelineView(.periodic(from: .now, by: 30)) { context in
+ Text(Fmt.clockTime(context.date, locale: store.locale))
+ .font(.system(size: 13, weight: .medium))
+ .monospacedDigit()
+ .opacity(0.8)
+ .padding(.horizontal, 8)
+ }
+ }
+ .foregroundStyle(dark ? Color(white: 0.957) : Color(white: 0.063))
+ .padding(.horizontal, 14)
+ .frame(height: 30)
+ .background(.ultraThinMaterial)
+ .padding(.top, 22)
+ }
+ .frame(height: 96)
+ .clipShape(RoundedRectangle(cornerRadius: 20, style: .circular))
+ .overlay(RoundedRectangle(cornerRadius: 20, style: .circular).strokeBorder(Palette.line, lineWidth: 0.5))
+ .animation(Motion.quick, value: text)
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(text.isEmpty ? "Cindy" : "Cindy \(text)")
+ }
+
+ private func wallpaper(dark: Bool) -> some View {
+ ZStack {
+ (dark ? Color(red: 0.055, green: 0.059, blue: 0.071) : Color(red: 0.89, green: 0.882, blue: 0.859))
+ RadialGradient(colors: [dark ? Color(red: 0.165, green: 0.137, blue: 0.251) : Color(red: 0.965, green: 0.937, blue: 0.894), .clear], center: UnitPoint(x: 0.15, y: 0.15), startRadius: 0, endRadius: 220)
+ RadialGradient(colors: [dark ? Color(red: 0.29, green: 0.165, blue: 0.11) : Color(red: 0.941, green: 0.788, blue: 0.651), .clear], center: UnitPoint(x: 0.85, y: 0.25), startRadius: 0, endRadius: 200)
+ RadialGradient(colors: [dark ? Color(red: 0.071, green: 0.231, blue: 0.227) : Color(red: 0.663, green: 0.765, blue: 0.776), .clear], center: UnitPoint(x: 0.7, y: 1), startRadius: 0, endRadius: 220)
+ }
+ }
+}
+
+// MARK: - App
+
+@MainActor
+final class AppDelegate: NSObject, NSApplicationDelegate {
+ let store = MenubarStore()
+ var controller: StatusController?
+ private let decoder = JSONDecoder()
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ controller = StatusController(store: store)
+ let args = CommandLine.arguments
+ if let index = args.firstIndex(of: "--preview"), index + 1 < args.count {
+ startPreview(path: args[index + 1], args: args)
+ return
+ }
+ startReadingStdin()
+ Bridge.emit(["type": "ready"])
+ }
+
+ /// Development preview: render a saved view model and open the panel without main.
+ private func startPreview(path: String, args: [String]) {
+ guard let data = FileManager.default.contents(atPath: path) else {
+ FileHandle.standardError.write(Data("menubar: preview file missing\n".utf8))
+ NSApp.terminate(nil)
+ return
+ }
+ do {
+ let view = try decoder.decode(MBView.self, from: data)
+ store.apply(view)
+ } catch {
+ FileHandle.standardError.write(Data("menubar: preview decode failed: \(error)\n".utf8))
+ NSApp.terminate(nil)
+ return
+ }
+ if let index = args.firstIndex(of: "--appearance"), index + 1 < args.count {
+ NSApp.appearance = NSAppearance(named: args[index + 1] == "dark" ? .darkAqua : .aqua)
+ }
+ var page: Page = .main
+ if let index = args.firstIndex(of: "--page"), index + 1 < args.count {
+ let value = args[index + 1]
+ if value == "wide" { page = .wide }
+ if value == "manage" { page = .manage }
+ if value.hasPrefix("detail:") { page = .detail(String(value.dropFirst(7))) }
+ }
+ if let index = args.firstIndex(of: "--list"), index + 1 < args.count, args[index + 1] == "tasks" {
+ store.wideList = .tasks
+ }
+ var snapshotPath: String?
+ if let index = args.firstIndex(of: "--snapshot"), index + 1 < args.count {
+ snapshotPath = args[index + 1]
+ }
+ var snapshotDelay = 1.2
+ if let index = args.firstIndex(of: "--delay"), index + 1 < args.count, let value = Double(args[index + 1]) {
+ snapshotDelay = value
+ }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in
+ self?.controller?.openForPreview(page: page)
+ guard let window = NSApp.windows.first(where: { $0 is MenubarPanel }) else { return }
+ FileHandle.standardError.write(Data("menubar: preview window \(window.windowNumber)\n".utf8))
+ guard let snapshotPath else { return }
+ DispatchQueue.main.asyncAfter(deadline: .now() + snapshotDelay) {
+ Self.writeSnapshot(of: window, to: snapshotPath)
+ NSApp.terminate(nil)
+ }
+ }
+ }
+
+ /// Renders the panel into a PNG without screen recording access. The frosted material
+ /// cannot be sampled this way, so the backdrop is a flat stand-in for it.
+ private static func writeSnapshot(of window: NSWindow, to path: String) {
+ guard let view = window.contentView else { return }
+ let scale = window.backingScaleFactor
+ let size = view.bounds.size
+ guard let rep = NSBitmapImageRep(
+ bitmapDataPlanes: nil, pixelsWide: Int(size.width * scale), pixelsHigh: Int(size.height * scale),
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)
+ else { return }
+ rep.size = size
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
+ let dark = NSApp.effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
+ (dark ? NSColor(white: 0.17, alpha: 1) : NSColor(white: 0.93, alpha: 1)).setFill()
+ NSBezierPath(roundedRect: view.bounds, xRadius: PanelBackgroundView.radius, yRadius: PanelBackgroundView.radius).fill()
+ NSGraphicsContext.restoreGraphicsState()
+ view.cacheDisplay(in: view.bounds, to: rep)
+ try? rep.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path))
+ }
+
+ private func startReadingStdin() {
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
+ while let line = readLine(strippingNewline: true) {
+ self?.handle(line)
+ }
+ DispatchQueue.main.async { NSApp.terminate(nil) }
+ }
+ }
+
+ nonisolated private func handle(_ line: String) {
+ guard let data = line.data(using: .utf8) else { return }
+ let decoder = JSONDecoder()
+ do {
+ let message = try decoder.decode(MBIncoming.self, from: data)
+ switch message.type {
+ case "shutdown":
+ DispatchQueue.main.async { NSApp.terminate(nil) }
+ case "update":
+ guard let view = message.view else { return }
+ DispatchQueue.main.async { [weak self] in
+ MainActor.assumeIsolated { self?.store.apply(view) }
+ }
+ case "open":
+ DispatchQueue.main.async { [weak self] in
+ MainActor.assumeIsolated { self?.controller?.open() }
+ }
+ default:
+ break
+ }
+ } catch {
+ Bridge.emit(["type": "error", "message": "Could not decode menu bar update: \(error)"])
+ }
+ }
+}
+
+@main
+enum MenubarHelperMain {
+ static func main() {
+ let app = NSApplication.shared
+ let delegate = AppDelegate()
+ app.delegate = delegate
+ app.setActivationPolicy(.accessory)
+ withExtendedLifetime(delegate) { app.run() }
+ }
+}
+
+// The Cindy "A" mark from the brand kit (24pt viewBox, 20pt ink, even-odd `>` cut-out).
+let cindyMarkPath = "M 18.163,3.549 C 18.561,3.879 18.876,4.238 19.198,4.64 C 19.268,4.71 19.339,4.78 19.411,4.852 C 19.492,4.934 19.574,5.015 19.658,5.099 C 19.707,5.148 19.756,5.196 19.807,5.246 C 20.975,6.474 21.548,8.384 21.521,10.044 C 21.495,10.615 21.368,11.261 20.977,11.697 C 20.936,11.732 20.894,11.768 20.852,11.805 C 20.852,11.562 20.852,11.32 20.852,11.07 C 20.633,11.931 20.637,12.526 20.946,13.369 C 21.317,14.501 21.213,15.792 20.72,16.867 C 20.364,17.549 20.364,17.549 20.025,17.775 C 20.039,17.703 20.054,17.631 20.068,17.557 C 20.077,17.511 20.077,17.511 20.123,17.275 C 20.141,17.183 20.159,17.09 20.178,16.994 C 20.188,16.919 20.198,16.843 20.209,16.764 C 20.178,16.734 20.148,16.704 20.117,16.673 C 20.107,16.753 20.098,16.833 20.088,16.915 C 19.896,17.855 19.189,18.653 18.463,19.244 C 17.965,19.568 17.495,19.757 16.902,19.796 C 17.054,19.644 17.205,19.492 17.361,19.336 C 17.086,19.336 17.086,19.336 16.81,19.428 C 16.621,19.435 16.431,19.436 16.242,19.434 C 16.142,19.433 16.042,19.432 15.939,19.431 C 15.863,19.43 15.787,19.429 15.708,19.428 C 15.799,19.368 15.89,19.307 15.983,19.244 C 15.898,19.247 15.813,19.249 15.725,19.251 C 15.611,19.253 15.498,19.254 15.381,19.256 C 15.269,19.258 15.157,19.26 15.042,19.262 C 14.677,19.243 14.4,19.174 14.055,19.061 C 14.149,18.786 14.248,18.513 14.347,18.24 C 14.374,18.162 14.401,18.084 14.429,18.003 C 14.638,17.438 14.638,17.438 14.908,17.298 C 15.231,17.321 15.513,17.399 15.823,17.494 C 16.353,17.646 16.809,17.746 17.361,17.683 C 17.713,17.485 17.801,17.281 17.918,16.902 C 18.096,16.333 18.096,16.333 18.372,16.122 C 18.432,16.122 18.493,16.122 18.555,16.122 C 18.55,16.051 18.544,15.981 18.538,15.909 C 18.555,15.662 18.555,15.662 18.693,15.533 C 18.87,15.345 18.853,15.256 18.848,15.002 C 18.875,14.596 19.004,14.442 19.302,14.17 C 19.37,14.114 19.439,14.059 19.509,14.002 C 19.658,13.825 19.658,13.825 19.651,13.601 C 19.559,13.348 19.446,13.159 19.29,12.941 C 18.966,12.484 18.91,12.168 18.897,11.606 C 18.895,11.541 18.894,11.477 18.892,11.41 C 18.886,11.203 18.882,10.996 18.877,10.788 C 18.858,9.96 18.837,9.138 18.739,8.314 C 18.678,8.314 18.618,8.314 18.555,8.314 C 18.538,8.426 18.521,8.538 18.504,8.653 C 18.133,10.262 16.849,11.349 15.68,12.413 C 14.855,13.168 14.222,13.835 14.115,14.994 C 14.099,15.675 14.158,16.228 14.422,16.856 C 14.109,16.759 13.87,16.672 13.595,16.489 C 13.563,16.603 13.531,16.716 13.498,16.833 C 13.279,17.493 12.925,18.134 12.467,18.657 C 12.309,18.877 12.309,18.877 12.315,19.07 C 12.413,19.269 12.522,19.396 12.677,19.554 C 12.985,19.893 13.235,20.25 13.481,20.634 C 13.515,20.688 13.55,20.741 13.585,20.797 C 14.146,21.686 14.146,21.686 14.146,22 C 13.75,21.874 13.374,21.722 12.993,21.558 C 11.378,20.9 9.722,20.714 7.992,20.622 C 8.028,20.575 8.064,20.528 8.101,20.479 C 8.37,20.121 8.637,19.761 8.894,19.394 C 8.947,19.317 9.001,19.241 9.056,19.162 C 9.187,18.969 9.187,18.969 9.278,18.785 C 9.245,18.78 9.245,18.78 9.077,18.756 C 8.797,18.688 8.6,18.576 8.36,18.418 C 8.36,18.478 8.36,18.539 8.36,18.602 C 7.479,18.463 6.695,17.922 6.155,17.224 C 5.981,16.926 5.832,16.623 5.696,16.305 C 5.74,16.453 5.784,16.6 5.828,16.747 C 5.853,16.829 5.877,16.911 5.903,16.996 C 5.954,17.164 6.008,17.332 6.064,17.499 C 5.299,17.281 4.772,16.857 4.318,16.213 C 3.714,15.033 3.82,13.901 4.043,12.631 C 3.577,13.432 3.387,14.102 3.308,15.019 C 2.824,14.591 2.572,13.903 2.481,13.274 C 2.397,11.547 3.913,10.126 4.944,8.882 C 5.479,8.227 5.879,7.592 6.224,6.822 C 6.567,6.064 6.997,5.455 7.533,4.824 C 7.593,4.75 7.652,4.675 7.713,4.599 C 10.235,1.556 15.063,1.158 18.163,3.549 Z M 11.024,12.539 L 13.412,14.009 L 13.412,14.56 L 11.024,16.03 L 11.024,15.203 L 12.585,14.284 L 11.024,13.366 L 11.024,12.539 Z"
diff --git a/apps/desktop/native/menubar/wordmark-dark.png b/apps/desktop/native/menubar/wordmark-dark.png
new file mode 100644
index 0000000000..61ab6b7b60
Binary files /dev/null and b/apps/desktop/native/menubar/wordmark-dark.png differ
diff --git a/apps/desktop/native/menubar/wordmark-light.png b/apps/desktop/native/menubar/wordmark-light.png
new file mode 100644
index 0000000000..1f34d34fcc
Binary files /dev/null and b/apps/desktop/native/menubar/wordmark-light.png differ
diff --git a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
index c1be46dfab..2d4ef7527b 100644
--- a/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/MacAgentIslandNativeHost.test.ts
@@ -13,6 +13,7 @@ import {
createEmptyAgentIslandPillSnapshot,
type AgentIslandDisplayState,
} from '../../../shared/agentIsland.js';
+import { CLAUDE_CODE_MARK_PATH, CODEX_FLOWER_OUTLINE, CODEX_PROMPT_GLYPHS } from '../../../shared/brandMarkPaths.js';
import type { AgentIslandNativeFrame } from '../MacAgentIslandNativeHost.js';
const h = vi.hoisted(() => ({
@@ -126,9 +127,13 @@ describe('MacAgentIslandNativeHost', () => {
new URL('../../../renderer/components/icons/CodexMark.tsx', import.meta.url),
'utf8',
);
- const claudePath = claudeSource.match(/<path[\s\S]*?\bd="([^"]+)"/)?.[1];
- const codexOutline = codexSource.match(/const FLOWER_OUTLINE =\s*'([^']+)'/)?.[1];
- const codexPrompt = codexSource.match(/const PROMPT_GLYPHS =\s*'([^']+)'/)?.[1];
+ // The renderer icons draw these shared paths; the native helper must carry the same ones.
+ expect(claudeSource).toContain('d={CLAUDE_CODE_MARK_PATH}');
+ expect(codexSource).toContain('d={`${CODEX_FLOWER_OUTLINE}z`}');
+ expect(codexSource).toContain('d={CODEX_PROMPT_GLYPHS}');
+ const claudePath = CLAUDE_CODE_MARK_PATH;
+ const codexOutline = CODEX_FLOWER_OUTLINE;
+ const codexPrompt = CODEX_PROMPT_GLYPHS;
const codexSmallStrokeWidth = codexSource.match(
/const monoStrokeWidth = size <= 14 \? ([\d.]+) : [\d.]+;/,
)?.[1];
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 2a244ef953..8210967337 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -5,6 +5,8 @@ import { listWorktreeRecycleStatus, controlWorktreeRecycle } from './worktree/re
import { registerFilePeerIpc } from './device-link/filePeer';
import { registerTaskMigrationIpc } from './task-migration/service';
import { registerLoginItemIpc } from './login-item-ipc.js';
+import { registerMenubarIpc } from './menubar/ipc.js';
+import { initMenubarService, refreshMenubarLocalization, stopMenubarService } from './menubar/service.js';
import {
createLatestSourceVersionReader,
sourceChannel,
@@ -2410,6 +2412,7 @@ registerAppShortcutIpc();
registerAppearanceSettingsIpc();
registerAccessibilitySupportIpc();
registerLoginItemIpc();
+registerMenubarIpc();
// ── 资源用量面板 IPC ─────────────────────────────────────────────────
// 订阅驱动采样(面板不开不采样),interval 已 unref 不拖退出;terminate 只认
@@ -2977,6 +2980,7 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
}
invalidateWindowsTrayMenu();
getAgentIslandService()?.refreshLocalization();
+ refreshMenubarLocalization();
return { ok: true };
});
@@ -4352,6 +4356,15 @@ const registerIpcHandlers = () => {
});
});
+ // macOS 菜单栏余量:原生 helper 在 Agent Island 之后启动,复用它的任务活动订阅。
+ initMenubarService({
+ openNewTask: () => {
+ const win = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;
+ if (win) dispatchApplicationMenuCommand(win, resolveNewMakerMenuCommand(false));
+ },
+ });
+ app.once('will-quit', stopMenubarService);
+
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session, 初始 bounds 取主窗。
ipcMain.handle(
MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW,
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index d7e6913bcc..f738af44ce 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -88,7 +88,7 @@ export type DeepLinkPayload =
* 供应商接入流程)。URL 域只开放 tab=providers;connect 是可选的内置
* provider / preset id,经白名单校验后透传给 renderer 已有的消费逻辑。
*/
- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string }
+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' }
/**
* 纯"把窗口拉回前台"意图,不携带导航语义 (典型来源:OAuth 授权成功页的
* "打开 xdt-maker" 按钮 / 自动唤起)。main 进程内消化,不发给 renderer、
@@ -398,6 +398,11 @@ export function openMainWindowVoiceSettings(tab: 'voice-input' | 'providers'): v
dispatchDeepLink({ type: 'settings', tab });
}
+/** 主进程内部入口(菜单栏余量面板)打开账单页的充值流程;URL 深链不开放这个 tab。 */
+export function openMainWindowBillingTopUp(): void {
+ dispatchDeepLink({ type: 'settings', tab: 'billing', intent: 'topup' });
+}
+
/**
* 主进程内部发起的会话聚焦(workspace 槽 focus:true)。复用 deep link 的
* 前台 + renderer dispatch 通道,行为与用户点 cindy://session/<id> 一致。
diff --git a/apps/desktop/src/main/i18n.ts b/apps/desktop/src/main/i18n.ts
index de6112a672..8b884fbf13 100644
--- a/apps/desktop/src/main/i18n.ts
+++ b/apps/desktop/src/main/i18n.ts
@@ -140,3 +140,36 @@ export function lookupWithFallbackForTest(
const fallbackBundle = bundles[DEFAULT_LOCALE];
return (fallbackBundle ? lookup(fallbackBundle, key) : null) ?? key;
}
+
+/**
+ * Raw template for `key` (no interpolation) walking the same fallback chain as t(), or null
+ * when no locale has it. For native surfaces that fill their own placeholders.
+ */
+export function rawMainString(key: string, locale?: SupportedLocale): string | null {
+ const loc = locale ?? getMainLocale();
+ for (const chainLocale of FALLBACK_CHAIN[loc]) {
+ const raw = lookup(resources[chainLocale], key);
+ if (raw !== null) return raw.replaceAll('{{appName}}', BRAND_NAME);
+ }
+ return null;
+}
+
+/** Leaf keys under `prefix` in the default locale, relative to `prefix` (dot-separated). */
+export function mainStringKeysUnder(prefix: string): string[] {
+ let cur: unknown = resources[DEFAULT_LOCALE];
+ for (const part of prefix.split('.')) {
+ if (typeof cur !== 'object' || cur === null) return [];
+ cur = (cur as Record<string, unknown>)[part];
+ }
+ const keys: string[] = [];
+ const walk = (node: unknown, path: string): void => {
+ if (typeof node === 'string') {
+ keys.push(path);
+ return;
+ }
+ if (typeof node !== 'object' || node === null) return;
+ for (const [key, value] of Object.entries(node)) walk(value, path ? `${path}.${key}` : key);
+ };
+ walk(cur, '');
+ return keys;
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2907cc83fc..f502313e69 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -481,7 +481,7 @@ import {
orcaWorkerCreationReservations,
sessions,
} from '../localDb/schema.js';
-import { nextBotModelRoute, normalizeBotModelChain } from '../../shared/botModelChain.js';
+import { nextBotModelRoute, normalizeBotModelChain, type BotModelRoute } from '../../shared/botModelChain.js';
import { createBotModelRouteReconciler } from './botModelRouteReconciler.js';
import { readEffectiveBotModelChain, readEffectiveBotModelSelection } from '../maker-host/bot-model-chain-settings-store.js';
import {
@@ -5594,6 +5594,21 @@ export interface RegisterMakerIpcOptions {
let disposePiPackagesChangedBroadcast: (() => void) | null = null;
+/**
+ * Preselects a route in the local new-task draft, the same push the app-default model
+ * selection uses. The menu bar calls it before opening a new task for one account.
+ */
+export function applyNewMakerDraftRoute(route: BotModelRoute): void {
+ broadcastToAllWindows(MAKER_PUSH.DRAFT_PREF_APPLY, {
+ agent: route.harness === 'claude' ? 'claude-code' : route.harness,
+ providerId: route.providerId ?? '',
+ modelId: route.model,
+ active: true,
+ ...(route.effort ? { effort: route.effort } : {}),
+ ...(route.fastMode ? { fast: true } : {}),
+ });
+}
+
/**
* Register before the first BrowserWindow: modelVisibilityPrefs mirrors its initial snapshot as
* soon as the Renderer selects an owner, before the splash-gated Maker IPC bundle is available.
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index 5d2c7acb7b..ee56c12c98 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -6,6 +6,7 @@
* handler 时拉起 Electron / runtime config 副作用。
*/
+import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import type { XaiSubscriptionUsageSnapshot } from '../../shared/xaiSubscriptionUsage.js';
import { createHash } from 'node:crypto';
import { readSubscriptionAccountUsage, triggerSubscriptionAccountUsage, syncSubscriptionAccountUsage, setSubscriptionAccountUsageBroadcaster } from '../usage/subscriptionAccountUsage.js';
@@ -248,6 +249,17 @@ export function triggerCodexAccountUsageRefresh(providerId?: string): void {
});
}
+type CodexRateLimitsReader = (providerId?: string) => Promise<MobileCodexRateLimitsResult>;
+let codexRateLimitsReader: CodexRateLimitsReader | null = null;
+
+/**
+ * Codex 限额与重置次数的同一次读取(与设置页、用量 chip 同一个 reset service)。供菜单栏等
+ * 主进程消费方使用;IPC 尚未注册时返回 null。
+ */
+export async function readCodexRateLimitsForHost(providerId?: string): Promise<MobileCodexRateLimitsResult | null> {
+ return codexRateLimitsReader ? codexRateLimitsReader(providerId) : null;
+}
+
export function registerMakerUsageIpc(maker: Maker): void {
log.info('registering maker:usage:* IPC handlers');
@@ -284,22 +296,25 @@ export function registerMakerUsageIpc(maker: Maker): void {
return service;
}
+ // Bind recovery confirmation to the exact owner, marker and OAuth credential observed before
+ // this account-level RPC. A stale response still returns its usage payload but cannot consume a
+ // newer recovery state.
+ const readCodexRateLimits: CodexRateLimitsReader = async (providerId) => {
+ const scope = activeOwnerScopeKey();
+ const service = getResetService(providerId);
+ const result = providerId && providerId !== 'openai'
+ ? await service.read()
+ : await desktopCodexAuthAdapter.verifyRecoveryWithAccountRpc(() => service.read());
+ if (scope !== activeOwnerScopeKey()) throw new Error('PRECONDITION_FAILED: Account scope changed');
+ return { ...result, providerId: providerId ?? 'openai' };
+ };
+ codexRateLimitsReader = readCodexRateLimits;
+
setSubscriptionAccountUsageBroadcaster(broadcastSubscriptionAccountUsage, clearXaiRateLimitSnapshot);
registerMakerUsageHandlers(createElectronIpcHandlerRegistry(), {
readAgentTodayUsage,
readCodexAccountUsageSnapshot: readCodexAccountUsageSnapshotWithWebRefresh,
- // Bind recovery confirmation to the exact owner, marker and OAuth credential observed before
- // this account-level RPC. A stale response still returns its usage payload but cannot consume a
- // newer recovery state.
- readCodexRateLimits: async (providerId) => {
- const scope = activeOwnerScopeKey();
- const service = getResetService(providerId);
- const result = providerId && providerId !== 'openai'
- ? await service.read()
- : await desktopCodexAuthAdapter.verifyRecoveryWithAccountRpc(() => service.read());
- if (scope !== activeOwnerScopeKey()) throw new Error('PRECONDITION_FAILED: Account scope changed');
- return { ...result, providerId: providerId ?? 'openai' };
- },
+ readCodexRateLimits,
consumeCodexRateLimitReset: async (key, providerId) => {
const scope = activeOwnerScopeKey();
const result = await getResetService(providerId).consume(key);
diff --git a/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts b/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts
new file mode 100644
index 0000000000..e6eb92fa34
--- /dev/null
+++ b/apps/desktop/src/main/menubar/MacMenubarNativeHost.ts
@@ -0,0 +1,446 @@
+/**
+ * Runs the macOS menu bar helper (SwiftUI status item + panel) and talks to it over
+ * newline-delimited JSON on stdin/stdout.
+ *
+ * Same lifecycle as the Agent Island helper: a `ready` handshake, a bounded number of
+ * restarts with backoff, and `suspend()` for when the user turns the menu bar item off.
+ */
+
+import { app } from 'electron';
+import { execFile, spawn, type ChildProcessByStdio } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import type { Readable, Writable } from 'node:stream';
+
+import {
+ MENUBAR_STATUS_TEXT_MODES,
+ MENUBAR_USAGE_SCOPES,
+ type MenubarHelperMessage,
+ type MenubarSettingsPatch,
+ type MenubarView,
+} from '../../shared/menubarQuota.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('menubar:native');
+
+const HELPER_NAME = 'xdt-macos-menubar-helper';
+const HELPER_RESOURCE = path.join('tools', 'menubar', HELPER_NAME);
+const HELPER_SOURCE_RELATIVE = path.join('native', 'menubar', 'macos-menubar-helper.swift');
+const HELPER_ASSETS = ['wordmark-light.png', 'wordmark-dark.png'] as const;
+const HELPER_DEPLOYMENT_TARGET = 'macos14.0';
+const HELPER_START_TIMEOUT_MS = 2_500;
+const HELPER_RESTART_MAX_ATTEMPTS = 3;
+const HELPER_RESTART_BASE_DELAY_MS = 1_000;
+const HELPER_RESTART_MAX_DELAY_MS = 5_000;
+const HELPER_RESTART_HEALTHY_RESET_MS = 30_000;
+const DEV_BUILD_TIMEOUT_MS = 180_000;
+
+type NativeProcess = ChildProcessByStdio<Writable, Readable, Readable>;
+
+export interface MacMenubarNativeHostOptions {
+ onMessage: (message: MenubarHelperMessage) => void;
+}
+
+export class MacMenubarNativeHost {
+ private child: NativeProcess | null = null;
+ private starting: Promise<boolean> | null = null;
+ private ready = false;
+ private stdoutBuffer = '';
+ private pendingView: MenubarView | null = null;
+ private pendingOpen = false;
+ private restartTimer: ReturnType<typeof setTimeout> | null = null;
+ private restartHealthyTimer: ReturnType<typeof setTimeout> | null = null;
+ private restartAttempts = 0;
+ private permanentlyFailed = false;
+ /** Set by stop(): the app is quitting and the helper must never come back. */
+ private stopped = false;
+ private lifecycleToken = 0;
+ private helperBinaryPath: string | null = null;
+ private helperBinaryPromise: Promise<string> | null = null;
+
+ constructor(private readonly options: MacMenubarNativeHostOptions) {}
+
+ get failed(): boolean {
+ return this.permanentlyFailed;
+ }
+
+ get running(): boolean {
+ return this.ready && this.child !== null;
+ }
+
+ /** Sends the latest view; the helper starts on first publish. */
+ publish(view: MenubarView): boolean {
+ if (this.permanentlyFailed) return false;
+ this.pendingView = view;
+ if (this.ready && this.child) {
+ this.write({ type: 'update', view });
+ return true;
+ }
+ if (!this.restartTimer) void this.ensureStarted();
+ return true;
+ }
+
+ /** Opens the panel under the status item (used by the app menu and deep links). */
+ open(): void {
+ if (this.permanentlyFailed) return;
+ if (this.ready && this.child) {
+ this.write({ type: 'open' });
+ return;
+ }
+ this.pendingOpen = true;
+ if (!this.restartTimer) void this.ensureStarted();
+ }
+
+ prepare(): void {
+ if (this.permanentlyFailed) return;
+ void this.resolveHelperBinary().catch((error) => {
+ log.warn('menu bar helper prewarm failed', { error: errorMessage(error) });
+ });
+ }
+
+ stop(): void {
+ this.stopped = true;
+ this.permanentlyFailed = true;
+ this.suspend();
+ }
+
+ /** Gives a helper that hit the restart limit another chance, e.g. when the user turns the item back on. */
+ resetFailure(): void {
+ if (this.stopped) return;
+ this.permanentlyFailed = false;
+ this.restartAttempts = 0;
+ }
+
+ /** Removes the status item but keeps the host reusable for a later publish. */
+ suspend(): void {
+ this.lifecycleToken += 1;
+ this.clearRestartTimer();
+ this.clearRestartHealthyTimer();
+ this.restartAttempts = 0;
+ this.pendingView = null;
+ this.pendingOpen = false;
+ this.stdoutBuffer = '';
+ const child = this.child;
+ this.child = null;
+ this.ready = false;
+ this.starting = null;
+ if (!child || child.killed) return;
+ try {
+ child.stdin.write(`${JSON.stringify({ type: 'shutdown' })}\n`);
+ } catch {
+ // The process may already be gone.
+ }
+ child.kill();
+ }
+
+ private write(payload: Record<string, unknown>): void {
+ if (!this.child) return;
+ try {
+ this.child.stdin.write(`${JSON.stringify(payload)}\n`);
+ } catch (error) {
+ log.warn('failed to write to menu bar helper', { type: payload.type, error: errorMessage(error) });
+ }
+ }
+
+ private async ensureStarted(): Promise<boolean> {
+ if (this.ready && this.child) return true;
+ if (this.starting) return this.starting;
+ const starting = this.startChildProcess().finally(() => {
+ // A start abandoned by suspend() must not clear a newer one.
+ if (this.starting === starting) this.starting = null;
+ });
+ this.starting = starting;
+ return starting;
+ }
+
+ private async startChildProcess(): Promise<boolean> {
+ const lifecycleToken = this.lifecycleToken;
+ let binary: string;
+ try {
+ binary = await this.resolveHelperBinary();
+ } catch (error) {
+ this.permanentlyFailed = true;
+ log.warn('menu bar helper could not be prepared; the menu bar item stays hidden', {
+ error: errorMessage(error),
+ });
+ return false;
+ }
+ if (this.lifecycleToken !== lifecycleToken || this.permanentlyFailed) return false;
+
+ return new Promise<boolean>((resolve) => {
+ let settled = false;
+ const child = spawn(binary, [], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env: { ...process.env, CINDY_MENUBAR_ASSET_DIR: path.dirname(binary) },
+ });
+ if (this.lifecycleToken !== lifecycleToken || this.permanentlyFailed) {
+ if (!child.killed) child.kill();
+ resolve(false);
+ return;
+ }
+ this.child = child;
+ this.ready = false;
+ this.stdoutBuffer = '';
+
+ let startTimer: ReturnType<typeof setTimeout> | null = null;
+ const settle = (ok: boolean): void => {
+ if (settled) return;
+ settled = true;
+ if (startTimer) clearTimeout(startTimer);
+ if (!ok) {
+ if (this.child === child) {
+ this.child = null;
+ this.ready = false;
+ }
+ // Also covers a child from an abandoned start that is no longer current.
+ if (!child.killed) child.kill();
+ }
+ resolve(ok);
+ };
+
+ startTimer = setTimeout(() => {
+ if (this.lifecycleToken !== lifecycleToken || this.permanentlyFailed) {
+ settle(false);
+ return;
+ }
+ log.warn('menu bar helper did not become ready in time');
+ settle(false);
+ this.scheduleRestart(null, null);
+ }, HELPER_START_TIMEOUT_MS);
+
+ child.stdout.setEncoding('utf8');
+ child.stdout.on('data', (chunk: string) => {
+ this.stdoutBuffer += chunk;
+ let newlineIndex = this.stdoutBuffer.indexOf('\n');
+ while (newlineIndex >= 0) {
+ const line = this.stdoutBuffer.slice(0, newlineIndex).trim();
+ this.stdoutBuffer = this.stdoutBuffer.slice(newlineIndex + 1);
+ if (line) this.handleLine(line, child, settle);
+ newlineIndex = this.stdoutBuffer.indexOf('\n');
+ }
+ });
+
+ child.stderr.setEncoding('utf8');
+ child.stderr.on('data', (chunk: string) => {
+ const text = chunk.trim();
+ if (text) log.debug('menu bar helper stderr', { text });
+ });
+
+ const onLost = (reason: string, code: number | null, signal: NodeJS.Signals | null): void => {
+ const wasCurrent = this.child === child;
+ if (wasCurrent) {
+ this.child = null;
+ this.ready = false;
+ this.clearRestartHealthyTimer();
+ if (!child.killed) child.kill();
+ }
+ if (!settled) settle(false);
+ log.debug('menu bar helper lost', { reason, code, signal });
+ if (wasCurrent && this.pendingView && !this.permanentlyFailed) this.scheduleRestart(code, signal);
+ };
+ child.stdin.on('error', (error) => onLost(`stdin: ${error.message}`, null, null));
+ child.on('error', (error) => onLost(`process: ${error.message}`, null, null));
+ child.on('exit', (code, signal) => onLost('exit', code, signal));
+ });
+ }
+
+ private handleLine(line: string, child: NativeProcess, settle: (ok: boolean) => void): void {
+ if (this.child !== child) return;
+ let payload: unknown;
+ try {
+ payload = JSON.parse(line);
+ } catch {
+ log.debug('menu bar helper emitted non-json line', { line });
+ return;
+ }
+ const message = parseHelperMessage(payload);
+ if (!message) {
+ log.debug('menu bar helper emitted unknown message', { line: line.slice(0, 200) });
+ return;
+ }
+ if (message.type === 'ready') {
+ this.ready = true;
+ settle(true);
+ this.armRestartHealthyReset(child);
+ if (this.pendingView) this.write({ type: 'update', view: this.pendingView });
+ if (this.pendingOpen) {
+ this.pendingOpen = false;
+ this.write({ type: 'open' });
+ }
+ return;
+ }
+ if (message.type === 'error') {
+ log.warn('menu bar helper reported an error', { message: message.message });
+ return;
+ }
+ this.options.onMessage(message);
+ }
+
+ private resolveHelperBinary(): Promise<string> {
+ if (this.helperBinaryPath) return Promise.resolve(this.helperBinaryPath);
+ if (this.helperBinaryPromise) return this.helperBinaryPromise;
+ this.helperBinaryPromise = resolveHelperBinary()
+ .then((binaryPath) => {
+ this.helperBinaryPath = binaryPath;
+ return binaryPath;
+ })
+ .finally(() => {
+ this.helperBinaryPromise = null;
+ });
+ return this.helperBinaryPromise;
+ }
+
+ private scheduleRestart(code: number | null, signal: NodeJS.Signals | null): void {
+ if (this.restartTimer || this.permanentlyFailed) return;
+ if (this.restartAttempts >= HELPER_RESTART_MAX_ATTEMPTS) {
+ this.permanentlyFailed = true;
+ log.warn('menu bar helper restart limit reached; the menu bar item stays hidden', { code, signal });
+ return;
+ }
+ this.restartAttempts += 1;
+ const delayMs = Math.min(HELPER_RESTART_BASE_DELAY_MS * 2 ** (this.restartAttempts - 1), HELPER_RESTART_MAX_DELAY_MS);
+ log.warn('menu bar helper exited unexpectedly; scheduling restart', {
+ attempt: this.restartAttempts,
+ code,
+ signal,
+ delayMs,
+ });
+ this.restartTimer = setTimeout(() => {
+ this.restartTimer = null;
+ if (this.ready || this.child || this.permanentlyFailed) return;
+ void this.ensureStarted();
+ }, delayMs);
+ }
+
+ private clearRestartTimer(): void {
+ if (!this.restartTimer) return;
+ clearTimeout(this.restartTimer);
+ this.restartTimer = null;
+ }
+
+ private armRestartHealthyReset(child: NativeProcess): void {
+ this.clearRestartHealthyTimer();
+ this.restartHealthyTimer = setTimeout(() => {
+ this.restartHealthyTimer = null;
+ if (this.child === child && this.ready) this.restartAttempts = 0;
+ }, HELPER_RESTART_HEALTHY_RESET_MS);
+ }
+
+ private clearRestartHealthyTimer(): void {
+ if (!this.restartHealthyTimer) return;
+ clearTimeout(this.restartHealthyTimer);
+ this.restartHealthyTimer = null;
+ }
+}
+
+/** Validates helper output; the helper is ours, but main never trusts a child process blindly. */
+export function parseHelperMessage(input: unknown): MenubarHelperMessage | null {
+ if (!input || typeof input !== 'object') return null;
+ const value = input as Record<string, unknown>;
+ switch (value.type) {
+ case 'ready':
+ case 'refresh':
+ case 'open-app':
+ case 'open-provider-settings':
+ return { type: value.type };
+ case 'error':
+ return { type: 'error', message: typeof value.message === 'string' ? value.message.slice(0, 500) : '' };
+ case 'panel':
+ return typeof value.open === 'boolean' ? { type: 'panel', open: value.open } : null;
+ case 'open-session':
+ return typeof value.sessionId === 'string' && value.sessionId ? { type: 'open-session', sessionId: value.sessionId } : null;
+ case 'detail-action':
+ return typeof value.sourceId === 'string' && value.sourceId ? { type: 'detail-action', sourceId: value.sourceId } : null;
+ case 'settings':
+ return value.patch && typeof value.patch === 'object'
+ ? { type: 'settings', patch: pickSettingsPatch(value.patch as Record<string, unknown>) }
+ : null;
+ default:
+ return null;
+ }
+}
+
+function pickSettingsPatch(raw: Record<string, unknown>): MenubarSettingsPatch {
+ const patch: MenubarSettingsPatch = {};
+ for (const key of ['order', 'hidden', 'shown'] as const) {
+ if (Array.isArray(raw[key])) patch[key] = (raw[key] as unknown[]).filter((id): id is string => typeof id === 'string');
+ }
+ for (const key of ['lowAlert', 'privacy'] as const) {
+ if (typeof raw[key] === 'boolean') patch[key] = raw[key] as boolean;
+ }
+ if (MENUBAR_STATUS_TEXT_MODES.includes(raw.statusText as never)) patch.statusText = raw.statusText as MenubarSettingsPatch['statusText'];
+ if (MENUBAR_USAGE_SCOPES.includes(raw.scope as never)) patch.scope = raw.scope as MenubarSettingsPatch['scope'];
+ return patch;
+}
+
+async function resolveHelperBinary(): Promise<string> {
+ if (app.isPackaged) return path.join(process.resourcesPath, HELPER_RESOURCE);
+ await buildDevHelper();
+ return devBinaryPath();
+}
+
+/** Dev builds compile the single-file helper on demand, keyed by the source hash. */
+async function buildDevHelper(): Promise<void> {
+ const source = devSourcePath(HELPER_SOURCE_RELATIVE);
+ const binary = devBinaryPath();
+ if (!fs.existsSync(source)) throw new Error(`menu bar helper source missing at ${source}`);
+ copyDevAssets(path.dirname(source), path.dirname(binary));
+ const sourceHash = createHash('sha256').update(fs.readFileSync(source)).digest('hex');
+ const hashFile = `${binary}.sha256`;
+ if (fs.existsSync(binary) && fs.existsSync(hashFile) && fs.readFileSync(hashFile, 'utf8').trim() === sourceHash) {
+ return;
+ }
+ fs.mkdirSync(path.dirname(binary), { recursive: true });
+ const arch = process.arch === 'arm64' ? 'arm64' : 'x86_64';
+ await execFilePromise(
+ 'swiftc',
+ [source, '-O', '-parse-as-library', '-target', `${arch}-apple-${HELPER_DEPLOYMENT_TARGET}`, '-o', binary],
+ DEV_BUILD_TIMEOUT_MS,
+ );
+ fs.chmodSync(binary, 0o755);
+ fs.writeFileSync(hashFile, `${sourceHash}\n`, 'utf8');
+ log.info('built dev macOS menu bar helper', { path: binary });
+}
+
+function devSourcePath(relative: string): string {
+ const fromAppPath = path.join(app.getAppPath(), relative);
+ if (fs.existsSync(fromAppPath)) return fromAppPath;
+ return path.join(__dirname, '..', '..', relative);
+}
+
+function devBinaryPath(): string {
+ return path.join(app.getPath('userData'), 'menubar', HELPER_NAME);
+}
+
+function copyDevAssets(sourceDir: string, destDir: string): void {
+ fs.mkdirSync(destDir, { recursive: true });
+ for (const name of HELPER_ASSETS) {
+ const source = path.join(sourceDir, name);
+ if (!fs.existsSync(source)) throw new Error(`menu bar helper asset missing at ${source}`);
+ const dest = path.join(destDir, name);
+ const sourceStat = fs.statSync(source);
+ if (fs.existsSync(dest)) {
+ const destStat = fs.statSync(dest);
+ if (destStat.mtimeMs >= sourceStat.mtimeMs && destStat.size === sourceStat.size) continue;
+ }
+ fs.copyFileSync(source, dest);
+ }
+}
+
+function execFilePromise(file: string, args: string[], timeoutMs: number): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const child = execFile(file, args, { timeout: timeoutMs }, (error, _stdout, stderr) => {
+ if (error) {
+ reject(new Error(stderr?.trim() ? `${error.message}: ${stderr.trim()}` : error.message));
+ return;
+ }
+ resolve();
+ });
+ child.on('error', reject);
+ });
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
diff --git a/apps/desktop/src/main/menubar/__tests__/collect.test.ts b/apps/desktop/src/main/menubar/__tests__/collect.test.ts
new file mode 100644
index 0000000000..d01c682883
--- /dev/null
+++ b/apps/desktop/src/main/menubar/__tests__/collect.test.ts
@@ -0,0 +1,232 @@
+import type { ProviderView } from '@cindy/model-providers';
+import { describe, expect, it } from 'vitest';
+
+import {
+ claudeSource,
+ codexSource,
+ collectMenubarInputs,
+ dayKeysEndingAt,
+ distinctRemoteSubscriptions,
+ paygSource,
+ planLabel,
+ type MenubarCollectDeps,
+} from '../collect';
+import { topModels, type MenubarSubscriptionInput } from '../snapshot';
+
+const NOW = Date.UTC(2026, 9, 11, 3, 0, 0);
+const nowSec = NOW / 1000;
+
+function provider(overrides: Partial<ProviderView> & { id: string }): ProviderView {
+ return {
+ name: overrides.id,
+ connected: true,
+ suspended: false,
+ removed: false,
+ source: 'builtin',
+ auth: { method: 'oauth' },
+ access: { kind: 'subscription' },
+ ...overrides,
+ } as unknown as ProviderView;
+}
+
+describe('source mapping', () => {
+ it('reads the generic Codex bucket and its credits', () => {
+ const source = codexSource(
+ provider({ id: 'codex-a', openAiAccount: { identity: '[email protected]' } } as never),
+ {
+ planType: 'pro',
+ appServerBuckets: {
+ codex: {
+ limitId: 'codex',
+ primary: { usedPercent: 40, windowMinutes: 10_080, resetsAt: nowSec + 86_400 },
+ credits: { hasCredits: true, unlimited: false, balance: '1234.5' },
+ },
+ },
+ } as never,
+ NOW,
+ );
+ expect(source).toMatchObject({
+ account: '[email protected]',
+ plan: 'Pro',
+ credits: 1234.5,
+ windows: [{ kind: 'week', usedPercent: 40, resetsAtMs: (nowSec + 86_400) * 1000 }],
+ });
+ });
+
+ it('drops a window whose reset already passed', () => {
+ const source = codexSource(
+ provider({ id: 'openai' }),
+ { primary: { usedPercent: 90, windowMinutes: 300, resetsAt: nowSec - 10 } } as never,
+ NOW,
+ );
+ expect(source.windows).toEqual([]);
+ });
+
+ it('maps Claude session, week and per-model windows', () => {
+ const source = claudeSource(
+ provider({ id: 'anthropic' }),
+ {
+ subscriptionType: 'max',
+ fiveHour: { utilization: 10, resetsAt: nowSec + 3600 },
+ sevenDay: { utilization: 30, resetsAt: nowSec + 86_400 },
+ scoped: [{ modelDisplayName: 'Fable', utilization: 50, resetsAt: nowSec + 86_400 }],
+ } as never,
+ NOW,
+ );
+ expect(source.account).toBeNull();
+ expect(source.windows.map((w) => [w.kind, w.label ?? null, w.usedPercent])).toEqual([
+ ['session', null, 10],
+ ['week', null, 30],
+ ['scoped', 'Fable', 50],
+ ]);
+ });
+
+ it('leaves local runtimes and the Cindy gateway out of pay-as-you-go', () => {
+ expect(paygSource(provider({ id: 'ollama', auth: { method: 'none' } } as never))).toBeNull();
+ expect(paygSource(provider({ id: 'xd', auth: { method: 'apiKey' } } as never))).toBeNull();
+ expect(paygSource(provider({ id: 'glm', name: 'GLM', auth: { method: 'apiKey' }, access: { kind: 'api' } } as never))).toMatchObject({
+ kind: 'payg',
+ billing: 'api',
+ });
+ });
+
+ it('formats plan labels', () => {
+ expect(planLabel('max_20x')).toBe('Max 20x');
+ expect(planLabel('SuperGrok Heavy')).toBe('SuperGrok Heavy');
+ expect(planLabel(' ')).toBeNull();
+ });
+
+ it('lists calendar days across a month boundary', () => {
+ expect(dayKeysEndingAt('2026-10-02', 3)).toEqual(['2026-09-30', '2026-10-01', '2026-10-02']);
+ });
+});
+
+describe('collectMenubarInputs', () => {
+ function deps(overrides: Partial<MenubarCollectDeps> = {}): MenubarCollectDeps {
+ return {
+ nowMs: NOW,
+ listProviders: async () => [
+ provider({ id: 'openai', auth: { method: 'oauth', native: 'codex' } } as never),
+ provider({ id: 'anthropic' }),
+ ],
+ readCodex: async () => ({ primary: { usedPercent: 20, windowMinutes: 10_080, resetsAt: nowSec + 86_400 } }) as never,
+ readClaude: async () => {
+ throw new Error('offline');
+ },
+ readXai: async () => null,
+ readBalance: async () => null,
+ readUsage: async () => null,
+ activities: () => [],
+ sessionRow: async () => null,
+ selfDeviceName: 'Mac',
+ ...overrides,
+ };
+ }
+
+ it('keeps the other sources when one reader fails', async () => {
+ const errors: string[] = [];
+ const collected = await collectMenubarInputs(deps({ onError: (scope) => errors.push(scope) }));
+ expect(collected.sources.map((s) => s.id)).toEqual(['openai', 'anthropic']);
+ expect(errors).toEqual(['claude:anthropic']);
+ const claude = collected.sources[1];
+ expect(claude.kind === 'subscription' && claude.windows).toEqual([]);
+ });
+
+ it('keeps a Codex account that needs reconnecting as a subscription without numbers', async () => {
+ let codexReads = 0;
+ const collected = await collectMenubarInputs(
+ deps({
+ listProviders: async () => [
+ provider({
+ id: 'codex-b',
+ auth: { method: 'oauth', native: 'codex' },
+ openAiAccount: { identity: '[email protected]', reconnectRequired: true },
+ } as never),
+ ],
+ readCodex: async () => {
+ codexReads += 1;
+ return null;
+ },
+ }),
+ );
+ expect(collected.sources).toEqual([
+ expect.objectContaining({ kind: 'subscription', id: 'codex-b', account: '[email protected]', windows: [] }),
+ ]);
+ expect(codexReads).toBe(0);
+ });
+
+ it('puts the Cindy balance first and lists running tasks', async () => {
+ const collected = await collectMenubarInputs(
+ deps({
+ readBalance: async () => ({ available: 5, fullAmount: 10, burnPerDay: 1, observedAtMs: NOW, currency: 'USD', quota: null }),
+ activities: () => [{ sessionId: 's1', phase: 'running', startedAtMs: NOW - 60_000, lastActivityAtMs: NOW } as never],
+ sessionRow: async () => ({ title: 'Fix the chart', model: 'gpt-6-astra', agentKind: 'codex' }),
+ }),
+ );
+ expect(collected.sources[0]).toMatchObject({ kind: 'balance', id: 'cindy', available: 5 });
+ expect(collected.tasks).toEqual([
+ expect.objectContaining({ sessionId: 's1', title: 'Fix the chart', harness: 'codex', running: true, startedAtMs: NOW - 60_000 }),
+ ]);
+ expect(collected.usage.days).toHaveLength(90);
+ });
+});
+
+describe('distinctRemoteSubscriptions', () => {
+ const week = (usedPercent: number, resetsAtMs = NOW + 3 * 86_400_000) =>
+ ({ kind: 'week' as const, usedPercent, resetsAtMs, windowMinutes: 10_080 });
+
+ function sub(id: string, extra: Partial<MenubarSubscriptionInput> = {}): MenubarSubscriptionInput {
+ return {
+ kind: 'subscription', id, providerId: 'anthropic', family: 'claude', logoSvg: '', brand: 'Claude',
+ account: null, plan: 'Max', windows: [week(40)], credits: null, creditsUnlimited: false, prepaidUsd: null,
+ updatedAtMs: NOW, accountKeys: [], ...extra,
+ };
+ }
+ const remote = (id: string, extra: Partial<MenubarSubscriptionInput> = {}) =>
+ sub(`remote:${id}`, { device: { id, name: id }, ...extra });
+
+ it('drops an account this computer already shows, matched by its fingerprint', () => {
+ const local = sub('anthropic', { accountKeys: ['claude:fp:abc'], windows: [week(40)] });
+ const same = remote('studio', { accountKeys: ['claude:fp:abc'], windows: [week(55)] });
+ expect(distinctRemoteSubscriptions([local], [same])).toEqual([]);
+ });
+
+ it('keeps a different account even when its numbers happen to match', () => {
+ const local = sub('anthropic', { accountKeys: ['claude:fp:abc'] });
+ const other = remote('studio', { accountKeys: ['claude:fp:xyz'] });
+ expect(distinctRemoteSubscriptions([local], [other])).toEqual([other]);
+ });
+
+ it('does not merge two people in one Codex workspace', () => {
+ const local = sub('openai', { family: 'codex', accountKeys: ['codex:id:ws-1', 'codex:identity:[email protected]'] });
+ const teammate = remote('studio', { family: 'codex', accountKeys: ['codex:id:ws-1', 'codex:identity:[email protected]'] });
+ expect(distinctRemoteSubscriptions([local], [teammate])).toEqual([teammate]);
+ });
+
+ it('falls back to identical windows when neither side names the account', () => {
+ const local = sub('anthropic', { windows: [week(40)] });
+ const mirror = remote('studio', { windows: [week(41, NOW + 3 * 86_400_000 + 30_000)] });
+ const other = remote('laptop', { windows: [week(70)] });
+ expect(distinctRemoteSubscriptions([local], [mirror, other])).toEqual([other]);
+ });
+
+ it('lists an account shared by two other computers once, from the fresher reading', () => {
+ const older = remote('studio', { accountKeys: ['claude:fp:abc'], updatedAtMs: NOW - 600_000 });
+ const newer = remote('laptop', { accountKeys: ['claude:fp:abc'], updatedAtMs: NOW });
+ expect(distinctRemoteSubscriptions([], [older, newer])).toEqual([newer]);
+ });
+
+ it('leaves out other-computer accounts it could not read', () => {
+ expect(distinctRemoteSubscriptions([], [remote('studio', { windows: [] })])).toEqual([]);
+ });
+});
+
+describe('topModels', () => {
+ it('keeps the token leaders even when they cost little', () => {
+ const rows = Array.from({ length: 10 }, (_, i) => ({ name: `paid-${i}`, harness: 'codex' as const, money: 100 - i, tokens: 10 }));
+ rows.push({ name: 'free-heavy', harness: 'codex' as const, money: 0, tokens: 1_000_000 });
+ const top = topModels(rows);
+ expect(top.slice(0, 8).map((row) => row.name)).toEqual(rows.slice(0, 8).map((row) => row.name));
+ expect(top.map((row) => row.name)).toContain('free-heavy');
+ });
+});
diff --git a/apps/desktop/src/main/menubar/__tests__/creditSamples.test.ts b/apps/desktop/src/main/menubar/__tests__/creditSamples.test.ts
new file mode 100644
index 0000000000..25c59ba4d5
--- /dev/null
+++ b/apps/desktop/src/main/menubar/__tests__/creditSamples.test.ts
@@ -0,0 +1,85 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ appendCreditSample,
+ CreditSampleStore,
+ estimateDailyBurn,
+ largestCreditSample,
+} from '../creditSamples';
+
+const DAY = 86_400_000;
+const T0 = Date.UTC(2026, 9, 1);
+
+describe('credit samples', () => {
+ it('estimates burn from drops only and ignores top-ups', () => {
+ const samples = [
+ { atMs: T0, available: 100 },
+ { atMs: T0 + DAY, available: 90 },
+ { atMs: T0 + 2 * DAY, available: 200 }, // top-up
+ { atMs: T0 + 3 * DAY, available: 180 },
+ ];
+ expect(estimateDailyBurn(samples, T0 + 3 * DAY)).toBeCloseTo(10);
+ });
+
+ it('needs a day of history before estimating', () => {
+ expect(estimateDailyBurn([{ atMs: T0, available: 10 }, { atMs: T0 + DAY / 2, available: 5 }], T0 + DAY / 2)).toBeNull();
+ });
+
+ it('collapses samples taken minutes apart but keeps the span', () => {
+ let samples = appendCreditSample([], { atMs: T0, available: 10 }, T0);
+ samples = appendCreditSample(samples, { atMs: T0 + 60_000, available: 9 }, T0 + 60_000);
+ samples = appendCreditSample(samples, { atMs: T0 + 120_000, available: 8 }, T0 + 120_000);
+ expect(samples).toEqual([{ atMs: T0, available: 10 }, { atMs: T0 + 120_000, available: 8 }]);
+ });
+
+ it('still keeps one sample per 10 minutes when read every minute', () => {
+ let samples: ReturnType<typeof appendCreditSample> = [];
+ for (let minute = 0; minute <= 60; minute += 1) {
+ const atMs = T0 + minute * 60_000;
+ samples = appendCreditSample(samples, { atMs, available: 100 - minute }, atMs);
+ }
+ expect(samples.length).toBeGreaterThanOrEqual(6);
+ // No gap longer than the sampling period, so a dip between reads is never far from a kept sample.
+ for (let i = 1; i < samples.length; i += 1) expect(samples[i].atMs - samples[i - 1].atMs).toBeLessThanOrEqual(600_000);
+ expect(samples[samples.length - 1]).toEqual({ atMs: T0 + 3_600_000, available: 40 });
+ });
+
+ it('drops samples past the retention window', () => {
+ const now = T0 + 40 * DAY;
+ const samples = appendCreditSample([{ atMs: T0, available: 10 }], { atMs: now, available: 5 }, now);
+ expect(samples).toEqual([{ atMs: now, available: 5 }]);
+ expect(largestCreditSample(samples)).toBe(5);
+ });
+});
+
+describe('CreditSampleStore', () => {
+ const dirs: string[] = [];
+ afterEach(() => {
+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('persists per key and starts over for another account', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'menubar-credits-'));
+ dirs.push(dir);
+ const file = path.join(dir, 'samples.json');
+ const store = new CreditSampleStore(() => file);
+ store.record('user-a:USD', 10, T0);
+ expect(new CreditSampleStore(() => file).record('user-a:USD', 8, T0 + DAY)).toHaveLength(2);
+ expect(new CreditSampleStore(() => file).record('user-b:USD', 50, T0 + DAY)).toEqual([{ atMs: T0 + DAY, available: 50 }]);
+ });
+
+ it('follows the file of the signed-in account', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'menubar-credits-'));
+ dirs.push(dir);
+ let file = path.join(dir, 'owner-a.json');
+ const store = new CreditSampleStore(() => file);
+ store.record('USD', 10, T0);
+ file = path.join(dir, 'owner-b.json');
+ expect(store.record('USD', 50, T0 + DAY)).toEqual([{ atMs: T0 + DAY, available: 50 }]);
+ file = path.join(dir, 'owner-a.json');
+ expect(store.record('USD', 8, T0 + DAY)).toHaveLength(2);
+ });
+});
diff --git a/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts b/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts
new file mode 100644
index 0000000000..f4ec4e4fc8
--- /dev/null
+++ b/apps/desktop/src/main/menubar/__tests__/helperProtocol.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from 'vitest';
+
+import { DEFAULT_MENUBAR_SETTINGS, isMenubarSupportedPlatform } from '../../../shared/menubarQuota';
+import { parseHelperMessage } from '../MacMenubarNativeHost';
+import { normalizeMenubarSettings, sanitizeMenubarSettingsPatch } from '../settingsStore';
+
+describe('parseHelperMessage', () => {
+ it('accepts well-formed messages', () => {
+ expect(parseHelperMessage({ type: 'panel', open: true })).toEqual({ type: 'panel', open: true });
+ expect(parseHelperMessage({ type: 'open-session', sessionId: 's1' })).toEqual({ type: 'open-session', sessionId: 's1' });
+ expect(parseHelperMessage({ type: 'refresh', extra: 1 })).toEqual({ type: 'refresh' });
+ });
+
+ it('rejects malformed or unknown messages', () => {
+ expect(parseHelperMessage(null)).toBeNull();
+ expect(parseHelperMessage({ type: 'panel', open: 'yes' })).toBeNull();
+ expect(parseHelperMessage({ type: 'open-session', sessionId: '' })).toBeNull();
+ expect(parseHelperMessage({ type: 'exec', command: 'rm' })).toBeNull();
+ expect(parseHelperMessage({ type: 'quit' })).toBeNull();
+ });
+
+ it('keeps only valid settings keys from the helper', () => {
+ expect(
+ parseHelperMessage({ type: 'settings', patch: { privacy: true, statusText: 'bogus', enabled: false, order: ['a', 1] } }),
+ ).toEqual({ type: 'settings', patch: { privacy: true, order: ['a'] } });
+ });
+});
+
+describe('menu bar settings', () => {
+ it('falls back to defaults for invalid stored values', () => {
+ expect(normalizeMenubarSettings({ statusText: 'nope', scope: 'world', hidden: 'x' })).toEqual(DEFAULT_MENUBAR_SETTINGS);
+ });
+
+ it('dedupes and bounds id lists', () => {
+ const ids = Array.from({ length: 300 }, (_, i) => `id-${i}`);
+ const settings = normalizeMenubarSettings({ order: ['a', 'a', '', 'x'.repeat(201), ...ids] });
+ expect(settings.order[0]).toBe('a');
+ expect(settings.order).toHaveLength(200);
+ });
+
+ it('sanitizes patches to recognised keys', () => {
+ expect(sanitizeMenubarSettingsPatch({ lowAlert: false, scope: 'local', junk: 1, statusText: 'x' })).toEqual({
+ lowAlert: false,
+ scope: 'local',
+ });
+ });
+});
+
+describe('isMenubarSupportedPlatform', () => {
+ it('requires macOS 14 (Darwin 23) or later', () => {
+ expect(isMenubarSupportedPlatform('darwin', '23.0.0')).toBe(true);
+ expect(isMenubarSupportedPlatform('darwin', '22.6.0')).toBe(false);
+ expect(isMenubarSupportedPlatform('win32', '10.0.22631')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/menubar/__tests__/ownedInFlight.test.ts b/apps/desktop/src/main/menubar/__tests__/ownedInFlight.test.ts
new file mode 100644
index 0000000000..0da36565f7
--- /dev/null
+++ b/apps/desktop/src/main/menubar/__tests__/ownedInFlight.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { OwnedInFlight } from '../ownedInFlight';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+describe('OwnedInFlight', () => {
+ it('lets callers for the same owner share one read', async () => {
+ const inFlight = new OwnedInFlight<string[]>();
+ const read = deferred<string[]>();
+ let starts = 0;
+ const start = () => {
+ starts += 1;
+ return read.promise;
+ };
+ const first = inFlight.run('a', start);
+ const second = inFlight.run('a', start);
+ read.resolve(['a-source']);
+ expect(await first).toEqual(['a-source']);
+ expect(await second).toEqual(['a-source']);
+ expect(starts).toBe(1);
+ });
+
+ it('never hands an earlier account its read after a switch', async () => {
+ const inFlight = new OwnedInFlight<string[]>();
+ const forA = deferred<string[]>();
+ const forB = deferred<string[]>();
+ const fromA = inFlight.run('a', () => forA.promise);
+ const fromB = inFlight.run('b', () => forB.promise);
+ forA.resolve(['a-source']);
+ forB.resolve(['b-source']);
+ expect(await fromA).toEqual(['a-source']);
+ expect(await fromB).toEqual(['b-source']);
+ });
+
+ it('starts a fresh read once the previous one settled, even if the stale one settles late', async () => {
+ const inFlight = new OwnedInFlight<string>();
+ const forA = deferred<string>();
+ const forB = deferred<string>();
+ void inFlight.run('a', () => forA.promise);
+ const fromB = inFlight.run('b', () => forB.promise);
+ forA.resolve('a');
+ await Promise.resolve();
+ // A's late settle must not clear B's read: another B caller still joins it.
+ let restarted = false;
+ const again = inFlight.run('b', () => {
+ restarted = true;
+ return Promise.resolve('b2');
+ });
+ forB.resolve('b');
+ expect(await fromB).toBe('b');
+ expect(await again).toBe('b');
+ expect(restarted).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts b/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts
new file mode 100644
index 0000000000..95399f83da
--- /dev/null
+++ b/apps/desktop/src/main/menubar/__tests__/snapshot.test.ts
@@ -0,0 +1,240 @@
+import { describe, expect, it } from 'vitest';
+
+import { DEFAULT_MENUBAR_SETTINGS, type MenubarSettings } from '../../../shared/menubarQuota';
+import type { SupportedLocale } from '../../../shared/locale';
+import { mainStringKeysUnder, rawMainString } from '../../i18n';
+import { familyLogo, MENUBAR_CINDY_LOGO, MENUBAR_HARNESS_LOGOS } from '../logos';
+import {
+ buildMenubarView,
+ isLowOnEverything,
+ type MenubarBuildInput,
+ type MenubarSourceInput,
+ type MenubarSubscriptionInput,
+} from '../snapshot';
+import { buildMenubarUiStrings, createMenubarTranslate, fillTemplate } from '../strings';
+
+const NOW = Date.UTC(2026, 9, 11, 3, 0, 0);
+const HOUR = 3_600_000;
+const DAY = 24 * HOUR;
+
+function codex(id: string, usedPercent: number, extra: Partial<MenubarSubscriptionInput> = {}): MenubarSubscriptionInput {
+ return {
+ kind: 'subscription',
+ id,
+ providerId: `codex-${id}`,
+ family: 'codex',
+ logoSvg: familyLogo('codex'),
+ brand: 'Codex',
+ account: `${id}@example.com`,
+ plan: 'Pro',
+ windows: [{ kind: 'week', usedPercent, resetsAtMs: NOW + 3 * DAY, windowMinutes: 10_080 }],
+ credits: null,
+ creditsUnlimited: false,
+ prepaidUsd: null,
+ updatedAtMs: NOW - 60_000,
+ ...extra,
+ };
+}
+
+function input(sources: MenubarSourceInput[], options: { locale?: SupportedLocale; settings?: Partial<MenubarSettings> } = {}): MenubarBuildInput {
+ const locale = options.locale ?? 'en';
+ const raw = (key: string) => rawMainString(key, locale);
+ const days = Array.from({ length: 90 }, (_, i) => new Date(NOW - (89 - i) * DAY).toISOString().slice(0, 10));
+ const daily = days.map(() => ({ money: [1, 1, 0] as [number, number, number], paid: 0, tokens: [10, 10, 0] as [number, number, number] }));
+ const scope = { daily, models: { '7': [], '30': [], '90': [] }, devices: [{ name: 'Mac', isSelf: true, syncedAtMs: null }] };
+ return {
+ nowMs: NOW,
+ locale,
+ moneySymbol: '$',
+ settings: { ...DEFAULT_MENUBAR_SETTINGS, ...options.settings },
+ sources,
+ tasks: [],
+ usage: { days, scopes: { local: scope, all: scope } },
+ updatedAtMs: NOW - 60_000,
+ harnessLogos: MENUBAR_HARNESS_LOGOS,
+ uiStrings: buildMenubarUiStrings(mainStringKeysUnder('menubar.ui'), raw, locale),
+ t: createMenubarTranslate(locale, raw),
+ };
+}
+
+describe('buildMenubarView', () => {
+ it('recommends the source with the most room and outlines its tube', () => {
+ const view = buildMenubarView(input([codex('alpha', 80), codex('beta', 20)]));
+ expect(view.headlinePrimary).toBe('beta has the most left.');
+ const beta = view.sources.find((s) => s.id === 'beta');
+ expect(beta).toMatchObject({ value: '80', valueUnit: '%', level: 'normal', fill: 0.8, emphasized: true });
+ expect(view.sources.find((s) => s.id === 'alpha')?.emphasized).toBe(false);
+ });
+
+ it('marks a nearly empty window as a warning', () => {
+ const view = buildMenubarView(input([codex('alpha', 93)]));
+ expect(view.sources[0]).toMatchObject({ value: '7', level: 'warn', fill: 0.07 });
+ });
+
+ it('hatches a used-up window that still has extra credits', () => {
+ const view = buildMenubarView(input([codex('alpha', 100, { credits: 61_838 }), codex('beta', 10)]));
+ const alpha = view.sources.find((s) => s.id === 'alpha');
+ expect(alpha).toMatchObject({ value: null, reserve: true, fill: 0, level: 'error' });
+ expect(view.details.alpha.action).toEqual({ kind: 'new-task', providerId: 'codex-alpha' });
+ });
+
+ it('follows the saved order and hides pay-as-you-go connections until shown', () => {
+ const payg: MenubarSourceInput = { kind: 'payg', id: 'glm', providerId: 'glm', logoSvg: '', name: 'GLM', billing: 'api' };
+ const sources = [codex('alpha', 10), codex('beta', 10), payg];
+ const ordered = buildMenubarView(input(sources, { settings: { order: ['beta', 'alpha'] } }));
+ expect(ordered.sources.map((s) => s.id)).toEqual(['beta', 'alpha']);
+ expect(ordered.manage.find((row) => row.id === 'glm')?.hidden).toBe(true);
+ const shown = buildMenubarView(input(sources, { settings: { shown: ['glm'] } }));
+ expect(shown.sources.map((s) => s.id)).toContain('glm');
+ });
+
+ it('masks account names in privacy mode', () => {
+ const view = buildMenubarView(input([codex('alpha', 10)], { settings: { privacy: true } }));
+ expect(view.sources[0].name).not.toContain('alpha');
+ });
+
+ it('sends the balance detail to top-up instead of a new task', () => {
+ const balance: MenubarSourceInput = {
+ kind: 'balance', id: 'cindy', logoSvg: MENUBAR_CINDY_LOGO, available: 12, fullAmount: 20,
+ burnPerDay: 3, observedAtMs: NOW, currency: 'USD', quota: null,
+ };
+ const view = buildMenubarView(input([balance]));
+ expect(view.details.cindy.action).toEqual({ kind: 'open-billing' });
+ expect(view.sources[0].fill).toBeCloseTo(0.6);
+ });
+
+ it('shows an organization quota with its reset and sends it to Settings', () => {
+ const quota: MenubarSourceInput = {
+ kind: 'balance', id: 'cindy', logoSvg: MENUBAR_CINDY_LOGO, available: 19_996.38, fullAmount: 20_000,
+ burnPerDay: null, observedAtMs: NOW, currency: 'USD', quota: { resetsAtMs: NOW + 20 * DAY + 3 * HOUR, todaySpend: 3.62 },
+ };
+ const view = buildMenubarView(input([quota], { locale: 'zh-CN' }));
+ expect(view.sources[0]).toMatchObject({ when: '20天3时后重置' });
+ expect(view.sources[0].fill).toBeCloseTo(0.9998);
+ expect(view.headlinePrimary).toBe('Cindy 本期配额还能用。');
+ expect(view.details.cindy).toMatchObject({ title: 'Cindy 本期配额', action: { kind: 'open-settings' } });
+ expect(view.details.cindy.facts).toContainEqual({ label: '今日已用', value: '$3.62', sub: '每日建议 $3,000 以内' });
+ });
+
+ it('splits a wallet into its pools and names the gift that expires first', () => {
+ const wallet: MenubarSourceInput = {
+ kind: 'balance', id: 'cindy', logoSvg: MENUBAR_CINDY_LOGO, available: 17, fullAmount: 20,
+ burnPerDay: 1, observedAtMs: NOW, currency: 'USD', quota: null,
+ pools: { plan: 0, purchased: 12, promotional: 5 },
+ promoExpiry: { amount: 5, expiresAtMs: NOW + 9 * DAY },
+ };
+ const facts = buildMenubarView(input([wallet])).details.cindy.facts;
+ expect(facts.map((fact) => fact.label)).toEqual(['Balance', 'Daily spend', 'Runs out', 'Top-up balance', 'Promo balance', 'Used for']);
+ expect(facts.find((fact) => fact.label === 'Promo balance')).toMatchObject({ value: '$5.00' });
+ expect(facts.find((fact) => fact.label === 'Promo balance')?.sub).toMatch(/^Expires /);
+ });
+
+ it('offers a Codex reset when the window is used up and resets are left', () => {
+ const view = buildMenubarView(input([codex('alpha', 100, { resetCredits: { count: 2, earliestExpiryMs: NOW + 5 * DAY } })]));
+ const detail = view.details.alpha;
+ expect(detail.saySecondary).toBe('2 resets are available; using one refills right away.');
+ expect(detail.action).toEqual({ kind: 'open-settings' });
+ expect(detail.facts).toContainEqual(expect.objectContaining({ label: 'Usage limit resets', value: '2 resets' }));
+ });
+
+ it('names an account on another computer by that computer and does not start a task on it', () => {
+ const remote = codex('alpha', 30, {
+ id: 'remote:dev-2:anthropic', account: null, device: { id: 'dev-2', name: 'Studio' },
+ });
+ const view = buildMenubarView(input([remote]));
+ expect(view.sources[0].name).toBe('Studio');
+ expect(view.manage[0].subtitle).toBe('Studio · Codex · Pro');
+ expect(view.details[remote.id].action).toEqual({ kind: 'open-app' });
+ expect(view.details[remote.id].facts).toContainEqual(expect.objectContaining({ label: 'Computer', value: 'Studio' }));
+ });
+
+ it('names a signed-in account on another computer by that computer, not the handle', () => {
+ const remote = codex('alpha', 30, { id: 'remote:dev-2:openai', device: { id: 'dev-2', name: 'Studio' } });
+ const view = buildMenubarView(input([remote]));
+ expect(view.sources[0].name).toBe('Studio');
+ });
+
+ it('says nothing was read instead of "used up" when no level is known', () => {
+ const unread = buildMenubarView(input([codex('alpha', 0, { windows: [] })]));
+ expect(unread.headlinePrimary).toBe('Quota not read yet.');
+ expect(unread.sources[0].fill).toBeNull();
+ const empty = buildMenubarView(input([]));
+ expect(empty.headlinePrimary).toBe('Nothing with a quota yet.');
+ const usedUp = buildMenubarView(input([codex('alpha', 100)]));
+ expect(usedUp.headlinePrimary).toBe('Everything is used up.');
+ });
+
+ it('carries the sign-in gate with no status text', () => {
+ const view = buildMenubarView({ ...input([]), gate: 'sign-in' });
+ expect(view.gate).toBe('sign-in');
+ expect(Object.values(view.statusTextByMode).every((text) => text === null)).toBe(true);
+ expect(view.strings.gateTitle).toBeTruthy();
+ expect(buildMenubarView(input([codex('alpha', 10)])).gate).toBeUndefined();
+ });
+
+ it('counts down to the reset of the window each cell shows', () => {
+ const claude = codex('alpha', 0, {
+ windows: [
+ { kind: 'session', usedPercent: 0, resetsAtMs: NOW + 4 * HOUR + 46 * 60_000, windowMinutes: 300 },
+ { kind: 'week', usedPercent: 10, resetsAtMs: NOW + 6 * DAY + 7 * HOUR + 30 * 60_000, windowMinutes: 10_080 },
+ ],
+ });
+ const view = buildMenubarView(input([claude], { locale: 'zh-CN' }));
+ expect(view.sources[0]).toMatchObject({ value: '90', when: '6天7时后重置', whenLevel: 'normal' });
+ // Plenty left: the headline does not narrate a reset.
+ expect(view.headlineSecondary).toBeNull();
+ });
+
+ it('names when a nearly empty source resets', () => {
+ const low = codex('alpha', 92, {
+ windows: [{ kind: 'session', usedPercent: 92, resetsAtMs: NOW + 3 * HOUR + 5 * 60_000, windowMinutes: 300 }],
+ });
+ const view = buildMenubarView(input([low, codex('beta', 20)]));
+ expect(view.sources.find((cell) => cell.id === 'alpha')).toMatchObject({ when: 'Resets in 3h 5m', whenLevel: 'warn' });
+ expect(view.headlineSecondary).toBe('alpha resets in 3h 5m.');
+ });
+
+ it('localizes the headline', () => {
+ const view = buildMenubarView(input([codex('alpha', 80), codex('beta', 20)], { locale: 'zh-CN' }));
+ expect(view.headlinePrimary).toBe('beta 余量最足。');
+ });
+});
+
+describe('isLowOnEverything', () => {
+ it('is true only when every readable source is nearly empty', () => {
+ expect(isLowOnEverything(input([codex('alpha', 95), codex('beta', 99)]))).toBe(true);
+ expect(isLowOnEverything(input([codex('alpha', 95), codex('beta', 50)]))).toBe(false);
+ });
+
+ it('ignores sources it cannot read and stays quiet with nothing known', () => {
+ const unread = codex('alpha', 0, { windows: [] });
+ expect(isLowOnEverything(input([unread]))).toBe(false);
+ });
+});
+
+describe('menubar strings', () => {
+ it('fills known placeholders and leaves unknown ones visible', () => {
+ expect(fillTemplate('{{a}} and {{b}}', { a: 1 })).toBe('1 and {{b}}');
+ });
+
+ it('picks plural variants by count', () => {
+ const table: Record<string, string> = { 'menubar.x_one': 'one item', 'menubar.x_other': '{{count}} items' };
+ const t = createMenubarTranslate('en', (key) => table[key] ?? null);
+ expect(t('x', { count: 1 })).toBe('one item');
+ expect(t('x', { count: 3 })).toBe('3 items');
+ expect(t('missing')).toBe('menubar.missing');
+ });
+
+ it('sends plural families to the helper with both forms', () => {
+ const table: Record<string, string> = { 'menubar.ui.n_one': 'a', 'menubar.ui.n_other': 'b', 'menubar.ui.plain': 'p' };
+ const strings = buildMenubarUiStrings(['n_one', 'n_other', 'plain'], (key) => table[key] ?? null, 'en');
+ expect(strings).toEqual({ n: 'b', n_one: 'a', n_other: 'b', plain: 'p' });
+ });
+
+ it('never takes a fallback-locale singular for locales without one', () => {
+ const raw = (key: string) => rawMainString(key, 'zh-CN');
+ const strings = buildMenubarUiStrings(mainStringKeysUnder('menubar.ui'), raw, 'zh-CN');
+ expect(strings.updatedMinutes_one).toBe(strings.updatedMinutes_other);
+ expect(strings.updatedMinutes_one).not.toMatch(/Updated/);
+ });
+});
diff --git a/apps/desktop/src/main/menubar/collect.ts b/apps/desktop/src/main/menubar/collect.ts
new file mode 100644
index 0000000000..6a76e1868d
--- /dev/null
+++ b/apps/desktop/src/main/menubar/collect.ts
@@ -0,0 +1,600 @@
+/**
+ * Turns Cindy's existing usage readers into the menu bar builder's inputs.
+ *
+ * Every reader is injected so this stays a pure mapping: `service.ts` passes the real
+ * cached-first readers (no credential reads happen here) and tests pass fixtures. A reader
+ * that fails only drops its own source; the rest of the panel still renders.
+ */
+
+import type { ProviderView } from '@cindy/model-providers';
+import { matchCodexBucketForModel } from '@cindy/maker-shared/codex-usage-buckets';
+import type {
+ ClaudeSubscriptionUsageSnapshot,
+ XaiSubscriptionUsageSnapshot,
+} from '@cindy/maker-shared/subscription-usage';
+import { isXaiWeeklyUsageCurrent } from '@cindy/maker-shared/subscription-usage';
+import { isSessionActivityRunning, type SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
+
+import type { MenubarModelUsage, MenubarUsageScope, MenubarUsageScopeData } from '../../shared/menubarQuota.js';
+import { providerWeeklyQuotaSource } from '../../shared/providerQuotaSource.js';
+import { formatModelShort } from '../../shared/usageModelLabel.js';
+import type { CodexAccountUsagePayload, RateLimitSnapshot, RateLimitWindow } from '../usageBroadcaster.js';
+import type { UsageHistoryPayload } from '../usage/usageHistory.js';
+import { familyLogo, MENUBAR_CINDY_LOGO, providerLogo } from './logos.js';
+import {
+ topModels,
+ type MenubarBalanceInput,
+ type MenubarHarness,
+ type MenubarPaygInput,
+ type MenubarQuotaPeriod,
+ type MenubarResetCredits,
+ type MenubarSourceInput,
+ type MenubarSubscriptionInput,
+ type MenubarTaskInput,
+ type MenubarUsageInput,
+ type MenubarUsageScopeInput,
+ type MenubarWalletPools,
+ type MenubarWindowInput,
+} from './snapshot.js';
+
+export const MENUBAR_USAGE_DAYS = 90;
+export const MENUBAR_BALANCE_SOURCE_ID = 'cindy';
+const WEEK_MINUTES = 10_080;
+const FIVE_HOUR_MINUTES = 300;
+/** Tasks beyond this are summarized as "N more"; the list stays cheap to build. */
+const MAX_TASK_ROWS = 30;
+const HARNESSES: readonly MenubarHarness[] = ['claude-code', 'codex', 'pi'];
+
+export interface MenubarBalanceReading {
+ available: number;
+ /** Sum of pool totals when the server reports them all. */
+ fullAmount: number | null;
+ burnPerDay: number | null;
+ observedAtMs: number | null;
+ currency: 'USD' | 'CNY';
+ /** Set for a period quota (organization or gateway key) rather than a wallet. */
+ quota: MenubarQuotaPeriod | null;
+ pools?: MenubarWalletPools | null;
+ promoExpiry?: { amount: number; expiresAtMs: number } | null;
+}
+
+export interface MenubarSessionRow {
+ title: string | null;
+ model: string | null;
+ agentKind: string | null;
+}
+
+export interface MenubarCollectDeps {
+ nowMs: number;
+ listProviders(): Promise<ProviderView[]>;
+ readCodex(providerId: string): Promise<CodexAccountUsagePayload | RateLimitSnapshot | null>;
+ readClaude(providerId: string): Promise<ClaudeSubscriptionUsageSnapshot | null>;
+ readXai(providerId: string): Promise<XaiSubscriptionUsageSnapshot | null>;
+ /** Codex resets left on a local account; absent in tests that do not cover them. */
+ readCodexResets?(providerId: string): Promise<MenubarResetCredits | null>;
+ /** Subscriptions on the user's other computers, already read and mapped. */
+ readRemoteSubscriptions?(): Promise<MenubarSubscriptionInput[]>;
+ /** Null when the account has no Cindy balance (organization accounts, signed out). */
+ readBalance(): Promise<MenubarBalanceReading | null>;
+ readUsage(scope: MenubarUsageScope): Promise<UsageHistoryPayload | null>;
+ activities(): readonly SessionActivitySnapshot[];
+ sessionRow(sessionId: string): Promise<MenubarSessionRow | null>;
+ /** Display name of this computer for the usage footnote. */
+ selfDeviceName: string;
+ onError?(scope: string, error: unknown): void;
+}
+
+export interface MenubarCollected {
+ sources: MenubarSourceInput[];
+ tasks: MenubarTaskInput[];
+ usage: MenubarUsageInput;
+ updatedAtMs: number | null;
+}
+
+export async function collectMenubarInputs(deps: MenubarCollectDeps): Promise<MenubarCollected> {
+ const safe = async <T>(scope: string, read: () => Promise<T>, fallback: T): Promise<T> => {
+ try {
+ return await read();
+ } catch (error) {
+ deps.onError?.(scope, error);
+ return fallback;
+ }
+ };
+
+ const [providers, balance, localUsage, allUsage, remote] = await Promise.all([
+ safe('providers', () => deps.listProviders(), [] as ProviderView[]),
+ safe('balance', () => deps.readBalance(), null),
+ safe('usage:local', () => deps.readUsage('local'), null),
+ safe('usage:all', () => deps.readUsage('all'), null),
+ safe('remote', async () => (await deps.readRemoteSubscriptions?.()) ?? [], [] as MenubarSubscriptionInput[]),
+ ]);
+
+ const sources: MenubarSourceInput[] = [];
+ if (balance) sources.push(balanceSource(balance));
+ const subscriptionReads = providers.map(async (provider): Promise<MenubarSourceInput | null> => {
+ if (!provider.connected || provider.suspended || provider.removed) return null;
+ const kind = providerWeeklyQuotaSource(provider);
+ // A Codex account waiting to be reconnected stays in the list without numbers instead
+ // of falling into the hidden pay-as-you-go group.
+ if (!kind && needsCodexReconnect(provider)) return codexSource(provider, null, deps.nowMs);
+ if (kind === 'codex') {
+ const [payload, resets] = await Promise.all([
+ safe(`codex:${provider.id}`, () => deps.readCodex(provider.id), null),
+ safe(`codex-resets:${provider.id}`, async () => (await deps.readCodexResets?.(provider.id)) ?? null, null),
+ ]);
+ return { ...codexSource(provider, payload, deps.nowMs), resetCredits: resets };
+ }
+ if (kind === 'claude') {
+ const snapshot = await safe(`claude:${provider.id}`, () => deps.readClaude(provider.id), null);
+ return claudeSource(provider, snapshot, deps.nowMs);
+ }
+ if (kind === 'xai') {
+ const snapshot = await safe(`xai:${provider.id}`, () => deps.readXai(provider.id), null);
+ return xaiSource(provider, snapshot, deps.nowMs);
+ }
+ return paygSource(provider);
+ });
+ for (const source of await Promise.all(subscriptionReads)) {
+ if (source) sources.push(source);
+ }
+ sources.push(...distinctRemoteSubscriptions(sources, remote));
+
+ const today = (allUsage ?? localUsage)?.todayKey ?? localDayKey(deps.nowMs);
+ const days = dayKeysEndingAt(today, MENUBAR_USAGE_DAYS);
+ const usage: MenubarUsageInput = {
+ days,
+ scopes: {
+ local: usageScope(localUsage, days, [{ name: deps.selfDeviceName, isSelf: true, syncedAtMs: null }]),
+ all: usageScope(allUsage ?? localUsage, days, devicesOf(allUsage, deps.selfDeviceName)),
+ },
+ };
+
+ const tasks = await collectTasks(deps, localUsage, today, safe);
+
+ let updatedAtMs: number | null = null;
+ for (const source of sources) {
+ const at = source.kind === 'subscription' ? source.updatedAtMs : source.kind === 'balance' ? source.observedAtMs : null;
+ if (at !== null && (updatedAtMs === null || at > updatedAtMs)) updatedAtMs = at;
+ }
+
+ return { sources, tasks, usage, updatedAtMs };
+}
+
+/** Nothing read: the inputs behind the sign-in gate. */
+export function emptyMenubarInputs(nowMs: number, selfDeviceName: string): MenubarCollected {
+ const days = dayKeysEndingAt(localDayKey(nowMs), MENUBAR_USAGE_DAYS);
+ const self = [{ name: selfDeviceName, isSelf: true, syncedAtMs: null }];
+ return {
+ sources: [],
+ tasks: [],
+ usage: { days, scopes: { local: emptyScope(days, self), all: emptyScope(days, self) } },
+ updatedAtMs: null,
+ };
+}
+
+// ── Sources ──────────────────────────────────────────────────────────────────
+
+function balanceSource(balance: MenubarBalanceReading): MenubarBalanceInput {
+ return {
+ kind: 'balance',
+ id: MENUBAR_BALANCE_SOURCE_ID,
+ logoSvg: MENUBAR_CINDY_LOGO,
+ available: balance.available,
+ fullAmount: balance.fullAmount,
+ burnPerDay: balance.burnPerDay,
+ observedAtMs: balance.observedAtMs,
+ currency: balance.currency,
+ quota: balance.quota,
+ pools: balance.pools ?? null,
+ promoExpiry: balance.promoExpiry ?? null,
+ };
+}
+
+// ── Accounts on other computers ──────────────────────────────────────────────
+
+/** A reset this close (and usage this close) means two readings describe the same window. */
+const SAME_RESET_TOLERANCE_MS = 2 * 60_000;
+const SAME_USAGE_TOLERANCE = 3;
+
+/** Key kind before the value: "codex:id", "claude:fp", "claude:identity". */
+function keyKind(key: string): string {
+ return key.split(':', 2).join(':');
+}
+
+function sameWindows(a: MenubarSubscriptionInput, b: MenubarSubscriptionInput): boolean {
+ const limits = (source: MenubarSubscriptionInput) => source.windows.filter((window) => window.kind !== 'scoped');
+ const left = limits(a);
+ const right = limits(b);
+ if (left.length === 0 || left.length !== right.length) return false;
+ return left.every((window) =>
+ right.some(
+ (other) =>
+ other.kind === window.kind &&
+ window.resetsAtMs !== null &&
+ other.resetsAtMs !== null &&
+ Math.abs(other.resetsAtMs - window.resetsAtMs) <= SAME_RESET_TOLERANCE_MS &&
+ Math.abs(other.usedPercent - window.usedPercent) <= SAME_USAGE_TOLERANCE,
+ ),
+ );
+}
+
+/**
+ * Whether two readings are one account. The same kind of key with different values rules it out
+ * (a ChatGPT workspace id can be shared by two people, their emails cannot); otherwise a shared
+ * key decides it; with nothing to compare, identical reset times do, since the service sets a
+ * window's reset per account.
+ */
+export function sameSubscriptionAccount(a: MenubarSubscriptionInput, b: MenubarSubscriptionInput): boolean {
+ if (a.family !== b.family) return false;
+ const left = a.accountKeys ?? [];
+ const right = b.accountKeys ?? [];
+ const valuesByKind = new Map<string, Set<string>>();
+ for (const key of right) {
+ const kind = keyKind(key);
+ valuesByKind.set(kind, (valuesByKind.get(kind) ?? new Set()).add(key));
+ }
+ if (left.some((key) => valuesByKind.has(keyKind(key)) && !valuesByKind.get(keyKind(key))!.has(key))) return false;
+ if (left.some((key) => right.includes(key))) return true;
+ return sameWindows(a, b);
+}
+
+/**
+ * Accounts on other computers that are not already listed. The same account signed in on this
+ * computer and on others is one source: this computer's reading wins, then the freshest remote
+ * one. Remote accounts without a reading add nothing and are left out.
+ */
+export function distinctRemoteSubscriptions(
+ listed: readonly MenubarSourceInput[],
+ remote: readonly MenubarSubscriptionInput[],
+): MenubarSubscriptionInput[] {
+ const kept: MenubarSubscriptionInput[] = listed.filter(
+ (source): source is MenubarSubscriptionInput => source.kind === 'subscription',
+ );
+ const added: MenubarSubscriptionInput[] = [];
+ const ordered = [...remote]
+ .filter((source) => source.windows.length > 0)
+ .sort((a, b) => (b.updatedAtMs ?? 0) - (a.updatedAtMs ?? 0));
+ for (const source of ordered) {
+ if (kept.some((other) => sameSubscriptionAccount(source, other))) continue;
+ kept.push(source);
+ added.push(source);
+ }
+ return added;
+}
+
+function identityKeys(family: string, provider: ProviderView, ...ids: [string, unknown][]): string[] {
+ const keys: string[] = [];
+ for (const [kind, value] of ids) {
+ if (typeof value === 'string' && value.trim()) keys.push(`${family}:${kind}:${value.trim()}`);
+ }
+ const identity = accountIdentity(provider);
+ if (identity) keys.push(`${family}:identity:${identity.toLowerCase()}`);
+ return keys;
+}
+
+function accountIdentity(provider: ProviderView): string | null {
+ const identity = provider.openAiAccount?.identity ?? provider.subscriptionAccount?.identity ?? null;
+ return identity && identity.trim() ? identity.trim() : null;
+}
+
+/** "pro" → "Pro", "max_20x" → "Max 20x"; product names stay as the service writes them. */
+export function planLabel(raw: string | null | undefined): string | null {
+ if (!raw || !raw.trim()) return null;
+ return raw
+ .trim()
+ .split(/[_\s-]+/)
+ .map((word) => (/^[a-z]/.test(word) ? word[0].toUpperCase() + word.slice(1) : word))
+ .join(' ');
+}
+
+/** A window whose reset already passed has unknown usage until the next read. */
+function liveResetMs(resetsAtSeconds: number | null | undefined, nowMs: number): number | null | undefined {
+ if (typeof resetsAtSeconds !== 'number' || !Number.isFinite(resetsAtSeconds) || resetsAtSeconds <= 0) return null;
+ const ms = resetsAtSeconds * 1000;
+ return ms <= nowMs ? undefined : ms;
+}
+
+function windowFromCodex(window: RateLimitWindow | null | undefined, nowMs: number): MenubarWindowInput | null {
+ if (!window || typeof window.usedPercent !== 'number' || !Number.isFinite(window.usedPercent)) return null;
+ const resetsAtMs = liveResetMs(window.resetsAt, nowMs);
+ if (resetsAtMs === undefined) return null;
+ const minutes = typeof window.windowMinutes === 'number' && window.windowMinutes > 0 ? window.windowMinutes : WEEK_MINUTES;
+ return {
+ kind: minutes >= WEEK_MINUTES ? 'week' : 'session',
+ usedPercent: clampPercent(window.usedPercent),
+ resetsAtMs,
+ windowMinutes: minutes,
+ };
+}
+
+export function codexSource(
+ provider: ProviderView,
+ payload: CodexAccountUsagePayload | RateLimitSnapshot | null,
+ nowMs: number,
+): MenubarSubscriptionInput {
+ const full = payload as CodexAccountUsagePayload | null;
+ const appBuckets =
+ full?.appServerBuckets && Object.keys(full.appServerBuckets).length > 0
+ ? full.appServerBuckets
+ : full && (full.primary || full.secondary) && full.source !== 'openai-web'
+ ? { [full.limitId ?? 'codex']: full }
+ : null;
+ // Only the account's generic bucket describes the account; model promotions never stand in.
+ const bucket = matchCodexBucketForModel(appBuckets, undefined, nowMs) ?? full?.webSnapshot ?? null;
+ const windows = [bucket?.primary, bucket?.secondary]
+ .map((window) => windowFromCodex(window, nowMs))
+ .filter((window): window is MenubarWindowInput => window !== null)
+ .sort((a, b) => a.windowMinutes - b.windowMinutes);
+ const credits = bucket?.credits ?? full?.credits ?? null;
+ const balance = credits?.balance != null ? Number(credits.balance) : NaN;
+ const creditAmount = !credits || credits.unlimited
+ ? null
+ : !credits.hasCredits
+ ? 0
+ : Number.isFinite(balance) ? balance : null;
+ return {
+ kind: 'subscription',
+ id: provider.id,
+ providerId: provider.id,
+ family: 'codex',
+ logoSvg: familyLogo('codex'),
+ brand: 'Codex',
+ account: accountIdentity(provider),
+ plan: planLabel(bucket?.planType ?? full?.planType),
+ windows,
+ credits: creditAmount,
+ creditsUnlimited: credits?.unlimited === true,
+ prepaidUsd: null,
+ updatedAtMs: bucket?.updatedAt ?? full?.updatedAt ?? null,
+ accountKeys: identityKeys('codex', provider, ['id', (full as { accountId?: unknown } | null)?.accountId]),
+ };
+}
+
+export function claudeSource(
+ provider: ProviderView,
+ snapshot: ClaudeSubscriptionUsageSnapshot | null,
+ nowMs: number,
+): MenubarSubscriptionInput {
+ const windows: MenubarWindowInput[] = [];
+ const add = (kind: MenubarWindowInput['kind'], minutes: number, utilization: unknown, resetsAt: unknown, label?: string) => {
+ if (typeof utilization !== 'number' || !Number.isFinite(utilization)) return;
+ const resetsAtMs = liveResetMs(resetsAt as number | null | undefined, nowMs);
+ if (resetsAtMs === undefined) return;
+ windows.push({ kind, label: label ?? null, usedPercent: clampPercent(utilization), resetsAtMs, windowMinutes: minutes });
+ };
+ add('session', FIVE_HOUR_MINUTES, snapshot?.fiveHour?.utilization, snapshot?.fiveHour?.resetsAt);
+ add('week', WEEK_MINUTES, snapshot?.sevenDay?.utilization, snapshot?.sevenDay?.resetsAt);
+ for (const scoped of snapshot?.scoped ?? []) {
+ add('scoped', WEEK_MINUTES, scoped.utilization, scoped.resetsAt, scoped.modelDisplayName);
+ }
+ return {
+ kind: 'subscription',
+ id: provider.id,
+ providerId: provider.id,
+ family: 'claude',
+ logoSvg: familyLogo('claude'),
+ brand: 'Claude',
+ account: provider.id === 'anthropic' ? null : accountIdentity(provider),
+ plan: planLabel(snapshot?.subscriptionType),
+ windows,
+ credits: null,
+ creditsUnlimited: false,
+ prepaidUsd: null,
+ updatedAtMs: snapshot?.updatedAt ?? null,
+ accountKeys: identityKeys('claude', provider, ['fp', snapshot?.accountFingerprint]),
+ };
+}
+
+export function xaiSource(
+ provider: ProviderView,
+ snapshot: XaiSubscriptionUsageSnapshot | null,
+ nowMs: number,
+): MenubarSubscriptionInput {
+ const current = snapshot && isXaiWeeklyUsageCurrent(snapshot, nowMs) ? snapshot : null;
+ const windows: MenubarWindowInput[] = [];
+ if (current && typeof current.creditUsagePercent === 'number') {
+ const resetsAtMs = liveResetMs(current.resetsAt, nowMs);
+ if (resetsAtMs !== undefined) {
+ windows.push({ kind: 'week', usedPercent: clampPercent(current.creditUsagePercent), resetsAtMs, windowMinutes: WEEK_MINUTES });
+ }
+ }
+ const prepaid = snapshot?.prepaidBalance;
+ return {
+ kind: 'subscription',
+ id: provider.id,
+ providerId: provider.id,
+ family: 'grok',
+ logoSvg: familyLogo('grok'),
+ brand: 'Grok',
+ account: provider.id === 'xai' ? null : accountIdentity(provider),
+ plan: snapshot?.planLabel?.trim() || null,
+ windows,
+ credits: null,
+ creditsUnlimited: false,
+ prepaidUsd: typeof prepaid === 'number' && Number.isFinite(prepaid) ? prepaid : null,
+ updatedAtMs: snapshot?.updatedAt ?? null,
+ accountKeys: identityKeys('xai', provider, ['fp', snapshot?.accountFingerprint]),
+ };
+}
+
+/**
+ * Connections whose remaining amount Cindy cannot read. Local runtimes (auth "none") and the
+ * Cindy gateway (shown as the balance) are not billed this way and stay out.
+ */
+function needsCodexReconnect(provider: ProviderView): boolean {
+ return (
+ provider.openAiAccount?.reconnectRequired === true &&
+ provider.auth.method === 'oauth' &&
+ (provider.id === 'openai' || provider.auth.native === 'codex')
+ );
+}
+
+export function paygSource(provider: ProviderView): MenubarPaygInput | null {
+ if (provider.auth.method === 'none' || provider.auth.method === 'managed') return null;
+ if (provider.access?.kind === 'managed' || provider.id === 'xd') return null;
+ return {
+ kind: 'payg',
+ id: provider.id,
+ providerId: provider.id,
+ logoSvg: providerLogo(provider.id, provider.name, provider.routing as never),
+ name: provider.name,
+ billing: provider.access?.kind === 'subscription' ? 'subscription' : 'api',
+ };
+}
+
+// ── Usage ────────────────────────────────────────────────────────────────────
+
+function clampPercent(value: number): number {
+ return Math.min(100, Math.max(0, value));
+}
+
+function pad(value: number): string {
+ return String(value).padStart(2, '0');
+}
+
+export function localDayKey(ms: number): string {
+ const date = new Date(ms);
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+/** `count` local calendar days ending at `todayKey`, oldest first. */
+export function dayKeysEndingAt(todayKey: string, count: number): string[] {
+ const [year, month, day] = todayKey.split('-').map(Number);
+ const keys: string[] = [];
+ for (let offset = count - 1; offset >= 0; offset -= 1) {
+ const date = new Date(year, month - 1, day - offset, 12);
+ keys.push(`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`);
+ }
+ return keys;
+}
+
+function harnessOf(kind: string | null | undefined): MenubarHarness {
+ return HARNESSES.includes(kind as MenubarHarness) ? (kind as MenubarHarness) : 'claude-code';
+}
+
+function emptyScope(days: readonly string[], devices: MenubarUsageScopeInput['devices']): MenubarUsageScopeInput {
+ return {
+ daily: days.map(() => ({ money: [0, 0, 0], paid: 0, tokens: [0, 0, 0] })),
+ models: { '7': [], '30': [], '90': [] },
+ devices,
+ };
+}
+
+export function usageScope(
+ payload: UsageHistoryPayload | null,
+ days: readonly string[],
+ devices: MenubarUsageScopeInput['devices'],
+): MenubarUsageScopeInput {
+ const scope = emptyScope(days, devices);
+ if (!payload) return scope;
+ const indexOfDay = new Map(days.map((day, index) => [day, index]));
+ const windows: Array<keyof MenubarUsageScopeData['models']> = ['7', '30', '90'];
+ const modelRows: Record<string, MenubarModelUsage[]> = { '7': [], '30': [], '90': [] };
+ for (const row of payload.modelDaily) {
+ const index = indexOfDay.get(row.day);
+ if (index === undefined) continue;
+ const harness = harnessOf(row.agentKind);
+ const slot = HARNESSES.indexOf(harness);
+ const money = finite(row.money?.amount);
+ const daily = scope.daily[index];
+ daily.money[slot] += money;
+ daily.tokens[slot] += finite(row.tokens);
+ daily.paid += finite(row.apiMoney?.amount);
+ const age = days.length - 1 - index;
+ for (const window of windows) {
+ if (age < Number(window)) {
+ modelRows[window].push({ name: formatModelShort(row.model), harness, money, tokens: finite(row.tokens) });
+ }
+ }
+ }
+ for (const window of windows) scope.models[window] = topModels(modelRows[window]);
+ return scope;
+}
+
+function devicesOf(payload: UsageHistoryPayload | null, selfName: string): MenubarUsageScopeInput['devices'] {
+ const devices = payload?.devices ?? [];
+ if (devices.length === 0) return [{ name: selfName, isSelf: true, syncedAtMs: null }];
+ return devices.map((device) => ({
+ name: device.isSelf ? selfName || device.name : device.name,
+ isSelf: device.isSelf,
+ syncedAtMs: device.syncedAt,
+ }));
+}
+
+function finite(value: unknown): number {
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
+}
+
+// ── Tasks ────────────────────────────────────────────────────────────────────
+
+type Safe = <T>(scope: string, read: () => Promise<T>, fallback: T) => Promise<T>;
+
+/**
+ * Today's tasks on this computer: everything with usage today plus anything running now.
+ * Value is the task's tokens priced at today's average rate for its model, the same
+ * subscription-equivalent basis as the usage chart.
+ */
+async function collectTasks(
+ deps: MenubarCollectDeps,
+ usage: UsageHistoryPayload | null,
+ today: string,
+ safe: Safe,
+): Promise<MenubarTaskInput[]> {
+ const tokensBySession = new Map<string, number>();
+ for (const row of usage?.taskDaily ?? []) {
+ if (row.day !== today) continue;
+ const [device, ...rest] = row.taskKey.split(':');
+ if (device !== 'local') continue;
+ const sessionId = rest.join(':');
+ tokensBySession.set(sessionId, (tokensBySession.get(sessionId) ?? 0) + finite(row.tokens));
+ }
+ const meta = new Map((usage?.tasks ?? []).filter((task) => task.deviceId === 'local').map((task) => [task.sessionId, task]));
+ const rates = new Map<string, { money: number; tokens: number; harness: MenubarHarness }>();
+ for (const row of usage?.modelDaily ?? []) {
+ if (row.day !== today) continue;
+ const rate = rates.get(row.model) ?? { money: 0, tokens: 0, harness: harnessOf(row.agentKind) };
+ rate.money += finite(row.money?.amount);
+ rate.tokens += finite(row.tokens);
+ rates.set(row.model, rate);
+ }
+
+ const activities = new Map(deps.activities().map((activity) => [activity.sessionId, activity]));
+ const ids = new Set(tokensBySession.keys());
+ for (const [sessionId, activity] of activities) {
+ if (isSessionActivityRunning(activity)) ids.add(sessionId);
+ }
+ const ranked = [...ids]
+ .sort((a, b) => {
+ const runningA = activities.get(a) && isSessionActivityRunning(activities.get(a)!) ? 1 : 0;
+ const runningB = activities.get(b) && isSessionActivityRunning(activities.get(b)!) ? 1 : 0;
+ return runningB - runningA || (tokensBySession.get(b) ?? 0) - (tokensBySession.get(a) ?? 0);
+ })
+ .slice(0, MAX_TASK_ROWS);
+
+ const rows = await Promise.all(
+ ranked.map(async (sessionId): Promise<MenubarTaskInput | null> => {
+ const row = await safe(`session:${sessionId}`, () => deps.sessionRow(sessionId), null);
+ const info = meta.get(sessionId);
+ const activity = activities.get(sessionId);
+ const model = info?.model || row?.model || '';
+ const title = row?.title?.trim() || info?.title?.trim() || '';
+ if (!title && !model) return null;
+ const tokens = tokensBySession.get(sessionId) ?? 0;
+ const rate = rates.get(model);
+ const running = activity ? isSessionActivityRunning(activity) : false;
+ return {
+ sessionId,
+ title,
+ harness: harnessOf(row?.agentKind ?? rate?.harness),
+ model: model ? formatModelShort(model) : '',
+ tokensToday: tokens,
+ valueToday: rate && rate.tokens > 0 ? (tokens * rate.money) / rate.tokens : 0,
+ contextPercent: info && info.contextWindow > 0 ? clampPercent((info.contextTokens / info.contextWindow) * 100) : null,
+ running,
+ startedAtMs: running ? (activity?.startedAtMs ?? null) : null,
+ lastActiveAtMs: activity?.lastActivityAtMs ?? info?.lastActiveAt ?? deps.nowMs,
+ };
+ }),
+ );
+ return rows.filter((row): row is MenubarTaskInput => row !== null);
+}
diff --git a/apps/desktop/src/main/menubar/creditSamples.ts b/apps/desktop/src/main/menubar/creditSamples.ts
new file mode 100644
index 0000000000..6c4f13ad3b
--- /dev/null
+++ b/apps/desktop/src/main/menubar/creditSamples.ts
@@ -0,0 +1,131 @@
+/**
+ * Local history of the Cindy balance, used to estimate daily burn for the menu bar.
+ *
+ * The server only reports the current balance, so main records what it observes. Rises
+ * (top-ups, grants) are ignored; only drops count as spending. Samples older than the
+ * retention window are dropped on every write, and the file holds amounts only. It lives in
+ * the signed-in account's own data folder, so another account never sees it.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { createLogger } from '../logger.js';
+
+const log = createLogger('menubar:credit-samples');
+
+const DAY_MS = 86_400_000;
+export const CREDIT_SAMPLE_RETENTION_MS = 30 * DAY_MS;
+export const CREDIT_BURN_WINDOW_MS = 7 * DAY_MS;
+/** Burn needs at least this much observed history to say anything useful. */
+export const CREDIT_BURN_MIN_SPAN_MS = DAY_MS;
+/** Samples closer together than this replace each other instead of piling up. */
+const MIN_SAMPLE_GAP_MS = 10 * 60_000;
+const MAX_SAMPLES = 2_000;
+
+export interface CreditSample {
+ atMs: number;
+ available: number;
+}
+
+interface CreditSampleFile {
+ version: 1;
+ /** Account scope plus currency; samples from another account or region are discarded. */
+ key: string;
+ samples: CreditSample[];
+}
+
+/** Adds a sample, keeping the list sorted, pruned and not denser than one per 10 minutes. */
+export function appendCreditSample(samples: readonly CreditSample[], next: CreditSample, nowMs: number): CreditSample[] {
+ const kept = samples.filter((sample) => nowMs - sample.atMs <= CREDIT_SAMPLE_RETENTION_MS && sample.atMs < next.atMs);
+ // Measured from the sample before the newest one: the newest is the running tail of the current
+ // 10 minutes and gets replaced, so frequent reads still leave one sample per 10 minutes.
+ const anchor = kept[kept.length - 2];
+ if (anchor && next.atMs - anchor.atMs < MIN_SAMPLE_GAP_MS) {
+ kept[kept.length - 1] = next;
+ } else {
+ kept.push(next);
+ }
+ return kept.slice(-MAX_SAMPLES);
+}
+
+/** Average daily spending over the last week, or null without a day of history. */
+export function estimateDailyBurn(samples: readonly CreditSample[], nowMs: number): number | null {
+ const recent = samples.filter((sample) => nowMs - sample.atMs <= CREDIT_BURN_WINDOW_MS);
+ if (recent.length < 2) return null;
+ const span = recent[recent.length - 1].atMs - recent[0].atMs;
+ if (span < CREDIT_BURN_MIN_SPAN_MS) return null;
+ let spent = 0;
+ for (let i = 1; i < recent.length; i += 1) {
+ const drop = recent[i - 1].available - recent[i].available;
+ if (drop > 0) spent += drop;
+ }
+ return spent / (span / DAY_MS);
+}
+
+/** Largest balance seen recently, the fallback for "full" when the server has no pool totals. */
+export function largestCreditSample(samples: readonly CreditSample[]): number | null {
+ let largest: number | null = null;
+ for (const sample of samples) {
+ if (largest === null || sample.available > largest) largest = sample.available;
+ }
+ return largest;
+}
+
+export class CreditSampleStore {
+ private cache: CreditSampleFile | null = null;
+ /** File the cache was read from; the path follows the signed-in account. */
+ private cachePath: string | null = null;
+
+ constructor(private readonly filePath: () => string = () => ownerScopedUserDataPath('menubar-credit-samples.json')) {}
+
+ /** Records an observation and returns the samples recorded under the same key. */
+ record(key: string, available: number, atMs: number): CreditSample[] {
+ const target = this.filePath();
+ const file = this.load(target);
+ // A region or currency change makes old amounts meaningless.
+ const base = file.key === key ? file.samples : [];
+ const samples = appendCreditSample(base, { atMs, available }, atMs);
+ this.cache = { version: 1, key, samples };
+ this.save(target, this.cache);
+ return samples;
+ }
+
+ private load(target: string): CreditSampleFile {
+ if (this.cache && this.cachePath === target) return this.cache;
+ this.cachePath = target;
+ try {
+ const parsed = JSON.parse(fs.readFileSync(target, 'utf8')) as Partial<CreditSampleFile>;
+ const samples = Array.isArray(parsed.samples)
+ ? parsed.samples.filter(
+ (sample): sample is CreditSample =>
+ !!sample &&
+ Number.isFinite((sample as CreditSample).atMs) &&
+ Number.isFinite((sample as CreditSample).available),
+ )
+ : [];
+ samples.sort((a, b) => a.atMs - b.atMs);
+ this.cache = { version: 1, key: typeof parsed.key === 'string' ? parsed.key : '', samples };
+ } catch {
+ this.cache = { version: 1, key: '', samples: [] };
+ }
+ return this.cache;
+ }
+
+ private save(target: string, file: CreditSampleFile): void {
+ const temp = `${target}.${process.pid}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(temp, JSON.stringify(file), 'utf8');
+ fs.renameSync(temp, target);
+ } catch (error) {
+ log.warn('could not save credit samples', { error: error instanceof Error ? error.message : String(error) });
+ try {
+ fs.rmSync(temp, { force: true });
+ } catch {
+ // Nothing else to clean up.
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/menubar/ipc.ts b/apps/desktop/src/main/menubar/ipc.ts
new file mode 100644
index 0000000000..7ce2c316a1
--- /dev/null
+++ b/apps/desktop/src/main/menubar/ipc.ts
@@ -0,0 +1,18 @@
+import { ipcMain } from 'electron';
+
+import { MENUBAR_GET_STATE_CHANNEL, MENUBAR_SET_ENABLED_CHANNEL } from '../../shared/menubarQuota.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { requireBoolean } from '../utils/ipcValidate.js';
+import { getMenubarState, setMenubarEnabled } from './service.js';
+
+/** Settings → Window behavior toggle. Local app renderer only; not a device-link capability. */
+export function registerMenubarIpc(): void {
+ ipcMain.handle(MENUBAR_GET_STATE_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ return getMenubarState();
+ });
+ ipcMain.handle(MENUBAR_SET_ENABLED_CHANNEL, (event, enabled: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return setMenubarEnabled(requireBoolean(enabled, 'enabled'));
+ });
+}
diff --git a/apps/desktop/src/main/menubar/logos.ts b/apps/desktop/src/main/menubar/logos.ts
new file mode 100644
index 0000000000..916265c9e4
--- /dev/null
+++ b/apps/desktop/src/main/menubar/logos.ts
@@ -0,0 +1,85 @@
+/**
+ * Monochrome logos for the menu bar panel, as standalone SVG documents.
+ *
+ * The helper loads them with NSImage and draws them as template images, so every shape is
+ * black and the panel tints it for Light and Dark. Unknown providers get a lettered tile
+ * instead of a borrowed brand.
+ */
+
+import {
+ PROVIDER_LOGO_PATHS,
+ resolveProviderLogoKind,
+ type ProviderLogoKind,
+ type ProviderLogoRouting,
+} from '@cindy/model-providers/branding';
+
+import {
+ ANTHROPIC_MARK_PATH,
+ CLAUDE_CODE_MARK_PATH,
+ CODEX_FLOWER_OUTLINE,
+ CODEX_PROMPT_GLYPHS,
+ OPENAI_MARK_PATH,
+} from '../../shared/brandMarkPaths.js';
+import type { MenubarFamily, MenubarHarness } from './snapshot.js';
+
+/** Sentinel the helper resolves to the built-in Cindy mark, so the long path crosses once. */
+export const MENUBAR_CINDY_LOGO = 'cindy:mark';
+
+const svg = (body: string): string =>
+ `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">${body}</svg>`;
+
+const filled = (d: string, evenOdd = false): string =>
+ svg(`<path fill="#000"${evenOdd ? ' fill-rule="evenodd"' : ''} d="${d}"/>`);
+
+const BRAND_SVG: Partial<Record<ProviderLogoKind, string>> = {
+ anthropic: filled(ANTHROPIC_MARK_PATH),
+ openai: filled(OPENAI_MARK_PATH),
+};
+
+function escapeXml(text: string): string {
+ return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
+}
+
+/** Rounded tile with the first letter of the name, for providers without an official mark. */
+export function monogramLogo(name: string): string {
+ const letter = escapeXml([...name.trim()][0]?.toUpperCase() ?? '?');
+ return svg(
+ '<rect x="2.5" y="2.5" width="19" height="19" rx="5" fill="none" stroke="#000" stroke-width="1.6"/>' +
+ `<text x="12" y="16.2" text-anchor="middle" font-family="-apple-system, Helvetica" font-size="11" font-weight="600" fill="#000">${letter}</text>`,
+ );
+}
+
+export function logoForKind(kind: ProviderLogoKind | null, fallbackName: string): string {
+ if (!kind) return monogramLogo(fallbackName);
+ const brand = BRAND_SVG[kind];
+ if (brand) return brand;
+ if (kind in PROVIDER_LOGO_PATHS) return filled(PROVIDER_LOGO_PATHS[kind as keyof typeof PROVIDER_LOGO_PATHS]);
+ return monogramLogo(fallbackName);
+}
+
+export function providerLogo(providerId: string, name: string, routing?: ProviderLogoRouting): string {
+ return logoForKind(resolveProviderLogoKind(providerId, routing), name);
+}
+
+/** Subscription logos follow the model maker: Anthropic for Claude, OpenAI for Codex, xAI for Grok. */
+export function familyLogo(family: MenubarFamily): string {
+ if (family === 'claude') return logoForKind('anthropic', 'Claude');
+ if (family === 'codex') return logoForKind('openai', 'Codex');
+ return logoForKind('xai', 'Grok');
+}
+
+/** Agent identity marks for task rows and the usage chart legend. */
+export const MENUBAR_HARNESS_LOGOS: Record<MenubarHarness, string> = {
+ 'claude-code': filled(CLAUDE_CODE_MARK_PATH, true),
+ codex: svg(
+ '<g transform="translate(12 12) scale(1.1) translate(-12 -12)">' +
+ `<path fill="none" stroke="#000" stroke-width="1.6" stroke-linejoin="round" d="${CODEX_FLOWER_OUTLINE}z"/>` +
+ `<path fill="#000" stroke="#000" stroke-width="0.5" stroke-linejoin="round" d="${CODEX_PROMPT_GLYPHS}"/>` +
+ '</g>',
+ ),
+ pi: svg(
+ '<g fill="none" stroke="#000" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">' +
+ '<path d="M3.6 6.6h16.8"/><path d="M8.4 6.6v11.8"/><path d="M15.6 6.6v9.6c0 1.5.9 2.2 2.4 2.2"/>' +
+ '</g>',
+ ),
+};
diff --git a/apps/desktop/src/main/menubar/ownedInFlight.ts b/apps/desktop/src/main/menubar/ownedInFlight.ts
new file mode 100644
index 0000000000..ceab8df045
--- /dev/null
+++ b/apps/desktop/src/main/menubar/ownedInFlight.ts
@@ -0,0 +1,20 @@
+/**
+ * One shared read per owner. Callers for the same owner join the read already out; a caller for
+ * another owner (an account switch while the read is out) starts its own, so a result is never
+ * handed to an account it was not read for.
+ */
+export class OwnedInFlight<T> {
+ private current: { owner: string | null; read: Promise<T> } | null = null;
+
+ run(owner: string | null, start: () => Promise<T>): Promise<T> {
+ if (this.current && this.current.owner === owner) return this.current.read;
+ const entry: { owner: string | null; read: Promise<T> } = {
+ owner,
+ read: start().finally(() => {
+ if (this.current === entry) this.current = null;
+ }),
+ };
+ this.current = entry;
+ return entry.read;
+ }
+}
diff --git a/apps/desktop/src/main/menubar/remoteSubscriptions.ts b/apps/desktop/src/main/menubar/remoteSubscriptions.ts
new file mode 100644
index 0000000000..1830c0f853
--- /dev/null
+++ b/apps/desktop/src/main/menubar/remoteSubscriptions.ts
@@ -0,0 +1,127 @@
+/**
+ * Subscription accounts on the user's other computers, for the menu bar.
+ *
+ * The same reach as the model picker's remote providers: computers on this account that are
+ * online, accept remote control and are not phones, and on them only the connections opened
+ * with "allow remote invocation". Each account is read through the same device-link usage
+ * channels the remote session chip uses, over a background link that does not put the other
+ * computer under control. Responses are data from another machine: anything malformed drops
+ * that one account. Deciding which of these duplicate an account already listed is left to
+ * `distinctRemoteSubscriptions`.
+ */
+
+import type { ProviderView } from '@cindy/model-providers';
+import type { ClaudeSubscriptionUsageSnapshot, XaiSubscriptionUsageSnapshot } from '@cindy/maker-shared/subscription-usage';
+
+import type { DeviceLinkDeviceView } from '../../shared/deviceLinkIpc.js';
+import { providerWeeklyQuotaSource } from '../../shared/providerQuotaSource.js';
+import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog.js';
+import { mayServeBackgroundRead } from '../usage/peerUsageSync.js';
+import type { CodexAccountUsagePayload } from '../usageBroadcaster.js';
+import { claudeSource, codexSource, xaiSource } from './collect.js';
+import type { MenubarRemoteDevice, MenubarSubscriptionInput } from './snapshot.js';
+
+const MOBILE_PLATFORMS = new Set(['ios', 'android']);
+const DEVICE_FANOUT = 3;
+
+type InvokeResult = { ok: true; result: unknown } | { ok: false; error: { code: string; message: string } };
+
+export interface RemoteSubscriptionDeps {
+ nowMs: number;
+ listDevices(): Promise<{ devices: DeviceLinkDeviceView[] }>;
+ invoke(deviceId: string, channel: string, args: unknown[]): Promise<InvokeResult>;
+ onError?(scope: string, error: unknown): void;
+}
+
+/** Same admission as the picker's other-computer providers and the cross-device usage sync. */
+export function isRemoteQuotaDevice(device: DeviceLinkDeviceView): boolean {
+ return (
+ !device.isSelf &&
+ device.online &&
+ device.remoteControlEnabled &&
+ device.controlEnabled &&
+ !MOBILE_PLATFORMS.has(device.platform ?? '') &&
+ mayServeBackgroundRead(device.appVersion)
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+/**
+ * Builtin accounts keep the legacy call shape; a named account passes its provider id and must
+ * be echoed back, so an older computer that ignores the argument cannot lend the builtin
+ * account's numbers to it.
+ */
+async function readUsage(
+ deps: RemoteSubscriptionDeps,
+ deviceId: string,
+ channel: string,
+ baseArgs: unknown[],
+ providerId: string,
+ defaultProviderId: string,
+): Promise<Record<string, unknown> | null> {
+ const scoped = providerId !== defaultProviderId;
+ const response = await deps.invoke(deviceId, channel, scoped ? [...baseArgs, providerId] : baseArgs);
+ if (!response.ok) throw Object.assign(new Error(response.error.message), { code: response.error.code });
+ const value = response.result;
+ if (!isRecord(value)) return null;
+ if (scoped && value.providerId !== providerId) return null;
+ return value;
+}
+
+async function readAccount(
+ deps: RemoteSubscriptionDeps,
+ device: MenubarRemoteDevice,
+ provider: ProviderView,
+): Promise<MenubarSubscriptionInput | null> {
+ const kind = providerWeeklyQuotaSource(provider);
+ let source: MenubarSubscriptionInput | null = null;
+ if (kind === 'codex') {
+ const payload = await readUsage(deps, device.id, 'maker:usage:account', ['codex'], provider.id, 'openai');
+ source = payload ? codexSource(provider, payload as unknown as CodexAccountUsagePayload, deps.nowMs) : null;
+ } else if (kind === 'claude') {
+ const payload = await readUsage(deps, device.id, 'maker:usage:claude-subscription', [], provider.id, 'anthropic');
+ source = payload ? claudeSource(provider, payload as unknown as ClaudeSubscriptionUsageSnapshot, deps.nowMs) : null;
+ } else if (kind === 'xai') {
+ const payload = await readUsage(deps, device.id, 'maker:usage:xai-subscription', [], provider.id, 'xai');
+ source = payload ? xaiSource(provider, payload as unknown as XaiSubscriptionUsageSnapshot, deps.nowMs) : null;
+ }
+ if (!source) return null;
+ return { ...source, id: `remote:${device.id}:${provider.id}`, device };
+}
+
+async function readDevice(deps: RemoteSubscriptionDeps, view: DeviceLinkDeviceView): Promise<MenubarSubscriptionInput[]> {
+ const device: MenubarRemoteDevice = { id: view.deviceId, name: view.name };
+ let providers: ProviderView[];
+ try {
+ providers = await readDeviceProviderViews(deps.invoke, device.id);
+ } catch (error) {
+ deps.onError?.(`remote:${device.id}:providers`, error);
+ return [];
+ }
+ const accounts = providers.filter((provider) => provider.connected && !provider.suspended && providerWeeklyQuotaSource(provider));
+ const read = await Promise.all(
+ accounts.map(async (provider) => {
+ try {
+ return await readAccount(deps, device, provider);
+ } catch (error) {
+ deps.onError?.(`remote:${device.id}:${provider.id}`, error);
+ return null;
+ }
+ }),
+ );
+ return read.filter((source): source is MenubarSubscriptionInput => source !== null);
+}
+
+export async function readRemoteSubscriptions(deps: RemoteSubscriptionDeps): Promise<MenubarSubscriptionInput[]> {
+ const { devices } = await deps.listDevices();
+ const targets = devices.filter(isRemoteQuotaDevice);
+ const sources: MenubarSubscriptionInput[] = [];
+ for (let offset = 0; offset < targets.length; offset += DEVICE_FANOUT) {
+ const batch = await Promise.all(targets.slice(offset, offset + DEVICE_FANOUT).map((device) => readDevice(deps, device)));
+ for (const read of batch) sources.push(...read);
+ }
+ return sources;
+}
diff --git a/apps/desktop/src/main/menubar/service.ts b/apps/desktop/src/main/menubar/service.ts
new file mode 100644
index 0000000000..53087bd481
--- /dev/null
+++ b/apps/desktop/src/main/menubar/service.ts
@@ -0,0 +1,761 @@
+/**
+ * macOS menu bar quota item: collects usage, builds the view and drives the native helper.
+ *
+ * Rebuilds are debounced and coalesced. They run on usage broadcasts, running-task
+ * transitions, settings and locale changes and a slow timer. Opening the panel or pressing
+ * refresh also asks every subscription reader to refresh, so values catch up while the
+ * panel is on screen. Everything here reads caches Cindy already keeps; the only extra
+ * network call is the Cindy balance, which is fetched at most once a minute.
+ */
+
+import { app, Notification } from 'electron';
+import os from 'node:os';
+
+import { isSessionActivityRunning } from '@cindy/maker-shared/session-activity';
+
+import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
+
+import type { ModelAccessCreditUsage } from '../../shared/modelAccess.js';
+import {
+ isMenubarSupportedPlatform,
+ type MenubarGate,
+ type MenubarHelperMessage,
+ type MenubarSettings,
+ type MenubarSettingsPatch,
+ type MenubarState,
+ type MenubarUsageScope,
+ type MenubarView,
+} from '../../shared/menubarQuota.js';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { getAgentIslandService } from '../agent-island/service.js';
+import { getAppCapabilities, requireAppCapability } from '../appCapabilities.js';
+import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
+import * as authManager from '../authManager.js';
+import { projectModelAccessBalance, projectModelAccessCreditUsage } from '../billing/projection.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import {
+ focusMainWindow,
+ openMainWindowBillingTopUp,
+ openMainWindowSession,
+ openMainWindowVoiceSettings,
+} from '../deepLink.js';
+import { remoteBackgroundInvoke } from '../device-link/index.js';
+import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
+import { deviceName } from '../device-link/deviceName.js';
+import { getResolvedMainLocale, mainStringKeysUnder, rawMainString } from '../i18n.js';
+import { getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
+import { createLogger } from '../logger.js';
+import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
+import { inspectAppDefaultModel } from '../maker-ipc/appDefaultModelControl.js';
+import { applyNewMakerDraftRoute } from '../maker-ipc/register.js';
+import {
+ readClaudeSubscriptionUsageSnapshotForDeviceLink,
+ readCodexRateLimitsForHost,
+ readXaiSubscriptionUsageSnapshotForDeviceLink,
+ triggerClaudeSubscriptionUsageRefresh,
+ triggerCodexAccountUsageRefresh,
+ triggerXaiSubscriptionUsageRefresh,
+} from '../maker-ipc/usage.js';
+import { getDesktopNotificationsEnabled } from '../notificationService.js';
+import { serverApiFetch } from '../serverApiClient.js';
+import { readClaudeAccountUsageSnapshot, triggerClaudeAccountUsageRefresh } from '../usage/claudeAccountUsage.js';
+import { currentLedgerCurrency } from '../usage/ledgerCurrency.js';
+import { readUsageHistory, type UsageHistoryPayload } from '../usage/usageHistory.js';
+import { observeUsageChanges, readCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
+import { providerWeeklyQuotaSource } from '../../shared/providerQuotaSource.js';
+import { CreditSampleStore, estimateDailyBurn, largestCreditSample } from './creditSamples.js';
+import {
+ collectMenubarInputs,
+ emptyMenubarInputs,
+ MENUBAR_USAGE_DAYS,
+ type MenubarBalanceReading,
+ type MenubarCollected,
+} from './collect.js';
+import { MacMenubarNativeHost } from './MacMenubarNativeHost.js';
+import { MENUBAR_HARNESS_LOGOS } from './logos.js';
+import { OwnedInFlight } from './ownedInFlight.js';
+import { readRemoteSubscriptions } from './remoteSubscriptions.js';
+import { readMenubarSettings, writeMenubarSettings } from './settingsStore.js';
+import {
+ buildMenubarView,
+ isLowOnEverything,
+ type MenubarBuildInput,
+ type MenubarResetCredits,
+ type MenubarSubscriptionInput,
+} from './snapshot.js';
+import { buildMenubarUiStrings, createMenubarTranslate } from './strings.js';
+
+const log = createLogger('menubar');
+
+const REBUILD_DEBOUNCE_MS = 400;
+const PERIODIC_REBUILD_MS = 5 * 60_000;
+/** A usage payload marked stale is being re-aggregated; look again shortly. */
+const STALE_FOLLOW_UP_MS = 3_000;
+const STALE_FOLLOW_UP_MAX = 5;
+const BALANCE_FRESH_WHILE_OPEN_MS = 60_000;
+const BALANCE_FRESH_WHILE_CLOSED_MS = 10 * 60_000;
+const BALANCE_TIMEOUT_MS = 20_000;
+/**
+ * Usage history keeps a single cache slot, and the two device ranges evict each other, so
+ * every read recomputes the history. Re-read on this cadence instead of on every token tick.
+ */
+const USAGE_FRESH_WHILE_OPEN_MS = 30_000;
+const USAGE_FRESH_WHILE_CLOSED_MS = 5 * 60_000;
+/**
+ * Other computers are read over a background device link, and Codex reset credits through the
+ * Codex account RPC. Both are slower and costlier than the local caches, so they keep their own
+ * longer cadence; opening the panel shortens it.
+ */
+const REMOTE_FRESH_WHILE_OPEN_MS = 60_000;
+const REMOTE_FRESH_WHILE_CLOSED_MS = 10 * 60_000;
+const RESETS_FRESH_WHILE_OPEN_MS = 3 * 60_000;
+const RESETS_FRESH_WHILE_CLOSED_MS = 30 * 60_000;
+
+export interface MenubarServiceDeps {
+ /** Opens a new task in the main window (the app menu's "New Task" command). */
+ openNewTask(): void;
+}
+
+interface UsageCacheEntry {
+ /** Data owner the history belongs to; a read that outlives an account switch is dropped. */
+ ownerId: string | null;
+ payload: UsageHistoryPayload;
+ readAtMs: number;
+}
+
+interface BalanceCache {
+ /** Account the reading belongs to; a different signed-in user invalidates it. */
+ accountKey: string;
+ reading: MenubarBalanceReading | null;
+ fetchedAtMs: number;
+}
+
+interface TimedCache<T> {
+ /** Data owner the reading belongs to; another owner invalidates it. */
+ ownerId: string | null;
+ value: T;
+ readAtMs: number;
+}
+
+class MenubarService {
+ private readonly host: MacMenubarNativeHost;
+ private readonly creditSamples = new CreditSampleStore();
+ private settings: MenubarSettings;
+ private started = false;
+ private panelOpen = false;
+ private lastView: MenubarView | null = null;
+ /** Null until the first build, so launching while low does not notify. */
+ private wasLow: boolean | null = null;
+ private lowNotification: Notification | null = null;
+ private balance: BalanceCache | null = null;
+ private readonly balanceInFlight = new OwnedInFlight<MenubarBalanceReading | null>();
+ private readonly usageCache = new Map<MenubarUsageScope, UsageCacheEntry>();
+ private usageOwnerId: string | null = null;
+ /** Serializes history reads so the two ranges never recompute at the same time. */
+ private usageChain: Promise<unknown> = Promise.resolve();
+ private remote: TimedCache<MenubarSubscriptionInput[]> | null = null;
+ private readonly remoteInFlight = new OwnedInFlight<MenubarSubscriptionInput[]>();
+ private readonly resets = new Map<string, TimedCache<MenubarResetCredits | null>>();
+
+ private rebuildTimer: ReturnType<typeof setTimeout> | null = null;
+ private periodicTimer: ReturnType<typeof setInterval> | null = null;
+ private building = false;
+ private rebuildQueued = false;
+ private forceNext = false;
+ private staleFollowUps = 0;
+ private disposers: (() => void)[] = [];
+
+ constructor(private readonly deps: MenubarServiceDeps) {
+ this.settings = readMenubarSettings();
+ this.host = new MacMenubarNativeHost({ onMessage: (message) => this.handleHelperMessage(message) });
+ }
+
+ get state(): MenubarState {
+ return { available: true, enabled: this.settings.enabled };
+ }
+
+ init(): void {
+ if (this.settings.enabled) this.start();
+ }
+
+ setEnabled(enabled: boolean): MenubarState {
+ this.settings = writeMenubarSettings({ enabled });
+ if (enabled) this.start();
+ else this.halt();
+ return this.state;
+ }
+
+ refreshLocalization(): void {
+ if (this.started) this.scheduleRebuild(0);
+ }
+
+ /** Opens the panel under the status item. */
+ openPanel(): void {
+ if (!this.started) return;
+ this.host.open();
+ }
+
+ stop(): void {
+ this.halt();
+ this.host.stop();
+ }
+
+ private start(): void {
+ if (this.started) return;
+ this.started = true;
+ this.wasLow = null;
+ this.usageOwnerId = getActiveAppSession().dataOwnerId;
+ this.host.resetFailure();
+ this.host.prepare();
+ this.disposers.push(
+ observeUsageChanges(() => this.scheduleRebuild()),
+ authManager.onAuthStateChange((state) => {
+ if (!state.isAuthenticated) this.balance = null;
+ // Usage history belongs to the data owner; token refreshes keep the cache.
+ const ownerId = getActiveAppSession().dataOwnerId;
+ if (ownerId !== this.usageOwnerId) {
+ this.usageOwnerId = ownerId;
+ this.usageCache.clear();
+ this.remote = null;
+ this.resets.clear();
+ }
+ this.scheduleRebuild();
+ }),
+ );
+ const island = getAgentIslandService();
+ if (island) {
+ this.disposers.push(
+ island.subscribeSessionActivity(({ previous, current }) => {
+ const wasRunning = previous ? isSessionActivityRunning(previous) : false;
+ const isRunning = current ? isSessionActivityRunning(current) : false;
+ if (wasRunning !== isRunning) this.scheduleRebuild();
+ }),
+ );
+ }
+ this.periodicTimer = setInterval(() => this.scheduleRebuild(), PERIODIC_REBUILD_MS);
+ this.scheduleRebuild(0);
+ }
+
+ private halt(): void {
+ if (!this.started) return;
+ this.started = false;
+ for (const dispose of this.disposers.splice(0)) {
+ try {
+ dispose();
+ } catch {
+ // Listener already gone.
+ }
+ }
+ if (this.periodicTimer) clearInterval(this.periodicTimer);
+ this.periodicTimer = null;
+ if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
+ this.rebuildTimer = null;
+ this.panelOpen = false;
+ this.lastView = null;
+ this.usageCache.clear();
+ this.remote = null;
+ this.resets.clear();
+ this.lowNotification?.close();
+ this.lowNotification = null;
+ this.host.suspend();
+ }
+
+ private scheduleRebuild(delayMs = REBUILD_DEBOUNCE_MS, force = false): void {
+ if (!this.started) return;
+ if (force) this.forceNext = true;
+ if (this.building) {
+ this.rebuildQueued = true;
+ return;
+ }
+ if (this.rebuildTimer) {
+ if (delayMs > 0) return;
+ clearTimeout(this.rebuildTimer);
+ }
+ this.rebuildTimer = setTimeout(() => {
+ this.rebuildTimer = null;
+ void this.rebuild();
+ }, delayMs);
+ }
+
+ private async rebuild(): Promise<void> {
+ if (!this.started || this.building) return;
+ this.building = true;
+ const force = this.forceNext;
+ this.forceNext = false;
+ let stale = false;
+ try {
+ const nowMs = Date.now();
+ // Until the user signs in or skips sign-in there is no data owner: read nothing and
+ // show the prompt. A pending owner switch keeps the last view; its commit rebuilds.
+ if (isAppSessionBoundaryPending()) {
+ // Nothing to publish yet.
+ } else if (!hasDataOwner()) {
+ this.publish(emptyMenubarInputs(nowMs, deviceName()), nowMs, 'sign-in');
+ } else {
+ await this.collectAndPublish(nowMs, force, () => {
+ stale = true;
+ });
+ }
+ } catch (error) {
+ log.warn('menu bar rebuild failed', { error: errorMessage(error) });
+ } finally {
+ this.building = false;
+ }
+ if (stale && this.staleFollowUps < STALE_FOLLOW_UP_MAX) {
+ this.staleFollowUps += 1;
+ this.scheduleRebuild(STALE_FOLLOW_UP_MS);
+ } else if (!stale) {
+ this.staleFollowUps = 0;
+ }
+ if (this.rebuildQueued) {
+ this.rebuildQueued = false;
+ this.scheduleRebuild();
+ }
+ }
+
+ private async collectAndPublish(nowMs: number, force: boolean, markStale: () => void): Promise<void> {
+ const generation = getActiveAppSession().generation;
+ const collected = await collectMenubarInputs({
+ nowMs,
+ listProviders: () => getDesktopProviderService().listProviders({ allowSideEffects: false }),
+ readCodex: (providerId) => readCodexAccountUsageSnapshot(providerId),
+ readClaude: (providerId) => readClaudeSubscriptionUsageSnapshotForDeviceLink(providerId),
+ readXai: (providerId) => readXaiSubscriptionUsageSnapshotForDeviceLink(providerId),
+ readCodexResets: (providerId) => this.readCodexResets(providerId, force, nowMs),
+ readRemoteSubscriptions: () => this.readRemote(force, nowMs),
+ readBalance: () => this.readBalance(force, nowMs),
+ readUsage: async (scope: MenubarUsageScope) => {
+ const payload = await this.readUsage(scope, force, nowMs);
+ if (payload.stale) markStale();
+ return payload;
+ },
+ activities: () => getAgentIslandService()?.getSessionActivitySnapshots() ?? [],
+ sessionRow: async (sessionId) => {
+ const row = await getSessionRowSnapshot(sessionId);
+ return row ? { title: row.title, model: row.model ?? null, agentKind: row.agentKind ?? null } : null;
+ },
+ selfDeviceName: deviceName(),
+ onError: (scope, error) => log.warn('menu bar source failed', { scope, error: errorMessage(error) }),
+ });
+ // An owner switch that started during the reads makes them the old owner's data.
+ const after = getActiveAppSession();
+ if (!this.started || isAppSessionBoundaryPending() || after.generation !== generation) return;
+ this.publish(collected, nowMs);
+ }
+
+ /** Cached usage history; a stale payload is re-read on the next build. */
+ private async readUsage(scope: MenubarUsageScope, force: boolean, nowMs: number): Promise<UsageHistoryPayload> {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ const entry = this.usageCache.get(scope);
+ const cached = entry?.ownerId === ownerId ? entry : null;
+ const maxAge = this.panelOpen ? USAGE_FRESH_WHILE_OPEN_MS : USAGE_FRESH_WHILE_CLOSED_MS;
+ if (cached && !force && !cached.payload.stale && nowMs - cached.readAtMs < maxAge) return cached.payload;
+ const read = this.usageChain.then(() =>
+ readUsageHistory({
+ days: MENUBAR_USAGE_DAYS,
+ modelDays: MENUBAR_USAGE_DAYS,
+ device: scope,
+ includeTasks: scope === 'local',
+ ...(force ? { forceRefresh: true } : {}),
+ }),
+ );
+ this.usageChain = read.catch(() => undefined);
+ const payload = await read;
+ if (getActiveAppSession().dataOwnerId === ownerId) this.usageCache.set(scope, { ownerId, payload, readAtMs: Date.now() });
+ return payload;
+ }
+
+ // ── Other computers and Codex resets ───────────────────────────────────────
+
+ /** Subscription accounts on the user's other computers; deduplicated later against local ones. */
+ private async readRemote(force: boolean, nowMs: number): Promise<MenubarSubscriptionInput[]> {
+ // Same gate as the device-link IPC: no device directory or peer link without an account.
+ if (!getAppCapabilities().canUseDeviceLink) {
+ this.remote = null;
+ return [];
+ }
+ const ownerId = getActiveAppSession().dataOwnerId;
+ const cached = this.remote?.ownerId === ownerId ? this.remote : null;
+ const maxAge = this.panelOpen ? REMOTE_FRESH_WHILE_OPEN_MS : REMOTE_FRESH_WHILE_CLOSED_MS;
+ if (cached && !force && nowMs - cached.readAtMs < maxAge) return cached.value;
+ // Joined only by callers of the same account; after a switch the new account reads its own.
+ const value = await this.remoteInFlight.run(ownerId, () =>
+ readRemoteSubscriptions({
+ nowMs,
+ listDevices: () => {
+ requireAppCapability('canUseDeviceLink', 'Device Link requires a Cindy account.');
+ return handleListDevices(deviceDirectoryDeps());
+ },
+ invoke: (deviceId, channel, args) => remoteBackgroundInvoke(deviceId, channel, args),
+ onError: (scope, error) => log.info('menu bar remote source failed', { scope, error: errorMessage(error) }),
+ }),
+ );
+ if (getActiveAppSession().dataOwnerId !== ownerId) return [];
+ this.remote = { ownerId, value, readAtMs: Date.now() };
+ return value;
+ }
+
+ /** Codex reset credits for one account; a failed read keeps the last known count. */
+ private async readCodexResets(providerId: string, force: boolean, nowMs: number): Promise<MenubarResetCredits | null> {
+ const ownerId = getActiveAppSession().dataOwnerId;
+ const entry = this.resets.get(providerId);
+ const cached = entry?.ownerId === ownerId ? entry : null;
+ const maxAge = this.panelOpen ? RESETS_FRESH_WHILE_OPEN_MS : RESETS_FRESH_WHILE_CLOSED_MS;
+ if (cached && !force && nowMs - cached.readAtMs < maxAge) return cached.value;
+ try {
+ const result = await readCodexRateLimitsForHost(providerId);
+ const value = resetCreditsOf(result, nowMs);
+ if (getActiveAppSession().dataOwnerId !== ownerId) return null;
+ this.resets.set(providerId, { ownerId, value, readAtMs: Date.now() });
+ return value;
+ } catch (error) {
+ log.info('menu bar codex resets unavailable', { providerId, error: errorMessage(error) });
+ // Do not retry on every rebuild; the next window of the cadence tries again.
+ this.resets.set(providerId, { ownerId, value: cached?.value ?? null, readAtMs: Date.now() });
+ return cached?.value ?? null;
+ }
+ }
+
+ private publish(collected: MenubarCollected, nowMs: number, gate?: MenubarGate): void {
+ const locale = getResolvedMainLocale();
+ const raw = (key: string) => rawMainString(key, locale);
+ const input: MenubarBuildInput = {
+ nowMs,
+ locale,
+ moneySymbol: currentLedgerCurrency() === 'CNY' ? '¥' : '$',
+ settings: this.settings,
+ sources: collected.sources,
+ tasks: collected.tasks,
+ usage: collected.usage,
+ updatedAtMs: collected.updatedAtMs,
+ harnessLogos: MENUBAR_HARNESS_LOGOS,
+ uiStrings: buildMenubarUiStrings(mainStringKeysUnder('menubar.ui'), raw, locale),
+ t: createMenubarTranslate(locale, raw),
+ ...(gate ? { gate } : {}),
+ };
+ const view = buildMenubarView(input);
+ this.lastView = view;
+ this.host.publish(view);
+ if (gate) {
+ // The first real build after signing in counts as a first build again.
+ this.wasLow = null;
+ return;
+ }
+ this.updateLowAlert(isLowOnEverything(input), input);
+ }
+
+ // ── Low alert ──────────────────────────────────────────────────────────────
+
+ /** Notifies once when everything usable drops to nearly empty; never on the first build. */
+ private updateLowAlert(low: boolean, input: MenubarBuildInput): void {
+ const previous = this.wasLow;
+ this.wasLow = low;
+ if (!low) {
+ this.lowNotification?.close();
+ this.lowNotification = null;
+ return;
+ }
+ if (previous !== false || !this.settings.lowAlert || !getDesktopNotificationsEnabled()) return;
+ if (!Notification.isSupported()) return;
+ const notification = new Notification({
+ title: input.t('notify.lowTitle'),
+ body: input.t('notify.lowBody'),
+ });
+ this.lowNotification = notification;
+ const release = () => {
+ if (this.lowNotification === notification) this.lowNotification = null;
+ };
+ notification.on('click', () => {
+ release();
+ this.openPanel();
+ });
+ notification.on('close', release);
+ notification.on('failed', (_event, error) => {
+ log.warn('menu bar low alert failed', { error: String(error) });
+ release();
+ });
+ notification.show();
+ }
+
+ // ── Cindy balance ──────────────────────────────────────────────────────────
+
+ /**
+ * Personal accounts have a wallet; organization accounts and a hand-entered gateway key have a
+ * period quota instead (what Settings shows as "本期剩余额度"). Null when there is neither.
+ */
+ private balanceAccountKey(): string | null {
+ const auth = authManager.getAuthState();
+ if (auth.mode === 'local') return auth.dataOwnerId ? `quota:local:${auth.dataOwnerId}` : null;
+ if (!getAppCapabilities().canUseCindyAccountServices) return null;
+ const user = auth.user;
+ if (!user) return null;
+ if (user.membershipKind === 'org') return auth.dataOwnerId ? `quota:cloud:${auth.dataOwnerId}` : null;
+ if (user.membershipKind !== 'personal') return null;
+ return `${user.id}:${CURRENT_CINDY_REGION}`;
+ }
+
+ private async readBalance(force: boolean, nowMs: number): Promise<MenubarBalanceReading | null> {
+ const accountKey = this.balanceAccountKey();
+ if (!accountKey) {
+ this.balance = null;
+ return null;
+ }
+ const cached = this.balance?.accountKey === accountKey ? this.balance : null;
+ const maxAge = this.panelOpen ? BALANCE_FRESH_WHILE_OPEN_MS : BALANCE_FRESH_WHILE_CLOSED_MS;
+ if (cached && !force && nowMs - cached.fetchedAtMs < maxAge) return cached.reading;
+ // A read still out for the previous account cannot answer for this one.
+ const read = this.balanceInFlight.run(accountKey, () =>
+ accountKey.startsWith('quota:') ? this.fetchQuota(accountKey, force) : this.fetchBalance(accountKey),
+ );
+ try {
+ const reading = await read;
+ // A sign-out or account switch while the request was out drops the result.
+ if (this.balanceAccountKey() !== accountKey) return null;
+ this.balance = { accountKey, reading, fetchedAtMs: Date.now() };
+ return reading;
+ } catch (error) {
+ log.warn('menu bar balance read failed', { error: errorMessage(error) });
+ // Keep showing the last known amount; its "updated" time tells the age.
+ return cached?.reading ?? null;
+ }
+ }
+
+ /** The gateway's period quota; the same reading Settings shows, refreshed through its throttle. */
+ private async fetchQuota(accountKey: string, force: boolean): Promise<MenubarBalanceReading | null> {
+ await triggerClaudeAccountUsageRefresh(force);
+ // Samples go to the signed-in account's folder; a switch mid-read must not file them there.
+ if (this.balanceAccountKey() !== accountKey) return null;
+ const quota = readClaudeAccountUsageSnapshot();
+ if (!quota || !(quota.maxBudget > 0)) return null;
+ const available = Math.max(0, quota.maxBudget - quota.spend);
+ const samples = this.creditSamples.record(`quota:${CURRENT_CINDY_REGION}:${quota.currency}`, available, quota.fetchedAt);
+ const resetsAtMs = quota.budgetResetAt ? Date.parse(quota.budgetResetAt) : NaN;
+ return {
+ available,
+ fullAmount: quota.maxBudget,
+ burnPerDay: estimateDailyBurn(samples, quota.fetchedAt),
+ observedAtMs: quota.fetchedAt,
+ currency: quota.currency,
+ quota: {
+ resetsAtMs: Number.isFinite(resetsAtMs) ? resetsAtMs : null,
+ todaySpend: Number.isFinite(quota.todaySpend) ? quota.todaySpend : null,
+ },
+ };
+ }
+
+ private async fetchBalance(accountKey: string): Promise<MenubarBalanceReading | null> {
+ const baseUrl = () => getClientEndpoint('modelAccessApiBaseUrl');
+ const options = { timeoutMs: BALANCE_TIMEOUT_MS, redactErrorDetails: true, baseUrl };
+ let available: number;
+ let pools: number | null = null;
+ let usage: ModelAccessCreditUsage | null = null;
+ let observedAt: string;
+ try {
+ usage = projectModelAccessCreditUsage(
+ await serverApiFetch<unknown>('/api/model-access/credit-usage', options),
+ );
+ available = Number(usage.available);
+ observedAt = usage.observedAt;
+ const totals = [usage.plan.total, usage.purchased.total, usage.promotional.total];
+ if (totals.every((total) => total !== null)) {
+ pools = totals.reduce((sum, total) => sum + Number(total), 0);
+ }
+ } catch (error) {
+ log.info('credit usage unavailable, falling back to balance', { error: errorMessage(error) });
+ const balance = projectModelAccessBalance(await serverApiFetch<unknown>('/api/model-access/balance', options));
+ available = Number(balance.available);
+ observedAt = balance.observedAt;
+ }
+ if (!Number.isFinite(available)) return null;
+ // The request used the old account's token; its amount must not land in the new account's samples.
+ if (this.balanceAccountKey() !== accountKey) return null;
+ const observedAtMs = Date.parse(observedAt);
+ const atMs = Number.isFinite(observedAtMs) ? observedAtMs : Date.now();
+ const currency = CURRENT_CINDY_REGION === 'global' ? 'USD' : 'CNY';
+ const samples = this.creditSamples.record(`${CURRENT_CINDY_REGION}:${currency}`, available, atMs);
+ const largest = largestCreditSample(samples);
+ const fullAmount = pools !== null && Number.isFinite(pools) && pools > 0 ? pools : largest;
+ return {
+ available,
+ fullAmount: fullAmount !== null && fullAmount >= available ? fullAmount : available,
+ burnPerDay: estimateDailyBurn(samples, atMs),
+ observedAtMs: Number.isFinite(observedAtMs) ? observedAtMs : null,
+ currency,
+ quota: null,
+ pools: usage ? walletPools(usage) : null,
+ promoExpiry: usage ? nearestPromoExpiry(usage, atMs) : null,
+ };
+ }
+
+ // ── Helper messages ────────────────────────────────────────────────────────
+
+ private handleHelperMessage(message: MenubarHelperMessage): void {
+ switch (message.type) {
+ case 'ready':
+ case 'error':
+ return;
+ case 'panel':
+ this.panelOpen = message.open;
+ if (message.open) this.refreshSources(false);
+ return;
+ case 'refresh':
+ this.refreshSources(true);
+ return;
+ case 'open-app':
+ this.showMainWindow();
+ return;
+ case 'open-session':
+ openMainWindowSession(message.sessionId);
+ return;
+ case 'detail-action':
+ void this.runDetailAction(message.sourceId);
+ return;
+ case 'open-provider-settings':
+ openMainWindowVoiceSettings('providers');
+ return;
+ case 'settings':
+ this.applySettingsPatch(message.patch);
+ return;
+ }
+ }
+
+ private applySettingsPatch(patch: MenubarSettingsPatch): void {
+ this.settings = writeMenubarSettings(patch);
+ if (!this.settings.enabled) {
+ this.halt();
+ return;
+ }
+ this.scheduleRebuild(0);
+ }
+
+ /** Asks every subscription reader to refresh; their broadcasts trigger the rebuild. */
+ private refreshSources(force: boolean): void {
+ // Behind the sign-in gate nothing is read, so there is nothing to refresh either.
+ if (!hasDataOwner()) {
+ this.scheduleRebuild(0, force);
+ return;
+ }
+ void getDesktopProviderService()
+ .listProviders({ allowSideEffects: false })
+ .then((providers) => {
+ for (const provider of providers) {
+ if (!provider.connected || provider.suspended || provider.removed) continue;
+ const kind = providerWeeklyQuotaSource(provider);
+ if (kind === 'codex') triggerCodexAccountUsageRefresh(provider.id);
+ else if (kind === 'claude') triggerClaudeSubscriptionUsageRefresh(provider.id);
+ else if (kind === 'xai') triggerXaiSubscriptionUsageRefresh(provider.id);
+ }
+ })
+ .catch((error) => log.warn('menu bar refresh could not list providers', { error: errorMessage(error) }));
+ this.scheduleRebuild(0, force);
+ }
+
+ private showMainWindow(): void {
+ if (!focusMainWindow()) app.focus({ steal: true });
+ }
+
+ private async runDetailAction(sourceId: string): Promise<void> {
+ const action = this.lastView?.details[sourceId]?.action;
+ if (!action) return;
+ switch (action.kind) {
+ case 'new-task':
+ await this.openTaskWith(action.providerId);
+ return;
+ case 'open-billing':
+ openMainWindowBillingTopUp();
+ return;
+ case 'open-settings':
+ openMainWindowVoiceSettings('providers');
+ return;
+ case 'open-app':
+ this.showMainWindow();
+ return;
+ case 'none':
+ return;
+ }
+ }
+
+ /** New task preselected on this account: the default model when it already uses it. */
+ private async openTaskWith(providerId: string): Promise<void> {
+ try {
+ const { current, available } = await inspectAppDefaultModel();
+ const route = current && current.providerId === providerId
+ ? current
+ : available.find((option) => option.route.providerId === providerId)?.route ?? null;
+ if (route) applyNewMakerDraftRoute(route);
+ else log.info('no model available for menu bar task', { providerId });
+ } catch (error) {
+ log.warn('menu bar could not preselect a model', { error: errorMessage(error) });
+ }
+ this.deps.openNewTask();
+ }
+}
+
+let service: MenubarService | null = null;
+
+export function initMenubarService(deps: MenubarServiceDeps): void {
+ if (service || !isMenubarSupportedPlatform(process.platform, os.release())) return;
+ service = new MenubarService(deps);
+ service.init();
+}
+
+export function getMenubarState(): MenubarState {
+ return service?.state ?? { available: false, enabled: false };
+}
+
+export function setMenubarEnabled(enabled: boolean): MenubarState {
+ return service ? service.setEnabled(enabled) : { available: false, enabled: false };
+}
+
+export function refreshMenubarLocalization(): void {
+ service?.refreshLocalization();
+}
+
+export function stopMenubarService(): void {
+ service?.stop();
+}
+
+/** Signed in or sign-in skipped: there is an owner whose data may be read. */
+function hasDataOwner(): boolean {
+ const session = getActiveAppSession();
+ return session.mode !== 'signed-out' && session.dataOwnerId !== null;
+}
+
+function resetCreditsOf(result: MobileCodexRateLimitsResult | null, nowMs: number): MenubarResetCredits | null {
+ const credits = result?.rateLimitResetCredits;
+ if (!credits) return null;
+ const count = Number.isFinite(credits.availableCount) ? Math.max(0, Math.floor(credits.availableCount)) : 0;
+ let earliestExpiryMs: number | null = null;
+ for (const credit of credits.credits ?? []) {
+ if (credit.status !== 'available' || credit.expiresAt === null) continue;
+ const expiresAtMs = credit.expiresAt * 1000;
+ if (expiresAtMs <= nowMs) continue;
+ if (earliestExpiryMs === null || expiresAtMs < earliestExpiryMs) earliestExpiryMs = expiresAtMs;
+ }
+ return { count, earliestExpiryMs };
+}
+
+function walletPools(usage: ModelAccessCreditUsage): MenubarBalanceReading['pools'] {
+ const plan = Number(usage.plan.remaining);
+ const purchased = Number(usage.purchased.remaining);
+ const promotional = Number(usage.promotional.remaining);
+ if (![plan, purchased, promotional].every(Number.isFinite)) return null;
+ return { plan, purchased, promotional };
+}
+
+/** The active gift that runs out first while it still has money left. */
+function nearestPromoExpiry(usage: ModelAccessCreditUsage, nowMs: number): MenubarBalanceReading['promoExpiry'] {
+ let nearest: { amount: number; expiresAtMs: number } | null = null;
+ for (const grant of usage.promotionalGrants) {
+ if (grant.state !== 'active') continue;
+ const amount = Number(grant.remainingAmount);
+ const expiresAtMs = Date.parse(grant.expiresAt);
+ if (!(amount > 0) || !Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs) continue;
+ if (!nearest || expiresAtMs < nearest.expiresAtMs) nearest = { amount, expiresAtMs };
+ }
+ return nearest;
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
diff --git a/apps/desktop/src/main/menubar/settingsStore.ts b/apps/desktop/src/main/menubar/settingsStore.ts
new file mode 100644
index 0000000000..a7d4c160cf
--- /dev/null
+++ b/apps/desktop/src/main/menubar/settingsStore.ts
@@ -0,0 +1,91 @@
+/**
+ * Menu bar quota settings, persisted as overrides in <userData>/menubar-settings.json.
+ *
+ * Only values the user changed are written, so new defaults reach everyone else. Source
+ * ids the user ordered or hid are kept even while that connection is gone, so reconnecting
+ * an account puts it back where it was.
+ */
+
+import { app } from 'electron';
+import path from 'node:path';
+
+import {
+ DEFAULT_MENUBAR_SETTINGS,
+ MENUBAR_STATUS_TEXT_MODES,
+ MENUBAR_USAGE_SCOPES,
+ type MenubarSettings,
+ type MenubarSettingsPatch,
+} from '../../shared/menubarQuota.js';
+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';
+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';
+
+const log = desktopMakerLogger.child('menubar-settings');
+const MAX_IDS = 200;
+const MAX_ID_LENGTH = 200;
+
+function idList(value: unknown): string[] | null {
+ if (!Array.isArray(value)) return null;
+ const seen = new Set<string>();
+ for (const item of value) {
+ if (typeof item !== 'string' || item.length === 0 || item.length > MAX_ID_LENGTH) continue;
+ seen.add(item);
+ if (seen.size >= MAX_IDS) break;
+ }
+ return [...seen];
+}
+
+export function normalizeMenubarSettings(raw: unknown): MenubarSettings {
+ const r = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
+ const d = DEFAULT_MENUBAR_SETTINGS;
+ return {
+ enabled: typeof r.enabled === 'boolean' ? r.enabled : d.enabled,
+ order: idList(r.order) ?? [...d.order],
+ hidden: idList(r.hidden) ?? [...d.hidden],
+ shown: idList(r.shown) ?? [...d.shown],
+ statusText: MENUBAR_STATUS_TEXT_MODES.includes(r.statusText as never)
+ ? (r.statusText as MenubarSettings['statusText'])
+ : d.statusText,
+ lowAlert: typeof r.lowAlert === 'boolean' ? r.lowAlert : d.lowAlert,
+ privacy: typeof r.privacy === 'boolean' ? r.privacy : d.privacy,
+ scope: MENUBAR_USAGE_SCOPES.includes(r.scope as never) ? (r.scope as MenubarSettings['scope']) : d.scope,
+ };
+}
+
+/** Keeps only recognised keys with valid values; anything else in a patch is dropped. */
+export function sanitizeMenubarSettingsPatch(raw: unknown): MenubarSettingsPatch {
+ if (!raw || typeof raw !== 'object') return {};
+ const r = raw as Record<string, unknown>;
+ const normalized = normalizeMenubarSettings(r);
+ const patch: MenubarSettingsPatch = {};
+ for (const key of Object.keys(DEFAULT_MENUBAR_SETTINGS) as (keyof MenubarSettings)[]) {
+ if (!(key in r)) continue;
+ const valid =
+ key === 'order' || key === 'hidden' || key === 'shown'
+ ? Array.isArray(r[key])
+ : key === 'statusText'
+ ? MENUBAR_STATUS_TEXT_MODES.includes(r[key] as never)
+ : key === 'scope'
+ ? MENUBAR_USAGE_SCOPES.includes(r[key] as never)
+ : typeof r[key] === 'boolean';
+ if (valid) (patch as Record<string, unknown>)[key] = normalized[key];
+ }
+ return patch;
+}
+
+const store = createOverrideSettingsFile<MenubarSettings>({
+ filePath: () => path.join(app.getPath('userData'), 'menubar-settings.json'),
+ defaults: DEFAULT_MENUBAR_SETTINGS,
+ normalize: normalizeMenubarSettings,
+ log,
+ label: 'menubar',
+});
+
+export function readMenubarSettings(): MenubarSettings {
+ return store.read();
+}
+
+export function writeMenubarSettings(patch: MenubarSettingsPatch): MenubarSettings {
+ const clean = sanitizeMenubarSettingsPatch(patch);
+ if (Object.keys(clean).length > 0) store.writePatch(clean);
+ return store.read();
+}
diff --git a/apps/desktop/src/main/menubar/snapshot.ts b/apps/desktop/src/main/menubar/snapshot.ts
new file mode 100644
index 0000000000..04c39b0a64
--- /dev/null
+++ b/apps/desktop/src/main/menubar/snapshot.ts
@@ -0,0 +1,1143 @@
+/**
+ * Builds the menu bar view model from normalized usage inputs.
+ *
+ * Pure: no Electron, no I/O, no clock. `collect.ts` gathers the inputs and `service.ts`
+ * sends the result to the native helper. Every product sentence is decided here so the
+ * Swift side never reasons about accounts, only renders.
+ *
+ * Wording rules: Cindy does not switch accounts on its own and has no default Codex
+ * account, so nothing here may claim it does. Suggestions describe the data ("has the most
+ * left", "resets Wednesday") and actions are explicit ("start a task with X").
+ */
+
+import {
+ type MenubarColor,
+ type MenubarDetail,
+ type MenubarDetailAction,
+ type MenubarFact,
+ type MenubarGate,
+ type MenubarLevel,
+ type MenubarManageRow,
+ type MenubarModelUsage,
+ type MenubarSettings,
+ type MenubarSourceCell,
+ type MenubarStatusTextMode,
+ type MenubarStrings,
+ type MenubarTask,
+ type MenubarUsage,
+ type MenubarUsageScope,
+ type MenubarUsageScopeData,
+ type MenubarView,
+} from '../../shared/menubarQuota.js';
+
+export type MenubarHarness = 'claude-code' | 'codex' | 'pi';
+export type MenubarFamily = 'claude' | 'codex' | 'grok';
+
+export interface MenubarWindowInput {
+ kind: 'session' | 'week' | 'scoped';
+ /** Model name for scoped windows ("Fable"). */
+ label?: string | null;
+ /** 0...100 used. */
+ usedPercent: number;
+ resetsAtMs: number | null;
+ windowMinutes: number;
+}
+
+export interface MenubarSubscriptionInput {
+ kind: 'subscription';
+ id: string;
+ providerId: string;
+ family: MenubarFamily;
+ logoSvg: string;
+ /** Brand shown as the detail title: Claude, Codex, Grok. */
+ brand: string;
+ /** Account email when the provider exposes one (Codex accounts). */
+ account: string | null;
+ plan: string | null;
+ /** Empty while the first read is still pending. */
+ windows: MenubarWindowInput[];
+ /** Codex extra credits; null when the account reports none. */
+ credits: number | null;
+ creditsUnlimited: boolean;
+ /** xAI prepaid balance in USD. */
+ prepaidUsd: number | null;
+ updatedAtMs: number | null;
+ /** Identity keys used only to recognize one account read on two computers; never shown. */
+ accountKeys?: readonly string[];
+ /** Set when the account is signed in on another of the user's computers. */
+ device?: MenubarRemoteDevice | null;
+ /** Codex rate-limit resets the user can redeem. */
+ resetCredits?: MenubarResetCredits | null;
+}
+
+export interface MenubarRemoteDevice {
+ id: string;
+ name: string;
+}
+
+export interface MenubarResetCredits {
+ count: number;
+ /** Soonest expiry among the available resets; null when none expires. */
+ earliestExpiryMs: number | null;
+}
+
+export interface MenubarBalanceInput {
+ kind: 'balance';
+ id: string;
+ logoSvg: string;
+ /** Remaining balance in the billing currency. */
+ available: number;
+ /** What a full tube means: the sum of pool totals, or the largest balance seen. */
+ fullAmount: number | null;
+ /** Average daily decrease over the sampled days; null until there is enough history. */
+ burnPerDay: number | null;
+ observedAtMs: number | null;
+ /** Billing currency, which can differ from the usage ledger currency. */
+ currency: 'USD' | 'CNY';
+ /** Set for a period quota (organization or gateway key) rather than a wallet. */
+ quota: MenubarQuotaPeriod | null;
+ /** What is left in each wallet pool; null when the server did not report them. */
+ pools?: MenubarWalletPools | null;
+ /** The promotional grant with money left that expires first. */
+ promoExpiry?: { amount: number; expiresAtMs: number } | null;
+}
+
+export interface MenubarWalletPools {
+ plan: number;
+ purchased: number;
+ promotional: number;
+}
+
+/** A gateway budget that refills each period, unlike a wallet that only grows by top-ups. */
+export interface MenubarQuotaPeriod {
+ resetsAtMs: number | null;
+ /** Spent today (UTC day) across every client; null when the gateway did not say. */
+ todaySpend: number | null;
+}
+
+export interface MenubarPaygInput {
+ kind: 'payg';
+ id: string;
+ providerId: string;
+ logoSvg: string;
+ name: string;
+ /** api = billed per use; subscription = a plan Cindy cannot read the remaining amount of. */
+ billing: 'api' | 'subscription';
+}
+
+export type MenubarSourceInput = MenubarSubscriptionInput | MenubarBalanceInput | MenubarPaygInput;
+
+export interface MenubarTaskInput {
+ sessionId: string;
+ title: string;
+ harness: MenubarHarness;
+ model: string;
+ tokensToday: number;
+ valueToday: number;
+ contextPercent: number | null;
+ running: boolean;
+ startedAtMs: number | null;
+ lastActiveAtMs: number;
+}
+
+export interface MenubarUsageDeviceInput {
+ name: string;
+ isSelf: boolean;
+ syncedAtMs: number | null;
+}
+
+export interface MenubarUsageScopeInput {
+ daily: MenubarUsageScopeData['daily'];
+ models: MenubarUsageScopeData['models'];
+ devices: MenubarUsageDeviceInput[];
+}
+
+export interface MenubarUsageInput {
+ days: string[];
+ scopes: Record<MenubarUsageScope, MenubarUsageScopeInput>;
+}
+
+/** Looks up `menubar.<key>` and fills `{{name}}`; a numeric `count` picks `_one` / `_other`. */
+export type MenubarTranslate = (key: string, vars?: Record<string, string | number>) => string;
+
+export interface MenubarBuildInput {
+ nowMs: number;
+ locale: string;
+ moneySymbol: string;
+ settings: MenubarSettings;
+ sources: MenubarSourceInput[];
+ tasks: MenubarTaskInput[];
+ usage: MenubarUsageInput;
+ updatedAtMs: number | null;
+ harnessLogos: Record<MenubarHarness, string>;
+ /** Raw templates the helper fills itself (relative times, clocks, page chrome). */
+ uiStrings: MenubarStrings;
+ t: MenubarTranslate;
+ /** Shows the gate instead of data; callers pass empty sources, tasks and usage with it. */
+ gate?: MenubarGate;
+}
+
+const HOUR_MS = 3_600_000;
+const DAY_MS = 86_400_000;
+const WARN_REMAINING = 15;
+const SOON_MS = 12 * HOUR_MS;
+const RESTORE_GROUP_MS = 6 * HOUR_MS;
+const RESTORE_HORIZON_MS = 7 * DAY_MS;
+const MIN_PACE_ELAPSED = 0.03;
+/** Up to this many visible cells have room for the full "resets in …" phrase. */
+const ROOMY_CELL_LIMIT = 4;
+/** Settings' soft daily limit for a period quota: period total / 30 × 4.5 (a display hint, not a cap). */
+const DAILY_SOFT_LIMIT_FACTOR = 4.5;
+const FAMILY_ORDER: Record<MenubarFamily, number> = { claude: 0, codex: 1, grok: 2 };
+const FAMILY_COLORS: Record<MenubarFamily, MenubarColor[]> = {
+ claude: ['claude', 'claude2', 'claude3'],
+ codex: ['codex'],
+ grok: ['fill'],
+};
+const HARNESS_ORDER: MenubarHarness[] = ['claude-code', 'codex', 'pi'];
+
+interface WindowState {
+ window: MenubarWindowInput;
+ remaining: number;
+ leftMs: number;
+ elapsed: number;
+ expected: number;
+ /** Positive = ahead of an even pace (spending fast), negative = in reserve. */
+ pace: number | null;
+ /** Time until empty at the current pace, when that comes before the reset. */
+ etaMs: number | null;
+}
+
+interface SubscriptionState {
+ windows: WindowState[];
+ /** The tightest window that limits the whole account (scoped windows excluded). */
+ limit: WindowState | null;
+ remaining: number | null;
+}
+
+function windowState(window: MenubarWindowInput, nowMs: number): WindowState {
+ const span = Math.max(1, window.windowMinutes) * 60_000;
+ const leftMs = window.resetsAtMs === null ? span : Math.max(0, window.resetsAtMs - nowMs);
+ const elapsed = Math.min(1, Math.max(0, 1 - leftMs / span));
+ const used = clamp(window.usedPercent, 0, 100);
+ const remaining = 100 - used;
+ const state: WindowState = {
+ window,
+ remaining,
+ leftMs,
+ elapsed,
+ expected: elapsed * 100,
+ pace: null,
+ etaMs: null,
+ };
+ if (elapsed >= MIN_PACE_ELAPSED && remaining > 0) {
+ state.pace = used - state.expected;
+ if (used > 0) {
+ const etaMs = remaining / (used / (elapsed * span));
+ if (etaMs < leftMs) state.etaMs = etaMs;
+ }
+ }
+ return state;
+}
+
+function subscriptionState(source: MenubarSubscriptionInput, nowMs: number): SubscriptionState {
+ const windows = source.windows.map((window) => windowState(window, nowMs));
+ const limits = windows.filter((state) => state.window.kind !== 'scoped');
+ const limit = limits.reduce<WindowState | null>(
+ (tightest, state) => (!tightest || state.remaining < tightest.remaining ? state : tightest),
+ null,
+ );
+ return { windows, limit, remaining: limit ? limit.remaining : null };
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(max, Math.max(min, value));
+}
+
+function levelOf(remaining: number): MenubarLevel {
+ if (remaining <= 0) return 'error';
+ if (remaining <= WARN_REMAINING) return 'warn';
+ return 'normal';
+}
+
+function levelColor(level: MenubarLevel): MenubarColor | null {
+ if (level === 'error') return 'error';
+ if (level === 'warn') return 'warn';
+ return null;
+}
+
+/** Ordered, visible sources. Pay-as-you-go connections start hidden until the user shows them. */
+export function orderSources<T extends { id: string; kind: string }>(
+ sources: readonly T[],
+ settings: MenubarSettings,
+): { ordered: T[]; isHidden: (source: T) => boolean } {
+ const rank = new Map(settings.order.map((id, index) => [id, index]));
+ const naturalRank = (source: T): number => (source.kind === 'balance' ? 0 : source.kind === 'subscription' ? 1 : 2);
+ const ordered = sources
+ .map((source, index) => ({ source, index }))
+ .sort((a, b) => {
+ const ra = rank.get(a.source.id);
+ const rb = rank.get(b.source.id);
+ if (ra !== undefined && rb !== undefined) return ra - rb;
+ if (ra !== undefined) return -1;
+ if (rb !== undefined) return 1;
+ return naturalRank(a.source) - naturalRank(b.source) || a.index - b.index;
+ })
+ .map(({ source }) => source);
+ const hidden = new Set(settings.hidden);
+ const shown = new Set(settings.shown);
+ const isHidden = (source: T): boolean =>
+ hidden.has(source.id) || (source.kind === 'payg' && !shown.has(source.id));
+ return { ordered, isHidden };
+}
+
+class Builder {
+ private readonly states = new Map<string, SubscriptionState>();
+ private readonly timeFormat: Intl.DateTimeFormat;
+ private readonly weekdayFormat: Intl.DateTimeFormat;
+ private readonly dateFormat: Intl.DateTimeFormat;
+ private readonly visible: MenubarSourceInput[];
+ private readonly ordered: MenubarSourceInput[];
+ private readonly isHidden: (source: MenubarSourceInput) => boolean;
+
+ constructor(private readonly input: MenubarBuildInput) {
+ this.timeFormat = new Intl.DateTimeFormat(input.locale, { hour: '2-digit', minute: '2-digit' });
+ this.weekdayFormat = new Intl.DateTimeFormat(input.locale, { weekday: 'short' });
+ this.dateFormat = new Intl.DateTimeFormat(input.locale, { month: 'short', day: 'numeric' });
+ const { ordered, isHidden } = orderSources(input.sources, input.settings);
+ this.ordered = ordered;
+ this.isHidden = isHidden;
+ const visible = ordered.filter((source) => !isHidden(source));
+ // Never render an empty menu: if every source is hidden, show them all.
+ this.visible = visible.length > 0 ? visible : ordered;
+ for (const source of input.sources) {
+ if (source.kind === 'subscription') this.states.set(source.id, subscriptionState(source, input.nowMs));
+ }
+ }
+
+ private get t(): MenubarTranslate {
+ return this.input.t;
+ }
+
+ private state(source: MenubarSubscriptionInput): SubscriptionState {
+ return this.states.get(source.id) ?? subscriptionState(source, this.input.nowMs);
+ }
+
+ // ── Formatting ────────────────────────────────────────────────────────────
+
+ private money(value: number, symbol = this.input.moneySymbol): string {
+ if (value >= 10_000) return `${symbol}${(value / 1000).toFixed(1)}k`;
+ if (value >= 100) return `${symbol}${Math.round(value).toLocaleString('en-US')}`;
+ return `${symbol}${value.toFixed(2)}`;
+ }
+
+ private balanceMoney(value: number, currency: 'USD' | 'CNY'): string {
+ return this.money(value, currency === 'CNY' ? '¥' : '$');
+ }
+
+ /** Full amount to the cent, for the detail facts where the tube's rounding would hide spend. */
+ private exactMoney(value: number, currency: 'USD' | 'CNY'): string {
+ const amount = value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+ return `${currency === 'CNY' ? '¥' : '$'}${amount}`;
+ }
+
+ private tokens(value: number): string {
+ const millions = value / 1e6;
+ if (millions >= 1000) return `${(millions / 1000).toFixed(1)}B`;
+ if (millions >= 1) return `${Math.round(millions)}M`;
+ return `${Math.round(millions * 1000)}K`;
+ }
+
+ private grouped(value: number): string {
+ return Math.round(value).toLocaleString('en-US');
+ }
+
+ private compact(value: number): string {
+ return new Intl.NumberFormat(this.input.locale, {
+ notation: 'compact',
+ maximumFractionDigits: 1,
+ }).format(value);
+ }
+
+ private dayOffset(ms: number): number {
+ const day = new Date(ms);
+ const now = new Date(this.input.nowMs);
+ const startOfDay = (date: Date): number =>
+ new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
+ return Math.round((startOfDay(day) - startOfDay(now)) / DAY_MS);
+ }
+
+ /** "今天 14:00" / "明天 14:00" / "周三 14:00" / "10月14日 14:00". */
+ private at(ms: number): string {
+ const time = this.timeFormat.format(ms);
+ const offset = this.dayOffset(ms);
+ if (offset === 0) return this.t('time.today', { time });
+ if (offset === 1) return this.t('time.tomorrow', { time });
+ if (offset > 1 && offset < 7) return this.t('time.weekday', { day: this.weekdayFormat.format(ms), time });
+ return this.t('time.date', { date: this.dateFormat.format(ms), time });
+ }
+
+ /** "6天7时" / "4时46分" / "12分": the same two units, compact enough for under a tube. */
+ private shortDuration(ms: number): string {
+ const minutes = Math.max(1, Math.floor(ms / 60_000));
+ const d = Math.floor(minutes / 1440);
+ const h = Math.floor((minutes % 1440) / 60);
+ const m = minutes % 60;
+ if (d) return h ? this.t('durationShort.daysHours', { d, h }) : this.t('durationShort.days', { d });
+ if (h) return m ? this.t('durationShort.hoursMinutes', { h, m }) : this.t('durationShort.hours', { h });
+ return this.t('durationShort.minutes', { m });
+ }
+
+ /** "3 天 4 小时" / "2 小时 5 分" / "12 分钟". */
+ private duration(ms: number): string {
+ const seconds = Math.max(0, ms / 1000);
+ const d = Math.floor(seconds / 86_400);
+ const h = Math.floor((seconds % 86_400) / 3600);
+ const m = Math.floor((seconds % 3600) / 60);
+ if (d) return h ? this.t('duration.daysHours', { d, h }) : this.t('duration.days', { count: d, d });
+ if (h) return m ? this.t('duration.hoursMinutes', { h, m }) : this.t('duration.hours', { count: h, h });
+ return this.t('duration.minutes', { count: Math.max(1, m), m: Math.max(1, m) });
+ }
+
+ private ago(ms: number): string {
+ const minutes = Math.max(1, Math.round((this.input.nowMs - ms) / 60_000));
+ if (minutes < 60) return this.t('time.minutesAgo', { count: minutes, n: minutes });
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return this.t('time.hoursAgo', { count: hours, n: hours });
+ const days = Math.floor(hours / 24);
+ return this.t('time.daysAgo', { count: days, n: days });
+ }
+
+ private windowLabel(window: MenubarWindowInput): string {
+ if (window.kind === 'session') return this.t('window.session', { hours: Math.round(window.windowMinutes / 60) });
+ if (window.kind === 'scoped') return this.t('window.scoped', { model: window.label ?? '' });
+ return this.t('window.week');
+ }
+
+ // ── Identity ──────────────────────────────────────────────────────────────
+
+ private handle(source: MenubarSubscriptionInput): string | null {
+ if (!source.account) return null;
+ const [local] = source.account.split('@');
+ if (!local) return null;
+ if (!this.input.settings.privacy) return local;
+ return `${local[0]}•••${local.length > 1 ? local[local.length - 1] : ''}`;
+ }
+
+ private email(source: MenubarSubscriptionInput): string {
+ if (!source.account) return '';
+ if (!this.input.settings.privacy) return source.account;
+ const domain = source.account.split('@')[1];
+ return domain ? `${this.handle(source)}@${domain}` : this.handle(source) ?? '';
+ }
+
+ /** Short name under a tube and in sentences: the other computer, else the account handle, else the brand. */
+ private who(source: MenubarSourceInput): string {
+ if (source.kind === 'subscription') return source.device?.name ?? this.handle(source) ?? source.brand;
+ if (source.kind === 'balance') return this.t('balance.short');
+ return source.name;
+ }
+
+ private sourceTitle(source: MenubarSourceInput): string {
+ if (source.kind === 'subscription') return source.device?.name ?? this.handle(source) ?? source.brand;
+ if (source.kind === 'balance') return this.t(source.quota ? 'balance.quotaName' : 'balance.name');
+ return source.name;
+ }
+
+ // ── Judgment ──────────────────────────────────────────────────────────────
+
+ private visibleSubscriptions(): MenubarSubscriptionInput[] {
+ return this.visible.filter((source): source is MenubarSubscriptionInput => source.kind === 'subscription');
+ }
+
+ private remaining(source: MenubarSubscriptionInput): number | null {
+ return this.state(source).remaining;
+ }
+
+ /** The subscription with the most room left, else a balance with money on it. */
+ private recommended(): MenubarSourceInput | null {
+ const subscriptions = this.visibleSubscriptions()
+ .filter((source) => (this.remaining(source) ?? 0) > 0)
+ .sort(
+ (a, b) =>
+ (this.remaining(b) ?? 0) - (this.remaining(a) ?? 0)
+ || FAMILY_ORDER[a.family] - FAMILY_ORDER[b.family],
+ );
+ if (subscriptions[0]) return subscriptions[0];
+ return this.visible.find((source) => source.kind === 'balance' && source.available > 0) ?? null;
+ }
+
+ /** The subscription closest to empty that still has room. */
+ private tightest(): MenubarSubscriptionInput | null {
+ return (
+ this.visibleSubscriptions()
+ .filter((source) => (this.remaining(source) ?? 0) > 0)
+ .sort((a, b) => (this.remaining(a) ?? 0) - (this.remaining(b) ?? 0))[0] ?? null
+ );
+ }
+
+ /**
+ * When nearly-empty sources get their limiting window back, within a week, grouped when the
+ * same family resets within 6 hours. Sources with plenty left are not worth a headline.
+ */
+ private restores(): { atMs: number; sources: MenubarSubscriptionInput[] }[] {
+ const events: { atMs: number; source: MenubarSubscriptionInput }[] = [];
+ for (const source of this.visibleSubscriptions()) {
+ const { limit, remaining } = this.state(source);
+ const atMs = limit?.window.resetsAtMs ?? null;
+ if (remaining === null || remaining > WARN_REMAINING || atMs === null) continue;
+ if (atMs - this.input.nowMs > RESTORE_HORIZON_MS) continue;
+ events.push({ atMs, source });
+ }
+ events.sort((a, b) => a.atMs - b.atMs);
+ const groups: { atMs: number; sources: MenubarSubscriptionInput[] }[] = [];
+ for (const event of events) {
+ const last = groups[groups.length - 1];
+ if (last && event.atMs - last.atMs < RESTORE_GROUP_MS && last.sources[0]?.family === event.source.family) {
+ if (!last.sources.includes(event.source)) last.sources.push(event.source);
+ } else {
+ groups.push({ atMs: event.atMs, sources: [event.source] });
+ }
+ }
+ return groups;
+ }
+
+ private headline(): { primary: string; secondary: string | null } {
+ const recommended = this.recommended();
+ const groups = this.restores();
+ const soon = this.visibleSubscriptions()
+ .map((source) => ({ source, eta: this.state(source).limit?.etaMs ?? null }))
+ .filter((entry): entry is { source: MenubarSubscriptionInput; eta: number } => entry.eta !== null && entry.eta < SOON_MS)
+ .sort((a, b) => a.eta - b.eta)[0];
+ const big = groups.find((group) => group.sources.length > 1) ?? groups[0];
+ const parts: string[] = [];
+ if (big) {
+ const first = big.sources[0]!;
+ const name = big.sources.length > 1 ? first.brand : this.who(first);
+ parts.push(this.t('headline.restore', { name, duration: this.duration(big.atMs - this.input.nowMs) }));
+ }
+ // A source already named for its reset does not also need "running low".
+ if (soon && !big?.sources.includes(soon.source)) parts.push(this.t('headline.soon', { name: this.who(soon.source) }));
+ const sentence = (items: string[]): string | null =>
+ items.length ? this.t('headline.sentence', { text: items.join(this.t('headline.joiner')) }) : null;
+ if (!recommended) {
+ // "Used up" is only true when something was actually measured empty.
+ const measured =
+ this.visible.some((source) => source.kind === 'balance')
+ || this.visibleSubscriptions().some((source) => this.remaining(source) !== null);
+ if (!measured) {
+ const unread = this.visibleSubscriptions().length > 0;
+ return unread
+ ? { primary: this.t('headline.unread'), secondary: null }
+ : { primary: this.t('headline.empty'), secondary: this.t('headline.emptyHint') };
+ }
+ return {
+ primary: this.t('headline.none'),
+ secondary: sentence(parts.length ? [parts[0]!] : [this.t('headline.waitReset')]),
+ };
+ }
+ if (recommended.kind === 'balance') {
+ const primary = this.t(recommended.quota ? 'headline.quota' : 'headline.balance');
+ return { primary, secondary: sentence([this.t('headline.subscriptionsUsed'), ...parts]) };
+ }
+ return { primary: this.t('headline.recommend', { name: this.who(recommended) }), secondary: sentence(parts) };
+ }
+
+ // ── Cells ─────────────────────────────────────────────────────────────────
+
+ private cells(): MenubarSourceCell[] {
+ const recommended = this.recommended();
+ const roomy = this.visible.length <= ROOMY_CELL_LIMIT;
+ return this.visible.map((source) => this.cell(source, source === recommended, roomy));
+ }
+
+ /** A quota counts down to its reset like a subscription; a wallet says how long it lasts. */
+ private balanceWhen(source: MenubarBalanceInput, days: number | null, roomy: boolean): string {
+ const resetsAtMs = source.quota?.resetsAtMs ?? null;
+ if (resetsAtMs !== null) {
+ const duration = this.shortDuration(resetsAtMs - this.input.nowMs);
+ return roomy ? this.t('cell.resetsIn', { duration }) : duration;
+ }
+ return days === null ? '' : this.t(roomy ? 'cell.lastsDays' : 'cell.lastsDaysShort', { n: days });
+ }
+
+ private cell(source: MenubarSourceInput, emphasized: boolean, roomy: boolean): MenubarSourceCell {
+ const base = { id: source.id, kind: source.kind, logoSvg: source.logoSvg, emphasized };
+ if (source.kind === 'payg') {
+ const label = this.t(source.billing === 'api' ? 'cell.payg' : 'cell.plan');
+ return {
+ ...base,
+ emphasized: false,
+ name: source.name,
+ value: null,
+ valueUnit: null,
+ valueLabel: label,
+ level: 'normal',
+ fill: null,
+ reserve: false,
+ when: this.t(source.billing === 'api' ? 'cell.noBalance' : 'cell.unknown'),
+ whenLevel: 'normal',
+ accessibilityLabel: this.t(source.billing === 'api' ? 'a11y.payg' : 'a11y.plan', { name: source.name }),
+ };
+ }
+ if (source.kind === 'balance') {
+ const days = source.burnPerDay && source.burnPerDay > 0 ? Math.floor(source.available / source.burnPerDay) : null;
+ const fill = source.fullAmount && source.fullAmount > 0 ? clamp(source.available / source.fullAmount, 0, 1) : source.available > 0 ? 1 : 0;
+ const amount = this.balanceMoney(source.available, source.currency);
+ return {
+ ...base,
+ name: this.t('balance.short'),
+ value: amount,
+ valueUnit: null,
+ valueLabel: null,
+ level: source.available > 0 ? 'normal' : 'error',
+ fill,
+ reserve: false,
+ when: this.balanceWhen(source, days, roomy),
+ whenLevel: 'normal',
+ accessibilityLabel: source.quota
+ ? this.t('a11y.quota', { amount })
+ : days === null
+ ? this.t('a11y.balance', { amount })
+ : this.t('a11y.balanceDays', { amount, n: days }),
+ };
+ }
+ const state = this.state(source);
+ const name = this.who(source);
+ if (!state.limit || state.remaining === null) {
+ return {
+ ...base,
+ emphasized: false,
+ name,
+ value: null,
+ valueUnit: null,
+ valueLabel: '—',
+ level: 'normal',
+ fill: null,
+ reserve: false,
+ when: this.t('cell.noData'),
+ whenLevel: 'normal',
+ accessibilityLabel: this.t('a11y.noData', { name: `${source.brand} ${name}`.trim() }),
+ };
+ }
+ const remaining = state.remaining;
+ const level = levelOf(remaining);
+ const reserve = remaining <= 0 && (source.creditsUnlimited || (source.credits ?? 0) > 0);
+ const limit = state.limit;
+ // Read together with the percentage above: "90% · resets in 6d 7h", for the window shown.
+ let when = '';
+ if (limit.window.resetsAtMs !== null) {
+ const duration = this.shortDuration(limit.window.resetsAtMs - this.input.nowMs);
+ when = roomy ? this.t('cell.resetsIn', { duration }) : duration;
+ }
+ const whenLevel: MenubarLevel = level;
+ return {
+ ...base,
+ name,
+ value: reserve ? null : String(Math.round(remaining)),
+ valueUnit: reserve ? null : '%',
+ valueLabel: reserve ? this.t('cell.credits') : null,
+ level,
+ fill: clamp(remaining / 100, 0, 1),
+ reserve,
+ when,
+ whenLevel,
+ accessibilityLabel: reserve
+ ? this.t('a11y.reserve', { name: `${source.brand} ${name}` })
+ : this.t('a11y.remaining', { name: source.brand === name ? name : `${source.brand} ${name}`, n: Math.round(remaining) }),
+ };
+ }
+
+ // ── Details ───────────────────────────────────────────────────────────────
+
+ private details(): Record<string, MenubarDetail> {
+ const details: Record<string, MenubarDetail> = {};
+ for (const source of this.ordered) details[source.id] = this.detail(source);
+ return details;
+ }
+
+ private detail(source: MenubarSourceInput): MenubarDetail {
+ if (source.kind === 'balance') return this.balanceDetail(source);
+ if (source.kind === 'payg') return this.paygDetail(source);
+ return this.subscriptionDetail(source);
+ }
+
+ private balanceDetail(source: MenubarBalanceInput): MenubarDetail {
+ const fraction = source.fullAmount && source.fullAmount > 0 ? clamp(source.available / source.fullAmount, 0, 1) : source.available > 0 ? 1 : 0;
+ const burn = source.burnPerDay && source.burnPerDay > 0 ? source.burnPerDay : null;
+ const days = burn ? source.available / burn : null;
+ const quota = source.quota;
+ const resetsAtMs = quota?.resetsAtMs ?? null;
+ const updated = source.observedAtMs ? this.t('fact.updatedAgo', { ago: this.ago(source.observedAtMs) }) : '';
+ const dailyUse: MenubarFact = {
+ label: this.t('fact.dailyUse'),
+ value: burn ? this.t('fact.about', { value: this.balanceMoney(burn, source.currency) }) : this.t('fact.estimating'),
+ sub: burn ? this.t('fact.last7Days') : this.t('fact.estimatingSub'),
+ };
+ const runsOutAtMs = days !== null ? this.input.nowMs + days * DAY_MS : null;
+ const runsOut: MenubarFact = {
+ label: this.t('fact.runsOut'),
+ value: runsOutAtMs !== null ? this.t('fact.aroundDate', { date: this.dateFormat.format(runsOutAtMs) }) : '—',
+ sub: runsOutAtMs !== null ? this.t('fact.atThisPace') : this.t('fact.estimatingSub'),
+ };
+ const facts: MenubarFact[] = [];
+ if (quota) {
+ facts.push(
+ { label: this.t('fact.quotaLeft'), value: this.exactMoney(source.available, source.currency), sub: updated },
+ {
+ label: this.t('fact.quotaTotal'),
+ value: source.fullAmount !== null ? this.exactMoney(source.fullAmount, source.currency) : '—',
+ sub: resetsAtMs !== null
+ ? this.t('fact.timeLeft', { duration: this.duration(resetsAtMs - this.input.nowMs) })
+ : this.t('fact.cindyModels'),
+ },
+ );
+ if (quota.todaySpend !== null) {
+ const suggested = source.fullAmount ? (source.fullAmount / 30) * DAILY_SOFT_LIMIT_FACTOR : null;
+ facts.push({
+ label: this.t('fact.todaySpent'),
+ value: this.exactMoney(quota.todaySpend, source.currency),
+ sub: suggested ? this.t('fact.dailySuggested', { value: this.balanceMoney(suggested, source.currency) }) : '',
+ });
+ }
+ facts.push(dailyUse);
+ // A quota that refills before it would run out has no run-out date worth showing.
+ if (runsOutAtMs !== null && (resetsAtMs === null || runsOutAtMs < resetsAtMs)) facts.push(runsOut);
+ } else {
+ facts.push({ label: this.t('fact.balance'), value: this.exactMoney(source.available, source.currency), sub: updated }, dailyUse, runsOut);
+ const pools = source.pools ?? null;
+ const promo = source.promoExpiry ?? null;
+ const poolFacts: MenubarFact[] = [];
+ if (pools && pools.plan > 0) {
+ poolFacts.push({ label: this.t('fact.poolPlan'), value: this.exactMoney(pools.plan, source.currency), sub: this.t('fact.poolPlanSub') });
+ }
+ if (pools && pools.purchased > 0) {
+ poolFacts.push({ label: this.t('fact.poolPurchased'), value: this.exactMoney(pools.purchased, source.currency), sub: this.t('fact.poolPurchasedSub') });
+ }
+ if ((pools && pools.promotional > 0) || promo) {
+ poolFacts.push({
+ label: this.t('fact.poolPromo'),
+ value: pools ? this.exactMoney(pools.promotional, source.currency) : '—',
+ // Name the amount only when just part of the gifts runs out first.
+ sub: !promo
+ ? this.t('fact.poolPromoSub')
+ : pools && promo.amount < pools.promotional - 0.005
+ ? this.t('fact.promoExpires', {
+ value: this.balanceMoney(promo.amount, source.currency),
+ date: this.dateFormat.format(promo.expiresAtMs),
+ })
+ : this.t('fact.promoExpiresAll', { date: this.dateFormat.format(promo.expiresAtMs) }),
+ });
+ }
+ facts.push(...poolFacts);
+ // The grid has two columns; the general note fills an odd row or stands in for the pools.
+ if (facts.length % 2 === 1) facts.push({ label: this.t('fact.usedFor'), value: this.t('fact.cindyModels'), sub: this.t('fact.chargedPerUse') });
+ }
+ const lasts = days !== null
+ ? this.t('say.balanceLasts', { count: Math.floor(days), n: Math.floor(days) })
+ : this.t('say.balanceEstimating');
+ return {
+ id: source.id,
+ logoSvg: source.logoSvg,
+ title: this.t(quota ? 'balance.quotaName' : 'balance.name'),
+ plan: '',
+ rings: [{ fraction, color: 'ink' }],
+ bigValue: this.balanceMoney(source.available, source.currency),
+ bigUnit: null,
+ bigColor: source.available > 0 ? null : 'error',
+ bigCompact: true,
+ bigCaption: this.t(quota ? 'detail.quotaCaption' : 'detail.balanceCaption'),
+ legend: [],
+ sayPrimary: !quota
+ ? this.t('say.balance')
+ : resetsAtMs !== null
+ ? this.t('say.quotaResets', { at: this.at(resetsAtMs) })
+ : this.t('say.quota'),
+ saySecondary: lasts,
+ facts,
+ // An organization quota is not topped up from here; its connection lives in Settings.
+ actionLabel: this.t(quota ? 'action.manage' : 'action.topUp'),
+ action: { kind: quota ? 'open-settings' : 'open-billing' },
+ };
+ }
+
+ private paygDetail(source: MenubarPaygInput): MenubarDetail {
+ const api = source.billing === 'api';
+ const hidden = this.isHidden(source);
+ return {
+ id: source.id,
+ logoSvg: source.logoSvg,
+ title: source.name,
+ plan: api ? this.t('detail.apiKey') : this.t('detail.subscription'),
+ rings: [{ fraction: 0, color: 'ink3' }],
+ bigValue: '—',
+ bigUnit: null,
+ bigColor: null,
+ bigCompact: false,
+ bigCaption: this.t(api ? 'detail.noBalance' : 'detail.unknownRemaining'),
+ legend: [],
+ sayPrimary: this.t(api ? 'say.payg' : 'say.plan', { name: source.name }),
+ saySecondary: this.t(api ? 'say.paygSub' : 'say.planSub'),
+ facts: [
+ { label: this.t('fact.billing'), value: this.t(api ? 'fact.perUse' : 'fact.subscription'), sub: this.t('fact.connected') },
+ { label: this.t('fact.balance'), value: '—', sub: this.t(api ? 'fact.notProvided' : 'fact.notReadable') },
+ { label: this.t('fact.inMenu'), value: this.t(hidden ? 'fact.hidden' : 'fact.shown'), sub: this.t('fact.editHint') },
+ { label: this.t('fact.usage'), value: this.t('fact.counted'), sub: this.t('fact.countedSub') },
+ ],
+ actionLabel: this.t('action.manage'),
+ action: { kind: 'open-settings' },
+ };
+ }
+
+ private subscriptionDetail(source: MenubarSubscriptionInput): MenubarDetail {
+ const state = this.state(source);
+ const limit = state.limit;
+ const handle = this.handle(source);
+ const resets = source.resetCredits?.count ?? 0;
+ // An account on another computer runs there; this computer cannot start a task on it directly.
+ let actionLabel = source.device
+ ? this.t('action.openApp')
+ : this.t('action.newTask', { name: handle ?? source.brand });
+ let action: MenubarDetailAction = source.device
+ ? { kind: 'open-app' }
+ : { kind: 'new-task', providerId: source.providerId };
+ if (!limit || state.remaining === null) {
+ return {
+ id: source.id,
+ logoSvg: source.logoSvg,
+ title: source.brand,
+ plan: source.plan ?? '',
+ rings: [{ fraction: 0, color: 'ink3' }],
+ bigValue: '—',
+ bigUnit: null,
+ bigColor: null,
+ bigCompact: false,
+ bigCaption: this.t('detail.noData'),
+ legend: [],
+ sayPrimary: this.t('say.noData'),
+ saySecondary: this.t('say.noDataSub'),
+ facts: this.accountFacts(source),
+ actionLabel,
+ action,
+ };
+ }
+ const remaining = state.remaining;
+ const level = levelOf(remaining);
+ const colors = FAMILY_COLORS[source.family];
+ const multi = state.windows.length > 1;
+ const ringColor = levelColor(level) ?? colors[0]!;
+ const rings = multi
+ ? state.windows.map((window, index) => ({
+ fraction: clamp(window.remaining / 100, 0, 1),
+ color: colors[index % colors.length]!,
+ }))
+ : [{ fraction: clamp(remaining / 100, 0, 1), color: ringColor }];
+ const limits = state.windows.filter((window) => window.window.kind !== 'scoped');
+ const refreshList = limits
+ .filter((window) => window.window.resetsAtMs !== null)
+ .map((window) => this.t('say.windowRefresh', { window: this.windowLabel(window.window), at: this.at(window.window.resetsAtMs!) }))
+ .join(this.t('headline.joiner'));
+ const resetAt = limit.window.resetsAtMs !== null ? this.at(limit.window.resetsAtMs) : null;
+ const credits = source.credits ?? 0;
+ const creditsLabel = source.creditsUnlimited ? this.t('fact.unlimited') : this.grouped(credits);
+ let sayPrimary: string;
+ let saySecondary: string | null = null;
+ if (remaining <= 0) {
+ sayPrimary = this.t('say.usedUp', { window: this.windowLabel(limit.window) });
+ if (source.creditsUnlimited || credits > 0) {
+ saySecondary = resetAt
+ ? this.t('say.usedUpWithCredits', { at: resetAt, credits: creditsLabel })
+ : this.t('say.creditsOnly', { credits: creditsLabel });
+ } else if (resets > 0 && !source.device) {
+ saySecondary = this.t('say.usedUpWithResets', { count: resets, n: resets });
+ // Resets are spent from Settings, next to the account.
+ actionLabel = this.t('action.useReset');
+ action = { kind: 'open-settings' };
+ } else if (resetAt) {
+ saySecondary = this.t('say.resetsAt', { at: resetAt });
+ }
+ } else if (limit.etaMs !== null) {
+ sayPrimary = this.t('say.emptyIn', { duration: this.duration(limit.etaMs) });
+ saySecondary = this.t('say.beforeReset', { duration: this.duration(limit.leftMs - limit.etaMs) });
+ } else if (remaining >= 99.5) {
+ sayPrimary = this.t('say.full');
+ saySecondary = refreshList ? this.t('headline.sentence', { text: refreshList }) : null;
+ } else if (limit.pace !== null && limit.pace < -3) {
+ sayPrimary = this.t('say.relaxed');
+ saySecondary = refreshList ? this.t('headline.sentence', { text: refreshList }) : null;
+ } else {
+ sayPrimary = this.t('say.onPace');
+ saySecondary = refreshList ? this.t('headline.sentence', { text: refreshList }) : null;
+ }
+ const facts: MenubarFact[] = [];
+ for (const window of limits) {
+ if (window.window.resetsAtMs === null) continue;
+ facts.push({
+ label: window.remaining <= 0 ? this.t('fact.resetsFull') : this.t('fact.windowResets', { window: this.windowLabel(window.window) }),
+ value: this.at(window.window.resetsAtMs),
+ sub: this.t('fact.timeLeft', { duration: this.duration(window.leftMs) }),
+ });
+ }
+ for (const window of state.windows.filter((entry) => entry.window.kind === 'scoped')) {
+ facts.push({
+ label: this.windowLabel(window.window),
+ value: this.t('fact.remainingPercent', { n: Math.round(window.remaining) }),
+ sub: this.t('fact.perModel'),
+ });
+ }
+ if (limit.pace !== null) {
+ facts.push({
+ label: this.t('fact.pace'),
+ value:
+ Math.abs(limit.pace) < 3
+ ? this.t('fact.paceNormal')
+ : limit.pace > 0
+ ? this.t('fact.paceAhead', { n: Math.round(limit.pace) })
+ : this.t('fact.paceReserve', { n: Math.round(-limit.pace) }),
+ sub: this.t('fact.paceSub', { n: Math.round(100 - limit.expected) }),
+ });
+ } else if (remaining <= 0) {
+ facts.push({ label: this.t('fact.pace'), value: this.t('fact.paceUsedUp'), sub: this.t('fact.paceWaiting') });
+ }
+ if (source.family === 'codex') {
+ facts.push({
+ label: this.t('fact.extraCredits'),
+ value: source.creditsUnlimited ? this.t('fact.unlimited') : this.grouped(credits),
+ sub: source.creditsUnlimited || credits > 0 ? this.t('fact.creditsUsedAfter') : this.t('fact.noCredits'),
+ });
+ }
+ if (resets > 0) {
+ const expiry = source.resetCredits?.earliestExpiryMs ?? null;
+ facts.push({
+ label: this.t('fact.resetCredits'),
+ value: this.t('fact.resetCount', { count: resets, n: resets }),
+ sub: expiry !== null
+ ? this.t('fact.resetExpires', { date: this.dateFormat.format(expiry) })
+ : this.t('fact.resetAtLimit'),
+ });
+ }
+ if (source.prepaidUsd !== null) {
+ facts.push({ label: this.t('fact.prepaid'), value: `$${source.prepaidUsd.toFixed(2)}`, sub: this.t('fact.xaiAccount') });
+ }
+ facts.push(...this.accountFacts(source));
+ return {
+ id: source.id,
+ logoSvg: source.logoSvg,
+ title: source.brand,
+ plan: source.plan ?? '',
+ rings,
+ bigValue: String(Math.round(remaining)),
+ bigUnit: '%',
+ bigColor: levelColor(level),
+ bigCompact: multi,
+ bigCaption: this.t('detail.windowLeft', { window: this.windowLabel(limit.window) }),
+ legend: multi
+ ? state.windows.map((window, index) => ({
+ label: `${this.windowLabel(window.window)} ${Math.round(window.remaining)}%`,
+ color: colors[index % colors.length]!,
+ }))
+ : [],
+ sayPrimary,
+ saySecondary,
+ facts,
+ actionLabel,
+ action,
+ };
+ }
+
+ private accountFacts(source: MenubarSubscriptionInput): MenubarFact[] {
+ const updated = source.updatedAtMs ? this.t('fact.updatedAgo', { ago: this.ago(source.updatedAtMs) }) : '';
+ const facts: MenubarFact[] = [];
+ if (source.device) facts.push({ label: this.t('fact.device'), value: source.device.name, sub: this.t('fact.deviceSub') });
+ if (source.account) facts.push({ label: this.t('fact.account'), value: this.email(source), sub: updated });
+ else if (source.device) facts[0] = { ...facts[0]!, sub: updated || this.t('fact.deviceSub') };
+ return facts;
+ }
+
+ // ── Tasks ─────────────────────────────────────────────────────────────────
+
+ private tasks(): { summary: string; tasks: MenubarTask[] } {
+ const sorted = [...this.input.tasks].sort((a, b) => b.valueToday - a.valueToday || b.tokensToday - a.tokensToday);
+ const running = sorted.filter((task) => task.running).length;
+ const count = sorted.length;
+ const base = this.t('tasks.today', { count, n: count });
+ const summary = running ? this.t('tasks.withRunning', { base, count: running, n: running }) : base;
+ return {
+ summary: count ? summary : '',
+ tasks: sorted.map((task) => {
+ const metaParts = [task.model, this.tokens(task.tokensToday)];
+ if (task.contextPercent !== null) metaParts.push(this.t('tasks.context', { n: Math.round(task.contextPercent) }));
+ return {
+ sessionId: task.sessionId,
+ title: this.input.settings.privacy ? this.t('tasks.private', { harness: this.harnessName(task.harness) }) : task.title,
+ harness: task.harness,
+ logoSvg: this.input.harnessLogos[task.harness],
+ value: task.valueToday,
+ tokens: task.tokensToday,
+ running: task.running,
+ startedAtMs: task.running ? task.startedAtMs ?? task.lastActiveAtMs : null,
+ idleStatus: this.ago(task.lastActiveAtMs),
+ meta: metaParts.filter(Boolean).join(' · '),
+ };
+ }),
+ };
+ }
+
+ private harnessName(harness: MenubarHarness): string {
+ return this.t(`harness.${harness}`);
+ }
+
+ // ── Usage ─────────────────────────────────────────────────────────────────
+
+ private usage(): MenubarUsage {
+ const scopes = {} as Record<MenubarUsageScope, MenubarUsageScopeData>;
+ for (const scope of ['local', 'all'] as const) {
+ const data = this.input.usage.scopes[scope];
+ scopes[scope] = { daily: data.daily, models: data.models, note: this.usageNote(scope, data.devices) };
+ }
+ return { days: this.input.usage.days, scopes };
+ }
+
+ private usageNote(scope: MenubarUsageScope, devices: MenubarUsageDeviceInput[]): string {
+ const lines = [this.t('usage.estimateNote')];
+ if (scope === 'all' && devices.length > 1) {
+ const list = devices
+ .map((device) =>
+ device.isSelf
+ ? this.t('usage.deviceSelf', { name: device.name })
+ : device.syncedAtMs
+ ? this.t('usage.deviceSynced', { name: device.name, date: this.dateFormat.format(device.syncedAtMs) })
+ : this.t('usage.deviceNotSynced', { name: device.name }),
+ )
+ .join(this.t('usage.deviceJoiner'));
+ lines.push(this.t('usage.allDevices', { list }));
+ }
+ return lines.join('\n');
+ }
+
+ // ── Manage & status ───────────────────────────────────────────────────────
+
+ private manage(): MenubarManageRow[] {
+ return this.ordered.map((source) => ({
+ id: source.id,
+ logoSvg: source.logoSvg,
+ title: this.sourceTitle(source),
+ subtitle: this.manageSubtitle(source),
+ value: this.manageValue(source),
+ hidden: this.isHidden(source),
+ }));
+ }
+
+ private manageSubtitle(source: MenubarSourceInput): string {
+ if (source.kind === 'balance') return this.t(source.quota ? 'manage.quota' : 'manage.balance');
+ if (source.kind === 'payg') return this.t(source.billing === 'api' ? 'manage.payg' : 'manage.plan');
+ const plan = source.plan ? ` · ${source.plan}` : '';
+ const windows = source.windows
+ .filter((window) => window.kind !== 'scoped')
+ .map((window) => this.windowLabel(window))
+ .join(' + ');
+ const subtitle = source.family === 'codex'
+ ? `Codex${plan}`
+ : this.t('manage.subscription', { plan: source.plan ?? source.brand, windows: windows || '—' });
+ return source.device ? this.t('manage.onDevice', { name: source.device.name, subtitle }) : subtitle;
+ }
+
+ private manageValue(source: MenubarSourceInput): string {
+ if (source.kind === 'balance') return this.balanceMoney(source.available, source.currency);
+ if (source.kind === 'payg') return '—';
+ const remaining = this.remaining(source);
+ if (remaining === null) return '—';
+ if (remaining <= 0 && (source.creditsUnlimited || (source.credits ?? 0) > 0)) return this.t('cell.credits');
+ return `${Math.round(remaining)}%`;
+ }
+
+ private statusTexts(): Record<MenubarStatusTextMode, string | null> {
+ const tightest = this.tightest();
+ const hasSubscriptions = this.visibleSubscriptions().some((source) => this.remaining(source) !== null);
+ const scope = this.input.usage.scopes[this.input.settings.scope];
+ const today = scope.daily[scope.daily.length - 1];
+ const running = this.input.tasks.filter((task) => task.running);
+ return {
+ icon: null,
+ lowest: tightest ? `${Math.round(this.remaining(tightest) ?? 0)}%` : hasSubscriptions ? '0%' : null,
+ today: today ? this.money(today.money.reduce((sum, value) => sum + value, 0)) : null,
+ task: running.length ? this.money(running.reduce((sum, task) => sum + task.valueToday, 0)) : null,
+ };
+ }
+
+ build(): MenubarView {
+ const headline = this.headline();
+ const tasks = this.tasks();
+ return {
+ locale: this.input.locale,
+ moneySymbol: this.input.moneySymbol,
+ strings: this.input.uiStrings,
+ statusTextByMode: this.input.gate ? { icon: null, lowest: null, today: null, task: null } : this.statusTexts(),
+ updatedAtMs: this.input.updatedAtMs,
+ headlinePrimary: headline.primary,
+ headlineSecondary: headline.secondary,
+ sources: this.cells(),
+ details: this.details(),
+ taskSummary: tasks.summary,
+ tasks: tasks.tasks,
+ usage: this.usage(),
+ manage: this.manage(),
+ settings: this.input.settings,
+ ...(this.input.gate ? { gate: this.input.gate } : {}),
+ };
+ }
+
+ /** Every visible source that can still be used is near empty (or already used up). */
+ lowOnEverything(): boolean {
+ const counted = this.visible.filter((source) => source.kind !== 'payg');
+ if (counted.length === 0) return false;
+ let known = 0;
+ for (const source of counted) {
+ if (source.kind === 'balance') {
+ known += 1;
+ const days = source.burnPerDay && source.burnPerDay > 0 ? source.available / source.burnPerDay : null;
+ if (source.available > 0 && (days === null || days > 1)) return false;
+ continue;
+ }
+ if (source.kind !== 'subscription') continue;
+ const remaining = this.remaining(source);
+ if (remaining === null) continue;
+ known += 1;
+ if (remaining > WARN_REMAINING) return false;
+ }
+ return known > 0;
+ }
+}
+
+export function buildMenubarView(input: MenubarBuildInput): MenubarView {
+ return new Builder(input).build();
+}
+
+/** Whether to raise the "running low everywhere" notification for this snapshot. */
+export function isLowOnEverything(input: MenubarBuildInput): boolean {
+ return new Builder(input).lowOnEverything();
+}
+
+/**
+ * Merges per-harness model rows into the menu's top models list: the leaders by money and by
+ * tokens, so the panel can rank either metric without losing a model that leads only one.
+ */
+export function topModels(rows: readonly MenubarModelUsage[], limit = 8): MenubarModelUsage[] {
+ const merged = new Map<string, MenubarModelUsage>();
+ for (const row of rows) {
+ const key = `${row.harness}:${row.name}`;
+ const existing = merged.get(key);
+ if (existing) {
+ existing.money += row.money;
+ existing.tokens += row.tokens;
+ } else {
+ merged.set(key, { ...row });
+ }
+ }
+ const used = [...merged.values()].filter((row) => row.money > 0 || row.tokens > 0);
+ const byMoney = [...used].sort((a, b) => b.money - a.money || b.tokens - a.tokens).slice(0, limit);
+ const byTokens = [...used].sort((a, b) => b.tokens - a.tokens || b.money - a.money).slice(0, limit);
+ return [...byMoney, ...byTokens.filter((row) => !byMoney.includes(row))];
+}
+
+export { HARNESS_ORDER as MENUBAR_HARNESS_ORDER };
diff --git a/apps/desktop/src/main/menubar/strings.ts b/apps/desktop/src/main/menubar/strings.ts
new file mode 100644
index 0000000000..e03f6ceec7
--- /dev/null
+++ b/apps/desktop/src/main/menubar/strings.ts
@@ -0,0 +1,70 @@
+import type { SupportedLocale } from '../../shared/locale.js';
+import type { MenubarStrings } from '../../shared/menubarQuota.js';
+import type { MenubarTranslate } from './snapshot.js';
+
+/** Raw template lookup with locale fallback; null when no locale has the key. */
+export type MenubarRawLookup = (key: string) => string | null;
+
+const PLURAL_SUFFIX = /_(zero|one|two|few|many|other)$/;
+
+/** Fills `{{name}}` placeholders; unknown placeholders stay visible so gaps are easy to spot. */
+export function fillTemplate(template: string, vars?: Record<string, string | number>): string {
+ if (!vars) return template;
+ return template.replace(/\{\{(\w+)\}\}/g, (match, name: string) =>
+ Object.prototype.hasOwnProperty.call(vars, name) ? String(vars[name]) : match,
+ );
+}
+
+/**
+ * Translator over the `menubar.*` namespace. A numeric `count` selects the CLDR plural
+ * variant (`_one`, `_other`, ...) the locale provides, falling back to `_other` and then
+ * the bare key.
+ */
+export function createMenubarTranslate(locale: SupportedLocale, raw: MenubarRawLookup): MenubarTranslate {
+ const plurals = new Intl.PluralRules(locale);
+ return (key, vars) => {
+ const full = `menubar.${key}`;
+ let template: string | null = null;
+ const count = vars?.count;
+ if (typeof count === 'number') {
+ template = raw(`${full}_${plurals.select(count)}`) ?? raw(`${full}_other`);
+ }
+ template ??= raw(full) ?? raw(`${full}_other`) ?? full;
+ return fillTemplate(template, vars);
+ };
+}
+
+/**
+ * Templates the helper fills itself. Plural families are sent as `key_one` / `key_other`
+ * so Swift can pick by count without plural rules of its own. Locales without a "one"
+ * category (Chinese, Japanese, Korean) send `other` for both, so a fallback-locale `_one`
+ * never leaks in.
+ */
+export function buildMenubarUiStrings(
+ keys: readonly string[],
+ raw: MenubarRawLookup,
+ locale: SupportedLocale,
+): MenubarStrings {
+ const hasOne = new Intl.PluralRules(locale).resolvedOptions().pluralCategories.includes('one');
+ const strings: MenubarStrings = {};
+ const families = new Set<string>();
+ for (const key of keys) {
+ const match = key.match(PLURAL_SUFFIX);
+ if (match) {
+ families.add(key.slice(0, -match[0].length));
+ continue;
+ }
+ const value = raw(`menubar.ui.${key}`);
+ if (value !== null) strings[key] = value;
+ }
+ for (const family of families) {
+ const other = raw(`menubar.ui.${family}_other`);
+ const one = (hasOne ? raw(`menubar.ui.${family}_one`) : null) ?? other;
+ if (other !== null) {
+ strings[`${family}_other`] = other;
+ strings[family] = other;
+ }
+ if (one !== null) strings[`${family}_one`] = one;
+ }
+ return strings;
+}
diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.ts
index 758b1f978e..d36252bfab 100644
--- a/apps/desktop/src/main/usageBroadcaster.ts
+++ b/apps/desktop/src/main/usageBroadcaster.ts
@@ -1169,7 +1169,29 @@ export async function readXaiSubscriptionUsageSnapshot(): Promise<XaiSubscriptio
// ── 内部广播 ─────────────────────────────────────────────────────────────────
+/** What changed, for in-process observers such as the macOS menu bar. */
+export type UsageChangeKind = 'spend' | 'tokens' | 'codex' | 'claude' | 'xai' | 'subscription';
+
+const usageChangeObservers = new Set<(kind: UsageChangeKind) => void>();
+
+/** Observes every usage broadcast in main; returns an unsubscribe function. */
+export function observeUsageChanges(listener: (kind: UsageChangeKind) => void): () => void {
+ usageChangeObservers.add(listener);
+ return () => usageChangeObservers.delete(listener);
+}
+
+function notifyUsageObservers(kind: UsageChangeKind): void {
+ for (const listener of usageChangeObservers) {
+ try {
+ listener(kind);
+ } catch (err) {
+ log.warn('usage change observer failed:', err instanceof Error ? err.message : String(err));
+ }
+ }
+}
+
function broadcastTodaySpend(payload: TodaySpendPayload): void {
+ notifyUsageObservers('spend');
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
win.webContents.send(USAGE_TODAY_SPEND_CHANGED, payload);
@@ -1178,6 +1200,7 @@ function broadcastTodaySpend(payload: TodaySpendPayload): void {
}
function broadcastCodexTokens(payload: CodexTokenSnapshot): void {
+ notifyUsageObservers('tokens');
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
win.webContents.send(USAGE_TODAY_TOKENS_CHANGED, payload);
@@ -1186,6 +1209,7 @@ function broadcastCodexTokens(payload: CodexTokenSnapshot): void {
}
function broadcastCodexAccountUsage(payload: RateLimitSnapshot | null, providerId = 'openai'): void {
+ notifyUsageObservers('codex');
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
if (providerId === 'openai') win.webContents.send(USAGE_CODEX_ACCOUNT_CHANGED, payload);
@@ -1199,6 +1223,7 @@ function broadcastCodexAccountUsage(payload: RateLimitSnapshot | null, providerI
}
function broadcastClaudeSubscriptionUsage(payload: ClaudeSubscriptionUsageSnapshot | null): void {
+ notifyUsageObservers('claude');
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) {
win.webContents.send(USAGE_CLAUDE_SUBSCRIPTION_CHANGED, payload);
@@ -1210,6 +1235,7 @@ function broadcastClaudeSubscriptionUsage(payload: ClaudeSubscriptionUsageSnapsh
}
export function broadcastSubscriptionAccountUsage(providerId: string, snapshot: ClaudeSubscriptionUsageSnapshot | XaiSubscriptionUsageSnapshot | null): void {
+ notifyUsageObservers('subscription');
for (const win of BrowserWindow.getAllWindows()) {
if (!isTrustedAppRendererWindow(win)) continue;
win.webContents.send('usage:subscription-provider-account-changed', { providerId, snapshot });
@@ -1218,6 +1244,7 @@ export function broadcastSubscriptionAccountUsage(providerId: string, snapshot:
}
function broadcastXaiSubscriptionUsage(payload: XaiSubscriptionUsageSnapshot | null): void {
+ notifyUsageObservers('xai');
for (const win of BrowserWindow.getAllWindows()) {
if (!isTrustedAppRendererWindow(win)) continue;
win.webContents.send(USAGE_XAI_SUBSCRIPTION_CHANGED, payload);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 5be29721f4..f8616a0ba6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -84,6 +84,11 @@ import {
type LinuxCloseBehavior,
type WindowsCloseBehavior,
} from '../shared/windowBehavior';
+import {
+ MENUBAR_GET_STATE_CHANNEL,
+ MENUBAR_SET_ENABLED_CHANNEL,
+ type MenubarState,
+} from '../shared/menubarQuota';
import {
CODEX_MICRO_GUARD_GET_STATE_CHANNEL,
CODEX_MICRO_GUARD_RECOVER_CHANNEL,
@@ -1777,6 +1782,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
getLoginItem: (): Promise<LoginItemState> => ipcRenderer.invoke(LOGIN_ITEM_GET_CHANNEL),
setLoginItem: (enabled: boolean): Promise<LoginItemState> =>
ipcRenderer.invoke(LOGIN_ITEM_SET_CHANNEL, enabled),
+ // macOS menu bar quota item; `available` is false on other platforms and before macOS 14.
+ getMenubarState: (): Promise<MenubarState> => ipcRenderer.invoke(MENUBAR_GET_STATE_CHANNEL),
+ setMenubarEnabled: (enabled: boolean): Promise<MenubarState> =>
+ ipcRenderer.invoke(MENUBAR_SET_ENABLED_CHANNEL, enabled),
// 通知 main 落盘"首次点击是否吞掉"。仅落盘,不改变已创建窗口的行为——macOS
// acceptFirstMouse 是 BrowserWindow 构造参数,需要下次启动才读到新值。Windows
// 上此调用只是保持 userData 落盘和 renderer localStorage 一致,Windows JS
diff --git a/apps/desktop/src/renderer/components/icons/AnthropicMark.tsx b/apps/desktop/src/renderer/components/icons/AnthropicMark.tsx
index 9f8c44388e..a88c5b94cb 100644
--- a/apps/desktop/src/renderer/components/icons/AnthropicMark.tsx
+++ b/apps/desktop/src/renderer/components/icons/AnthropicMark.tsx
@@ -4,6 +4,8 @@
* (2026-07-21 产品语义纠偏)。
*/
+import { ANTHROPIC_MARK_PATH } from '../../../shared/brandMarkPaths';
+
interface AnthropicMarkProps {
size?: number;
className?: string;
@@ -20,7 +22,7 @@ export function AnthropicMark({ size = 14, className }: AnthropicMarkProps) {
aria-hidden
>
<path
- d="M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.461H0L6.57 3.52zm4.132 9.876L8.453 7.247 6.205 13.396z"
+ d={ANTHROPIC_MARK_PATH}
fill="currentColor"
/>
</svg>
diff --git a/apps/desktop/src/renderer/components/icons/ClaudeMark.tsx b/apps/desktop/src/renderer/components/icons/ClaudeMark.tsx
index 5bda3df3a6..b613c1b1b2 100644
--- a/apps/desktop/src/renderer/components/icons/ClaudeMark.tsx
+++ b/apps/desktop/src/renderer/components/icons/ClaudeMark.tsx
@@ -10,6 +10,8 @@
* wordmark 辨识度高);单色为默认,彩色按场景显式启用。
*/
+import { CLAUDE_CODE_MARK_PATH } from '../../../shared/brandMarkPaths';
+
interface ClaudeMarkProps {
size?: number;
className?: string;
@@ -30,7 +32,7 @@ export function ClaudeMark({ size = 14, className, variant = 'mono' }: ClaudeMar
fill={variant === 'brand' ? '#d97757' : 'currentColor'}
fillRule="evenodd"
clipRule="evenodd"
- d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0v-3.1h3V5h17.998zM6 10.949h1.488V8.102H6zm10.51 0H18V8.102h-1.49z"
+ d={CLAUDE_CODE_MARK_PATH}
/>
</svg>
);
diff --git a/apps/desktop/src/renderer/components/icons/CodexMark.tsx b/apps/desktop/src/renderer/components/icons/CodexMark.tsx
index 98ff290f13..c0928a68a1 100644
--- a/apps/desktop/src/renderer/components/icons/CodexMark.tsx
+++ b/apps/desktop/src/renderer/components/icons/CodexMark.tsx
@@ -17,13 +17,7 @@
import { useId } from 'react';
-/** 花形轮廓(闭环子路径)。mono 描边 / brand 与 `>_` 合并填渐变。 */
-const FLOWER_OUTLINE =
- 'M9.064 3.344a4.6 4.6 0 0 1 2.285-.312q1.5.173 2.673 1.275.016.015.037.021a.1.1 0 0 0 .043 0 4.55 4.55 0 0 1 3.046.275l.047.022.116.057a4.58 4.58 0 0 1 2.188 2.399q.313.765.315 1.595a4.2 4.2 0 0 1-.134 1.223.12.12 0 0 0 .03.115q.89.91 1.183 2.17.433 2.138-.887 3.854l-.136.166a4.55 4.55 0 0 1-2.201 1.388.12.12 0 0 0-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838q-1.78-.009-3.157-1.302a.11.11 0 0 0-.105-.024c-.388.125-.78.143-1.204.138a4.44 4.44 0 0 1-1.945-.466 4.54 4.54 0 0 1-1.61-1.335c-.152-.202-.303-.392-.414-.617a6 6 0 0 1-.37-.961 4.6 4.6 0 0 1-.014-2.298.1.1 0 0 0 .006-.056.1.1 0 0 0-.027-.048 4.5 4.5 0 0 1-1.034-1.651 3.9 3.9 0 0 1-.251-1.192 5.2 5.2 0 0 1 .141-1.6Q3.659 7.92 5.086 6.97q.318-.212.601-.33a6 6 0 0 1 .646-.227.1.1 0 0 0 .065-.066 4.5 4.5 0 0 1 .829-1.615 4.54 4.54 0 0 1 1.837-1.388';
-
-/** `>_` 提示符(dash 已换算绝对坐标;chevron 原本就是绝对 M)。 */
-const PROMPT_GLYPHS =
- 'M12.546 13.909a.637.637 0 0 0 0 1.272h3.636a.637.637 0 1 0 0-1.272zM8.462 9.23a.637.637 0 0 0-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 1 0 1.095.649l1.454-2.455a.64.64 0 0 0 .005-.64z';
+import { CODEX_FLOWER_OUTLINE, CODEX_PROMPT_GLYPHS } from '../../../shared/brandMarkPaths';
interface CodexMarkProps {
size?: number;
@@ -46,7 +40,7 @@ export function CodexMark({ size = 14, className, variant = 'mono' }: CodexMarkP
{variant === 'brand' ? (
<>
{/* 官方原始形态:花形剪影 + `>_` 镂空,同一 path 填渐变(nonzero 反向子路径成孔)。 */}
- <path fill={`url(#${gradientId})`} d={`${FLOWER_OUTLINE}m3.482 10.565a.637.637 0 0 0 0 1.272h3.636a.637.637 0 1 0 0-1.272zM8.462 9.23a.637.637 0 0 0-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 1 0 1.095.649l1.454-2.455a.64.64 0 0 0 .005-.64z`} />
+ <path fill={`url(#${gradientId})`} d={`${CODEX_FLOWER_OUTLINE}m3.482 10.565a.637.637 0 0 0 0 1.272h3.636a.637.637 0 1 0 0-1.272zM8.462 9.23a.637.637 0 0 0-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 1 0 1.095.649l1.454-2.455a.64.64 0 0 0 .005-.64z`} />
<defs>
<linearGradient
id={gradientId}
@@ -69,14 +63,14 @@ export function CodexMark({ size = 14, className, variant = 'mono' }: CodexMarkP
stroke="currentColor"
strokeWidth={monoStrokeWidth}
strokeLinejoin="round"
- d={`${FLOWER_OUTLINE}z`}
+ d={`${CODEX_FLOWER_OUTLINE}z`}
/>
<path
fill="currentColor"
stroke="currentColor"
strokeWidth="0.5"
strokeLinejoin="round"
- d={PROMPT_GLYPHS}
+ d={CODEX_PROMPT_GLYPHS}
/>
</g>
)}
diff --git a/apps/desktop/src/renderer/components/icons/OpenAIMark.tsx b/apps/desktop/src/renderer/components/icons/OpenAIMark.tsx
index 22dd309185..662180c788 100644
--- a/apps/desktop/src/renderer/components/icons/OpenAIMark.tsx
+++ b/apps/desktop/src/renderer/components/icons/OpenAIMark.tsx
@@ -4,6 +4,8 @@
* (2026-07-21 产品语义纠偏)。
*/
+import { OPENAI_MARK_PATH } from '../../../shared/brandMarkPaths';
+
interface OpenAIMarkProps {
size?: number;
className?: string;
@@ -20,7 +22,7 @@ export function OpenAIMark({ size = 14, className }: OpenAIMarkProps) {
aria-hidden
>
<path
- d="M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.495 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.787a4.49 4.49 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.674zm2.01-3.026l-.142-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.607 1.5-2.602-1.5z"
+ d={OPENAI_MARK_PATH}
fill="currentColor"
/>
</svg>
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 89c919292c..a313279f1e 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -641,7 +641,7 @@ export function MainLayout() {
| { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'chat-invite'; token: string }
| { type: 'provider-share-join'; link: string }
- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },
+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' },
) => {
if (payload.type === 'chat-invite') {
requestChatInvite(payload.token);
@@ -689,7 +689,8 @@ export function MainLayout() {
payload.tab === 'providers' && payload.connect
? `&connect=${encodeURIComponent(payload.connect)}`
: '';
- navigate(`/settings?tab=${payload.tab}${connect}`);
+ const intent = payload.tab === 'billing' && payload.intent === 'topup' ? '&intent=topup' : '';
+ navigate(`/settings?tab=${payload.tab}${connect}${intent}`);
}
},
[navigate, navigateToSession, openShareImport],
diff --git a/apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts b/apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts
index f8fe9a3d0e..576000a401 100644
--- a/apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts
+++ b/apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useState } from 'react';
import type { ProviderView } from '@cindy/model-providers';
+import { providerWeeklyQuotaSource } from '../../../shared/providerQuotaSource';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import { matchCodexBucketForModel } from '@cindy/maker-shared/codex-usage-buckets';
import { useCodexRateLimits } from '@/hooks/useCodexRateLimits';
@@ -130,27 +131,7 @@ export function codexWeeklyQuota(
return null;
}
-export function providerWeeklyQuotaSource(
- provider: ProviderView,
-): 'codex' | 'claude' | 'xai' | null {
- if (
- !provider.connected ||
- provider.suspended ||
- provider.openAiAccount?.reconnectRequired ||
- provider.auth.method !== 'oauth' ||
- (provider.access && provider.access.kind !== 'subscription')
- )
- return null;
- if (provider.id === 'openai' || provider.auth.native === 'codex') return 'codex';
- if (provider.auth.native === 'claude') return 'claude';
- if (provider.auth.native === 'xai') return 'xai';
- // These APIs currently describe only the built-in native account, not any
- // arbitrary same-brand API/OAuth connection a user may add.
- if (provider.source !== 'builtin') return null;
- if (provider.id === 'anthropic') return 'claude';
- if (provider.id === 'xai') return 'xai';
- return null;
-}
+export { providerWeeklyQuotaSource };
export interface ProviderUsageSnapshots {
source: 'codex' | 'claude' | 'xai' | null;
diff --git a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts
index 161d78f38c..1bafbebd56 100644
--- a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts
+++ b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts
@@ -7,6 +7,7 @@ export default {
entries: [
{ id: 'settings.devices.keepAwake', fallbackTargetId: 'settings-window-behavior', tab: 'general', targetId: 'settings-search-settings-devices-keepAwake', titleKey: 'settings.devices.keepAwake', sectionKey: 'settings.sections.windowBehavior', descriptionKey: 'settings.devices.keepAwakeHint' },
{ id: 'settings.windowBehavior.loginItem.label', fallbackTargetId: 'settings-window-behavior', tab: 'general', targetId: 'settings-search-login-item', titleKey: 'settings.windowBehavior.loginItem.label', sectionKey: 'settings.sections.windowBehavior', descriptionKey: 'settings.windowBehavior.loginItem.hint', isVisible: ({ platform }) => platform === 'darwin' || platform === 'win32' },
+ { id: 'settings.windowBehavior.menubar.label', fallbackTargetId: 'settings-window-behavior', tab: 'general', targetId: 'settings-search-menubar', titleKey: 'settings.windowBehavior.menubar.label', sectionKey: 'settings.sections.windowBehavior', descriptionKey: 'settings.windowBehavior.menubar.hint', isVisible: ({ platform }) => platform === 'darwin' },
{ id: 'settings.windowBehavior.closeBehavior.label', fallbackTargetId: 'settings-window-behavior', tab: 'general', targetId: 'settings-search-settings-windowBehavior-closeBehavior-label', titleKey: 'settings.windowBehavior.closeBehavior.label', sectionKey: 'settings.sections.windowBehavior', descriptionKey: 'settings.windowBehavior.closeBehavior.hint', isVisible: ({ platform }) => platform === 'linux' || platform === 'win32' },
{ id: 'settings.windowBehavior.swallowActivationClickLabel', fallbackTargetId: 'settings-window-behavior', tab: 'general', targetId: 'settings-search-activation-click', titleKey: 'settings.windowBehavior.swallowActivationClickLabel', sectionKey: 'settings.sections.windowBehavior', descriptionKey: 'settings.windowBehavior.swallowActivationClickHint', isVisible: ({ platform }) => platform === 'darwin' || platform === 'win32' },
diff --git a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
index 7e4a523b28..a6b4d372db 100644
--- a/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx
@@ -3,6 +3,7 @@
*
* 应用设置:
* - 登录电脑后自动启动:Windows / macOS 的系统登录启动项,默认不注册。
+ * - 菜单栏余量:macOS 14+ 的原生菜单栏项,默认开启。
* 1. 「保持电脑唤醒」(keepAwake):main 用 powerSaveBlocker 防系统休眠、放行锁屏,
* 让后台 agent / 定时任务持续运行。跨平台生效(mac/win/linux),故常驻显示。
* 2. 「关闭主窗口时」:Windows 选择退出或收起到托盘,Linux 选择退出或最小化。
@@ -23,6 +24,7 @@ import { cn } from '@/lib/utils';
import { useSwallowActivationClickSettings } from '@/hooks/useSwallowActivationClickSettings';
import { useKeepAwakeSetting } from '@/hooks/useKeepAwakeSetting';
import { useLoginItemSetting } from '@/hooks/useLoginItemSetting';
+import { useMenubarSetting } from '@/hooks/useMenubarSetting';
import {
isLinuxCloseBehavior,
isWindowsCloseBehavior,
@@ -88,6 +90,7 @@ export function WindowBehaviorSection() {
const { enabled, setEnabled } = useSwallowActivationClickSettings();
const { keepAwake, setKeepAwake } = useKeepAwakeSetting();
const loginItem = useLoginItemSetting();
+ const menubar = useMenubarSetting();
const { t } = useTranslation();
// macOS 上 acceptFirstMouse 是 Cocoa 级参数、只在 BrowserWindow 构造时读一次,
// 用户切完开关下次启动才生效——单独渲染一行"需要重启应用"避免和主 hint 混在
@@ -176,6 +179,18 @@ export function WindowBehaviorSection() {
/>
)}
+ {menubar.available && (
+ <BehaviorCard
+ id="settings-search-menubar"
+ label={t('settings.windowBehavior.menubar.label')}
+ hint={t('settings.windowBehavior.menubar.hint')}
+ checked={menubar.state?.enabled === true}
+ disabled={menubar.busy}
+ onCheckedChange={(enabled) => void menubar.setEnabled(enabled)}
+ ariaLabel={t('settings.windowBehavior.menubar.label')}
+ />
+ )}
+
{(isWindows || isLinux) && (
<div
className={cn(
diff --git a/apps/desktop/src/renderer/hooks/useMenubarSetting.ts b/apps/desktop/src/renderer/hooks/useMenubarSetting.ts
new file mode 100644
index 0000000000..12c7294c1c
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useMenubarSetting.ts
@@ -0,0 +1,51 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import type { MenubarState } from '../../shared/menubarQuota';
+
+/** macOS menu bar quota item toggle; re-reads on focus because the panel can change it too. */
+export function useMenubarSetting() {
+ const [state, setState] = useState<MenubarState | null>(null);
+ const [busy, setBusy] = useState(false);
+ const mounted = useRef(false);
+ const generation = useRef(0);
+ const supported = window.electronAPI?.platform === 'darwin';
+
+ const refresh = useCallback(async () => {
+ const current = ++generation.current;
+ try {
+ const next = await window.electronAPI.windowBehavior.getMenubarState();
+ if (mounted.current && generation.current === current) setState(next);
+ } catch {
+ if (mounted.current && generation.current === current) setState(null);
+ }
+ }, []);
+
+ useEffect(() => {
+ mounted.current = true;
+ if (supported) {
+ void refresh();
+ window.addEventListener('focus', refresh);
+ }
+ return () => {
+ mounted.current = false;
+ ++generation.current;
+ window.removeEventListener('focus', refresh);
+ };
+ }, [supported, refresh]);
+
+ const setEnabled = useCallback(async (enabled: boolean) => {
+ const current = ++generation.current;
+ setBusy(true);
+ setState((previous) => (previous ? { ...previous, enabled } : previous));
+ try {
+ const next = await window.electronAPI.windowBehavior.setMenubarEnabled(enabled);
+ if (mounted.current && generation.current === current) setState(next);
+ } catch {
+ if (mounted.current && generation.current === current) void refresh();
+ } finally {
+ if (mounted.current) setBusy(false);
+ }
+ }, [refresh]);
+
+ return { available: supported && state?.available === true, state, busy, setEnabled };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7138415b47..e5a15b5595 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -838,6 +838,301 @@
"deny": "Deny"
}
},
+ "menubar": {
+ "balance": {
+ "name": "Cindy balance",
+ "quotaName": "Cindy quota",
+ "short": "Cindy"
+ },
+ "time": {
+ "today": "today at {{time}}",
+ "tomorrow": "tomorrow at {{time}}",
+ "weekday": "{{day}} at {{time}}",
+ "date": "{{date}} at {{time}}",
+ "minutesAgo_one": "{{n}} min ago",
+ "minutesAgo_other": "{{n}} min ago",
+ "hoursAgo_one": "{{n}} hr ago",
+ "hoursAgo_other": "{{n}} hr ago",
+ "daysAgo_one": "{{n}} day ago",
+ "daysAgo_other": "{{n}} days ago"
+ },
+ "duration": {
+ "daysHours": "{{d}}d {{h}}h",
+ "days_one": "{{d}} day",
+ "days_other": "{{d}} days",
+ "hoursMinutes": "{{h}}h {{m}}m",
+ "hours_one": "{{h}} hour",
+ "hours_other": "{{h}} hours",
+ "minutes_one": "{{m}} minute",
+ "minutes_other": "{{m}} minutes"
+ },
+ "durationShort": {
+ "daysHours": "{{d}}d {{h}}h",
+ "days": "{{d}}d",
+ "hoursMinutes": "{{h}}h {{m}}m",
+ "hours": "{{h}}h",
+ "minutes": "{{m}}m"
+ },
+ "window": {
+ "session": "{{hours}}-hour",
+ "week": "Weekly",
+ "scoped": "{{model}} weekly"
+ },
+ "headline": {
+ "recommend": "{{name}} has the most left.",
+ "balance": "Your Cindy balance still works.",
+ "quota": "Your Cindy quota still has room.",
+ "none": "Everything is used up.",
+ "unread": "Quota not read yet.",
+ "empty": "Nothing with a quota yet.",
+ "emptyHint": "Connect a subscription in Cindy to see what's left here.",
+ "restore": "{{name}} resets in {{duration}}",
+ "soon": "{{name}} is running low",
+ "subscriptionsUsed": "Subscriptions are used up",
+ "waitReset": "Wait for subscriptions to reset",
+ "sentence": "{{text}}.",
+ "joiner": ", "
+ },
+ "cell": {
+ "payg": "API",
+ "plan": "Plan",
+ "noBalance": "No balance",
+ "unknown": "Unknown",
+ "noData": "No data yet",
+ "lastsDays": "~{{n}}d left",
+ "lastsDaysShort": "{{n}}d",
+ "resetsIn": "Resets in {{duration}}",
+ "credits": "credits"
+ },
+ "a11y": {
+ "payg": "{{name}}, pay per use, no balance available",
+ "plan": "{{name}}, subscription, remaining amount unavailable",
+ "balance": "Cindy balance {{amount}}",
+ "balanceDays": "Cindy balance {{amount}}, lasts about {{n}} days",
+ "quota": "Cindy quota {{amount}} left",
+ "noData": "{{name}}, no data yet",
+ "reserve": "{{name}}, used up, credits still available",
+ "remaining": "{{name}}, {{n}}% left"
+ },
+ "detail": {
+ "balanceCaption": "Balance",
+ "quotaCaption": "Quota left",
+ "apiKey": "API Key",
+ "subscription": "Subscription",
+ "noBalance": "No balance available",
+ "unknownRemaining": "Remaining amount unavailable",
+ "noData": "No data yet",
+ "windowLeft": "{{window}} left"
+ },
+ "say": {
+ "balance": "The balance doesn't refill on its own.",
+ "quota": "The quota is granted each period; it isn't topped up here.",
+ "quotaResets": "The quota resets to full {{at}}.",
+ "balanceLasts_one": "At the last 7 days' pace, it lasts about {{n}} day.",
+ "balanceLasts_other": "At the last 7 days' pace, it lasts about {{n}} days.",
+ "balanceEstimating": "Spending history is still building up. An estimate appears in a few days.",
+ "payg": "{{name}} bills per use.",
+ "paygSub": "Its API doesn't report a balance, so there's nothing to show here. What you use still counts toward Cindy usage.",
+ "plan": "{{name}} is a subscription connection.",
+ "planSub": "Cindy can't read how much is left yet. What you use still counts toward Cindy usage.",
+ "noData": "Nothing read yet.",
+ "noDataSub": "It appears after a refresh or after you run a task with it.",
+ "usedUp": "{{window}} usage is used up.",
+ "usedUpWithCredits": "Back {{at}}. Until then, Codex keeps working on {{credits}} credits.",
+ "creditsOnly": "Codex keeps working on {{credits}} credits.",
+ "resetsAt": "Back {{at}}.",
+ "emptyIn": "At this pace, it runs out in about {{duration}}.",
+ "beforeReset": "That's {{duration}} before the reset.",
+ "full": "Full.",
+ "relaxed": "Plenty of room at this pace.",
+ "onPace": "On pace.",
+ "windowRefresh": "{{window}} window refreshes {{at}}",
+ "usedUpWithResets_one": "{{n}} reset is available; using it refills right away.",
+ "usedUpWithResets_other": "{{n}} resets are available; using one refills right away."
+ },
+ "fact": {
+ "balance": "Balance",
+ "quotaLeft": "Quota left",
+ "quotaTotal": "Quota this period",
+ "updatedAgo": "Updated {{ago}}",
+ "dailyUse": "Daily spend",
+ "about": "~{{value}}",
+ "estimating": "Estimating",
+ "estimatingSub": "Not enough data yet",
+ "last7Days": "Last 7 days",
+ "runsOut": "Runs out",
+ "aroundDate": "Around {{date}}",
+ "atThisPace": "At this pace",
+ "usedFor": "Used for",
+ "cindyModels": "Models from Cindy",
+ "chargedPerUse": "Charged per use",
+ "billing": "Billing",
+ "perUse": "Per use",
+ "subscription": "Subscription",
+ "connected": "Connected",
+ "notProvided": "Not reported by the API",
+ "notReadable": "Can't read it yet",
+ "inMenu": "In the menu",
+ "hidden": "Hidden",
+ "shown": "Shown",
+ "editHint": "Change it in Edit",
+ "usage": "Usage",
+ "counted": "Counted",
+ "countedSub": "In Cindy usage",
+ "resetsFull": "Back",
+ "windowResets": "{{window}} resets",
+ "timeLeft": "{{duration}} left",
+ "remainingPercent": "{{n}}% left",
+ "perModel": "Counted per model",
+ "pace": "Pace",
+ "paceNormal": "Normal",
+ "paceAhead": "{{n}}% ahead",
+ "paceReserve": "{{n}}% in reserve",
+ "paceSub": "Even use leaves {{n}}%",
+ "paceUsedUp": "Used up",
+ "paceWaiting": "Waiting to reset",
+ "extraCredits": "Extra credits",
+ "unlimited": "Unlimited",
+ "creditsUsedAfter": "Used by Codex after the limit",
+ "noCredits": "No extra credits",
+ "prepaid": "Prepaid balance",
+ "xaiAccount": "xAI account",
+ "account": "Account",
+ "todaySpent": "Spent today",
+ "dailySuggested": "Suggested under {{value}} a day",
+ "poolPlan": "Plan balance",
+ "poolPlanSub": "From your plan",
+ "poolPurchased": "Top-up balance",
+ "poolPurchasedSub": "Added by you",
+ "poolPromo": "Promo balance",
+ "poolPromoSub": "From promotions",
+ "promoExpires": "{{value}} expires {{date}}",
+ "promoExpiresAll": "Expires {{date}}",
+ "resetCredits": "Usage limit resets",
+ "resetCount_one": "{{n}} reset",
+ "resetCount_other": "{{n}} resets",
+ "resetExpires": "Valid until {{date}}",
+ "resetAtLimit": "Usable at a usage limit",
+ "device": "Computer",
+ "deviceSub": "One of your other computers"
+ },
+ "action": {
+ "newTask": "Start a task with {{name}}",
+ "topUp": "Top up in Cindy",
+ "manage": "Manage in Cindy settings",
+ "openApp": "Open Cindy",
+ "useReset": "Use a reset in Cindy settings"
+ },
+ "tasks": {
+ "today_one": "{{n}} today",
+ "today_other": "{{n}} today",
+ "withRunning_one": "{{base}} · {{n}} running",
+ "withRunning_other": "{{base}} · {{n}} running",
+ "context": "context {{n}}%",
+ "private": "{{harness}} task"
+ },
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "usage": {
+ "estimateNote": "Subscription value = what the usage would cost at API reference prices. It is not a bill.",
+ "deviceSelf": "this {{name}} (live)",
+ "deviceSynced": "{{name}} (synced {{date}})",
+ "deviceNotSynced": "{{name}} (not synced yet)",
+ "deviceJoiner": " + ",
+ "allDevices": "All devices = {{list}}."
+ },
+ "manage": {
+ "balance": "Balance · doesn't refill on its own",
+ "quota": "Quota · resets each period",
+ "payg": "API Key · pay per use, no balance",
+ "plan": "Subscription · remaining amount unavailable",
+ "subscription": "Subscription · {{plan}} · {{windows}}",
+ "onDevice": "{{name}} · {{subtitle}}"
+ },
+ "notify": {
+ "lowTitle": "Running low",
+ "lowBody": "Every source with room left is nearly empty. Click the Cindy icon in the menu bar to see when each one resets."
+ },
+ "ui": {
+ "updatedJustNow": "Updated just now",
+ "updatedMinutes_one": "Updated {{n}} min ago",
+ "updatedMinutes_other": "Updated {{n}} min ago",
+ "updatedHours_one": "Updated {{n}} hr ago",
+ "updatedHours_other": "Updated {{n}} hr ago",
+ "updatedDays_one": "Updated {{n}} day ago",
+ "updatedDays_other": "Updated {{n}} days ago",
+ "tasks": "Tasks",
+ "tokenUnit": "tokens",
+ "noTasksToday": "No tasks yet today",
+ "moreTasks_one": "{{n}} more task",
+ "moreTasks_other": "{{n}} more tasks",
+ "running": "Running",
+ "openApp": "Open Cindy",
+ "gateTitle": "Sign in to see what's left",
+ "gateBody": "Sign in to Cindy, or choose Skip Sign-In, and this panel shows your subscription quota and today's usage.",
+ "settings": "Manage",
+ "refresh": "Refresh",
+ "monthScopeLocal": "Last 30 days · This computer",
+ "monthScopeAll": "Last 30 days · All devices",
+ "expand": "Expand",
+ "expandUsage": "Expand usage",
+ "back": "Back",
+ "usageTitle": "Usage",
+ "wideCaptionMoney_one": "Last {{n}} day · Subscription value",
+ "wideCaptionMoney_other": "Last {{n}} days · Subscription value",
+ "wideCaptionTokens_one": "Last {{n}} day · Tokens",
+ "wideCaptionTokens_other": "Last {{n}} days · Tokens",
+ "scopeLocal": "This computer",
+ "scopeAll": "All devices",
+ "noUsage": "No usage",
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "dailyAverage": "Daily avg",
+ "paid": "Paid",
+ "tokenUnitTitle": "Tokens",
+ "peakDay": "Peak day",
+ "range7": "7 days",
+ "range30": "30 days",
+ "range90": "90 days",
+ "metricMoney": "Amount",
+ "metricTokens": "Tokens",
+ "listModels_one": "Models · {{n}} day",
+ "listModels_other": "Models · {{n}} days",
+ "listTasks": "Today's tasks",
+ "today": "Today",
+ "manageTitle": "Manage",
+ "done": "Done",
+ "manageHero": "What the menu shows,\nand in what order.",
+ "manageHeroSub": "Drag to reorder. Sources you turn off don't appear in the menu and aren't part of the summary above.",
+ "sources": "Sources",
+ "sourcesShown": "{{a}} of {{b}} shown",
+ "statusIcon": "Menu bar icon",
+ "statusIconSub": "Monochrome, follows the menu bar",
+ "statusIconMode": {
+ "icon": "Icon only",
+ "lowest": "Lowest left",
+ "today": "Today's usage",
+ "task": "Current task"
+ },
+ "other": "Other",
+ "lowAlert": "Notify when running low",
+ "lowAlertSub": "Sends a system notification when every source with room left is nearly empty",
+ "privacy": "Hide personal info",
+ "privacySub": "Shows only the first and last letter of accounts and hides task titles. Good for recordings and screenshots.",
+ "usageScope": "Usage covers",
+ "manageFoot": "Sign in to accounts and connect them in Cindy Settings › Model Providers.",
+ "showSource": "Show {{name}} in the menu",
+ "reorderHint": "Drag, or use the actions menu to reorder",
+ "moveUp": "Move up",
+ "moveDown": "Move down"
+ }
+ },
"settings": {
"title": "Settings",
"search": {
@@ -1358,6 +1653,10 @@
"wecomGroupClearFailed": "Could not remove the Webhook"
},
"windowBehavior": {
+ "menubar": {
+ "label": "Show remaining usage in the menu bar",
+ "hint": "Adds a Cindy icon to the macOS menu bar. Click it to see what's left on your subscriptions, your Cindy balance and today's usage."
+ },
"loginItem": {
"label": "Start at Login",
"hint": "Open Cindy when you sign in to your computer. Off by default.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 7dc8ba3ed9..a19f614426 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -832,6 +832,283 @@
"deny": "拒否"
}
},
+ "menubar": {
+ "balance": {
+ "name": "Cindy 残高",
+ "quotaName": "Cindy の今期クォータ",
+ "short": "Cindy"
+ },
+ "time": {
+ "today": "今日 {{time}}",
+ "tomorrow": "明日 {{time}}",
+ "weekday": "{{day}} {{time}}",
+ "date": "{{date}} {{time}}",
+ "minutesAgo_other": "{{n}} 分前",
+ "hoursAgo_other": "{{n}} 時間前",
+ "daysAgo_other": "{{n}} 日前"
+ },
+ "duration": {
+ "daysHours": "{{d}} 日 {{h}} 時間",
+ "days_other": "{{d}} 日",
+ "hoursMinutes": "{{h}} 時間 {{m}} 分",
+ "hours_other": "{{h}} 時間",
+ "minutes_other": "{{m}} 分"
+ },
+ "durationShort": {
+ "daysHours": "{{d}}日{{h}}時間",
+ "days": "{{d}}日",
+ "hoursMinutes": "{{h}}時間{{m}}分",
+ "hours": "{{h}}時間",
+ "minutes": "{{m}}分"
+ },
+ "window": {
+ "session": "{{hours}} 時間",
+ "week": "今週",
+ "scoped": "{{model}} 今週"
+ },
+ "headline": {
+ "recommend": "{{name}} がいちばん余裕があります。",
+ "balance": "Cindy 残高はまだ使えます。",
+ "quota": "Cindy の今期クォータはまだ使えます。",
+ "none": "すべて使い切りました。",
+ "unread": "残りをまだ取得できていません。",
+ "empty": "残りを表示できるアカウントがまだありません。",
+ "emptyHint": "Cindy でサブスクリプションを接続すると、ここに残りが表示されます。",
+ "restore": "{{name}} は{{duration}}後にリセット",
+ "soon": "{{name}} はまもなく上限",
+ "subscriptionsUsed": "サブスクリプションはすべて使い切り",
+ "waitReset": "サブスクリプションのリセット待ち",
+ "sentence": "{{text}}。",
+ "joiner": "、"
+ },
+ "cell": {
+ "payg": "従量",
+ "plan": "プラン",
+ "noBalance": "残高なし",
+ "unknown": "不明",
+ "noData": "残りをまだ取得できていません",
+ "lastsDays": "約{{n}}日",
+ "lastsDaysShort": "{{n}}日",
+ "resetsIn": "{{duration}}後にリセット",
+ "credits": "credits"
+ },
+ "a11y": {
+ "payg": "{{name}}、従量課金、残高は取得できません",
+ "plan": "{{name}}、サブスクリプション、残りは取得できません",
+ "balance": "Cindy 残高 {{amount}}",
+ "balanceDays": "Cindy 残高 {{amount}}、約 {{n}} 日分",
+ "quota": "Cindy クォータ残り {{amount}}",
+ "noData": "{{name}}、データなし",
+ "reserve": "{{name}}、使い切り、credits は使用可能",
+ "remaining": "{{name}} 残り {{n}}%"
+ },
+ "detail": {
+ "balanceCaption": "残高",
+ "quotaCaption": "今期のクォータ残り",
+ "apiKey": "API Key",
+ "subscription": "サブスクリプション",
+ "noBalance": "残高を取得できません",
+ "unknownRemaining": "残りを取得できません",
+ "noData": "データなし",
+ "windowLeft": "{{window}}の残り"
+ },
+ "say": {
+ "balance": "残高は自動では回復しません。",
+ "quota": "クォータは期間ごとに付与され、ここではチャージしません。",
+ "quotaResets": "クォータは{{at}}に満額へリセットされます。",
+ "balanceLasts_other": "直近 7 日のペースで約 {{n}} 日分です。",
+ "balanceEstimating": "利用記録を集めています。数日で残り日数を見積もれます。",
+ "payg": "{{name}} は従量課金です。",
+ "paygSub": "API が残高を返さないため、ここには表示できません。使った分は Cindy の使用量に通常どおり含まれます。",
+ "plan": "{{name}} はサブスクリプション接続です。",
+ "planSub": "Cindy はまだ残りを読み取れません。使った分は Cindy の使用量に通常どおり含まれます。",
+ "noData": "まだ読み取れていません。",
+ "noDataSub": "更新するか、これでタスクを一度実行すると表示されます。",
+ "usedUp": "{{window}}の上限に達しました。",
+ "usedUpWithCredits": "{{at}}に回復します。それまでは Codex が {{credits}} credits を使って作業を続けます。",
+ "creditsOnly": "Codex が {{credits}} credits を使って作業を続けます。",
+ "resetsAt": "{{at}}に回復します。",
+ "emptyIn": "今のペースだと約 {{duration}}で上限に達します。",
+ "beforeReset": "リセットより {{duration}}早いです。",
+ "full": "満タンです。",
+ "relaxed": "ペースに余裕があります。",
+ "onPace": "ペースは標準です。",
+ "windowRefresh": "{{window}}の枠は{{at}}に更新",
+ "usedUpWithResets_other": "リセットがあと {{n}} 回使えます。使うとすぐ満タンに戻ります。"
+ },
+ "fact": {
+ "balance": "残高",
+ "quotaLeft": "今期のクォータ残り",
+ "quotaTotal": "今期のクォータ",
+ "updatedAgo": "{{ago}}に更新",
+ "dailyUse": "1 日の平均消費",
+ "about": "約 {{value}}",
+ "estimating": "見積もり中",
+ "estimatingSub": "データが不足",
+ "last7Days": "直近 7 日",
+ "runsOut": "使い切る目安",
+ "aroundDate": "{{date}}ごろ",
+ "atThisPace": "今のペースで",
+ "usedFor": "用途",
+ "cindyModels": "Cindy が提供するモデル",
+ "chargedPerUse": "使用量に応じて請求",
+ "billing": "課金",
+ "perUse": "従量",
+ "subscription": "サブスクリプション",
+ "connected": "接続済み",
+ "notProvided": "API が返さない",
+ "notReadable": "まだ読み取れない",
+ "inMenu": "メニュー",
+ "hidden": "非表示",
+ "shown": "表示",
+ "editHint": "「編集」で変更できます",
+ "usage": "使用量",
+ "counted": "通常どおり集計",
+ "countedSub": "Cindy の使用量に含む",
+ "resetsFull": "回復",
+ "windowResets": "{{window}}のリセット",
+ "timeLeft": "あと {{duration}}",
+ "remainingPercent": "残り {{n}}%",
+ "perModel": "モデルごとに計算",
+ "pace": "ペース",
+ "paceNormal": "標準",
+ "paceAhead": "{{n}}% 先行",
+ "paceReserve": "{{n}}% 余裕",
+ "paceSub": "均等に使えば残り {{n}}%",
+ "paceUsedUp": "使い切り",
+ "paceWaiting": "回復待ち",
+ "extraCredits": "追加 credits",
+ "unlimited": "無制限",
+ "creditsUsedAfter": "上限後に Codex が使用",
+ "noCredits": "予備の credits なし",
+ "prepaid": "前払い残高",
+ "xaiAccount": "xAI アカウント",
+ "account": "アカウント",
+ "todaySpent": "今日の使用額",
+ "dailySuggested": "1 日 {{value}} 以内が目安",
+ "poolPlan": "プラン残高",
+ "poolPlanSub": "プランで付与",
+ "poolPurchased": "チャージ残高",
+ "poolPurchasedSub": "自分でチャージ",
+ "poolPromo": "特典残高",
+ "poolPromoSub": "キャンペーン特典",
+ "promoExpires": "{{value}} は{{date}}に期限切れ",
+ "promoExpiresAll": "{{date}}に期限切れ",
+ "resetCredits": "利用上限のリセット",
+ "resetCount_other": "{{n}} 回",
+ "resetExpires": "{{date}}まで有効",
+ "resetAtLimit": "上限に達すると使用可能",
+ "device": "コンピュータ",
+ "deviceSub": "自分の別のコンピュータ"
+ },
+ "action": {
+ "newTask": "{{name}} で新しいタスクを開始",
+ "topUp": "Cindy でチャージ",
+ "manage": "Cindy の設定で管理",
+ "openApp": "Cindy を開く",
+ "useReset": "Cindy の設定でリセットを使う"
+ },
+ "tasks": {
+ "today_other": "今日 {{n}} 件",
+ "withRunning_other": "{{base}} · {{n}} 件実行中",
+ "context": "コンテキスト {{n}}%",
+ "private": "{{harness}} のタスク"
+ },
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "usage": {
+ "estimateNote": "サブスク換算 = サブスクで使った分を API の参考価格で換算した額で、請求額ではありません。",
+ "deviceSelf": "この {{name}}(リアルタイム)",
+ "deviceSynced": "{{name}}({{date}} まで同期)",
+ "deviceNotSynced": "{{name}}(未同期)",
+ "deviceJoiner": " + ",
+ "allDevices": "すべてのデバイス = {{list}}。"
+ },
+ "manage": {
+ "balance": "残高 · 自動では回復しない",
+ "quota": "クォータ · 期間ごとにリセット",
+ "payg": "API Key · 従量、残高なし",
+ "plan": "サブスクリプション · 残りを取得できない",
+ "subscription": "サブスクリプション · {{plan}} · {{windows}}",
+ "onDevice": "{{name}} · {{subtitle}}"
+ },
+ "notify": {
+ "lowTitle": "残りわずかです",
+ "lowBody": "余裕のあるソースがどれも上限に近づいています。メニューバーの Cindy アイコンで回復時刻を確認できます。"
+ },
+ "ui": {
+ "updatedJustNow": "たった今更新",
+ "updatedMinutes_other": "{{n}} 分前に更新",
+ "updatedHours_other": "{{n}} 時間前に更新",
+ "updatedDays_other": "{{n}} 日前に更新",
+ "tasks": "タスク",
+ "tokenUnit": "token",
+ "noTasksToday": "今日のタスクはまだありません",
+ "moreTasks_other": "ほか {{n}} 件のタスク",
+ "running": "実行中",
+ "openApp": "Cindy を開く",
+ "gateTitle": "ログインすると残りを確認できます",
+ "gateBody": "Cindy にログインするか、ログインをスキップすると、ここにサブスクリプションの残りと今日の使用量が表示されます。",
+ "settings": "管理",
+ "refresh": "更新",
+ "monthScopeLocal": "直近 30 日 · このコンピュータ",
+ "monthScopeAll": "直近 30 日 · すべてのデバイス",
+ "expand": "展開",
+ "expandUsage": "使用量を展開",
+ "back": "戻る",
+ "usageTitle": "使用量",
+ "wideCaptionMoney_other": "直近 {{n}} 日 · サブスク換算",
+ "wideCaptionTokens_other": "直近 {{n}} 日 · Token",
+ "scopeLocal": "このコンピュータ",
+ "scopeAll": "すべてのデバイス",
+ "noUsage": "使用量なし",
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "dailyAverage": "1 日平均",
+ "paid": "支払額",
+ "tokenUnitTitle": "Token",
+ "peakDay": "最多の日",
+ "range7": "7 日",
+ "range30": "30 日",
+ "range90": "90 日",
+ "metricMoney": "金額",
+ "metricTokens": "Token",
+ "listModels_other": "直近 {{n}} 日のモデル",
+ "listTasks": "今日のタスク",
+ "today": "今日",
+ "manageTitle": "管理",
+ "done": "完了",
+ "manageHero": "メニューに何を、\nどの順で表示するか。",
+ "manageHeroSub": "ドラッグで並べ替えます。オフにしたソースはメニューに表示されず、上の判断にも含まれません。",
+ "sources": "ソース",
+ "sourcesShown": "{{b}} 件中 {{a}} 件を表示",
+ "statusIcon": "メニューバーのアイコン",
+ "statusIconSub": "モノクロで、メニューバーの明暗に合わせて変わります",
+ "statusIconMode": {
+ "icon": "アイコンのみ",
+ "lowest": "最小の残り",
+ "today": "今日の使用量",
+ "task": "実行中のタスク"
+ },
+ "other": "その他",
+ "lowAlert": "残りわずかで通知",
+ "lowAlertSub": "余裕のあるソースがどれも上限に近づいたら、システム通知を送ります",
+ "privacy": "個人情報を隠す",
+ "privacySub": "アカウントは最初と最後の文字だけ表示し、タスク名も隠します。録画やスクリーンショットに便利です",
+ "usageScope": "使用量の集計範囲",
+ "manageFoot": "アカウントのログインと接続は Cindy の設定 › モデルプロバイダー で管理します。",
+ "showSource": "{{name}} をメニューに表示",
+ "reorderHint": "ドラッグするか、アクションメニューで並べ替えます",
+ "moveUp": "上へ移動",
+ "moveDown": "下へ移動"
+ }
+ },
"settings": {
"title": "設定",
"search": {
@@ -1352,6 +1629,10 @@
"wecomGroupClearFailed": "Webhook を削除できませんでした"
},
"windowBehavior": {
+ "menubar": {
+ "label": "メニューバーに残りを表示",
+ "hint": "macOS のメニューバーに Cindy アイコンを置きます。クリックすると、サブスクリプションの残り、Cindy 残高、今日の使用量を確認できます。"
+ },
"loginItem": {
"label": "ログイン時に起動",
"hint": "パソコンにログインすると Cindy を開きます。初期設定はオフです。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 241029a59e..a1a9c57ec1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -832,6 +832,283 @@
"deny": "거부"
}
},
+ "menubar": {
+ "balance": {
+ "name": "Cindy 잔액",
+ "quotaName": "Cindy 이번 기간 할당량",
+ "short": "Cindy"
+ },
+ "time": {
+ "today": "오늘 {{time}}",
+ "tomorrow": "내일 {{time}}",
+ "weekday": "{{day}} {{time}}",
+ "date": "{{date}} {{time}}",
+ "minutesAgo_other": "{{n}}분 전",
+ "hoursAgo_other": "{{n}}시간 전",
+ "daysAgo_other": "{{n}}일 전"
+ },
+ "duration": {
+ "daysHours": "{{d}}일 {{h}}시간",
+ "days_other": "{{d}}일",
+ "hoursMinutes": "{{h}}시간 {{m}}분",
+ "hours_other": "{{h}}시간",
+ "minutes_other": "{{m}}분"
+ },
+ "durationShort": {
+ "daysHours": "{{d}}일 {{h}}시간",
+ "days": "{{d}}일",
+ "hoursMinutes": "{{h}}시간 {{m}}분",
+ "hours": "{{h}}시간",
+ "minutes": "{{m}}분"
+ },
+ "window": {
+ "session": "{{hours}}시간",
+ "week": "이번 주",
+ "scoped": "{{model}} 이번 주"
+ },
+ "headline": {
+ "recommend": "{{name}}에 가장 많이 남았어요.",
+ "balance": "Cindy 잔액은 아직 쓸 수 있어요.",
+ "quota": "Cindy 이번 기간 할당량이 아직 남아 있어요.",
+ "none": "모두 다 썼어요.",
+ "unread": "남은 양을 아직 읽지 못했어요.",
+ "empty": "남은 양을 보여 줄 계정이 아직 없어요.",
+ "emptyHint": "Cindy에서 구독을 연결하면 여기에 남은 양이 표시돼요.",
+ "restore": "{{name}} {{duration}} 후 초기화",
+ "soon": "{{name}} 곧 소진",
+ "subscriptionsUsed": "구독은 모두 다 썼어요",
+ "waitReset": "구독 초기화를 기다리는 중",
+ "sentence": "{{text}}.",
+ "joiner": ", "
+ },
+ "cell": {
+ "payg": "종량",
+ "plan": "플랜",
+ "noBalance": "잔액 없음",
+ "unknown": "알 수 없음",
+ "noData": "남은 양을 아직 읽지 못했어요",
+ "lastsDays": "약 {{n}}일",
+ "lastsDaysShort": "{{n}}일",
+ "resetsIn": "{{duration}} 후 초기화",
+ "credits": "credits"
+ },
+ "a11y": {
+ "payg": "{{name}}, 종량 과금, 잔액을 알 수 없음",
+ "plan": "{{name}}, 구독, 남은 양을 알 수 없음",
+ "balance": "Cindy 잔액 {{amount}}",
+ "balanceDays": "Cindy 잔액 {{amount}}, 약 {{n}}일 분량",
+ "quota": "Cindy 할당량 {{amount}} 남음",
+ "noData": "{{name}}, 데이터 없음",
+ "reserve": "{{name}}, 다 씀, credits 사용 가능",
+ "remaining": "{{name}} {{n}}% 남음"
+ },
+ "detail": {
+ "balanceCaption": "잔액",
+ "quotaCaption": "남은 할당량",
+ "apiKey": "API Key",
+ "subscription": "구독",
+ "noBalance": "잔액을 알 수 없음",
+ "unknownRemaining": "남은 양을 알 수 없음",
+ "noData": "데이터 없음",
+ "windowLeft": "{{window}} 남음"
+ },
+ "say": {
+ "balance": "잔액은 자동으로 다시 채워지지 않아요.",
+ "quota": "할당량은 기간마다 지급되며 여기서 충전하지 않아요.",
+ "quotaResets": "할당량은 {{at}}에 전액으로 초기화돼요.",
+ "balanceLasts_other": "최근 7일 속도라면 약 {{n}}일 쓸 수 있어요.",
+ "balanceEstimating": "사용 기록을 모으는 중이에요. 며칠 뒤면 남은 기간을 추정할 수 있어요.",
+ "payg": "{{name}}은(는) 쓴 만큼 과금돼요.",
+ "paygSub": "API가 잔액을 알려 주지 않아 여기에는 표시할 수 없어요. 쓴 만큼은 Cindy 사용량에 그대로 포함돼요.",
+ "plan": "{{name}}은(는) 구독 연결이에요.",
+ "planSub": "Cindy가 아직 남은 양을 읽지 못해요. 쓴 만큼은 Cindy 사용량에 그대로 포함돼요.",
+ "noData": "아직 읽지 못했어요.",
+ "noDataSub": "새로 고치거나 이것으로 작업을 한 번 실행하면 표시돼요.",
+ "usedUp": "{{window}} 사용량을 다 썼어요.",
+ "usedUpWithCredits": "{{at}}에 초기화돼요. 그때까지는 Codex가 {{credits}} credits로 계속 작업해요.",
+ "creditsOnly": "Codex가 {{credits}} credits로 계속 작업해요.",
+ "resetsAt": "{{at}}에 초기화돼요.",
+ "emptyIn": "지금 속도라면 약 {{duration}} 후 소진돼요.",
+ "beforeReset": "초기화보다 {{duration}} 빨라요.",
+ "full": "가득 찼어요.",
+ "relaxed": "속도에 여유가 있어요.",
+ "onPace": "속도가 적당해요.",
+ "windowRefresh": "{{window}} 구간은 {{at}}에 갱신",
+ "usedUpWithResets_other": "초기화를 {{n}}회 더 쓸 수 있어요. 쓰면 바로 다시 채워져요."
+ },
+ "fact": {
+ "balance": "잔액",
+ "quotaLeft": "남은 할당량",
+ "quotaTotal": "이번 기간 할당량",
+ "updatedAgo": "{{ago}} 업데이트",
+ "dailyUse": "하루 평균 소비",
+ "about": "약 {{value}}",
+ "estimating": "추정 중",
+ "estimatingSub": "데이터 부족",
+ "last7Days": "최근 7일",
+ "runsOut": "소진 예상",
+ "aroundDate": "{{date}}쯤",
+ "atThisPace": "현재 속도 기준",
+ "usedFor": "사용처",
+ "cindyModels": "Cindy가 제공하는 모델",
+ "chargedPerUse": "사용량만큼 차감",
+ "billing": "과금",
+ "perUse": "종량",
+ "subscription": "구독",
+ "connected": "연결됨",
+ "notProvided": "API가 제공하지 않음",
+ "notReadable": "아직 읽을 수 없음",
+ "inMenu": "메뉴",
+ "hidden": "숨김",
+ "shown": "표시",
+ "editHint": "「편집」에서 바꿀 수 있어요",
+ "usage": "사용량",
+ "counted": "그대로 집계",
+ "countedSub": "Cindy 사용량에 포함",
+ "resetsFull": "초기화",
+ "windowResets": "{{window}} 초기화",
+ "timeLeft": "{{duration}} 남음",
+ "remainingPercent": "{{n}}% 남음",
+ "perModel": "모델별로 계산",
+ "pace": "속도",
+ "paceNormal": "보통",
+ "paceAhead": "{{n}}% 빠름",
+ "paceReserve": "{{n}}% 여유",
+ "paceSub": "고르게 쓰면 {{n}}% 남음",
+ "paceUsedUp": "다 씀",
+ "paceWaiting": "초기화 대기",
+ "extraCredits": "추가 credits",
+ "unlimited": "무제한",
+ "creditsUsedAfter": "한도 소진 후 Codex가 사용",
+ "noCredits": "예비 credits 없음",
+ "prepaid": "선불 잔액",
+ "xaiAccount": "xAI 계정",
+ "account": "계정",
+ "todaySpent": "오늘 사용액",
+ "dailySuggested": "하루 {{value}} 이내 권장",
+ "poolPlan": "요금제 잔액",
+ "poolPlanSub": "요금제로 지급",
+ "poolPurchased": "충전 잔액",
+ "poolPurchasedSub": "직접 충전",
+ "poolPromo": "프로모션 잔액",
+ "poolPromoSub": "프로모션 지급",
+ "promoExpires": "{{value}} {{date}}에 만료",
+ "promoExpiresAll": "{{date}}에 만료",
+ "resetCredits": "사용 한도 초기화",
+ "resetCount_other": "{{n}}회",
+ "resetExpires": "{{date}}까지 유효",
+ "resetAtLimit": "한도에 도달하면 사용 가능",
+ "device": "컴퓨터",
+ "deviceSub": "내 다른 컴퓨터"
+ },
+ "action": {
+ "newTask": "{{name}}(으)로 새 작업 시작",
+ "topUp": "Cindy에서 충전",
+ "manage": "Cindy 설정에서 관리",
+ "openApp": "Cindy 열기",
+ "useReset": "Cindy 설정에서 초기화 사용"
+ },
+ "tasks": {
+ "today_other": "오늘 {{n}}개",
+ "withRunning_other": "{{base}} · {{n}}개 진행 중",
+ "context": "컨텍스트 {{n}}%",
+ "private": "{{harness}} 작업"
+ },
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "usage": {
+ "estimateNote": "구독 환산 = 구독에서 쓴 양을 API 참고 가격으로 환산한 금액이며, 청구서가 아니에요.",
+ "deviceSelf": "이 {{name}}(실시간)",
+ "deviceSynced": "{{name}}({{date}}까지 동기화)",
+ "deviceNotSynced": "{{name}}(아직 동기화 안 됨)",
+ "deviceJoiner": " + ",
+ "allDevices": "모든 기기 = {{list}}."
+ },
+ "manage": {
+ "balance": "잔액 · 자동으로 채워지지 않음",
+ "quota": "할당량 · 기간마다 초기화",
+ "payg": "API Key · 종량, 잔액 없음",
+ "plan": "구독 · 남은 양을 알 수 없음",
+ "subscription": "구독 · {{plan}} · {{windows}}",
+ "onDevice": "{{name}} · {{subtitle}}"
+ },
+ "notify": {
+ "lowTitle": "곧 소진돼요",
+ "lowBody": "여유가 남은 소스가 모두 거의 다 찼어요. 메뉴 막대의 Cindy 아이콘에서 초기화 시간을 확인하세요."
+ },
+ "ui": {
+ "updatedJustNow": "방금 업데이트",
+ "updatedMinutes_other": "{{n}}분 전 업데이트",
+ "updatedHours_other": "{{n}}시간 전 업데이트",
+ "updatedDays_other": "{{n}}일 전 업데이트",
+ "tasks": "작업",
+ "tokenUnit": "token",
+ "noTasksToday": "오늘은 아직 작업이 없어요",
+ "moreTasks_other": "작업 {{n}}개 더",
+ "running": "진행 중",
+ "openApp": "Cindy 열기",
+ "gateTitle": "로그인하면 남은 양을 볼 수 있어요",
+ "gateBody": "Cindy에 로그인하거나 로그인 건너뛰기를 선택하면 여기에 구독 남은 양과 오늘 사용량이 표시돼요.",
+ "settings": "관리",
+ "refresh": "새로 고침",
+ "monthScopeLocal": "최근 30일 · 이 컴퓨터",
+ "monthScopeAll": "최근 30일 · 모든 기기",
+ "expand": "펼치기",
+ "expandUsage": "사용량 펼치기",
+ "back": "뒤로",
+ "usageTitle": "사용량",
+ "wideCaptionMoney_other": "최근 {{n}}일 · 구독 환산",
+ "wideCaptionTokens_other": "최근 {{n}}일 · Token",
+ "scopeLocal": "이 컴퓨터",
+ "scopeAll": "모든 기기",
+ "noUsage": "사용량 없음",
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "dailyAverage": "하루 평균",
+ "paid": "실제 결제",
+ "tokenUnitTitle": "Token",
+ "peakDay": "최고 하루",
+ "range7": "7일",
+ "range30": "30일",
+ "range90": "90일",
+ "metricMoney": "금액",
+ "metricTokens": "Token",
+ "listModels_other": "최근 {{n}}일 모델",
+ "listTasks": "오늘의 작업",
+ "today": "오늘",
+ "manageTitle": "관리",
+ "done": "완료",
+ "manageHero": "메뉴에 무엇을,\n어떤 순서로 보여 줄지.",
+ "manageHeroSub": "드래그해서 순서를 바꿔요. 끈 소스는 메뉴에 나타나지 않고 위의 판단에도 포함되지 않아요.",
+ "sources": "소스",
+ "sourcesShown": "{{b}}개 중 {{a}}개 표시",
+ "statusIcon": "메뉴 막대 아이콘",
+ "statusIconSub": "단색이며 메뉴 막대 밝기에 맞춰 바뀌어요",
+ "statusIconMode": {
+ "icon": "아이콘만",
+ "lowest": "가장 적게 남음",
+ "today": "오늘 사용량",
+ "task": "현재 작업"
+ },
+ "other": "기타",
+ "lowAlert": "곧 소진될 때 알림",
+ "lowAlertSub": "여유가 남은 소스가 모두 거의 다 찼을 때 시스템 알림을 보내요",
+ "privacy": "개인 정보 숨기기",
+ "privacySub": "계정은 첫 글자와 마지막 글자만 보이고 작업 제목도 숨겨요. 녹화나 스크린샷에 좋아요",
+ "usageScope": "사용량 집계 범위",
+ "manageFoot": "계정 로그인과 연결은 Cindy 설정 › 모델 제공자에서 관리해요.",
+ "showSource": "메뉴에 {{name}} 표시",
+ "reorderHint": "드래그하거나 작업 메뉴로 순서를 바꿔요",
+ "moveUp": "위로 이동",
+ "moveDown": "아래로 이동"
+ }
+ },
"settings": {
"title": "설정",
"search": {
@@ -1352,6 +1629,10 @@
"wecomGroupClearFailed": "Webhook을 삭제하지 못했습니다"
},
"windowBehavior": {
+ "menubar": {
+ "label": "메뉴 막대에 남은 양 표시",
+ "hint": "macOS 메뉴 막대에 Cindy 아이콘을 둬요. 클릭하면 구독의 남은 양, Cindy 잔액, 오늘 사용량을 볼 수 있어요."
+ },
"loginItem": {
"label": "로그인 시 시작",
"hint": "컴퓨터에 로그인하면 Cindy를 엽니다. 기본값은 꺼짐입니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 34a8fd0348..6238f77aa9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -832,6 +832,283 @@
"deny": "拒绝"
}
},
+ "menubar": {
+ "balance": {
+ "name": "Cindy 余额",
+ "quotaName": "Cindy 本期配额",
+ "short": "Cindy"
+ },
+ "time": {
+ "today": "今天 {{time}}",
+ "tomorrow": "明天 {{time}}",
+ "weekday": "{{day}} {{time}}",
+ "date": "{{date}} {{time}}",
+ "minutesAgo_other": "{{n}} 分钟前",
+ "hoursAgo_other": "{{n}} 小时前",
+ "daysAgo_other": "{{n}} 天前"
+ },
+ "duration": {
+ "daysHours": "{{d}} 天 {{h}} 小时",
+ "days_other": "{{d}} 天",
+ "hoursMinutes": "{{h}} 小时 {{m}} 分",
+ "hours_other": "{{h}} 小时",
+ "minutes_other": "{{m}} 分钟"
+ },
+ "durationShort": {
+ "daysHours": "{{d}}天{{h}}时",
+ "days": "{{d}}天",
+ "hoursMinutes": "{{h}}时{{m}}分",
+ "hours": "{{h}}时",
+ "minutes": "{{m}}分"
+ },
+ "window": {
+ "session": "{{hours}} 小时",
+ "week": "本周",
+ "scoped": "{{model}} 本周"
+ },
+ "headline": {
+ "recommend": "{{name}} 余量最足。",
+ "balance": "Cindy 余额还能用。",
+ "quota": "Cindy 本期配额还能用。",
+ "none": "余量都用完了。",
+ "unread": "还没读到余量。",
+ "empty": "还没有带余量的账号。",
+ "emptyHint": "在 Cindy 里连上订阅,这里就会显示余量。",
+ "restore": "{{name}} {{duration}}后重置",
+ "soon": "{{name}} 快见底",
+ "subscriptionsUsed": "订阅都用完了",
+ "waitReset": "等订阅重置",
+ "sentence": "{{text}}。",
+ "joiner": ","
+ },
+ "cell": {
+ "payg": "按量",
+ "plan": "订阅",
+ "noBalance": "无余额",
+ "unknown": "查不到",
+ "noData": "还没读到余量",
+ "lastsDays": "约{{n}}天",
+ "lastsDaysShort": "{{n}}天",
+ "resetsIn": "{{duration}}后重置",
+ "credits": "credits"
+ },
+ "a11y": {
+ "payg": "{{name}},按量计费,查不到余额",
+ "plan": "{{name}},订阅,查不到余量",
+ "balance": "Cindy 余额 {{amount}}",
+ "balanceDays": "Cindy 余额 {{amount}},约够 {{n}} 天",
+ "quota": "Cindy 本期配额剩余 {{amount}}",
+ "noData": "{{name}},暂无数据",
+ "reserve": "{{name}},已用完,还有 credits 可用",
+ "remaining": "{{name}} 剩余 {{n}}%"
+ },
+ "detail": {
+ "balanceCaption": "余额",
+ "quotaCaption": "本期剩余配额",
+ "apiKey": "API Key",
+ "subscription": "订阅",
+ "noBalance": "查不到余额",
+ "unknownRemaining": "查不到余量",
+ "noData": "暂无数据",
+ "windowLeft": "{{window}}剩余"
+ },
+ "say": {
+ "balance": "余额不会自动回满。",
+ "quota": "配额按周期发放,不在这里充值。",
+ "quotaResets": "配额将于 {{at}} 重置为满额。",
+ "balanceLasts_other": "按近 7 天的消耗,约够 {{n}} 天。",
+ "balanceEstimating": "消耗记录还在积累,过几天就能估算还能用多久。",
+ "payg": "{{name}} 按用量付费。",
+ "paygSub": "它的接口不提供余额,所以这里没有余量;用掉的部分照常计入 Cindy 用量。",
+ "plan": "{{name}} 是订阅连接。",
+ "planSub": "Cindy 还读不到它的余量;用掉的部分照常计入 Cindy 用量。",
+ "noData": "还没读到余量。",
+ "noDataSub": "稍后刷新,或用它跑一次任务后就会显示。",
+ "usedUp": "{{window}}的用量已用完。",
+ "usedUpWithCredits": "{{at}}回满;在那之前 Codex 会扣 {{credits}} credits 继续工作。",
+ "creditsOnly": "Codex 会扣 {{credits}} credits 继续工作。",
+ "resetsAt": "{{at}}回满。",
+ "emptyIn": "按现在的速度,约 {{duration}}后见底。",
+ "beforeReset": "比重置早 {{duration}}。",
+ "full": "满格。",
+ "relaxed": "节奏宽松。",
+ "onPace": "节奏正常。",
+ "windowRefresh": "{{window}}窗口{{at}}刷新",
+ "usedUpWithResets_other": "还有 {{n}} 次额度重置可用,用一次立即回满。"
+ },
+ "fact": {
+ "balance": "余额",
+ "quotaLeft": "本期剩余配额",
+ "quotaTotal": "本期配额",
+ "updatedAgo": "{{ago}}更新",
+ "dailyUse": "日均消耗",
+ "about": "约 {{value}}",
+ "estimating": "估算中",
+ "estimatingSub": "数据还不够",
+ "last7Days": "近 7 天",
+ "runsOut": "预计用完",
+ "aroundDate": "{{date}}前后",
+ "atThisPace": "按当前速度",
+ "usedFor": "用于",
+ "cindyModels": "Cindy 提供的模型",
+ "chargedPerUse": "按实际用量扣费",
+ "billing": "计费",
+ "perUse": "按量",
+ "subscription": "订阅",
+ "connected": "已连接",
+ "notProvided": "接口不提供",
+ "notReadable": "暂时读不到",
+ "inMenu": "在菜单里",
+ "hidden": "已隐藏",
+ "shown": "显示",
+ "editHint": "可在「编辑」里调整",
+ "usage": "用量",
+ "counted": "照常统计",
+ "countedSub": "计入 Cindy 用量",
+ "resetsFull": "回满",
+ "windowResets": "{{window}}重置",
+ "timeLeft": "还有 {{duration}}",
+ "remainingPercent": "剩 {{n}}%",
+ "perModel": "按模型单独计算",
+ "pace": "节奏",
+ "paceNormal": "正常",
+ "paceAhead": "超前 {{n}}%",
+ "paceReserve": "储备 {{n}}%",
+ "paceSub": "均匀用应剩 {{n}}%",
+ "paceUsedUp": "已用完",
+ "paceWaiting": "等待回满",
+ "extraCredits": "额外 credits",
+ "unlimited": "不限",
+ "creditsUsedAfter": "配额用完后由 Codex 扣除",
+ "noCredits": "没有备用 credits",
+ "prepaid": "预付余额",
+ "xaiAccount": "xAI 账户",
+ "account": "账号",
+ "todaySpent": "今日已用",
+ "dailySuggested": "每日建议 {{value}} 以内",
+ "poolPlan": "套餐余额",
+ "poolPlanSub": "随套餐发放",
+ "poolPurchased": "充值余额",
+ "poolPurchasedSub": "自己充值",
+ "poolPromo": "赠送余额",
+ "poolPromoSub": "活动赠送",
+ "promoExpires": "{{value}} {{date}}到期",
+ "promoExpiresAll": "{{date}}到期",
+ "resetCredits": "额度重置",
+ "resetCount_other": "{{n}} 次",
+ "resetExpires": "{{date}}前有效",
+ "resetAtLimit": "达到用量上限时可用",
+ "device": "所在电脑",
+ "deviceSub": "我的其他电脑"
+ },
+ "action": {
+ "newTask": "用 {{name}} 开新任务",
+ "topUp": "在 Cindy 里充值",
+ "manage": "在 Cindy 设置中管理",
+ "openApp": "打开 Cindy",
+ "useReset": "在 Cindy 设置中使用重置"
+ },
+ "tasks": {
+ "today_other": "今天 {{n}} 个",
+ "withRunning_other": "{{base}} · {{n}} 个运行中",
+ "context": "上下文 {{n}}%",
+ "private": "{{harness}} 任务"
+ },
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "usage": {
+ "estimateNote": "订阅等值 = 按 API 参考价折算订阅里用掉的量,不是账单。",
+ "deviceSelf": "这台 {{name}}(实时)",
+ "deviceSynced": "{{name}}(同步到 {{date}})",
+ "deviceNotSynced": "{{name}}(还没同步)",
+ "deviceJoiner": " + ",
+ "allDevices": "全部设备 = {{list}}。"
+ },
+ "manage": {
+ "balance": "余额 · 不会自动回满",
+ "quota": "配额 · 按周期重置",
+ "payg": "API Key · 按量,查不到余额",
+ "plan": "订阅 · 查不到余量",
+ "subscription": "订阅 · {{plan}} · {{windows}}",
+ "onDevice": "{{name}} · {{subtitle}}"
+ },
+ "notify": {
+ "lowTitle": "余量快用完了",
+ "lowBody": "所有还有余量的来源都快见底了。点菜单栏的 Cindy 图标,看看哪些什么时候回满。"
+ },
+ "ui": {
+ "updatedJustNow": "刚刚更新",
+ "updatedMinutes_other": "{{n}} 分钟前更新",
+ "updatedHours_other": "{{n}} 小时前更新",
+ "updatedDays_other": "{{n}} 天前更新",
+ "tasks": "任务",
+ "tokenUnit": "token",
+ "noTasksToday": "今天还没有任务",
+ "moreTasks_other": "另外 {{n}} 个任务",
+ "running": "运行中",
+ "openApp": "打开 Cindy",
+ "gateTitle": "登录后查看余量",
+ "gateBody": "在 Cindy 里登录,或选择跳过登录,这里就会显示订阅余量和今天的用量。",
+ "settings": "管理",
+ "refresh": "刷新",
+ "monthScopeLocal": "近 30 天 · 这台电脑",
+ "monthScopeAll": "近 30 天 · 全部设备",
+ "expand": "展开",
+ "expandUsage": "展开用量",
+ "back": "返回",
+ "usageTitle": "用量",
+ "wideCaptionMoney_other": "近 {{n}} 天 · 订阅等值估算",
+ "wideCaptionTokens_other": "近 {{n}} 天 · Token",
+ "scopeLocal": "这台电脑",
+ "scopeAll": "全部设备",
+ "noUsage": "没有用量",
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "dailyAverage": "日均",
+ "paid": "实付",
+ "tokenUnitTitle": "Token",
+ "peakDay": "最高单日",
+ "range7": "7 天",
+ "range30": "30 天",
+ "range90": "90 天",
+ "metricMoney": "金额",
+ "metricTokens": "Token",
+ "listModels_other": "近 {{n}} 天模型",
+ "listTasks": "今天的任务",
+ "today": "今天",
+ "manageTitle": "管理",
+ "done": "完成",
+ "manageHero": "菜单里显示什么,\n按什么顺序。",
+ "manageHeroSub": "拖动调整顺序;关掉的来源不在菜单里出现,也不参与上面的余量判断。",
+ "sources": "余量来源",
+ "sourcesShown": "{{a}} / {{b}} 显示",
+ "statusIcon": "菜单栏图标",
+ "statusIconSub": "单色,随菜单栏深浅变化",
+ "statusIconMode": {
+ "icon": "只图标",
+ "lowest": "最低余量",
+ "today": "今日用量",
+ "task": "当前任务"
+ },
+ "other": "其他",
+ "lowAlert": "快用完时通知",
+ "lowAlertSub": "所有还有余量的来源都快见底时,发一条系统通知",
+ "privacy": "隐藏个人信息",
+ "privacySub": "账号只显示首尾字母,任务标题也会隐藏,适合录屏和截图",
+ "usageScope": "用量统计范围",
+ "manageFoot": "账号登录和连接在 Cindy 设置 › 模型供应商 里管理。",
+ "showSource": "在菜单里显示 {{name}}",
+ "reorderHint": "拖动,或用操作菜单调整顺序",
+ "moveUp": "上移",
+ "moveDown": "下移"
+ }
+ },
"settings": {
"title": "设置",
"search": {
@@ -1352,6 +1629,10 @@
"wecomGroupClearFailed": "Webhook 移除失败"
},
"windowBehavior": {
+ "menubar": {
+ "label": "在菜单栏显示余量",
+ "hint": "在 macOS 菜单栏放一个 Cindy 图标,点开查看订阅余量、Cindy 余额和今天的用量。"
+ },
"loginItem": {
"label": "自动启动",
"hint": "登录电脑后打开 Cindy,默认关闭",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c8b6c70ad0..a6d3be7051 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -832,6 +832,283 @@
"deny": "拒絕"
}
},
+ "menubar": {
+ "balance": {
+ "name": "Cindy 餘額",
+ "quotaName": "Cindy 本期配額",
+ "short": "Cindy"
+ },
+ "time": {
+ "today": "今天 {{time}}",
+ "tomorrow": "明天 {{time}}",
+ "weekday": "{{day}} {{time}}",
+ "date": "{{date}} {{time}}",
+ "minutesAgo_other": "{{n}} 分鐘前",
+ "hoursAgo_other": "{{n}} 小時前",
+ "daysAgo_other": "{{n}} 天前"
+ },
+ "duration": {
+ "daysHours": "{{d}} 天 {{h}} 小時",
+ "days_other": "{{d}} 天",
+ "hoursMinutes": "{{h}} 小時 {{m}} 分",
+ "hours_other": "{{h}} 小時",
+ "minutes_other": "{{m}} 分鐘"
+ },
+ "durationShort": {
+ "daysHours": "{{d}}天{{h}}時",
+ "days": "{{d}}天",
+ "hoursMinutes": "{{h}}時{{m}}分",
+ "hours": "{{h}}時",
+ "minutes": "{{m}}分"
+ },
+ "window": {
+ "session": "{{hours}} 小時",
+ "week": "本週",
+ "scoped": "{{model}} 本週"
+ },
+ "headline": {
+ "recommend": "{{name}} 餘量最足。",
+ "balance": "Cindy 餘額還能用。",
+ "quota": "Cindy 本期配額還能用。",
+ "none": "餘量都用完了。",
+ "unread": "還沒讀到餘量。",
+ "empty": "還沒有帶餘量的帳號。",
+ "emptyHint": "在 Cindy 裡連上訂閱,這裡就會顯示餘量。",
+ "restore": "{{name}} {{duration}}後重置",
+ "soon": "{{name}} 快見底",
+ "subscriptionsUsed": "訂閱都用完了",
+ "waitReset": "等訂閱重置",
+ "sentence": "{{text}}。",
+ "joiner": ","
+ },
+ "cell": {
+ "payg": "按量",
+ "plan": "訂閱",
+ "noBalance": "無餘額",
+ "unknown": "查不到",
+ "noData": "還沒讀到餘量",
+ "lastsDays": "約{{n}}天",
+ "lastsDaysShort": "{{n}}天",
+ "resetsIn": "{{duration}}後重置",
+ "credits": "credits"
+ },
+ "a11y": {
+ "payg": "{{name}},按量計費,查不到餘額",
+ "plan": "{{name}},訂閱,查不到餘量",
+ "balance": "Cindy 餘額 {{amount}}",
+ "balanceDays": "Cindy 餘額 {{amount}},約夠 {{n}} 天",
+ "quota": "Cindy 本期配額剩餘 {{amount}}",
+ "noData": "{{name}},暫無資料",
+ "reserve": "{{name}},已用完,還有 credits 可用",
+ "remaining": "{{name}} 剩餘 {{n}}%"
+ },
+ "detail": {
+ "balanceCaption": "餘額",
+ "quotaCaption": "本期剩餘配額",
+ "apiKey": "API Key",
+ "subscription": "訂閱",
+ "noBalance": "查不到餘額",
+ "unknownRemaining": "查不到餘量",
+ "noData": "暫無資料",
+ "windowLeft": "{{window}}剩餘"
+ },
+ "say": {
+ "balance": "餘額不會自動回滿。",
+ "quota": "配額按週期發放,不在這裡儲值。",
+ "quotaResets": "配額將於 {{at}} 重置為滿額。",
+ "balanceLasts_other": "按近 7 天的消耗,約夠 {{n}} 天。",
+ "balanceEstimating": "消耗記錄還在積累,過幾天就能估算還能用多久。",
+ "payg": "{{name}} 按用量付費。",
+ "paygSub": "它的接口不提供餘額,所以這裡沒有餘量;用掉的部分照常計入 Cindy 用量。",
+ "plan": "{{name}} 是訂閱連接。",
+ "planSub": "Cindy 還讀不到它的餘量;用掉的部分照常計入 Cindy 用量。",
+ "noData": "還沒讀到餘量。",
+ "noDataSub": "稍後重新整理,或用它跑一次任務後就會顯示。",
+ "usedUp": "{{window}}的用量已用完。",
+ "usedUpWithCredits": "{{at}}回滿;在那之前 Codex 會扣 {{credits}} credits 繼續工作。",
+ "creditsOnly": "Codex 會扣 {{credits}} credits 繼續工作。",
+ "resetsAt": "{{at}}回滿。",
+ "emptyIn": "按现在的速度,約 {{duration}}後見底。",
+ "beforeReset": "比重置早 {{duration}}。",
+ "full": "滿格。",
+ "relaxed": "節奏寬鬆。",
+ "onPace": "節奏正常。",
+ "windowRefresh": "{{window}}週期{{at}}更新",
+ "usedUpWithResets_other": "還有 {{n}} 次額度重置可用,用一次立即回滿。"
+ },
+ "fact": {
+ "balance": "餘額",
+ "quotaLeft": "本期剩餘配額",
+ "quotaTotal": "本期配額",
+ "updatedAgo": "{{ago}}更新",
+ "dailyUse": "日均消耗",
+ "about": "約 {{value}}",
+ "estimating": "估算中",
+ "estimatingSub": "資料還不夠",
+ "last7Days": "近 7 天",
+ "runsOut": "預計用完",
+ "aroundDate": "{{date}}前後",
+ "atThisPace": "按當前速度",
+ "usedFor": "用于",
+ "cindyModels": "Cindy 提供的模型",
+ "chargedPerUse": "按實際用量扣費",
+ "billing": "計費",
+ "perUse": "按量",
+ "subscription": "訂閱",
+ "connected": "已連接",
+ "notProvided": "接口不提供",
+ "notReadable": "暫時讀不到",
+ "inMenu": "在選單裡",
+ "hidden": "已隱藏",
+ "shown": "顯示",
+ "editHint": "可在「編輯」裡調整",
+ "usage": "用量",
+ "counted": "照常統計",
+ "countedSub": "計入 Cindy 用量",
+ "resetsFull": "回滿",
+ "windowResets": "{{window}}重置",
+ "timeLeft": "還有 {{duration}}",
+ "remainingPercent": "剩 {{n}}%",
+ "perModel": "按模型單獨計算",
+ "pace": "節奏",
+ "paceNormal": "正常",
+ "paceAhead": "超前 {{n}}%",
+ "paceReserve": "儲備 {{n}}%",
+ "paceSub": "均匀用應剩 {{n}}%",
+ "paceUsedUp": "已用完",
+ "paceWaiting": "等待回滿",
+ "extraCredits": "額外 credits",
+ "unlimited": "不限",
+ "creditsUsedAfter": "配額用完後由 Codex 扣除",
+ "noCredits": "沒有備用 credits",
+ "prepaid": "預付餘額",
+ "xaiAccount": "xAI 帳戶",
+ "account": "帳號",
+ "todaySpent": "今日已用",
+ "dailySuggested": "每日建議 {{value}} 以內",
+ "poolPlan": "方案餘額",
+ "poolPlanSub": "隨方案發放",
+ "poolPurchased": "儲值餘額",
+ "poolPurchasedSub": "自行儲值",
+ "poolPromo": "贈送餘額",
+ "poolPromoSub": "活動贈送",
+ "promoExpires": "{{value}} {{date}}到期",
+ "promoExpiresAll": "{{date}}到期",
+ "resetCredits": "額度重置",
+ "resetCount_other": "{{n}} 次",
+ "resetExpires": "{{date}}前有效",
+ "resetAtLimit": "達到用量上限時可用",
+ "device": "所在電腦",
+ "deviceSub": "我的其他電腦"
+ },
+ "action": {
+ "newTask": "用 {{name}} 開新任務",
+ "topUp": "在 Cindy 裡儲值",
+ "manage": "在 Cindy 設定中管理",
+ "openApp": "打開 Cindy",
+ "useReset": "在 Cindy 設定中使用重置"
+ },
+ "tasks": {
+ "today_other": "今天 {{n}} 個",
+ "withRunning_other": "{{base}} · {{n}} 個執行中",
+ "context": "上下文 {{n}}%",
+ "private": "{{harness}} 任務"
+ },
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "usage": {
+ "estimateNote": "訂閱等值 = 按 API 參考價折算訂閱裡用掉的量,不是帳單。",
+ "deviceSelf": "這台 {{name}}(實時)",
+ "deviceSynced": "{{name}}(同步到 {{date}})",
+ "deviceNotSynced": "{{name}}(還沒同步)",
+ "deviceJoiner": " + ",
+ "allDevices": "所有裝置 = {{list}}。"
+ },
+ "manage": {
+ "balance": "餘額 · 不會自動回滿",
+ "quota": "配額 · 按週期重置",
+ "payg": "API Key · 按量,查不到餘額",
+ "plan": "訂閱 · 查不到餘量",
+ "subscription": "訂閱 · {{plan}} · {{windows}}",
+ "onDevice": "{{name}} · {{subtitle}}"
+ },
+ "notify": {
+ "lowTitle": "餘量快用完了",
+ "lowBody": "所有還有餘量的來源都快見底了。點選單列的 Cindy 圖示,看看哪些什麼時候回滿。"
+ },
+ "ui": {
+ "updatedJustNow": "剛剛更新",
+ "updatedMinutes_other": "{{n}} 分鐘前更新",
+ "updatedHours_other": "{{n}} 小時前更新",
+ "updatedDays_other": "{{n}} 天前更新",
+ "tasks": "任務",
+ "tokenUnit": "token",
+ "noTasksToday": "今天還沒有任務",
+ "moreTasks_other": "另外 {{n}} 個任務",
+ "running": "執行中",
+ "openApp": "打開 Cindy",
+ "gateTitle": "登入後查看餘量",
+ "gateBody": "在 Cindy 裡登入,或選擇跳過登入,這裡就會顯示訂閱餘量和今天的用量。",
+ "settings": "管理",
+ "refresh": "重新整理",
+ "monthScopeLocal": "近 30 天 · 這台電腦",
+ "monthScopeAll": "近 30 天 · 所有裝置",
+ "expand": "展開",
+ "expandUsage": "展開用量",
+ "back": "返回",
+ "usageTitle": "用量",
+ "wideCaptionMoney_other": "近 {{n}} 天 · 訂閱等值估算",
+ "wideCaptionTokens_other": "近 {{n}} 天 · Token",
+ "scopeLocal": "這台電腦",
+ "scopeAll": "所有裝置",
+ "noUsage": "沒有用量",
+ "harness": {
+ "claude-code": "Claude Code",
+ "codex": "Codex",
+ "pi": "Pi"
+ },
+ "dailyAverage": "日均",
+ "paid": "實付",
+ "tokenUnitTitle": "Token",
+ "peakDay": "最高單日",
+ "range7": "7 天",
+ "range30": "30 天",
+ "range90": "90 天",
+ "metricMoney": "金額",
+ "metricTokens": "Token",
+ "listModels_other": "近 {{n}} 天模型",
+ "listTasks": "今天的任務",
+ "today": "今天",
+ "manageTitle": "管理",
+ "done": "完成",
+ "manageHero": "選單裡顯示什麼,\n按什麼順序。",
+ "manageHeroSub": "拖動調整順序;關掉的來源不在選單裡出現,也不參與上面的餘量判斷。",
+ "sources": "餘量來源",
+ "sourcesShown": "{{a}} / {{b}} 顯示",
+ "statusIcon": "選單列圖示",
+ "statusIconSub": "單色,隨選單列深淺變化",
+ "statusIconMode": {
+ "icon": "只圖標",
+ "lowest": "最低餘量",
+ "today": "今日用量",
+ "task": "當前任務"
+ },
+ "other": "其他",
+ "lowAlert": "快用完時通知",
+ "lowAlertSub": "所有還有餘量的來源都快見底時,發一則系統通知",
+ "privacy": "隱藏個人資訊",
+ "privacySub": "帳號只顯示首尾字母,任務標題也會隱藏,適合錄影和截圖",
+ "usageScope": "用量統計範圍",
+ "manageFoot": "帳號登入和連線在 Cindy 設定 › 模型供應商 裡管理。",
+ "showSource": "在選單裡顯示 {{name}}",
+ "reorderHint": "拖動,或用操作選單調整順序",
+ "moveUp": "上移",
+ "moveDown": "下移"
+ }
+ },
"settings": {
"title": "設定",
"search": {
@@ -1352,6 +1629,10 @@
"wecomGroupClearFailed": "Webhook 移除失敗"
},
"windowBehavior": {
+ "menubar": {
+ "label": "在選單列顯示餘量",
+ "hint": "在 macOS 選單列放一個 Cindy 圖示,點開查看訂閱餘量、Cindy 餘額和今天的用量。"
+ },
"loginItem": {
"label": "自動啟動",
"hint": "登入電腦後開啟 Cindy,預設關閉",
diff --git a/apps/desktop/src/renderer/lib/usageFormat.ts b/apps/desktop/src/renderer/lib/usageFormat.ts
index a41eb2b2b6..7a6a1d5214 100644
--- a/apps/desktop/src/renderer/lib/usageFormat.ts
+++ b/apps/desktop/src/renderer/lib/usageFormat.ts
@@ -5,10 +5,11 @@
*/
import { formatCompactTokens } from '@cindy/maker-shared/usage-format';
-import { stripCodexGatewayWirePrefix } from '@cindy/model-providers';
import type { RegionalMoney } from '../../shared/regionalMoney';
+export { formatModelShort } from '../../shared/usageModelLabel';
+
// token 紧凑口径由 maker-shared 提供(mobile 消息动作行同源复用),这里只再导出,
// 现有 import 路径不变。
export { formatCompactTokens };
@@ -72,24 +73,3 @@ export function formatTurnCostMoney(money: RegionalMoney): string {
return `<${symbol}0.01`;
}
-/**
- * 把 SDK / 网关 model id 收成简短可读标签, 供 tooltip「按模型成本明细」展示。
- * 依次剥掉 SDK 路由后缀 `[..]`、尾部日期 `-YYYYMMDD`、`openai-codex/` / `codex/` 预算前缀, 再美化家族名。
- * 认不出的安全回退原始 id (绝不返回空串)。
- * 'claude-opus-4-8[1m]' → 'Opus 4.8'
- * 'claude-haiku-4-5-20251001' → 'Haiku 4.5'
- * 'gpt-5.5' / 'codex/gpt-5.5' / 'openai-codex/gpt-5.5' → 'GPT-5.5'
- */
-export function formatModelShort(id: string): string {
- if (typeof id !== 'string' || !id.trim()) return id;
- const s = stripCodexGatewayWirePrefix(id.trim()
- .replace(/\[[^\]]*\]\s*$/, '') // 去 [1m] 等 SDK 路由后缀
- .replace(/-\d{6,8}$/, '')); // 去尾部日期 -YYYYMMDD / -YYMMDD
- const claude = s.match(/^claude-(opus|sonnet|haiku)-(\d+)-(\d+)$/i);
- if (claude) {
- const family = claude[1][0].toUpperCase() + claude[1].slice(1).toLowerCase();
- return `${family} ${claude[2]}.${claude[3]}`;
- }
- if (/^gpt-/i.test(s)) return s.toUpperCase();
- return s || id;
-}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 115c0a8370..300eeddccb 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1914,6 +1914,8 @@ interface ElectronAPI {
windowBehavior: {
getLoginItem: () => Promise<import('../shared/loginItem').LoginItemState>;
setLoginItem: (enabled: boolean) => Promise<import('../shared/loginItem').LoginItemState>;
+ getMenubarState: () => Promise<import('../shared/menubarQuota').MenubarState>;
+ setMenubarEnabled: (enabled: boolean) => Promise<import('../shared/menubarQuota').MenubarState>;
setSwallowActivationClick: (enabled: boolean) => Promise<{ ok: true }>;
getWindowsCloseBehavior: () => Promise<'quit' | 'tray' | null>;
setWindowsCloseBehavior: (behavior: 'quit' | 'tray') => Promise<'quit' | 'tray'>;
@@ -2958,7 +2960,7 @@ interface ElectronAPI {
| { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'chat-invite'; token: string }
| { type: 'provider-share-join'; link: string }
- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string },
+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' },
) => void,
) => () => void;
@@ -2977,7 +2979,7 @@ interface ElectronAPI {
| { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'chat-invite'; token: string }
| { type: 'provider-share-join'; link: string }
- | { type: 'settings'; tab: 'voice-input' | 'providers'; connect?: string }
+ | { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing'; connect?: string; intent?: 'topup' }
| null
>;
diff --git a/apps/desktop/src/shared/brandMarkPaths.ts b/apps/desktop/src/shared/brandMarkPaths.ts
new file mode 100644
index 0000000000..26bd59910c
--- /dev/null
+++ b/apps/desktop/src/shared/brandMarkPaths.ts
@@ -0,0 +1,24 @@
+/**
+ * Monochrome brand and agent mark paths (24×24 viewBox) shared by the renderer icon
+ * components and main-process surfaces that draw outside React, such as the macOS menu bar.
+ */
+
+/** Anthropic "A\" wordmark glyph. */
+export const ANTHROPIC_MARK_PATH =
+ 'M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.461H0L6.57 3.52zm4.132 9.876L8.453 7.247 6.205 13.396z';
+
+/** OpenAI blossom. */
+export const OPENAI_MARK_PATH =
+ 'M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.142-.08 4.778-2.758a.795.795 0 0 0 .393-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.495 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.787a4.49 4.49 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.674zm2.01-3.026l-.142-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365l2.602-1.5 2.607 1.5v2.999l-2.607 1.5-2.602-1.5z';
+
+/** Claude Code CLI pixel face; draw with fill-rule evenodd. */
+export const CLAUDE_CODE_MARK_PATH =
+ 'M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0v-3.1h3V5h17.998zM6 10.949h1.488V8.102H6zm10.51 0H18V8.102h-1.49z';
+
+/** Codex CLI flower outline, open at the end so callers can append `z` or the prompt glyphs. */
+export const CODEX_FLOWER_OUTLINE =
+ 'M9.064 3.344a4.6 4.6 0 0 1 2.285-.312q1.5.173 2.673 1.275.016.015.037.021a.1.1 0 0 0 .043 0 4.55 4.55 0 0 1 3.046.275l.047.022.116.057a4.58 4.58 0 0 1 2.188 2.399q.313.765.315 1.595a4.2 4.2 0 0 1-.134 1.223.12.12 0 0 0 .03.115q.89.91 1.183 2.17.433 2.138-.887 3.854l-.136.166a4.55 4.55 0 0 1-2.201 1.388.12.12 0 0 0-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838q-1.78-.009-3.157-1.302a.11.11 0 0 0-.105-.024c-.388.125-.78.143-1.204.138a4.44 4.44 0 0 1-1.945-.466 4.54 4.54 0 0 1-1.61-1.335c-.152-.202-.303-.392-.414-.617a6 6 0 0 1-.37-.961 4.6 4.6 0 0 1-.014-2.298.1.1 0 0 0 .006-.056.1.1 0 0 0-.027-.048 4.5 4.5 0 0 1-1.034-1.651 3.9 3.9 0 0 1-.251-1.192 5.2 5.2 0 0 1 .141-1.6Q3.659 7.92 5.086 6.97q.318-.212.601-.33a6 6 0 0 1 .646-.227.1.1 0 0 0 .065-.066 4.5 4.5 0 0 1 .829-1.615 4.54 4.54 0 0 1 1.837-1.388';
+
+/** Codex CLI `>_` prompt glyphs. */
+export const CODEX_PROMPT_GLYPHS =
+ 'M12.546 13.909a.637.637 0 0 0 0 1.272h3.636a.637.637 0 1 0 0-1.272zM8.462 9.23a.637.637 0 0 0-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 1 0 1.095.649l1.454-2.455a.64.64 0 0 0 .005-.64z';
diff --git a/apps/desktop/src/shared/menubarQuota.ts b/apps/desktop/src/shared/menubarQuota.ts
new file mode 100644
index 0000000000..3b0ec60a18
--- /dev/null
+++ b/apps/desktop/src/shared/menubarQuota.ts
@@ -0,0 +1,236 @@
+/**
+ * macOS menu bar quota panel: settings and the view model main sends to the native helper.
+ *
+ * Main owns every product decision and sentence (it reads usage, applies the user's
+ * order/visibility and localizes). The Swift helper only renders, animates and formats the
+ * few values that change while the panel stays open (relative "updated" time, a running
+ * task's clock, chart scrub readouts).
+ */
+
+export const MENUBAR_STATUS_TEXT_MODES = ['icon', 'lowest', 'today', 'task'] as const;
+export type MenubarStatusTextMode = (typeof MENUBAR_STATUS_TEXT_MODES)[number];
+
+export const MENUBAR_USAGE_SCOPES = ['local', 'all'] as const;
+export type MenubarUsageScope = (typeof MENUBAR_USAGE_SCOPES)[number];
+
+/** Effective menu bar settings. Persisted as overrides only; absent keys use the defaults. */
+export interface MenubarSettings {
+ enabled: boolean;
+ /** Source ids in the user's order. Unknown ids are kept so a reconnect restores the slot. */
+ order: string[];
+ /** Source ids the user turned off. Pay-as-you-go connections start hidden. */
+ hidden: string[];
+ /** Source ids the user turned back on after being hidden by default. */
+ shown: string[];
+ statusText: MenubarStatusTextMode;
+ lowAlert: boolean;
+ privacy: boolean;
+ scope: MenubarUsageScope;
+}
+
+export const DEFAULT_MENUBAR_SETTINGS: MenubarSettings = {
+ enabled: true,
+ order: [],
+ hidden: [],
+ shown: [],
+ statusText: 'icon',
+ lowAlert: true,
+ privacy: false,
+ scope: 'all',
+};
+
+export type MenubarSettingsPatch = Partial<MenubarSettings>;
+
+/** Semantic colors. The helper maps them to dynamic NSColors for Light and Dark. */
+export type MenubarColor =
+ | 'ink'
+ | 'ink2'
+ | 'ink3'
+ | 'fill'
+ | 'warn'
+ | 'error'
+ | 'claude'
+ | 'claude2'
+ | 'claude3'
+ | 'codex'
+ | 'pi';
+
+export type MenubarLevel = 'normal' | 'warn' | 'error';
+
+export type MenubarSourceKind = 'subscription' | 'balance' | 'payg';
+
+export interface MenubarSourceCell {
+ id: string;
+ kind: MenubarSourceKind;
+ /** Complete monochrome SVG, rendered as a template image. */
+ logoSvg: string;
+ /** Account or brand label under the tube (already masked in privacy mode). */
+ name: string;
+ /** Number above the tube; null shows `valueLabel` instead (credits, pay-as-you-go). */
+ value: string | null;
+ valueUnit: string | null;
+ valueLabel: string | null;
+ level: MenubarLevel;
+ /** Liquid height 0...1; null draws the dashed empty tube for pay-as-you-go. */
+ fill: number | null;
+ /** Diagonal hatch: the window is used up but extra credits keep the account working. */
+ reserve: boolean;
+ /** Outline the tube: the source with the most room left. */
+ emphasized: boolean;
+ when: string;
+ whenLevel: MenubarLevel;
+ accessibilityLabel: string;
+}
+
+export interface MenubarRing {
+ /** 0...1 remaining. */
+ fraction: number;
+ color: MenubarColor;
+}
+
+export interface MenubarFact {
+ label: string;
+ value: string;
+ sub: string;
+}
+
+export type MenubarDetailAction =
+ | { kind: 'new-task'; providerId: string }
+ | { kind: 'open-billing' }
+ | { kind: 'open-settings' }
+ | { kind: 'open-app' }
+ | { kind: 'none' };
+
+export interface MenubarDetail {
+ id: string;
+ logoSvg: string;
+ title: string;
+ plan: string;
+ rings: MenubarRing[];
+ bigValue: string;
+ bigUnit: string | null;
+ bigColor: MenubarColor | null;
+ /** Smaller numerals for multi-ring and balance details. */
+ bigCompact: boolean;
+ bigCaption: string;
+ legend: { label: string; color: MenubarColor }[];
+ sayPrimary: string;
+ saySecondary: string | null;
+ facts: MenubarFact[];
+ actionLabel: string;
+ action: MenubarDetailAction;
+}
+
+export interface MenubarTask {
+ sessionId: string;
+ title: string;
+ harness: 'claude-code' | 'codex' | 'pi';
+ logoSvg: string;
+ /** Estimated value today, in the ledger currency. */
+ value: number;
+ tokens: number;
+ running: boolean;
+ /** Present while running; the helper ticks the clock. */
+ startedAtMs: number | null;
+ /** Shown instead of the clock when not running ("5 分钟前"). */
+ idleStatus: string;
+ /** "GPT-6 Astra · 299M · 上下文 85%"; the helper prefixes the status. */
+ meta: string;
+}
+
+export interface MenubarModelUsage {
+ name: string;
+ harness: 'claude-code' | 'codex' | 'pi';
+ money: number;
+ tokens: number;
+}
+
+export interface MenubarUsageScopeData {
+ /** One entry per day, oldest first, aligned with `MenubarUsage.days`. */
+ daily: {
+ /** Subscription-equivalent value by harness: claude-code, codex, pi. */
+ money: [number, number, number];
+ /** Actually paid (API) part of `money`, summed across harnesses. */
+ paid: number;
+ tokens: [number, number, number];
+ }[];
+ /** Model totals for the last 7, 30 and 90 days. */
+ models: { '7': MenubarModelUsage[]; '30': MenubarModelUsage[]; '90': MenubarModelUsage[] };
+ /** Footnote describing which devices the scope covers. */
+ note: string;
+}
+
+export interface MenubarUsage {
+ /** ISO dates (YYYY-MM-DD), oldest first, ending today. */
+ days: string[];
+ scopes: Record<MenubarUsageScope, MenubarUsageScopeData>;
+}
+
+export interface MenubarManageRow {
+ id: string;
+ logoSvg: string;
+ title: string;
+ subtitle: string;
+ value: string;
+ hidden: boolean;
+}
+
+export interface MenubarStrings {
+ [key: string]: string;
+}
+
+export interface MenubarView {
+ /** BCP 47 locale for dates and numbers. */
+ locale: string;
+ /** Symbol of the usage ledger currency: "$" on Global, "¥" in mainland China. */
+ moneySymbol: string;
+ strings: MenubarStrings;
+ /** Text after the menu bar icon for each mode; the active one is `settings.statusText`. */
+ statusTextByMode: Record<MenubarStatusTextMode, string | null>;
+ updatedAtMs: number | null;
+ headlinePrimary: string;
+ headlineSecondary: string | null;
+ sources: MenubarSourceCell[];
+ details: Record<string, MenubarDetail>;
+ taskSummary: string;
+ tasks: MenubarTask[];
+ usage: MenubarUsage;
+ manage: MenubarManageRow[];
+ settings: MenubarSettings;
+ /**
+ * Set while nothing may be read yet: "sign-in" until the user signs in or skips sign-in.
+ * The panel then shows only the prompt and the icon carries no text.
+ */
+ gate?: MenubarGate;
+}
+
+export type MenubarGate = 'sign-in';
+
+/** Messages the helper sends to main. */
+export type MenubarHelperMessage =
+ | { type: 'ready' }
+ | { type: 'error'; message: string }
+ | { type: 'panel'; open: boolean }
+ | { type: 'refresh' }
+ | { type: 'open-app' }
+ | { type: 'open-session'; sessionId: string }
+ | { type: 'detail-action'; sourceId: string }
+ | { type: 'open-provider-settings' }
+ | { type: 'settings'; patch: MenubarSettingsPatch };
+
+/** Settings → Window behavior toggle; only the local app renderer may call these. */
+export const MENUBAR_GET_STATE_CHANNEL = 'menubar:get-state';
+export const MENUBAR_SET_ENABLED_CHANNEL = 'menubar:set-enabled';
+
+export interface MenubarState {
+ /** macOS 14 or later; the helper relies on SwiftUI APIs introduced in Sonoma. */
+ available: boolean;
+ enabled: boolean;
+}
+
+/** Darwin 23 is macOS 14 Sonoma. */
+export function isMenubarSupportedPlatform(platform: string, osRelease: string): boolean {
+ if (platform !== 'darwin') return false;
+ const major = Number.parseInt(osRelease.split('.')[0] ?? '', 10);
+ return Number.isFinite(major) && major >= 23;
+}
diff --git a/apps/desktop/src/shared/providerQuotaSource.ts b/apps/desktop/src/shared/providerQuotaSource.ts
new file mode 100644
index 0000000000..10171a01e8
--- /dev/null
+++ b/apps/desktop/src/shared/providerQuotaSource.ts
@@ -0,0 +1,27 @@
+import type { ProviderView } from '@cindy/model-providers';
+
+/**
+ * Which subscription usage reader describes a connection, or null when Cindy cannot read
+ * its remaining quota. Shared by the model picker, settings and the macOS menu bar.
+ */
+export function providerWeeklyQuotaSource(
+ provider: ProviderView,
+): 'codex' | 'claude' | 'xai' | null {
+ if (
+ !provider.connected ||
+ provider.suspended ||
+ provider.openAiAccount?.reconnectRequired ||
+ provider.auth.method !== 'oauth' ||
+ (provider.access && provider.access.kind !== 'subscription')
+ )
+ return null;
+ if (provider.id === 'openai' || provider.auth.native === 'codex') return 'codex';
+ if (provider.auth.native === 'claude') return 'claude';
+ if (provider.auth.native === 'xai') return 'xai';
+ // These APIs currently describe only the built-in native account, not any
+ // arbitrary same-brand API/OAuth connection a user may add.
+ if (provider.source !== 'builtin') return null;
+ if (provider.id === 'anthropic') return 'claude';
+ if (provider.id === 'xai') return 'xai';
+ return null;
+}
diff --git a/apps/desktop/src/shared/usageModelLabel.ts b/apps/desktop/src/shared/usageModelLabel.ts
new file mode 100644
index 0000000000..4f8062d86f
--- /dev/null
+++ b/apps/desktop/src/shared/usageModelLabel.ts
@@ -0,0 +1,23 @@
+import { stripCodexGatewayWirePrefix } from '@cindy/model-providers';
+
+/**
+ * 把 SDK / 网关 model id 收成简短可读标签, 供 tooltip「按模型成本明细」展示。
+ * 依次剥掉 SDK 路由后缀 `[..]`、尾部日期 `-YYYYMMDD`、`openai-codex/` / `codex/` 预算前缀, 再美化家族名。
+ * 认不出的安全回退原始 id (绝不返回空串)。
+ * 'claude-opus-4-8[1m]' → 'Opus 4.8'
+ * 'claude-haiku-4-5-20251001' → 'Haiku 4.5'
+ * 'gpt-5.5' / 'codex/gpt-5.5' / 'openai-codex/gpt-5.5' → 'GPT-5.5'
+ */
+export function formatModelShort(id: string): string {
+ if (typeof id !== 'string' || !id.trim()) return id;
+ const s = stripCodexGatewayWirePrefix(id.trim()
+ .replace(/\[[^\]]*\]\s*$/, '') // 去 [1m] 等 SDK 路由后缀
+ .replace(/-\d{6,8}$/, '')); // 去尾部日期 -YYYYMMDD / -YYMMDD
+ const claude = s.match(/^claude-(opus|sonnet|haiku)-(\d+)-(\d+)$/i);
+ if (claude) {
+ const family = claude[1][0].toUpperCase() + claude[1].slice(1).toLowerCase();
+ return `${family} ${claude[2]}.${claude[3]}`;
+ }
+ if (/^gpt-/i.test(s)) return s.toUpperCase();
+ return s || id;
+}
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index e9f31a8f77..751a561198 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -531,6 +531,14 @@ Reference implementation: `apps/desktop/src/renderer/components/ui/confirm-dialo
The usage heatmap, daily-token bars and their separate interaction indicators follow [the Usage History component specification](./usage-history-charts.md). Their 2px data-mark geometry is set by the §5 registered data-mark members (`usage-heatmap-day` / `usage-token-bar`); the bounded hover/focus/selection emphasis is registered with those members in §5 (interaction constraints), and the extensible model palette, fixed Agent/harness colors and heatmap blue are the §2 Usage History color registration. Date filtering enters through the charts themselves (cell / bar hit targets), the range selector on the page, and the DS-11-restored 36px labelled date field beside it, which writes the same single-day filter as chart activation and shares the charts' selected-day state — the previously owed equivalent entry (the component spec keeps the unchanged hit-target geometry and the pending platform/user acceptance record).
+### macOS menu bar quota panel (owner-approved v6 prototype, 2026-10-11)
+
+- A native status item (`NSStatusItem`) and panel rendered by the Swift helper in `apps/desktop/native/menubar/`, not an HTML window. Main builds every sentence and value; the helper renders, animates and formats only times that tick while the panel is open. Available on macOS 14+ and toggled in Settings → Window behavior (default on).
+- The panel uses the system popover material (`NSVisualEffectView`, `.popover`) with a 0.5pt hairline edge, so it follows the desktop wallpaper and Light/Dark automatically. Native SwiftUI controls (segmented `Picker`, `Toggle`, Swift Charts) are used as-is; their system geometry is not restyled to Web tokens.
+- The menu bar icon and every provider/harness logo are template images (monochrome, tinted by the system). Brand red appears only in the Cindy wordmark, a fixed Light/Dark image pair; it is never used for state.
+- Status colors are fixed native values shared by both appearances: warning `#EA6B17` (15% or less left, or a pace that runs out before reset) and error `#D91F37` (used up). Agent/harness fills reuse the identity colors of the §2 Usage History registration: `--engine-badge-cc` `#D97757` (with two lighter steps for Claude's session/per-model rings), `--engine-badge-codex` `#7A9DFF` and `--usage-model-1` teal for Pi; neutral ink fills carry no state.
+- Copy is truthful: Cindy does not switch accounts automatically and has no default account per service, so the headline recommends the source with the most room ("{{name}} has the most left.") instead of claiming which one is in use.
+
### Desktop chat and operation authorization (DS-9, 2026-09-11)
Chat prose and compact code use the existing `chatChrome.ts` presentation entry; activity rows reuse `activityRowChrome.ts`. Keep user/assistant, tool, code, thinking and media theme aliases local. Icon actions use the ordinary pill frame with their contextual targets, visible keyboard focus and a Tip; a hidden message action bar becomes visible when keyboard focus enters it. Media previews and content-clipping cards retain their content geometry under §5. Do not change message identity, streaming, history, Diff Worker/virtualization or media/file lifecycles to share presentation.
@@ -1067,6 +1075,8 @@ long duration to leak into any other hover or transition.
**Mobile image viewer edge elasticity (owner request, 2026-10-10).** In the mobile full-screen image viewer (`apps/mobile/src/session/ImageLightbox.tsx`), direct manipulation follows the system Photos physics instead of hard stops: a zoomed one-finger pan may run past the image edge with rubber-band resistance (UIScrollView coefficient 0.55 over the container size), and a pinch may overshoot 1x / the maximum zoom with the same resistance. On release, anything out of bounds returns on a near-critically damped spring (no visible oscillation, about 0.3s); an in-bounds release continues with inertial decay that may briefly overrun the edge and return; a touch catches it in place. Scale and translation settle on the same spring so the point under the fingers stays put. These are physics responses to the hand, not duration-tier transitions, so they use spring/decay parameters rather than motion tokens; the parameters and decisions live in `imageLightboxModel.ts`. A single image at 1x keeps the native horizontal edge bounce. This exception does not apply to any other surface.
+**macOS menu bar quota fill (owner request, 2026-10-11).** The native menu bar panel (`apps/desktop/native/menubar/`) fills its usage tubes and detail rings from empty over 0.5s with `timingCurve(0.22, 1, 0.36, 1)` (no overshoot) each time the panel opens or a page loads; page switches use the same curve and duration. This is a one-shot loading reveal in SwiftUI, not a Web duration tier: the Web tokens do not apply inside the native helper. Reduced motion shows the final values without animation. This exception does not apply to any other surface.
+
#### Semantics → motion prototypes (one semantic, one motion, app-wide)
| Semantic | Spec | Reference implementation |
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 950012c7b6..871c1f05ad 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -196,6 +196,9 @@ Desktop 的运行时 refresh 遇到瞬时失败后,主动调用与定时重试
| 跨 profile 的 worktree 回收日志位置 | `app.getPath('appData')/Cindy/shared-worktree-recycle-journals`,仍按日志目录哈希发布原 profile 日志位置,兼容可能同时运行的旧客户端;新客户端不再读取其他 profile 的日志来借用工程。不复制恢复状态、不代替 owner 执行恢复 |
| 供应商分享:分享者电脑上的受邀者用量 | `userData/remote-agent/provider-share-usage.json`,按(日期、分享、成员、Agent、供应商、模型)聚合 token 与轮次,行内 `byMember` 按组内电脑的键再分(2026-10-11 加;行键与合计不变,旧版本照常累计并原样写回,合计多出各台之和的部分算没区分电脑),原子替换写入,保留 400 天;只含服务端生成的分享与成员 id,不含昵称、对话或凭证。成员删除后保留(管理页不再显示),同一人重新加入时接续 |
| 供应商按使用方的用量 | `userData/owners/<账号>/provider-usage-by-party.json`,按(日期、供应商、使用方、设备 id、组内电脑的键、Agent、模型)聚合 token 与轮次。使用方:本机、同账号另一台电脑、经同账号组所在电脑转来的受邀者任务、本机经另一台电脑的组在别的组内电脑上运行的(只用来报告给那台组所在电脑)、同账号电脑报告来的(每次报告整体替换那台从某天起的行);没有使用方字段的旧行按设备 id 推出。原子替换写入,保留 400 天;只含供应商 id、设备 id、组内电脑的键与模型名,不含对话或凭证。按账号存放(供应商 id 在不同账号下会重复),从开始记录起不补历史 |
+| macOS 菜单栏余量设置 | `userData/menubar-settings.json`,本机偏好:是否显示、来源顺序与显隐、菜单栏文字、快见底通知、隐藏个人信息、统计范围;只含供应商 id,不含凭证或用量数值 |
+| macOS 菜单栏 Cindy 余额样本 | `userData/owners/<账号>/menubar-credit-samples.json`,只记录观测到的余额数值与时间(按区域与币种分组),用于估算日均消耗;保留 30 天、原子替换写入,不含凭证或账号标识 |
+| macOS 菜单栏 helper(开发构建) | `userData/menubar/`,开发时由 `swiftc` 编译的 helper 及其 wordmark 图片和源码哈希;打包版改用 `resources/tools/menubar/`,不在 userData 落盘 |
| 供应商分享:受邀者会话登记 | `userData/remote-agent/guest-sessions.json`(控制端摘要 → 本机侧任务与原生会话 id),只用来限制受邀者只能恢复自己的会话,并在分享删除时精确清理影子工作区、附件与会话记录 |
| 供应商分享:跨区域标记 | `userData/remote-agent/provider-share-regions.json`,账号摘要 → 对方区域;**不含凭证**。跨区连接凭证只在内存里,用新身份名片重新换取;没有标记的账号从不联系对方区域 |
| 用户明确导出的文件 | 用户选择或任务明确指定的目标路径 |
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index c87edf69de..08cf4049b6 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -79,6 +79,10 @@
| **Credits** | zh-TW | 點數 | 默认 |
| Credits | zh-TW | credits | 指第三方服務自身的 credits(如 Codex / ChatGPT 訂閱餘量),保留其原生叫法 |
| Credits | zh-TW | 重置次數 | reset credits——指可用的配額重置次數,與計費點數無關 |
+| **Credits** | ja | クレジット | 默认 |
+| Credits | ja | credits | サードパーティ自身の credits(Codex / ChatGPT のサブスクリプション残量など)は原語のまま表記する |
+| **Credits** | ko | 크레딧 | 默认 |
+| Credits | ko | credits | 서드파티 자체의 credits(Codex / ChatGPT 구독 잔량 등)는 원래 이름 그대로 표기 |
| **Provider** | zh-CN | 供应商 | 默认 |
| Provider | zh-CN | 模型供应商 | 首次出现或需要消歧时用全称,如设置页标题 |
| **Provider** | zh-TW | 供應商 | 默认 |
diff --git a/i18n/glossary.json b/i18n/glossary.json
index c2336402af..bb361b481f 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -916,6 +916,18 @@
"text": "重置次數",
"when": "reset credits——指可用的配額重置次數,與計費點數無關"
}
+ ],
+ "ja": [
+ {
+ "text": "credits",
+ "when": "サードパーティ自身の credits(Codex / ChatGPT のサブスクリプション残量など)は原語のまま表記する"
+ }
+ ],
+ "ko": [
+ {
+ "text": "credits",
+ "when": "서드파티 자체의 credits(Codex / ChatGPT 구독 잔량 등)는 원래 이름 그대로 표기"
+ }
]
},
"forbidden": {