Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

feat: 显示积分余额并统一构建目录

Bob38f282acd316
diff --git a/.gitignore b/.gitignore
index 869c75f..bc74d60 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,7 @@
# Xcode
DerivedData/
-build/
+Build/
*.xcarchive
*.xcresult
*.dSYM
diff --git a/CLAUDE.md b/CLAUDE.md
index a7cb6a6..27cd6cf 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -55,7 +55,7 @@ Scripts/cleanup.swift --help
日常调试直接 `open CodexBar.xcodeproj` 用 Xcode 跑 Debug scheme; 注意 Debug 产物用的是 `app.zabrian.codexbar.debug` 这个 bundle ID, 与 Release 安装版可以共存, 排查防睡眠问题时要确认自己看的是哪一套 helper
-`Scripts/build.sh` 会先清空 `build/` 目录, 成功后只留最终产物 `.app` 文件; 凭据推荐用 keychain profile, 先跑一次 `xcrun notarytool store-credentials "codexbar-notary" --apple-id "<Apple ID>" --team-id "<Team ID>"` 存好, 之后构建加上 `--notary-profile codexbar-notary`
+`Scripts/build.sh` 会先清空 `Build/` 目录, 成功后只留最终产物 `.app` 文件; 凭据推荐用 keychain profile, 先跑一次 `xcrun notarytool store-credentials "codexbar-notary" --apple-id "<Apple ID>" --team-id "<Team ID>"` 存好, 之后构建加上 `--notary-profile codexbar-notary`
Debug 与 Release 使用不同 bundle ID, 分别是 `app.zabrian.codexbar.debug` 与 `app.zabrian.codexbar` 两个, helper 相应带 `.debug.helper` 与 `.helper` 后缀, 所以 `CodexBarHelper/` 下有两份 LaunchDaemon plist, `cleanup.swift` 也需要同时处理两套
diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swift
index 1562a5c..54b35e1 100644
--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift
+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift
@@ -80,7 +80,7 @@ final class SettingsOptionsPanelController {
self.willShow = willShow
self.contentControllerProvider = contentControllerProvider
// 内容行数随开关增删, 高度得跟着重算
- // 订阅整个 ObservableObject 而不是逐个 @Published: 那种列表漏一项就会让面板裁掉底部或留下空白,
+ // 订阅整个 ObservableObject 而不是逐个 @Published: 那种列表漏一项就会让面板裁掉底部或留下空白
// 而多余的触发在面板收着时被 scheduleResize 的守卫挡掉, 展开时也只是一次尺寸相同的空转
contentChanges
.sink { [weak self] in
@@ -167,7 +167,7 @@ final class SettingsOptionsPanelController {
// 只有刚构造出来的那一次需要重建, hosting controller 之后常驻, portal 已经建好
let needsEntryRebuild = panel == nil
let panel = ensurePanel()
- // 这里不必先布局: 下面 measuredPanelSize 走的 validFittingSize 第一句就是 layoutSubtreeIfNeeded,
+ // 这里不必先布局: 下面 measuredPanelSize 走的 validFittingSize 第一句就是 layoutSubtreeIfNeeded
// 而中间两句只碰设置窗口那棵树, 不会把面板弄脏
let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.frame
let screen = window.screen ?? NSScreen.main
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index c8c1dc6..a2a60ec 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -17,7 +17,7 @@ final class SettingsWindowController: HostingWindowController {
private let keepAliveController: KeepAliveController
private let onSyncChanged: (Bool) -> Void
private let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler
- /// 只在真的要展开时构造: 控制器一建就挂上内容变化订阅并常驻到 App 结束,
+ /// 只在真的要展开时构造: 控制器一建就挂上内容变化订阅并常驻到 App 结束
/// 而用户可能一次子面板都没开过
private var notificationOptionsPanelController: SettingsOptionsPanelController?
private var keepAliveOptionsPanelController: SettingsOptionsPanelController?
diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swift
index d8eca2d..0a74b8f 100644
--- a/CodexBar/Controllers/SidePanelSupport.swift
+++ b/CodexBar/Controllers/SidePanelSupport.swift
@@ -267,8 +267,7 @@ final class SidePanelDrawerPresenter {
// MARK: - 内容宿主
-/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView →
-/// configureLayers → setContentSize"的更新序列
+/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView → configureLayers → setContentSize"的更新序列
/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送
@MainActor
final class SidePanelContentHost<Root: View> {
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index 79ae3e1..315fb56 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -4,6 +4,7 @@ import Foundation
nonisolated struct CodexQuotaSnapshot: Equatable {
let account: CodexAccount
let planType: String?
+ let credits: RateLimitCreditsSnapshot?
let resetCreditsAvailableCount: Int?
let resetCreditExpirationDates: [Date]?
let generatedAt: Date
@@ -142,6 +143,14 @@ nonisolated struct RateLimitSnapshot: Decodable {
let planType: String?
let primary: RateLimitWindow?
let secondary: RateLimitWindow?
+ let credits: RateLimitCreditsSnapshot?
+}
+
+/// app-server 返回的 Credits 余额状态
+nonisolated struct RateLimitCreditsSnapshot: Decodable, Equatable {
+ let balance: String?
+ let hasCredits: Bool
+ let unlimited: Bool
}
/// resetsAt 是 Unix 时间戳, 在模型层先转成 Date 方便 UI 格式化
@@ -186,6 +195,7 @@ nonisolated extension CodexQuotaSnapshot {
self.init(
account: account,
planType: rateLimitsResponse?.rateLimits.planType,
+ credits: rateLimitsResponse.flatMap { Self.primaryCredits(from: $0) },
resetCreditsAvailableCount: rateLimitsResponse?.rateLimitResetCredits?.availableCount,
resetCreditExpirationDates: resetCreditExpirationDates,
generatedAt: generatedAt,
@@ -196,6 +206,11 @@ nonisolated extension CodexQuotaSnapshot {
)
}
+ private static func primaryCredits(from response: AccountRateLimitsResponse) -> RateLimitCreditsSnapshot? {
+ let primaryLimitId = response.rateLimits.limitId ?? "codex"
+ return response.rateLimitsByLimitId?[primaryLimitId]?.credits ?? response.rateLimits.credits
+ }
+
// 展示顺序: 顶层 rateLimits 指向的主 limit 置顶, 其余按名称排序
private static func orderedSnapshots(
from response: AccountRateLimitsResponse
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index f26a9bc..c15b1cc 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -1,3 +1,4 @@
+import Foundation
import SwiftUI
/// 菜单面板内共享的固定尺寸, 保持各分区对齐
@@ -137,6 +138,7 @@ struct EmptyDataPanel: View {
/// 多个 limit 的额度区, 使用 stale 透明度标记缓存回退数据
struct QuotaLimitsSection: View {
let limits: [CodexQuotaLimitSnapshot]
+ let credits: RateLimitCreditsSnapshot?
let resetCreditsAvailableCount: Int?
let resetCreditExpirationDates: [Date]?
let isStale: Bool
@@ -151,7 +153,7 @@ struct QuotaLimitsSection: View {
LiquidGlassDivider()
}
- quotaLimitSection(limit, showsResetCredits: isPrimary)
+ quotaLimitSection(limit, showsPrimaryMetadata: isPrimary)
}
}
.markStale(isStale)
@@ -162,7 +164,7 @@ struct QuotaLimitsSection: View {
}
}
- private func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot, showsResetCredits: Bool) -> some View {
+ private func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot, showsPrimaryMetadata: Bool) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Text(limit.title)
@@ -173,7 +175,11 @@ struct QuotaLimitsSection: View {
Spacer(minLength: 8)
- if showsResetCredits, let resetCreditsAvailableCount, resetCreditsAvailableCount > 0 {
+ if showsPrimaryMetadata, let credits, let value = creditsDisplayValue(credits) {
+ creditsBalance(value: value, credits: credits)
+ }
+
+ if showsPrimaryMetadata, let resetCreditsAvailableCount, resetCreditsAvailableCount > 0 {
resetCreditsButton(count: resetCreditsAvailableCount)
}
}
@@ -186,6 +192,74 @@ struct QuotaLimitsSection: View {
}
}
+ @ViewBuilder
+ private func creditsBalance(value: String, credits: RateLimitCreditsSnapshot) -> some View {
+ let capsule = metadataCapsule("积分: \(value)")
+
+ if let helpText = creditsHelpText(value: value, credits: credits) {
+ capsule.help(helpText)
+ } else {
+ capsule
+ }
+ }
+
+ private func creditsDisplayValue(_ credits: RateLimitCreditsSnapshot) -> String? {
+ if credits.unlimited {
+ return "无限"
+ }
+
+ if let balance = normalizedCreditsBalance(credits.balance) {
+ return compactCreditsBalance(balance)
+ }
+
+ return credits.hasCredits ? "可用" : nil
+ }
+
+ private func creditsHelpText(value: String, credits: RateLimitCreditsSnapshot) -> String? {
+ guard value.hasSuffix("K") || value.hasSuffix("M"),
+ let balance = normalizedCreditsBalance(credits.balance) else {
+ return nil
+ }
+
+ return balance
+ }
+
+ private func normalizedCreditsBalance(_ balance: String?) -> String? {
+ guard let balance = balance?.trimmingCharacters(in: .whitespacesAndNewlines), !balance.isEmpty else {
+ return nil
+ }
+
+ return balance
+ }
+
+ private func compactCreditsBalance(_ balance: String) -> String {
+ guard let amount = Double(balance), amount.isFinite else {
+ return truncatedCreditsBalance(balance)
+ }
+
+ let magnitude = abs(amount)
+ guard magnitude >= Self.compactCreditsThreshold else {
+ return truncatedCreditsBalance(balance)
+ }
+
+ guard let unit = Self.compactCreditsUnits.first(where: { magnitude >= $0.divisor }),
+ let formattedAmount = Self.compactCreditsFormatter.string(
+ from: NSNumber(value: amount / unit.divisor)
+ ) else {
+ return truncatedCreditsBalance(balance)
+ }
+
+ return truncatedCreditsBalance("\(formattedAmount)\(unit.suffix)")
+ }
+
+ private func truncatedCreditsBalance(_ balance: String) -> String {
+ guard balance.count > Self.maximumFallbackCreditsCharacters else {
+ return balance
+ }
+
+ return "\(balance.prefix(Self.maximumFallbackCreditsCharacters - 3))..."
+ }
+
private func resetCreditsButton(count: Int) -> some View {
Button {
onResetCreditsTap(
@@ -196,17 +270,41 @@ struct QuotaLimitsSection: View {
)
)
} label: {
- Text("重置次数: \(count)")
- .font(.caption2.weight(.medium))
- .foregroundStyle(.green)
- .lineLimit(1)
- .fixedSize(horizontal: true, vertical: false)
- .padding(.horizontal, 6)
- .padding(.vertical, 2)
- .liquidGlassCapsule(tint: .green)
+ metadataCapsule("重置次数: \(count)")
}
.buttonStyle(.plain)
}
+
+ private func metadataCapsule(_ text: String) -> some View {
+ Text(text)
+ .font(.caption2.weight(.medium))
+ .monospacedDigit()
+ .foregroundStyle(.green)
+ .lineLimit(1)
+ .fixedSize(horizontal: true, vertical: false)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .liquidGlassCapsule(tint: .green)
+ }
+
+ private static let compactCreditsThreshold = 10000.0
+ private static let maximumFallbackCreditsCharacters = 12
+ private static let compactCreditsUnits: [(divisor: Double, suffix: String)] = [
+ (1000000000000, "T"),
+ (1000000000, "B"),
+ (1000000, "M"),
+ (1000, "K")
+ ]
+
+ private static let compactCreditsFormatter: NumberFormatter = {
+ let formatter = NumberFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.numberStyle = .decimal
+ formatter.usesGroupingSeparator = false
+ formatter.minimumFractionDigits = 0
+ formatter.maximumFractionDigits = 1
+ return formatter
+ }()
}
/// 底部更新时间行, 同时承载 Sparkle 被动更新提示
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index 6794c47..54288ee 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -104,6 +104,7 @@ private extension CodexStatusMenuView {
if !snapshot.limits.isEmpty {
QuotaLimitsSection(
limits: snapshot.limits,
+ credits: snapshot.credits,
resetCreditsAvailableCount: snapshot.resetCreditsAvailableCount,
resetCreditExpirationDates: snapshot.resetCreditExpirationDates,
isStale: snapshot.isRateLimitsStale,
diff --git a/Scripts/appcast.sh b/Scripts/appcast.sh
index f215e12..5557386 100755
--- a/Scripts/appcast.sh
+++ b/Scripts/appcast.sh
@@ -3,7 +3,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
-BUILD_DIR="${BUILD_DIR:-${PROJECT_DIR}/build}"
+BUILD_DIR="${BUILD_DIR:-${PROJECT_DIR}/Build}"
DMG_PATH="${1:-}"
APPCAST_PATH="${APPCAST_PATH:-${PROJECT_DIR}/appcast.xml}"
@@ -25,7 +25,7 @@ usage: Scripts/appcast.sh [CodexBar-vX.Y.Z.dmg]
Environment:
BUILD_DIR Directory used for default DMG lookup.
- Defaults to build/.
+ Defaults to Build/.
APPCAST_PATH Path to appcast.xml. Defaults to appcast.xml.
DOWNLOAD_BASE_URL Base URL for DMG downloads.
Defaults to https://codexbar.zabrian.app/download.
diff --git a/Scripts/build.sh b/Scripts/build.sh
index 1c9fe26..0c6137d 100755
--- a/Scripts/build.sh
+++ b/Scripts/build.sh
@@ -7,7 +7,7 @@ PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
XCODE_PROJECT="${PROJECT_DIR}/CodexBar.xcodeproj"
XCODE_SCHEME="CodexBar"
CONFIGURATION="Release"
-BUILD_DIR="${PROJECT_DIR}/build"
+BUILD_DIR="${PROJECT_DIR}/Build"
DERIVED_DATA_PATH=""
ARCHIVE_PATH=""
EXPORT_OPTIONS_PLIST=""
@@ -28,17 +28,16 @@ usage() {
usage: Scripts/build.sh [options] [Output.app]
Builds a Release archive, exports a Developer ID app, submits it to Apple
-notarization, staples the ticket, validates the result, and writes the final app to build/.
-After a successful build, build/ keeps only the final .app.
+notarization, staples the ticket, validates the result, and writes the final app to build/
Options:
--project PATH Xcode project. Defaults to CodexBar.xcodeproj.
--scheme NAME Xcode scheme. Defaults to CodexBar.
--configuration NAME Xcode configuration. Defaults to Release.
- --build-dir DIR Build output directory. Defaults to build/.
+ --build-dir DIR Build output directory. Defaults to Build/.
Cleaned before each build.
- --derived-data PATH DerivedData path. Defaults to build/DerivedData.
- --archive-path PATH Archive path. Defaults to build/<scheme>.xcarchive.
+ --derived-data PATH DerivedData path. Defaults to Build/DerivedData.
+ --archive-path PATH Archive path. Defaults to Build/<scheme>.xcarchive.
--export-options PATH Export options plist. Generated when unset.
--team-id ID Apple Developer team ID. Defaults to the
DEVELOPMENT_TEAM build setting.
@@ -49,7 +48,7 @@ Options:
--notary-password PASSWORD App-specific password fallback. Prefer profile.
--skip-notarization Build/export without notarytool and stapling.
--skip-spctl-assess Skip final Gatekeeper spctl assessment.
- --output-app PATH Final app path. Defaults to build/CodexBar.app.
+ --output-app PATH Final app path. Defaults to Build/CodexBar.app.
-h, --help Show this help.
Recommended credential setup:
diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swift
index 358b366..f8e9f4b 100755
--- a/Scripts/cleanup.swift
+++ b/Scripts/cleanup.swift
@@ -187,7 +187,7 @@ private final class KeepAliveCleanupCommand {
candidates.append(registeredURL)
}
if configuration == .release {
- candidates.append(projectURL.appending(path: "build/CodexBar.app"))
+ candidates.append(projectURL.appending(path: "Build/CodexBar.app"))
}
for candidate in candidates {
diff --git a/Scripts/dmg.sh b/Scripts/dmg.sh
index 577cb56..bcfb344 100755
--- a/Scripts/dmg.sh
+++ b/Scripts/dmg.sh
@@ -3,7 +3,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
-BUILD_DIR="${BUILD_DIR:-${PROJECT_DIR}/build}"
+BUILD_DIR="${BUILD_DIR:-${PROJECT_DIR}/Build}"
APP_PATH="${1:-}"
OUTPUT_PATH="${2:-}"