CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 改进额度用量读取回退
Bob44ae4125e313
diff --git a/AGENTS.md b/AGENTS.mdindex da9813d..b725a69 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -141,8 +141,12 @@ codex app-server --listen stdio://- `account/rateLimits/read` 读取额度。- `account/usage/read` 读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。- 认证失败时同会话最多调用一次 `account/read`(`refreshToken: true`) 后重试原读取。-- usage 方法不支持时, 将当前连接的 `isUsageReadAvailable` 置为 false, 本连接后续不再请求 usage。-- 非认证业务错误不阻断整轮刷新, 详情只进日志。+- 所有走 `AppServerSession.request` 的方法, 收到方法不支持错误后都记录到当前会话的 `unsupportedMethods`, 本连接后续不再请求该方法。+- 方法不支持必须是 JSON-RPC error, 且 message 包含 `Invalid request: unknown variant`。+- 请求有 JSON-RPC error 响应, 且不是认证失败、不是方法不支持、不是传输/解析故障时, 先立即重试同一个请求一次。+- 非认证业务错误重试后仍失败时不阻断整轮刷新, 详情只进日志。+- `account/rateLimits/read` 和 `account/usage/read` 重试后仍失败时, 若同账号有上次成功数据则复用旧数据并标记为 stale; 没有旧数据则不展示对应区域。+- 方法不支持不复用旧数据; 对应读取结果视为空。- 传输/解析故障归为需要重建连接。连接细节:@@ -186,6 +190,7 @@ UI 只展示「未登录」和「初始化失败」两类特殊状态; 具体请- 必须有 `AccountReadResponse.account`, 否则视为未登录。- `rateLimitsResponse` 和 `usageResponse` 都可以为空; 账户有效时仍生成快照, UI 展示「暂无数据」。+- `isRateLimitsStale` / `isUsageStale` 标记额度或 token 区域是否来自同账号旧缓存; 本轮对应接口成功后重新生成 snapshot 并恢复为 `false`。- 优先读取 `rateLimitsByLimitId`; 为空时回退顶层 `rateLimits`。- 顶层 `rateLimits.limitId` 指向的主 limit 置顶, 缺省 `"codex"`。- 其余 limit 按 `limitName ?? limitId` 做 localized standard 排序, 再按 `limitId` 稳定排序。@@ -227,6 +232,7 @@ Popover:- 计划名是右侧加粗纯文字; `planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。- 额度条展示剩余百分比, 颜色按 20% 一档: 红、橙、黄、薄荷、绿。- 无 quota 数据时显示 `--` / `暂无数据`, 并使用占位色。+- `rateLimits` 或 `usage` 使用旧缓存时, 对应区域通过 `.markStale(true)` 降低透明度到 0.55, 不降低饱和度; 下一轮对应接口成功后恢复正常透明度。- 重置时间格式是 `MM-dd HH:mm`。- 更新时间行显示倒计时圆环、「数据更新时间」和 `HH:mm:ss`。- 倒计时只在 popover 可见时用 `TimelineView` 每秒 tick; 普通 tick 不做连续动画, 仅刷新起点变化时播放恢复动画。@@ -281,6 +287,7 @@ Popover:- 不要主动 push。- 不要回滚或覆盖你没做的未提交改动。+- 提交代码的时候不要做任何额外的改动,仅对目前代码进行提交即可。- 提交 message 使用 Conventional Commits 前缀 + 中文标题 + 空行 + 4 空格缩进 bullet body。- 提交 body 中多条 bullet 必须连续排列, bullet 之间不要空行; 使用命令提交时, 将完整 body 放在同一个 `-m` 参数或 `git commit -F` 文件中, 不要为每条 bullet 单独使用 `-m`。- 标题格式: `<type>: <中文描述>`, 不加句号。@@ -310,8 +317,3 @@ Tag:- 是否运行了与改动匹配的验证命令。- 是否说明了未验证项和原因。- 是否避免泄露本机认证、路径之外的敏感信息或原始错误噪音。--<!-- SPECKIT START -->-For additional context about technologies to be used, project structure,-shell commands, and other important information, read the current plan-<!-- SPECKIT END -->diff --git a/CodexBar/CodexQuotaModels.swift b/CodexBar/CodexQuotaModels.swiftindex 5012938..5e6cf9b 100644--- a/CodexBar/CodexQuotaModels.swift+++ b/CodexBar/CodexQuotaModels.swift@@ -6,6 +6,8 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let generatedAt: Datelet limits: [CodexQuotaLimitSnapshot]let usage: CodexUsageSnapshot?+ let isRateLimitsStale: Bool+ let isUsageStale: Boolvar accountLabel: String {account.displayName@@ -225,6 +227,8 @@ nonisolated extension CodexQuotaSnapshot {accountResponse: AccountReadResponse,rateLimitsResponse: AccountRateLimitsResponse?,usageResponse: AccountUsageResponse? = nil,+ isRateLimitsStale: Bool = false,+ isUsageStale: Bool = false,generatedAt: Date = Date()) throws {guard let account = accountResponse.account else {@@ -247,7 +251,9 @@ nonisolated extension CodexQuotaSnapshot {planType: rateLimitsResponse?.rateLimits.planType,generatedAt: generatedAt,limits: limits,- usage: usage+ usage: usage,+ isRateLimitsStale: isRateLimitsStale,+ isUsageStale: isUsageStale)}@@ -316,6 +322,7 @@ nonisolated enum CodexStatusError: LocalizedError {case serverConnectionClosedcase invalidServerResponsecase serverError(String)+ case unsupportedMethodcase notLoggedInvar errorDescription: String? {@@ -327,17 +334,27 @@ nonisolated enum CodexStatusError: LocalizedError {}}- /// codex app-server 目前通过 serverError 文案表示认证失败+ /// codex app-server 未登录var isAuthenticationRequired: Bool {- serverErrorMessageContains("authentication required")+ serverErrorMessageContains("codex account authentication required")}- var isUnsupportedUsageMethod: Bool {- serverErrorMessageContains("unknown variant")- || serverErrorMessageContains("method not found")- || serverErrorMessageContains("unknown method")- || serverErrorMessageContains("unsupported")- || serverErrorMessageContains("not supported")+ /// codex app-server 不支持的方法+ var isUnsupportedMethod: Bool {+ switch self {+ case .unsupportedMethod:+ return true+ default:+ return serverErrorMessageContains("Invalid request: unknown variant")+ }+ }++ var isRetriableServerError: Bool {+ guard case .serverError = self else {+ return false+ }++ return !isAuthenticationRequired && !isUnsupportedMethod}/// 连接断开、超时、无法解析都需要重建 app-server 会话diff --git a/CodexBar/CodexStatusMenuView.swift b/CodexBar/CodexStatusMenuView.swiftindex c9c14f3..93e4103 100644--- a/CodexBar/CodexStatusMenuView.swift+++ b/CodexBar/CodexStatusMenuView.swift@@ -62,11 +62,11 @@ private extension CodexStatusMenuView {emptyPanel} else {if !snapshot.limits.isEmpty {- quotaLimitsView(snapshot.limits)+ quotaLimitsView(snapshot.limits, isStale: snapshot.isRateLimitsStale)}if let usage = snapshot.usage {- UsageSummaryView(usage: usage)+ UsageSummaryView(usage: usage, isStale: snapshot.isUsageStale)}}@@ -130,7 +130,7 @@ private extension CodexStatusMenuView {.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)}- func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot]) -> some View {+ func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot], isStale: Bool) -> some View {VStack(alignment: .leading, spacing: 8) {ForEach(limits) { limit inif limit.id != limits.first?.id {@@ -140,6 +140,7 @@ private extension CodexStatusMenuView {quotaLimitSection(limit)}}+ .markStale(isStale).padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .green)}diff --git a/CodexBar/CodexStatusService.swift b/CodexBar/CodexStatusService.swiftindex b303bac..de22b0c 100644--- a/CodexBar/CodexStatusService.swift+++ b/CodexBar/CodexStatusService.swift@@ -16,16 +16,37 @@ private enum ConnectionResolution {/// 单接口读取结果按后续动作分类: 跳过、刷新认证、重建连接private enum ReadResult<Value> {case value(Value)- case skipped+ case skipped(ReadSkipReason)case authRequiredcase broken}+private enum ReadSkipReason {+ case requestFailed+ case methodUnsupported+}+private enum FetchFailure: Error {case notLoggedIncase needsRebuild}+nonisolated private struct CachedSupplementalRead<Value> {+ let value: Value?+ let isStale: Bool+}++nonisolated private struct SupplementalDataCache {+ var account: CodexAccount?+ var rateLimits: AccountRateLimitsResponse?+ var usage: AccountUsageResponse?++ mutating func useAccount(_ account: CodexAccount) {+ guard self.account != account else { return }+ self = Self(account: account)+ }+}+nonisolated private extension ReadResult {var isAuthenticationRequired: Bool {if case .authRequired = self {@@ -34,12 +55,18 @@ nonisolated private extension ReadResult {return false}- func valueAfterAuthAttempt() throws -> Value? {- switch self {- case .value(let value):+ var value: Value? {+ if case .value(let value) = self {return value- case .skipped:- return nil+ }+ return nil+ }++ /// 认证刷新后仍是 authRequired/broken 则上抛, 其余原样返回交给调用方按缓存策略处理+ func resultAfterAuthAttempt() throws -> ReadResult<Value> {+ switch self {+ case .value, .skipped:+ return selfcase .authRequired:throw FetchFailure.notLoggedIncase .broken:@@ -58,6 +85,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {// connection 只在这个队列上访问private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)private var connection: AppServerConnection?+ private var supplementalDataCache = SupplementalDataCache()// app-server 退出后继续写管道会触发 SIGPIPE; 忽略信号, 让 write 抛错后走重建private static let ignoreBrokenPipeSignal: Void = {@@ -97,9 +125,10 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return .initializationFailedcase .ready(let connection, let reused):do {- let snapshot = try Self.fetchData(using: connection, refreshAccountInfo: reused)+ let snapshot = try fetchData(using: connection, refreshAccountInfo: reused)return .data(snapshot)} catch FetchFailure.notLoggedIn {+ supplementalDataCache = SupplementalDataCache()teardownConnection()return .notLoggedIn} catch FetchFailure.needsRebuild {@@ -157,48 +186,74 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}/// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接- private static func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {+ private func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {var didRefresh = falsefunc refreshTokenIfNeeded() throws {guard !didRefresh else { throw FetchFailure.notLoggedIn }didRefresh = true- try refreshAccount(using: connection)+ try Self.refreshAccount(using: connection)}- func readWithAuthRefresh<Value>(_ read: () -> ReadResult<Value>) throws -> Value? {+ func readResultWithAuthRefresh<Value>(_ read: () -> ReadResult<Value>) throws -> ReadResult<Value> {let firstAttempt = read()guard firstAttempt.isAuthenticationRequired else {- return try firstAttempt.valueAfterAuthAttempt()+ return try firstAttempt.resultAfterAuthAttempt()}try refreshTokenIfNeeded()- return try read().valueAfterAuthAttempt()+ return try read().resultAfterAuthAttempt()+ }++ func readSupplemental<Value: Decodable>(+ _ method: String,+ as type: Value.Type,+ cache: inout Value?+ ) throws -> CachedSupplementalRead<Value> {+ try cachedRead(+ readResultWithAuthRefresh {+ Self.read(method, using: connection, as: type)+ },+ cache: &cache+ )}// 新建连接已读过 account; 复用连接才刷新账户状态if refreshAccountInfo {- if let response: AccountReadResponse = try readWithAuthRefresh({- read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)- }) {+ let accountResult: ReadResult<AccountReadResponse> = try readResultWithAuthRefresh {+ Self.read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)+ }+ if let response = accountResult.value {guard response.account != nil else { throw FetchFailure.notLoggedIn }connection.accountResponse = response}}- let rateLimits: AccountRateLimitsResponse? = try readWithAuthRefresh({- read("account/rateLimits/read", using: connection, as: AccountRateLimitsResponse.self)- })-- let usage: AccountUsageResponse? = try readWithAuthRefresh {- readUsage(using: connection)+ guard let account = connection.accountResponse.account else {+ throw FetchFailure.notLoggedIn}+ supplementalDataCache.useAccount(account)++ let rateLimitsRead = try readSupplemental(+ "account/rateLimits/read",+ as: AccountRateLimitsResponse.self,+ cache: &supplementalDataCache.rateLimits+ )++ let usageRead = try readSupplemental(+ "account/usage/read",+ as: AccountUsageResponse.self,+ cache: &supplementalDataCache.usage+ )+// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"guard let snapshot = try? CodexQuotaSnapshot(accountResponse: connection.accountResponse,- rateLimitsResponse: rateLimits,- usageResponse: usage+ rateLimitsResponse: rateLimitsRead.value,+ usageResponse: usageRead.value,+ isRateLimitsStale: rateLimitsRead.isStale,+ isUsageStale: usageRead.isStale) else {throw FetchFailure.notLoggedIn}@@ -206,6 +261,22 @@ nonisolated final class CodexStatusService: @unchecked Sendable {return snapshot}+ /// 新值更新缓存; 本轮请求失败则回退到缓存并标记陈旧; 方法不支持/认证/断连一律视为无数据+ private func cachedRead<Value>(+ _ result: ReadResult<Value>,+ cache: inout Value?+ ) -> CachedSupplementalRead<Value> {+ switch result {+ case .value(let value):+ cache = value+ return CachedSupplementalRead(value: value, isStale: false)+ case .skipped(.requestFailed):+ return CachedSupplementalRead(value: cache, isStale: cache != nil)+ default:+ return CachedSupplementalRead(value: nil, isStale: false)+ }+ }+private static func read<Value: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -221,30 +292,15 @@ nonisolated final class CodexStatusService: @unchecked Sendable {}}- private static func readUsage(using connection: AppServerConnection) -> ReadResult<AccountUsageResponse> {- guard connection.isUsageReadAvailable else {- return .skipped- }-- do {- return .value(try connection.session.request("account/usage/read", as: AccountUsageResponse.self))- } catch let error as CodexStatusError where error.isUnsupportedUsageMethod {- // 老版本 codex 不支持该方法时, 后续轮询不再请求 usage- connection.isUsageReadAvailable = false- return .skipped- } catch let error as CodexStatusError {- return classify(error)- } catch {- return .broken- }- }-private static func classify<Value>(_ error: CodexStatusError) -> ReadResult<Value> {if error.isAuthenticationRequired {return .authRequired}- // 非认证的业务错误不阻断整轮刷新, 详情只保留在日志中- return error.isTransportFailure ? .broken : .skipped+ if error.isUnsupportedMethod {+ return .skipped(.methodUnsupported)+ }+ // 重试后仍失败的非认证业务错误不阻断整轮刷新+ return error.isTransportFailure ? .broken : .skipped(.requestFailed)}private static func refreshAccount(using connection: AppServerConnection) throws {@@ -376,7 +432,6 @@ private nonisolated final class AppServerConnection {let session: AppServerSessionlet commandInfo: CodexCLIConnectionInfovar accountResponse: AccountReadResponse- var isUsageReadAvailable = truevar openedAt: Date { commandInfo.openedAt }@@ -406,6 +461,7 @@ private nonisolated final class AppServerSession {private let errorReader: PipeDrainprivate let timeout: TimeIntervalprivate var nextId = 1+ private var unsupportedMethods: Set<String> = []init(process: Process,@@ -444,6 +500,37 @@ private nonisolated final class AppServerSession {_ method: String,params: [String: Any]? = nil,as type: Response.Type+ ) throws -> Response {+ guard !unsupportedMethods.contains(method) else {+ throw CodexStatusError.unsupportedMethod+ }++ do {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ } catch let error as CodexStatusError where error.isRetriableServerError {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ }+ }++ private func performRequestRememberingUnsupported<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ do {+ return try performRequest(method, params: params, as: type)+ } catch let error as CodexStatusError {+ if error.isUnsupportedMethod {+ unsupportedMethods.insert(method)+ }+ throw error+ }+ }++ private func performRequest<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type) throws -> Response {let id = nextIdnextId += 1diff --git a/CodexBar/LiquidGlassStyle.swift b/CodexBar/LiquidGlassStyle.swiftindex b0dfaf1..ab51c33 100644--- a/CodexBar/LiquidGlassStyle.swift+++ b/CodexBar/LiquidGlassStyle.swift@@ -47,6 +47,11 @@ extension View {LiquidGlassCapsule(tint: tint)}}++ // 数据为缓存回退(本轮刷新失败)时弱化显示+ func markStale(_ isStale: Bool) -> some View {+ opacity(isStale ? 0.55 : 1)+ }}struct LiquidGlassDivider: View {diff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/UsageHeatmap.swiftindex 3deae3c..a55043d 100644--- a/CodexBar/UsageHeatmap.swift+++ b/CodexBar/UsageHeatmap.swift@@ -2,11 +2,13 @@ import SwiftUIstruct UsageSummaryView: View {let usage: CodexUsageSnapshot+ let isStale: Boolprivate let days: [DailyUsageBucket?]@State private var hoveredDay: DailyUsageBucket?- init(usage: CodexUsageSnapshot) {+ init(usage: CodexUsageSnapshot, isStale: Bool = false) {self.usage = usage+ self.isStale = isStaleself.days = usage.recentWeekGrid(columnCount: UsageHeatmap.Metrics.columnCount, endingDaysAgo: 1)}@@ -16,6 +18,7 @@ struct UsageSummaryView: View {UsageHeatmap(days: days, hoveredDay: $hoveredDay)}+ .markStale(isStale).padding(10).liquidGlassSurface(cornerRadius: 8, tint: .blue).onAppear {