CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
Add usage chart and quota notifications
Bob9b9f78bc978f
diff --git a/AGENTS.md b/AGENTS.mdindex e8cfc20..0937de4 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -12,11 +12,14 @@ CodexBar 是一个 macOS 菜单栏应用,用来展示当前本机 Codex 账号- 弹窗第一行展示账号信息和套餐。- 弹窗展示两行分段电量条,额度行标签根据 `windowDurationMins` 动态生成。- 每行额度在进度条右侧展示剩余百分比和重置时间。+- 弹窗展示最近 14 个完整自然日的 token 柱状图、累计 token 和单日峰值 token。+- 鼠标划过 token 柱状图中的单日柱子时,展示对应日期和用量。- 更新时间显示在左侧。- 应用运行时每分钟自动刷新,即使弹窗未打开也会刷新。+- 收到 `account/rateLimits/updated` 后会重新查询额度,并在「额度通知」已开启时发送 macOS 本地通知。- 双击账号图标可手动刷新。- 按住 Option/Alt 点击菜单栏图标时,才展示控制区。-- Option/Alt 控制区包含「开机启动」开关和「退出」按钮,不展示刷新按钮。+- Option/Alt 设置区左侧上下排列「开机启动」和「额度通知」开关,右下方展示「退出」按钮,不展示刷新按钮。- 弹窗错误只展示普通红色错误文案,不包含 Debug 明细或环境变量模拟入口。## Codex 数据来源@@ -42,10 +45,18 @@ codex app-server --listen stdio://{"method":"initialized"}{"method":"account/read","id":2,"params":{"refreshToken":false}}{"method":"account/rateLimits/read","id":3}+{"method":"account/usage/read","id":4}```注意:不能在 `initialize` 和 `initialized` 完成前请求额度,否则 Codex app-server 会拒绝请求。+每日 token 统计使用 `account/usage/read`,读取 `summary.lifetimeTokens`、`summary.peakDailyTokens` 和 `dailyUsageBuckets`。+如果本机 Codex app-server 不支持 `account/usage/read`,token 统计区域不展示,额度信息仍正常显示。++`account/rateLimits/updated` 是 app-server notification,不是可请求方法。应用后台保留一个 app-server 连接监听该 notification;收到后重新调用 `account/rateLimits/read` 获取完整额度并更新 UI,在「额度通知」开启且系统通知权限已授权时发送本地通知。不要直接用 notification 中的稀疏 `rateLimits` payload 覆盖完整快照。++后台监听连接启动时也必须按 `account/read`、`account/rateLimits/read` 的顺序初始化额度路径;如果监听连接因为 app-server 退出、认证失败或响应超时而断开,应用会在 30 秒后重新启动监听连接。+## 认证和沙盒CodexBar 必须使用真实 macOS 用户的 Codex 登录数据。之前遇到过 Xcode 运行时 `HOME` 指向 app container,导致 app-server 读取不到 `/Users/{username}/.codex`,报错:@@ -90,11 +101,15 @@ Xcode target 已关闭 App Sandbox,因为应用需要启动本机 Codex CLI- 额度行标签示例:`300` 分钟显示 `5 小时`,`10080` 分钟显示 `7 天`;缺少 `windowDurationMins` 时再回退到默认文案。- 重置时间格式使用 `MM-dd HH:mm`。- 更新时间格式使用 `HH:mm:ss`。+- token 数按 `M`、`B` 紧凑单位展示。+- token 柱状图使用橙色,单日用量越高颜色越浓。## 错误和调试- 当前代码不包含 Debug UI、Debug 详情展示或环境变量模拟错误入口。- Codex 交互错误会通过 `CodexRateLimitError.localizedDescription` 展示在弹窗中。+- 每分钟自动刷新失败时,如果已有旧额度快照,旧快照不会被清空;弹窗继续显示上一次成功读取的数据和对应更新时间,同时展示错误文案。+- `account/rateLimits/updated` 触发的刷新如果失败,不会更新 UI,也不会发送通知;只有当前没有旧快照时才会把错误展示到弹窗中。- 开机启动设置失败会展示 `设置开机启动失败: ...`。## 构建验证diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex c1b7d0d..3b2136a 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -263,12 +263,12 @@INFOPLIST_KEY_CFBundleDisplayName = CodexBar;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_LSUIElement = YES;- INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 Bob. All rights reserved.";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.0.0;+ MARKETING_VERSION = 1.1.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -300,12 +300,12 @@INFOPLIST_KEY_CFBundleDisplayName = CodexBar;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_LSUIElement = YES;- INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSHumanReadableCopyright = "Copyright © 2026 Bob. All rights reserved.";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.0.0;+ MARKETING_VERSION = 1.1.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swiftindex 8368878..9110d72 100644--- a/CodexBar/CodexRateLimitService.swift+++ b/CodexBar/CodexRateLimitService.swift@@ -10,9 +10,9 @@ import Foundationstruct CodexRateLimitService: Sendable {private nonisolated static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"-+nonisolated init() {}-+nonisolated func fetchRateLimits() async throws -> CodexQuotaSnapshot {return try await Task.detached(priority: .utility) {let environment = Self.appServerEnvironment()@@ -27,51 +27,138 @@ struct CodexRateLimitService: Sendable {)}.value}-++ nonisolated func observeRateLimitUpdates(onUpdate: @escaping @Sendable () -> Void) async {+ let environment = Self.appServerEnvironment()+ let clientVersion = Self.clientVersion()++ while !Task.isCancelled {+ do {+ let command = try Self.resolveAppServerCommand(environment: environment)+ try Self.observeRateLimitUpdatesSynchronously(+ command: command,+ environment: environment,+ clientVersion: clientVersion,+ timeout: 20,+ onUpdate: onUpdate+ )+ } catch {+ guard !Task.isCancelled else {+ return+ }++ try? await Task.sleep(nanoseconds: 30_000_000_000)+ }+ }+ }+private nonisolated static func fetchRateLimitsSynchronously(command: AppServerCommand,environment: [String: String],clientVersion: String,timeout: TimeInterval) throws -> CodexQuotaSnapshot {+ try withRateLimitsSession(+ command: command,+ environment: environment,+ clientVersion: clientVersion,+ timeout: timeout+ ) { connection in+ let usageResponse = try? connection.session.request(+ "account/usage/read",+ as: AccountUsageResponse.self+ )++ return try CodexQuotaSnapshot(+ accountResponse: connection.accountResponse,+ rateLimitsResponse: connection.rateLimitsResponse,+ usageResponse: usageResponse+ )+ }+ }++ private nonisolated static func observeRateLimitUpdatesSynchronously(+ command: AppServerCommand,+ environment: [String: String],+ clientVersion: String,+ timeout: TimeInterval,+ onUpdate: @escaping @Sendable () -> Void+ ) throws {+ try withRateLimitsSession(+ command: command,+ environment: environment,+ clientVersion: clientVersion,+ timeout: timeout+ ) { connection in+ let decoder = JSONDecoder()+ while !Task.isCancelled {+ guard let line = connection.lineReader.nextLine(timeout: 0.5) else {+ if !connection.process.isRunning {+ let stderr = connection.errorReader.text.trimmingCharacters(in: .whitespacesAndNewlines)+ throw CodexRateLimitError.serverTimeout(stderr.isEmpty ? "account/rateLimits/updated" : stderr)+ }++ continue+ }++ guard let data = line.data(using: .utf8),+ let notification = try? decoder.decode(RPCNotificationEnvelope.self, from: data),+ notification.method == "account/rateLimits/updated" else {+ continue+ }++ onUpdate()+ }+ }+ }++ /// 启动 app-server 进程并完成 initialize、account/read、account/rateLimits/read+ /// (含认证失败重试)初始化序列,fetch 和监听两条路径共用,保证握手始终一致。+ private nonisolated static func withRateLimitsSession<T>(+ command: AppServerCommand,+ environment: [String: String],+ clientVersion: String,+ timeout: TimeInterval,+ body: (AppServerConnection) throws -> T+ ) throws -> T {let process = Process()process.executableURL = URL(fileURLWithPath: command.executablePath)process.arguments = command.argumentsprocess.environment = environment-+let standardInput = Pipe()let standardOutput = Pipe()let standardError = Pipe()let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)let errorReader = PipeTextCollector(fileHandle: standardError.fileHandleForReading)-+process.standardInput = standardInputprocess.standardOutput = standardOutputprocess.standardError = standardError-+do {try process.run()} catch {throw CodexRateLimitError.serverStartFailed(error.localizedDescription)}-+defer {lineReader.stop()errorReader.stop()try? standardInput.fileHandleForWriting.close()-+if process.isRunning {process.terminate()}}-+let session = AppServerSession(input: standardInput,lineReader: lineReader,errorReader: errorReader,timeout: timeout)-+_ = try session.request("initialize",params: [@@ -83,15 +170,15 @@ struct CodexRateLimitService: Sendable {],as: EmptyResponse.self)-+try session.notify("initialized")-+var accountResponse = try session.request("account/read",params: ["refreshToken": false],as: AccountReadResponse.self)-+let rateLimitsResponse: AccountRateLimitsResponsedo {rateLimitsResponse = try session.request(@@ -104,7 +191,7 @@ struct CodexRateLimitService: Sendable {params: ["refreshToken": true],as: AccountReadResponse.self)-+do {rateLimitsResponse = try session.request("account/rateLimits/read",@@ -114,13 +201,19 @@ struct CodexRateLimitService: Sendable {throw CodexRateLimitError.authenticationRequired}}-- return try CodexQuotaSnapshot(- accountResponse: accountResponse,- rateLimitsResponse: rateLimitsResponse++ return try body(+ AppServerConnection(+ process: process,+ session: session,+ lineReader: lineReader,+ errorReader: errorReader,+ accountResponse: accountResponse,+ rateLimitsResponse: rateLimitsResponse+ ))}-+private nonisolated static func appServerEnvironment() -> [String: String] {var environment = ProcessInfo.processInfo.environmentlet homeDirectory = realUserHomeDirectory()@@ -136,34 +229,34 @@ struct CodexRateLimitService: Sendable {"/usr/sbin","/sbin"]-+environment["HOME"] = homeDirectoryenvironment["USER"] = NSUserName()environment["LOGNAME"] = NSUserName()environment["PATH"] = mergedPath(path, fallbackPaths: fallbackPaths)environment["TERM"] = environment["TERM"] ?? "xterm-256color"-+return environment}-+private nonisolated static func resolveAppServerCommand(environment: [String: String]) throws -> AppServerCommand {let cliPath = findExecutable(named: "codex", environment: environment)-+if let cliPath, standardizedPath(cliPath) != standardizedPath(bundledExecutablePath) {return AppServerCommand(executablePath: cliPath)}-+if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {return AppServerCommand(executablePath: bundledExecutablePath)}-+if let cliPath {return AppServerCommand(executablePath: cliPath)}-+throw CodexRateLimitError.executableNotFound}-+private nonisolated static func findExecutable(named executableName: String,environment: [String: String]@@ -171,52 +264,52 @@ struct CodexRateLimitService: Sendable {guard let path = environment["PATH"] else {return nil}-+for directory in path.split(separator: ":") {let executablePath = "\(directory)/\(executableName)"if FileManager.default.isExecutableFile(atPath: executablePath) {return executablePath}}-+return nil}-+private nonisolated static func mergedPath(_ path: String, fallbackPaths: [String]) -> String {var components: [String] = []var seen = Set<String>()-+for component in path.split(separator: ":").map(String.init) + fallbackPaths {guard !component.isEmpty, !seen.contains(component) else {continue}-+components.append(component)seen.insert(component)}-+return components.joined(separator: ":")}-+private nonisolated static func standardizedPath(_ path: String) -> String {URL(fileURLWithPath: path).standardizedFileURL.path}-+private nonisolated static func clientVersion() -> String {guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,!version.isEmpty else {return "1.0.0"}-+return version}-+private nonisolated static func realUserHomeDirectory() -> String {guard let passwd = getpwuid(getuid()),let home = passwd.pointee.pw_dir else {return NSHomeDirectory()}-+return String(cString: home)}}@@ -227,18 +320,18 @@ private nonisolated final class AppServerSession {private let errorReader: PipeTextCollectorprivate let timeout: TimeIntervalprivate var nextId = 1-+init(input: Pipe, lineReader: JSONLineReader, errorReader: PipeTextCollector, timeout: TimeInterval) {self.input = inputself.lineReader = lineReaderself.errorReader = errorReaderself.timeout = timeout}-+func notify(_ method: String, params: [String: Any]? = nil) throws {try write(message(method: method, id: nil, params: params))}-+func request<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -249,7 +342,7 @@ private nonisolated final class AppServerSession {try write(message(method: method, id: id, params: params))return try waitForResponse(id: id, step: method, decode: type)}-+private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {var object: [String: Any] = ["method": method]if let id {@@ -260,13 +353,13 @@ private nonisolated final class AppServerSession {}return object}-+private func write(_ object: [String: Any]) throws {var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])data.append(0x0A)input.fileHandleForWriting.write(data)}-+private func waitForResponse<Response: Decodable>(id: Int,step: String,@@ -274,36 +367,36 @@ private nonisolated final class AppServerSession {) throws -> Response {let deadline = Date().addingTimeInterval(timeout)let decoder = JSONDecoder()-+while Date() < deadline {guard let line = lineReader.nextLine(timeout: 0.2) else {continue}-+guard let data = line.data(using: .utf8) else {continue}-+if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: data),errorEnvelope.id == id,let error = errorEnvelope.error {throw CodexRateLimitError.serverError(error.message)}-+guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: data),envelope.id == id,let result = envelope.result else {continue}-+return result}-+let stderr = errorReader.text.trimmingCharacters(in: .whitespacesAndNewlines)if stderr.isEmpty {throw CodexRateLimitError.serverTimeout(step)}-+throw CodexRateLimitError.serverTimeout("\(step):\(stderr)")}}@@ -313,6 +406,15 @@ private nonisolated struct AppServerCommand: Sendable {let arguments = ["app-server", "--listen", "stdio://"]}+private nonisolated struct AppServerConnection {+ let process: Process+ let session: AppServerSession+ let lineReader: JSONLineReader+ let errorReader: PipeTextCollector+ let accountResponse: AccountReadResponse+ let rateLimitsResponse: AccountRateLimitsResponse+}+private nonisolated struct EmptyResponse: Decodable {}private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {@@ -329,51 +431,55 @@ private nonisolated struct RPCError: Decodable {let message: String}+private nonisolated struct RPCNotificationEnvelope: Decodable {+ let method: String?+}+private nonisolated final class JSONLineReader: @unchecked Sendable {private let lock = NSLock()private let semaphore = DispatchSemaphore(value: 0)private let fileHandle: FileHandleprivate var buffer = Data()private var lines: [String] = []-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { [weak self] handle inself?.append(handle.availableData)}}-+func nextLine(timeout: TimeInterval) -> String? {if let line = popLine() {return line}-+let result = semaphore.wait(timeout: .now() + timeout)guard result == .success else {return nil}-+return popLine()}-+func stop() {fileHandle.readabilityHandler = nil}-+private func append(_ data: Data) {guard !data.isEmpty else {return}-+lock.lock()defer { lock.unlock() }-+buffer.append(data)-+while let newlineRange = buffer.firstRange(of: Data([0x0A])) {let lineData = buffer[..<newlineRange.lowerBound]buffer.removeSubrange(...newlineRange.lowerBound)-+if let line = String(data: lineData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),!line.isEmpty {@@ -382,49 +488,55 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {}}}-+private func popLine() -> String? {lock.lock()defer { lock.unlock() }-+guard !lines.isEmpty else {return nil}-+return lines.removeFirst()}}private nonisolated final class PipeTextCollector: @unchecked Sendable {+ // 监听连接会随应用运行数小时甚至数天,stderr 只保留末尾,避免无界增长。+ private static let maxBytes = 16_384+private let lock = NSLock()private let fileHandle: FileHandleprivate var data = Data()-+var text: String {lock.lock()defer { lock.unlock() }return String(data: data, encoding: .utf8) ?? ""}-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { [weak self] handle inself?.append(handle.availableData)}}-+func stop() {fileHandle.readabilityHandler = nil}-+private func append(_ newData: Data) {guard !newData.isEmpty else {return}-+lock.lock()defer { lock.unlock() }-+data.append(newData)+ if data.count > Self.maxBytes {+ data = Data(data.suffix(Self.maxBytes))+ }}}diff --git a/CodexBar/NotificationSettings.swift b/CodexBar/NotificationSettings.swiftnew file mode 100644index 0000000..9fae6d3--- /dev/null+++ b/CodexBar/NotificationSettings.swift@@ -0,0 +1,135 @@+//+// NotificationSettings.swift+// CodexBar+//+// Created by Bob on 2026-06-11.+//++import Combine+import Foundation+import UserNotifications++@MainActor+final class NotificationSettings: ObservableObject {+ @Published private(set) var isEnabled = NotificationSettingsStore.isEnabled+ @Published private(set) var errorMessage: String?++ init() {+ refresh()+ }++ func refresh() {+ Task {+ await refreshAuthorizationState()+ }+ }++ func setEnabled(_ enabled: Bool) {+ errorMessage = nil++ guard enabled else {+ NotificationSettingsStore.isEnabled = false+ isEnabled = false+ return+ }++ Task {+ await enable()+ }+ }++ private func enable() async {+ let center = UNUserNotificationCenter.current()+ let status = await center.notificationSettings().authorizationStatus++ if status.allowsNotifications {+ NotificationSettingsStore.isEnabled = true+ isEnabled = true+ return+ }++ if status == .notDetermined {+ let granted = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false+ NotificationSettingsStore.isEnabled = granted+ isEnabled = granted++ if !granted {+ errorMessage = "系统通知权限未开启"+ }++ return+ }++ NotificationSettingsStore.isEnabled = false+ isEnabled = false+ errorMessage = status == .denied ? "系统通知权限被拒绝" : "系统通知权限不可用"+ }++ private func refreshAuthorizationState() async {+ let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus++ if status.allowsNotifications {+ isEnabled = NotificationSettingsStore.isEnabled+ } else {+ if status != .notDetermined {+ NotificationSettingsStore.isEnabled = false+ }++ isEnabled = false+ }+ }+}++extension UNAuthorizationStatus {+ var allowsNotifications: Bool {+ switch self {+ case .authorized, .provisional, .ephemeral:+ return true+ case .notDetermined, .denied:+ return false+ @unknown default:+ return false+ }+ }+}++enum NotificationSettingsStore {+ private static let enabledKey = "rateLimitNotificationsEnabled"++ static var isEnabled: Bool {+ get {+ UserDefaults.standard.bool(forKey: enabledKey)+ }+ set {+ UserDefaults.standard.set(newValue, forKey: enabledKey)+ }+ }+}++struct QuotaNotificationService {+ func sendRateLimitUpdatedNotification() async {+ guard NotificationSettingsStore.isEnabled,+ await hasAuthorization else {+ return+ }++ let content = UNMutableNotificationContent()+ content.title = "Codex 额度已更新"+ content.sound = .default++ let request = UNNotificationRequest(+ identifier: "codex-rate-limits-updated-\(UUID().uuidString)",+ content: content,+ trigger: nil+ )++ try? await UNUserNotificationCenter.current().add(request)+ }++ private var hasAuthorization: Bool {+ get async {+ await UNUserNotificationCenter.current().notificationSettings().authorizationStatus.allowsNotifications+ }+ }++}diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/RateLimitModels.swiftindex 52d81fa..b64696c 100644--- a/CodexBar/RateLimitModels.swift+++ b/CodexBar/RateLimitModels.swift@@ -14,19 +14,20 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let generatedAt: Datelet fiveHour: QuotaWindowlet weekly: QuotaWindow-+ let usage: CodexUsageSnapshot?+var title: String {if let limitName, !limitName.isEmpty {return limitName}-+return "Codex"}-+var accountLabel: String {account?.displayName ?? "未登录"}-+var planLabel: String? {account?.planType ?? planType}@@ -36,12 +37,12 @@ nonisolated struct CodexAccount: Decodable, Equatable {let type: Stringlet email: String?let planType: String?-+var displayName: String {if let email, !email.isEmpty {return email}-+switch type {case "apiKey":return "API Key"@@ -65,22 +66,22 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {case fiveHourcase weekly}-+let kind: Kindlet label: Stringlet usedPercent: Int?let resetsAt: Date?-+var id: String { kind.rawValue }-+var remainingPercent: Int {guard let usedPercent else {return 0}-+return max(0, min(100, 100 - usedPercent))}-+var hasData: Bool {usedPercent != nil}@@ -89,7 +90,7 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {nonisolated struct AccountRateLimitsResponse: Decodable {let rateLimits: RateLimitSnapshotlet rateLimitsByLimitId: [String: RateLimitSnapshot]?-+var codexSnapshot: RateLimitSnapshot {rateLimitsByLimitId?["codex"] ?? rateLimits}@@ -106,41 +107,95 @@ nonisolated struct RateLimitWindow: Decodable {let usedPercent: Intlet resetsAt: Int?let windowDurationMins: Int?-+var resetDate: Date? {guard let resetsAt else { return nil }return Date(timeIntervalSince1970: TimeInterval(resetsAt))}}+nonisolated struct AccountUsageResponse: Decodable {+ let summary: UsageSummary+ let dailyUsageBuckets: [DailyUsageBucket]+}++nonisolated struct UsageSummary: Decodable, Equatable {+ let lifetimeTokens: Int+ let peakDailyTokens: Int+}++nonisolated struct DailyUsageBucket: Decodable, Equatable {+ let startDate: String+ let tokens: Int+}++nonisolated struct CodexUsageSnapshot: Equatable {+ struct Day: Equatable, Identifiable {+ let startDate: String+ let tokens: Int++ var id: String { startDate }+ }++ let summary: UsageSummary+ let dailyBuckets: [DailyUsageBucket]++ func recentDays(count: Int, endingDaysAgo: Int = 0) -> [Day] {+ let calendar = Calendar.current+ let today = calendar.startOfDay(for: Date())+ let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket in+ result[bucket.startDate, default: 0] += bucket.tokens+ }++ return (0..<count).reversed().compactMap { offset in+ guard let date = calendar.date(byAdding: .day, value: -(offset + endingDaysAgo), to: today) else {+ return nil+ }++ let startDate = Self.dayFormatter.string(from: date)+ return Day(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)+ }+ }++ private nonisolated static let dayFormatter: DateFormatter = {+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.dateFormat = "yyyy-MM-dd"+ return formatter+ }()+}+nonisolated extension CodexQuotaSnapshot {init(accountResponse: AccountReadResponse,rateLimitsResponse: AccountRateLimitsResponse,+ usageResponse: AccountUsageResponse? = nil,generatedAt: Date = Date()) throws {guard let account = accountResponse.account else {throw CodexRateLimitError.notLoggedIn}-+let snapshot = rateLimitsResponse.codexSnapshot-+try self.init(account: account,snapshot: snapshot,+ usageResponse: usageResponse,generatedAt: generatedAt)}-+private init(account: CodexAccount?,snapshot: RateLimitSnapshot,+ usageResponse: AccountUsageResponse?,generatedAt: Date) throws {guard let primary = snapshot.primary else {throw CodexRateLimitError.missingRateLimitWindow("5 小时额度")}-+self.init(account: account,planType: snapshot.planType,@@ -157,27 +212,30 @@ nonisolated extension CodexQuotaSnapshot {label: Self.windowLabel(for: snapshot.secondary?.windowDurationMins, fallback: "7 天"),usedPercent: snapshot.secondary?.usedPercent,resetsAt: snapshot.secondary?.resetDate- )+ ),+ usage: usageResponse.map {+ CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)+ })}-+private static func windowLabel(for minutes: Int?, fallback: String) -> String {guard let minutes, minutes > 0 else {return fallback}-+if minutes < 60 {return "\(minutes) 分钟"}-+if minutes.isMultiple(of: 1_440) {return "\(minutes / 1_440) 天"}-+if minutes.isMultiple(of: 60) {return "\(minutes / 60) 小时"}-+return "\(minutes) 分钟"}}@@ -190,7 +248,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {case missingRateLimitWindow(String)case notLoggedIncase authenticationRequired-+var errorDescription: String? {switch self {case .executableNotFound:@@ -209,7 +267,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {return "Codex 需要身份验证"}}-+var isAuthenticationRequired: Bool {switch self {case .serverError(let message):diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swiftindex 2a39956..e662ac9 100644--- a/CodexBar/RateLimitsMenuView.swift+++ b/CodexBar/RateLimitsMenuView.swift@@ -10,22 +10,25 @@ import SwiftUIstruct RateLimitsMenuView: View {static let menuWidth: CGFloat = 360-+@ObservedObject var viewModel: RateLimitsViewModel@StateObject private var loginItemSettings = LoginItemSettings()+ @StateObject private var notificationSettings = NotificationSettings()@State private var showsControls = false-+var body: some View {VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {contenterrorView(viewModel.errorMessage)errorView(loginItemSettings.errorMessage)+ errorView(notificationSettings.errorMessage)controls}.padding(Metrics.padding).onAppear {viewModel.refreshIfNeeded()loginItemSettings.refresh()+ notificationSettings.refresh()showsControls = NSEvent.modifierFlags.contains(.option)}}@@ -38,17 +41,21 @@ private extension RateLimitsMenuView {static let accountIconSize: CGFloat = 14static let loadingVerticalPadding: CGFloat = 16}-+@ViewBuildervar content: some View {if let snapshot = viewModel.snapshot {accountRow(title: snapshot.accountLabel, plan: snapshot.planLabel)-+VStack(spacing: 8) {QuotaRow(window: snapshot.fiveHour)QuotaRow(window: snapshot.weekly)}-++ if let usage = snapshot.usage {+ UsageSummaryView(usage: usage)+ }+updatedAtRow(for: snapshot)} else if viewModel.isRefreshing {accountRow(title: "Codex")@@ -58,34 +65,34 @@ private extension RateLimitsMenuView {emptyView}}-+@ViewBuildervar controls: some View {if showsControls {Divider()- controlsRow+ settingsView}}-+var loadingView: some View {HStack(spacing: 10) {ProgressView().controlSize(.small)-+Text("正在获取数据").foregroundStyle(.secondary)}.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, Metrics.loadingVerticalPadding)}-+var emptyView: some View {Text("暂无数据").foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, Metrics.loadingVerticalPadding)}-+func accountRow(title: String, plan: String? = nil) -> some View {HStack(spacing: 8) {Image(systemName: "person.fill")@@ -94,20 +101,20 @@ private extension RateLimitsMenuView {.onTapGesture(count: 2) {viewModel.refresh()}-+Text(title).font(.caption.weight(.semibold)).lineLimit(1).truncationMode(.middle)-+if viewModel.isRefreshing {ProgressView().controlSize(.small).padding(.leading, 2)}-+Spacer()-+if let plan {Text(plan.uppercased()).font(.caption2)@@ -119,43 +126,64 @@ private extension RateLimitsMenuView {}}}-+func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {HStack {Text("更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)").font(.caption2).foregroundStyle(.secondary)-+Spacer()}}-- var controlsRow: some View {- HStack {- loginItemToggle-- Spacer()-- Button("退出") {- NSApplication.shared.terminate(nil)++ var settingsView: some View {+ VStack(spacing: 8) {+ VStack(alignment: .leading, spacing: 8) {+ loginItemToggle+ notificationToggle+ }+ .frame(maxWidth: .infinity, alignment: .leading)++ HStack {+ Spacer()++ Button("退出") {+ NSApplication.shared.terminate(nil)+ }+ .foregroundStyle(.red)+ .keyboardShortcut("q")}- .keyboardShortcut("q")}}-+var loginItemToggle: some View {- Toggle(- "开机启动",- isOn: Binding(- get: { loginItemSettings.isEnabled },- set: { loginItemSettings.setEnabled($0) }- )+ settingsToggle(+ "开机自动启动",+ isEnabled: loginItemSettings.isEnabled,+ setEnabled: { loginItemSettings.setEnabled($0) })- .toggleStyle(.switch)- .controlSize(.small)- .font(.caption)}-++ var notificationToggle: some View {+ settingsToggle(+ "额度重置通知",+ isEnabled: notificationSettings.isEnabled,+ setEnabled: { notificationSettings.setEnabled($0) }+ )+ }++ func settingsToggle(+ _ title: String,+ isEnabled: Bool,+ setEnabled: @escaping (Bool) -> Void+ ) -> some View {+ Toggle(title, isOn: Binding(get: { isEnabled }, set: setEnabled))+ .toggleStyle(.switch)+ .controlSize(.small)+ .font(.caption)+ }+@ViewBuilderfunc errorView(_ message: String?) -> some View {if let message {@@ -166,7 +194,7 @@ private extension RateLimitsMenuView {.frame(maxWidth: .infinity, alignment: .leading)}}-+static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")@@ -175,6 +203,164 @@ private extension RateLimitsMenuView {}()}+private struct UsageSummaryView: View {+ let usage: CodexUsageSnapshot+ private let recentDays: [CodexUsageSnapshot.Day]+ @State private var hoveredDay: CodexUsageSnapshot.Day?++ init(usage: CodexUsageSnapshot) {+ self.usage = usage+ self.recentDays = usage.recentDays(count: 14, endingDaysAgo: 1)+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ Divider()++ HStack(alignment: .firstTextBaseline) {+ metric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .leading)+ Spacer()+ hoveredMetric+ Spacer()+ metric(label: "累计 Token", value: usage.summary.lifetimeTokens, alignment: .trailing)+ }++ UsageBarChart(days: recentDays, hoveredDay: $hoveredDay)+ }+ .onAppear {+ hoveredDay = nil+ }+ }++ var hoveredMetric: some View {+ VStack(spacing: 2) {+ Text(hoveredDateText)+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.secondary)++ Text(hoveredTokensText)+ .font(.caption.monospacedDigit().weight(.semibold))+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+ .opacity(hoveredDay == nil ? 0 : 1)+ .frame(width: 112, alignment: .center)+ }++ private var hoveredDateText: String {+ hoveredDay?.startDate ?? " "+ }++ private var hoveredTokensText: String {+ guard let hoveredDay else {+ return " "+ }++ return TokenCountFormatter.string(from: hoveredDay.tokens)+ }++ private func metric(label: String, value: Int, alignment: Alignment) -> some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(label)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: alignment)++ Text(TokenCountFormatter.string(from: value))+ .font(.caption.monospacedDigit().weight(.semibold))+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ .frame(maxWidth: .infinity, alignment: alignment)+ }+ .frame(width: 96)+ }+}++private struct UsageBarChart: View {+ let days: [CodexUsageSnapshot.Day]+ @Binding var hoveredDay: CodexUsageSnapshot.Day?++ private var peakTokens: Int {+ max(days.map(\.tokens).max() ?? 0, 1)+ }++ var body: some View {+ HStack(alignment: .bottom, spacing: 5) {+ ForEach(days) { day in+ UsageBar(+ day: day,+ percent: Double(day.tokens) / Double(peakTokens),+ isHovered: hoveredDay?.id == day.id+ )+ .onHover { isHovering in+ if isHovering {+ hoveredDay = day+ } else if hoveredDay?.id == day.id {+ hoveredDay = nil+ }+ }+ }+ }+ .frame(height: 58)+ }+}++private struct UsageBar: View {+ let day: CodexUsageSnapshot.Day+ let percent: Double+ let isHovered: Bool++ var body: some View {+ GeometryReader { proxy in+ let barHeight = max(day.tokens > 0 ? 2 : 0, proxy.size.height * clampedPercent)++ ZStack(alignment: .bottom) {+ Rectangle()+ .fill(.secondary.opacity(isHovered ? 0.20 : 0.12))++ Rectangle()+ .fill(Color.orange.opacity(day.tokens > 0 ? barOpacity : 0))+ .frame(height: barHeight)+ }+ }+ .frame(maxWidth: .infinity)+ .contentShape(Rectangle())+ }++ private var clampedPercent: Double {+ min(max(percent, 0), 1)+ }++ private var barOpacity: Double {+ let opacity = 0.28 + clampedPercent * 0.62+ return isHovered ? min(opacity + 0.10, 1.0) : opacity+ }+}++private enum TokenCountFormatter {+ static func string(from tokens: Int) -> String {+ if tokens >= 1_000_000_000 {+ return decimal(Double(tokens) / 1_000_000_000) + "B"+ }++ return decimal(Double(tokens) / 1_000_000) + "M"+ }++ private static func decimal(_ value: Double) -> String {+ let rounded = value >= 0.1 ? (value * 10).rounded() / 10 : (value * 100).rounded() / 100+ return formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)+ }++ private static let formatter: NumberFormatter = {+ let formatter = NumberFormatter()+ formatter.numberStyle = .decimal+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.minimumFractionDigits = 0+ formatter.maximumFractionDigits = 2+ return formatter+ }()+}+#Preview {let viewModel = RateLimitsViewModel()return RateLimitsMenuView(viewModel: viewModel)diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/RateLimitsViewModel.swiftindex 8b434dc..eee80e0 100644--- a/CodexBar/RateLimitsViewModel.swift+++ b/CodexBar/RateLimitsViewModel.swift@@ -13,47 +13,58 @@ final class RateLimitsViewModel: ObservableObject {@Published private(set) var snapshot: CodexQuotaSnapshot?@Published private(set) var isRefreshing = false@Published private(set) var errorMessage: String?-+private static let refreshInterval: TimeInterval = 60-+private let service: CodexRateLimitService+ private let notificationService: QuotaNotificationServiceprivate var autoRefreshTask: Task<Void, Never>?-+ private var rateLimitUpdateTask: Task<Void, Never>?+ private var isHandlingRateLimitUpdate = false+init(service: CodexRateLimitService = CodexRateLimitService()) {self.service = service+ self.notificationService = QuotaNotificationService()+ }++ deinit {+ autoRefreshTask?.cancel()+ rateLimitUpdateTask?.cancel()}-+func refreshIfNeeded() {guard snapshot == nil || Date().timeIntervalSince(snapshot?.generatedAt ?? .distantPast) > Self.refreshInterval else {return}-+refresh()}-+func startAutoRefresh() {+ startRateLimitUpdateObserver()+guard autoRefreshTask == nil else {return}-+autoRefreshTask = Task { [weak self] inself?.refreshIfNeeded()-+while !Task.isCancelled {try? await Task.sleep(nanoseconds: UInt64(Self.refreshInterval * 1_000_000_000))self?.refresh()}}}-+func refresh() {guard !isRefreshing else {return}-+isRefreshing = trueerrorMessage = nil-+Task {do {let snapshot = try await service.fetchRateLimits()@@ -61,8 +72,55 @@ final class RateLimitsViewModel: ObservableObject {} catch {self.errorMessage = error.localizedDescription}-+self.isRefreshing = false}}++ private func startRateLimitUpdateObserver() {+ guard rateLimitUpdateTask == nil else {+ return+ }++ let viewModelBox = WeakRateLimitsViewModelBox(self)+ rateLimitUpdateTask = Task.detached(priority: .utility) { [service, viewModelBox] in+ await service.observeRateLimitUpdates {+ Task { @MainActor [viewModelBox] in+ await viewModelBox.value?.handleRateLimitUpdate()+ }+ }+ }+ }++ private func handleRateLimitUpdate() async {+ guard !isHandlingRateLimitUpdate else {+ return+ }++ isHandlingRateLimitUpdate = true+ defer {+ isHandlingRateLimitUpdate = false+ }++ do {+ let updatedSnapshot = try await service.fetchRateLimits()+ snapshot = updatedSnapshot+ errorMessage = nil++ await notificationService.sendRateLimitUpdatedNotification()+ } catch {+ if snapshot == nil {+ errorMessage = error.localizedDescription+ }+ }+ }+}++private final class WeakRateLimitsViewModelBox: @unchecked Sendable {+ weak var value: RateLimitsViewModel?++ @MainActor+ init(_ value: RateLimitsViewModel) {+ self.value = value+ }}diff --git a/README.md b/README.mdindex fe44f69..5ccfac8 100644--- a/README.md+++ b/README.md@@ -10,11 +10,14 @@ CodexBar 是一个轻量级 macOS 菜单栏应用,用来查看当前本机 Cod- 弹窗第一行展示账号信息和套餐- 弹窗使用两行分段电量条展示额度窗口,标签根据 `windowDurationMins` 动态生成- 每行额度在进度条右侧展示剩余百分比和重置时间+- 弹窗展示最近 14 个完整自然日的 token 柱状图、累计 token 和单日峰值 token+- 鼠标划过 token 柱状图中的单日柱子时,展示对应日期和用量- 更新时间显示在额度行下方,并使用 `HH:mm:ss` 格式- 应用运行时每分钟自动刷新额度,即使弹窗未打开也会刷新+- 收到 `account/rateLimits/updated` 后会重新查询额度,并在「额度通知」已开启时发送本地通知- 双击账号图标可手动刷新- 不按 Option/Alt 点击菜单栏图标时,只展示额度内容-- 按住 Option/Alt 点击菜单栏图标时,才展示「开机启动」开关和「退出」按钮+- 按住 Option/Alt 点击菜单栏图标时,才展示设置区;设置区包含「开机启动」「额度通知」开关和「退出」按钮## 运行要求@@ -43,6 +46,7 @@ codex app-server --listen stdio://{"method":"initialized"}{"method":"account/read","id":2,"params":{"refreshToken":false}}{"method":"account/rateLimits/read","id":3}+{"method":"account/usage/read","id":4}```额度窗口来自 Codex app-server 返回的 `primary` 和 `secondary`:@@ -53,10 +57,29 @@ codex app-server --listen stdio://剩余额度统一按 `100 - usedPercent` 计算。+应用会保留一个后台 app-server 连接监听 `account/rateLimits/updated` 通知。该通知是稀疏更新,收到后不会直接用通知 payload 更新 UI,而是重新调用 `account/rateLimits/read` 获取完整额度并更新 UI;如果「额度通知」开启且系统通知权限已授权,则发送 macOS 本地通知。++后台监听连接启动时也会按 `account/read`、`account/rateLimits/read` 的顺序初始化额度路径。如果监听连接因为 app-server 退出、认证失败或响应超时而断开,应用会在 30 秒后重新启动监听连接。++「额度通知」开关只在按住 Option/Alt 打开菜单栏弹窗时展示。开启该开关时会请求 macOS 通知权限;关闭后不再发送额度更新通知。++token 使用量来自 Codex app-server 返回的 `account/usage/read`:++- `summary.lifetimeTokens`:累计 token+- `summary.peakDailyTokens`:单日峰值 token+- `dailyUsageBuckets`:按天聚合的 token 使用量,日期字段为 `startDate`++如果本机 Codex app-server 不支持 `account/usage/read`,token 统计区域不会展示,额度信息仍会正常显示。++token 数使用 `M`、`B` 紧凑单位展示。+token 柱状图使用橙色,单日用量越高颜色越浓。+## 错误展示CodexBar 会在弹窗中用红色小字展示错误,例如未安装 Codex、app-server 启动失败、响应超时、当前未登录、需要重新验证身份、响应中缺少额度窗口等。应用不包含调试模拟入口,也不会在窗口里展示 Debug 明细。+如果应用运行期间 Codex 退出登录或认证失效,每分钟自动刷新会继续尝试读取额度;刷新失败时会展示对应错误。如果之前已经成功读取过额度,旧的额度快照不会被清空,弹窗会继续显示上一次成功读取的数据和对应更新时间,同时显示错误文案。收到 `account/rateLimits/updated` 后触发的刷新如果失败,不会更新 UI,也不会发送通知;只有在当前没有任何旧快照时才会把该错误展示到弹窗中。+## 构建可以直接用 Xcode 打开 `CodexBar.xcodeproj`,也可以使用命令行构建: