Skip to content

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

feat: 添加菜单栏额度指示

Bobfed40b0e449c
diff --git a/AGENTS.md b/AGENTS.md
index 93b50e8..03fbc44 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -130,6 +130,7 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
- `isRateLimitsStale` / `isUsageStale` 标记额度或 token 区域是否来自同账号旧缓存; 本轮对应接口成功后重新生成 snapshot 并恢复为 `false`。
- 优先读取 `rateLimitsByLimitId`; 为空时回退顶层 `rateLimits`。
- 顶层 `rateLimits.limitId` 指向的主 limit 置顶, 缺省 `"codex"`。
+- `codexLimit` 返回 `limitId` 大小写不敏感等于 `"codex"` 的第一个 limit, 供菜单栏额度指示选择窗口使用。
- 其余 limit 按 `limitName ?? limitId` 做 localized standard 排序, 再按 `limitId` 稳定排序。
- `rateLimitResetCredits.availableCount` 读入 `resetCreditsAvailableCount`; 缺失时为 `nil`。
- `resetCreditsAvailableCount > 0` 时, 主 App 可使用本机 Codex OAuth token 请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits`; 401/403 时复用本轮认证刷新预算重试; 只保留可用且未过期的 `credits[].expires_at` 到 `resetCreditExpirationDates`, 请求失败时为 `nil` 且 UI 不展示过期时间 help text。
@@ -169,8 +170,10 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
- 正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`。
- 菜单栏不展示额度数字; 详情只在菜单面板中展示。
+- 设置页「菜单栏额度指示」使用独立开关控制启用状态; 开启后同一行显示额度窗口菜单, 选项来自当前账号 Codex limit 返回的窗口, 当前保留选择不在返回窗口中时用 fallback 标题追加到菜单。关闭开关时设置页保留最后一个非关闭窗口值参与菜单淡出, 避免过渡期间回退到默认窗口。关闭时菜单栏只展示原图标, 开启时将所选 Codex 窗口剩余额度进度条绘制在 `person.fill.checkmark` / `person.fill.xmark` 图标左侧, 以竖条形式作为单个菜单栏图像自动随状态刷新; 合成图尺寸为 `27 x 17`, 图标本体保持原始 `24 x 17`, 左侧竖条轨道为 `2 x 15`; 开启或关闭时竖条透明度做 0.18 秒过渡, 过渡期间合成图宽度和图标绘制坐标保持固定。
- 左键或全局快捷键切换菜单面板; 右键或 Control 点击显示「设置 / 日志 / 退出」。
-- 全局快捷键打开菜单面板前必须校验当前 status item 锚点可信; 锚点无 window、无有效 screen、按钮隐藏、bounds 为空、屏幕矩形异常, 或屏幕矩形没有落在目标屏幕范围内时, 使用无箭头 fallback `NSPanel` 在目标屏幕顶部居中打开。目标屏幕优先取鼠标所在屏幕, 找不到时取主屏幕。快捷键关闭已打开的菜单面板不受此校验影响。
+- 上下文菜单由 `NSStatusBarButton.performClick(nil)` 触发; 设置和日志菜单项 action 需要等 `NSMenuDelegate.menuDidClose(_:)` 确认菜单结束并清空 `statusItem.menu` 后再打开窗口, 避免键盘等效键在 `NSMenu` tracking 期间打开窗口导致无法激活到最前。
+- 全局快捷键打开菜单面板前必须短暂禁止设置窗口和日志窗口成为 key window, 避免已有设置/日志窗口被 App 激活一起带到前台; 随后校验当前 status item 锚点可信。锚点无 window、无有效 screen、按钮隐藏、bounds 为空、屏幕矩形异常, 或屏幕矩形没有落在目标屏幕范围内时, 使用无箭头 fallback `NSPanel` 在目标屏幕顶部居中打开。目标屏幕优先取鼠标所在屏幕, 找不到时取主屏幕。快捷键关闭已打开的菜单面板不受此校验影响。
菜单面板:
@@ -179,7 +182,7 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
- `LiquidGlassStyle.swift` 是自绘玻璃效果, 不是 macOS 原生 `.glassEffect`; 没有明确设计要求时不要切换。
- 账号图标双击触发刷新。邮箱文本双击切换模糊。
- 计划名是右侧加粗纯文字; `planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。
-- `resetCreditsAvailableCount` 有值时, 只在置顶主 limit 标题右侧显示 `重置次数: N`; `resetCreditExpirationDates` 非空时, 鼠标悬停在该文本上通过 help text 按升序逐行展示 `过期时间: yyyy-MM-dd HH:mm:ss • 可用: N`, 相同展示时间合并数量, 单个显示 `可用: 1`。
+- `resetCreditsAvailableCount` 有值时, 只在置顶主 limit 标题右侧显示 `重置次数: N`; `resetCreditExpirationDates` 非空时, 鼠标悬停在该文本上通过 help text 按升序逐行展示 `过期: yyyy-MM-dd HH:mm:ss • 可用: N`, 相同展示时间合并数量, 单个显示 `可用: 1`。
- 额度条展示剩余百分比, 固定为 50 个胶囊, 每个胶囊宽 `3.5`, 间距 `2`, 高 `12`; 颜色按 20% 一档: 红、橙、黄、薄荷、绿。
- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到额度条间距 `12`, 额度条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`; 不通过加宽菜单面板解决额度行溢出。
- 无 quota 数据时显示 `--` / `暂无数据`, 并使用占位色。
@@ -202,7 +205,8 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m
- 通过右键菜单「设置」打开独立 `AppSettingsView` 窗口。
- 不要恢复为 Option 点击或菜单面板内设置区。
-- 设置页包含「使用快捷键」行、「CodexBar 版本」和「Codex 版本」区域。
+- 设置页包含「菜单栏额度指示」、「使用快捷键」行、「CodexBar 版本」和「Codex 版本」区域。
+- 设置窗口按 SwiftUI 内容自适应高度时必须校验 `fittingSize` 有限并夹紧到安全上限; 设置页 `onAppear` / `didBecomeActive` 中触发的设置刷新不得同步发布 `@Published` 变化。
- `Codex CLI` 行图标用 `terminal`; `Codex APP` 行图标用 `app.badge`。
- 当前运行来源显示「当前使用」。
- 当前行优先展示 app-server 握手自报版本; 非当前行展示磁盘安装版本。
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index a5acc70..47718e3 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -282,7 +282,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 31;
+ CURRENT_PROJECT_VERSION = 32;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
@@ -298,7 +298,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.2.3;
+ MARKETING_VERSION = 3.2.4;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
@@ -321,7 +321,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 31;
+ CURRENT_PROJECT_VERSION = 32;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
@@ -337,7 +337,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 3.2.3;
+ MARKETING_VERSION = 3.2.4;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/Controllers/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swift
index 9dc12c2..374ea14 100644
--- a/CodexBar/Controllers/HostingWindowController.swift
+++ b/CodexBar/Controllers/HostingWindowController.swift
@@ -65,7 +65,7 @@ class HostingWindowController {
(window as? AuxiliaryHostingWindow)?.allowsKeyFocus = true
window.orderFrontRegardless()
- NSRunningApplication.current.activate(options: [])
+ NSApplication.shared.activate()
window.makeKeyAndOrderFront(nil)
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index fe731ee..952de40 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -9,6 +9,7 @@ final class SettingsWindowController: HostingWindowController {
private let codexHookSettings: CodexHookSettings
private let syncSettings: WorkflowSyncSettings
private let globalHotKeySettings: GlobalHotKeySettings
+ private let menuBarQuotaSettings: MenuBarQuotaSettings
private let onSyncChanged: (Bool) -> Void
init(
@@ -17,6 +18,7 @@ final class SettingsWindowController: HostingWindowController {
codexHookSettings: CodexHookSettings,
syncSettings: WorkflowSyncSettings,
globalHotKeySettings: GlobalHotKeySettings,
+ menuBarQuotaSettings: MenuBarQuotaSettings,
screenProvider: @escaping () -> NSScreen?,
onSyncChanged: @escaping (Bool) -> Void
) {
@@ -25,6 +27,7 @@ final class SettingsWindowController: HostingWindowController {
self.codexHookSettings = codexHookSettings
self.syncSettings = syncSettings
self.globalHotKeySettings = globalHotKeySettings
+ self.menuBarQuotaSettings = menuBarQuotaSettings
self.onSyncChanged = onSyncChanged
super.init(screenProvider: screenProvider)
}
@@ -40,6 +43,7 @@ final class SettingsWindowController: HostingWindowController {
codexHookSettings: codexHookSettings,
syncSettings: syncSettings,
globalHotKeySettings: globalHotKeySettings,
+ menuBarQuotaSettings: menuBarQuotaSettings,
onSyncChanged: onSyncChanged
)
.environmentObject(viewModel)
@@ -58,14 +62,8 @@ final class SettingsWindowController: HostingWindowController {
window.contentViewController?.view.layoutSubtreeIfNeeded()
if let fittingSize = window.contentViewController?.view.fittingSize,
- fittingSize.width > 0,
- fittingSize.height > 0 {
- window.setContentSize(
- NSSize(
- width: max(Metrics.minimumContentSize.width, fittingSize.width),
- height: max(Metrics.minimumContentSize.height, fittingSize.height)
- )
- )
+ let contentSize = clampedContentSize(fittingSize, for: window) {
+ window.setContentSize(contentSize)
}
super.prepareForDisplay(window)
@@ -73,11 +71,64 @@ final class SettingsWindowController: HostingWindowController {
private enum Metrics {
static let minimumContentSize = NSSize(width: 420, height: 240)
+ static let maximumFallbackContentSize = NSSize(width: 560, height: 720)
+ static let screenInset: CGFloat = 80
}
private func refreshSettingsState() {
codexHookSettings.refresh()
codexHookSettings.verifyInstalledHooks()
syncSettings.refresh()
+ menuBarQuotaSettings.refresh()
+ }
+
+ private func maximumContentSize(for window: NSWindow) -> NSSize {
+ guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {
+ return Metrics.maximumFallbackContentSize
+ }
+
+ return NSSize(
+ width: clampedContentDimension(
+ screen.visibleFrame.width - Metrics.screenInset,
+ minimum: Metrics.minimumContentSize.width,
+ maximum: Metrics.maximumFallbackContentSize.width
+ ),
+ height: clampedContentDimension(
+ screen.visibleFrame.height - Metrics.screenInset,
+ minimum: Metrics.minimumContentSize.height,
+ maximum: Metrics.maximumFallbackContentSize.height
+ )
+ )
+ }
+
+ private func clampedContentSize(_ fittingSize: NSSize, for window: NSWindow) -> NSSize? {
+ guard fittingSize.width.isFinite,
+ fittingSize.height.isFinite,
+ fittingSize.width > 0,
+ fittingSize.height > 0 else {
+ return nil
+ }
+
+ let maximumContentSize = maximumContentSize(for: window)
+ return NSSize(
+ width: clampedContentDimension(
+ fittingSize.width,
+ minimum: Metrics.minimumContentSize.width,
+ maximum: maximumContentSize.width
+ ),
+ height: clampedContentDimension(
+ fittingSize.height,
+ minimum: Metrics.minimumContentSize.height,
+ maximum: maximumContentSize.height
+ )
+ )
+ }
+
+ private func clampedContentDimension(
+ _ value: CGFloat,
+ minimum: CGFloat,
+ maximum: CGFloat
+ ) -> CGFloat {
+ min(maximum, max(minimum, value))
}
}
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index bbc8a73..5d3e14b 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -11,6 +11,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)
let syncSettings = WorkflowSyncSettings()
let globalHotKeySettings = GlobalHotKeySettings()
+ let menuBarQuotaSettings = MenuBarQuotaSettings()
let appUpdater = AppUpdater()
private var statusItemController: StatusItemController?
@@ -22,6 +23,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
codexHookSettings: codexHookSettings,
syncSettings: syncSettings,
globalHotKeySettings: globalHotKeySettings,
+ menuBarQuotaSettings: menuBarQuotaSettings,
appUpdater: appUpdater
)
controller.install()
@@ -35,12 +37,13 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
/// 菜单栏入口控制器, 统一管理状态图标, 菜单面板, 右键菜单和全局快捷键
@MainActor
-private final class StatusItemController: NSObject {
+private final class StatusItemController: NSObject, NSMenuDelegate {
private let viewModel: CodexStatusViewModel
private let workflowViewModel: WorkflowViewModel
private let codexHookSettings: CodexHookSettings
private let syncSettings: WorkflowSyncSettings
private let globalHotKeySettings: GlobalHotKeySettings
+ private let menuBarQuotaSettings: MenuBarQuotaSettings
private let appUpdater: AppUpdater
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let popover = NSPopover()
@@ -60,7 +63,8 @@ private final class StatusItemController: NSObject {
appUpdater: appUpdater,
codexHookSettings: codexHookSettings,
syncSettings: syncSettings,
- globalHotKeySettings: globalHotKeySettings
+ globalHotKeySettings: globalHotKeySettings,
+ menuBarQuotaSettings: menuBarQuotaSettings
) { [weak self] in
self?.statusItem.button?.window?.screen
} onSyncChanged: { [weak self] enabled in
@@ -100,12 +104,12 @@ private final class StatusItemController: NSObject {
private var delayedStatusRefreshTask: Task<Void, Never>?
private var menuSurfaceState = MenuSurfaceState.hidden
private var cancellables = Set<AnyCancellable>()
- private var isShowingErrorImage: Bool?
+ private var statusIconState: StatusIconState?
+ private var statusIconAnimationTask: Task<Void, Never>?
private var registeredHotKeyShortcut: GlobalHotKeyShortcut?
private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?
-
- private static let normalImage = makeStatusImage("person.fill.checkmark")
- private static let errorImage = makeStatusImage("person.fill.xmark")
+ private var activeStatusItemMenu: NSMenu?
+ private var pendingStatusItemMenuAction: (@MainActor () -> Void)?
init(
viewModel: CodexStatusViewModel,
@@ -113,6 +117,7 @@ private final class StatusItemController: NSObject {
codexHookSettings: CodexHookSettings,
syncSettings: WorkflowSyncSettings,
globalHotKeySettings: GlobalHotKeySettings,
+ menuBarQuotaSettings: MenuBarQuotaSettings,
appUpdater: AppUpdater
) {
self.viewModel = viewModel
@@ -120,20 +125,177 @@ private final class StatusItemController: NSObject {
self.codexHookSettings = codexHookSettings
self.syncSettings = syncSettings
self.globalHotKeySettings = globalHotKeySettings
+ self.menuBarQuotaSettings = menuBarQuotaSettings
self.appUpdater = appUpdater
super.init()
}
- private static func makeStatusImage(_ symbolName: String) -> NSImage? {
+ private static func makeStatusImage(
+ _ symbolName: String,
+ progress: StatusIconProgress? = nil,
+ progressVisibility: CGFloat = 1
+ ) -> NSImage? {
+ guard let symbolImage = makeStatusSymbolImage(symbolName) else {
+ return nil
+ }
+
+ guard let progress else {
+ symbolImage.isTemplate = true
+ return symbolImage
+ }
+
+ let progressVisibility = clampedProgressVisibility(progressVisibility)
+ let progressImage = NSImage(size: Metrics.progressStatusImageSize, flipped: false) { _ in
+ Self.drawStatusSymbol(
+ symbolImage,
+ in: Metrics.progressStatusSymbolRect,
+ isStale: progress.isStale
+ )
+ Self.drawProgress(progress, visibility: progressVisibility)
+ return true
+ }
+ progressImage.isTemplate = false
+ progressImage.alignmentRect = NSRect(
+ x: 0,
+ y: symbolImage.alignmentRect.minY,
+ width: Metrics.progressStatusImageSize.width,
+ height: symbolImage.alignmentRect.height
+ )
+ return progressImage
+ }
+
+ private static func makeStatusSymbolImage(_ symbolName: String) -> NSImage? {
let configuration = NSImage.SymbolConfiguration(
pointSize: 16,
weight: .regular,
scale: .medium
)
- let image = NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
+ return NSImage(systemSymbolName: symbolName, accessibilityDescription: nil)?
.withSymbolConfiguration(configuration)
- image?.isTemplate = true
- return image
+ }
+
+ private static func drawStatusSymbol(
+ _ image: NSImage,
+ in rect: NSRect,
+ isStale: Bool
+ ) {
+ NSGraphicsContext.saveGraphicsState()
+ NSColor.labelColor
+ .withAlphaComponent(isStale ? Metrics.staleIconAlpha : 1)
+ .setFill()
+ rect.fill()
+ image.draw(
+ in: rect,
+ from: .zero,
+ operation: .destinationIn,
+ fraction: 1
+ )
+ NSGraphicsContext.restoreGraphicsState()
+ }
+
+ private static func drawProgress(
+ _ progress: StatusIconProgress,
+ visibility: CGFloat
+ ) {
+ let visibility = clampedProgressVisibility(visibility)
+ guard visibility > 0 else {
+ return
+ }
+
+ let trackRect = Metrics.progressTrackRect
+ let cornerRadius = Metrics.progressTrackCornerRadius
+ let progressAlpha = (progress.isStale ? Metrics.staleProgressAlpha : 1) * visibility
+ NSColor.tertiaryLabelColor
+ .withAlphaComponent(Metrics.progressTrackAlpha * progressAlpha)
+ .setFill()
+ NSBezierPath(
+ roundedRect: trackRect,
+ xRadius: cornerRadius,
+ yRadius: cornerRadius
+ )
+ .fill()
+
+ let fillHeight = trackRect.height * CGFloat(progress.percent) / 100
+ guard fillHeight > 0 else {
+ return
+ }
+
+ let fillRect = NSRect(
+ x: trackRect.minX,
+ y: trackRect.minY,
+ width: trackRect.width,
+ height: fillHeight
+ )
+ quotaProgressColor(for: progress.percent)
+ .withAlphaComponent(progressAlpha)
+ .setFill()
+ NSBezierPath(
+ roundedRect: fillRect,
+ xRadius: cornerRadius,
+ yRadius: cornerRadius
+ )
+ .fill()
+ }
+
+ private static func clampedProgressVisibility(_ value: CGFloat) -> CGFloat {
+ min(max(value, 0), 1)
+ }
+
+ private static func easedProgressVisibility(_ value: CGFloat) -> CGFloat {
+ let value = clampedProgressVisibility(value)
+ return value * value * (3 - 2 * value)
+ }
+
+ private static func quotaProgressColor(for percent: Int) -> NSColor {
+ switch percent {
+ case 80...:
+ nsColor(hex: 0x16A085)
+ case 60 ..< 80:
+ nsColor(hex: 0x5DADE2)
+ case 40 ..< 60:
+ nsColor(hex: 0xF5B041)
+ case 20 ..< 40:
+ nsColor(hex: 0xFF7A59)
+ default:
+ nsColor(hex: 0xEE3F3F)
+ }
+ }
+
+ private static func nsColor(hex: Int) -> NSColor {
+ NSColor(
+ red: CGFloat((hex >> 16) & 0xFF) / 255.0,
+ green: CGFloat((hex >> 8) & 0xFF) / 255.0,
+ blue: CGFloat(hex & 0xFF) / 255.0,
+ alpha: 1
+ )
+ }
+
+ private struct StatusIconState: Equatable {
+ let usesErrorImage: Bool
+ let progress: StatusIconProgress?
+
+ var symbolName: String {
+ usesErrorImage ? Metrics.errorStatusSymbolName : Metrics.normalStatusSymbolName
+ }
+ }
+
+ private struct StatusIconProgress: Equatable {
+ let percent: Int
+ let isStale: Bool
+
+ init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {
+ guard let targetWindowId = selection.windowId,
+ let snapshot,
+ let window = snapshot.codexLimit?.windows.first(where: {
+ $0.id == targetWindowId
+ }),
+ window.hasData else {
+ return nil
+ }
+
+ percent = window.remainingPercent
+ isStale = snapshot.isRateLimitsStale
+ }
}
func install() {
@@ -150,6 +312,7 @@ private final class StatusItemController: NSObject {
func uninstall() {
closeMenuSurface(animated: false)
auxiliaryWindowFocusRestoreTask?.cancel()
+ statusIconAnimationTask?.cancel()
workflowSyncScheduler.cancel()
setAuxiliaryWindowKeyFocus(true)
globalHotKeyController.uninstall()
@@ -165,6 +328,7 @@ private final class StatusItemController: NSObject {
button.target = self
button.action = #selector(statusItemClicked(_:))
button.imagePosition = .imageOnly
+ button.imageScaling = .scaleNone
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
@@ -198,15 +362,22 @@ private final class StatusItemController: NSObject {
}
private func observeViewModel() {
- Publishers.CombineLatest(viewModel.$loadState, viewModel.$snapshot)
- .map { loadState, snapshot in
- loadState.isError || snapshot?.hasTrustedData == false
- }
- .removeDuplicates()
- .sink { [weak self] usesErrorImage in
- self?.updateStatusImage(usesErrorImage: usesErrorImage)
- }
- .store(in: &cancellables)
+ Publishers.CombineLatest3(
+ viewModel.$loadState,
+ viewModel.$snapshot,
+ menuBarQuotaSettings.$selection
+ )
+ .map { loadState, snapshot, selection in
+ StatusIconState(
+ usesErrorImage: loadState.isError || snapshot?.hasTrustedData == false,
+ progress: StatusIconProgress(snapshot: snapshot, selection: selection)
+ )
+ }
+ .removeDuplicates()
+ .sink { [weak self] state in
+ self?.updateStatusImage(state)
+ }
+ .store(in: &cancellables)
viewModel.$autoRefreshCountdownStartedAt
.compactMap(\.self)
@@ -290,16 +461,104 @@ private final class StatusItemController: NSObject {
}
private func updateStatusImage() {
- updateStatusImage(usesErrorImage: viewModel.usesErrorImage)
+ updateStatusImage(currentStatusIconState)
}
- private func updateStatusImage(usesErrorImage: Bool) {
- guard usesErrorImage != isShowingErrorImage else {
+ private var currentStatusIconState: StatusIconState {
+ StatusIconState(
+ usesErrorImage: viewModel.usesErrorImage,
+ progress: StatusIconProgress(
+ snapshot: viewModel.snapshot,
+ selection: menuBarQuotaSettings.selection
+ )
+ )
+ }
+
+ private func updateStatusImage(_ state: StatusIconState) {
+ guard state != statusIconState else {
+ return
+ }
+
+ let previousState = statusIconState
+ statusIconAnimationTask?.cancel()
+ statusIconState = state
+
+ guard let previousState else {
+ statusItem.button?.image = Self.makeStatusImage(state.symbolName, progress: state.progress)
+ return
+ }
+
+ if let animation = statusProgressAnimation(
+ from: previousState.progress,
+ to: state.progress
+ ) {
+ animateStatusProgress(
+ symbolName: state.symbolName,
+ progress: animation.progress,
+ finalState: state,
+ fromVisibility: animation.fromVisibility,
+ toVisibility: animation.toVisibility
+ )
return
}
- isShowingErrorImage = usesErrorImage
- statusItem.button?.image = usesErrorImage ? Self.errorImage : Self.normalImage
+ statusItem.button?.image = Self.makeStatusImage(state.symbolName, progress: state.progress)
+ }
+
+ private func statusProgressAnimation(
+ from previousProgress: StatusIconProgress?,
+ to progress: StatusIconProgress?
+ ) -> (progress: StatusIconProgress, fromVisibility: CGFloat, toVisibility: CGFloat)? {
+ switch (previousProgress, progress) {
+ case (nil, let progress?):
+ (progress, 0, 1)
+ case (let progress?, nil):
+ (progress, 1, 0)
+ default:
+ nil
+ }
+ }
+
+ private func animateStatusProgress(
+ symbolName: String,
+ progress: StatusIconProgress,
+ finalState: StatusIconState,
+ fromVisibility: CGFloat,
+ toVisibility: CGFloat
+ ) {
+ statusIconAnimationTask = Task { @MainActor [weak self] in
+ for frame in 0 ... Metrics.statusIconProgressAnimationFrameCount {
+ guard let self,
+ !Task.isCancelled,
+ statusIconState == finalState else {
+ return
+ }
+
+ let rawProgress = CGFloat(frame) / CGFloat(Metrics.statusIconProgressAnimationFrameCount)
+ let easedProgress = Self.easedProgressVisibility(rawProgress)
+ let visibility = fromVisibility + (toVisibility - fromVisibility) * easedProgress
+ statusItem.button?.image = Self.makeStatusImage(
+ symbolName,
+ progress: progress,
+ progressVisibility: visibility
+ )
+
+ if frame < Metrics.statusIconProgressAnimationFrameCount {
+ try? await Task.sleep(
+ nanoseconds: Metrics.statusIconProgressAnimationFrameDelayNanoseconds
+ )
+ }
+ }
+
+ guard let self,
+ !Task.isCancelled,
+ statusIconState == finalState else {
+ return
+ }
+
+ statusItem.button?.image = Self.makeStatusImage(symbolName, progress: finalState.progress)
+ statusIconAnimationTask = nil
+ }
}
@objc private func statusItemClicked(_ sender: NSStatusBarButton) {
@@ -335,9 +594,18 @@ private final class StatusItemController: NSObject {
private func toggleMenuSurfaceFromHotKey() {
let targetScreen = screenContainingMouse() ?? NSScreen.main
+ let opensMenuSurface = menuSurfaceState == .hidden || menuSurfaceState == .closing
+ if opensMenuSurface {
+ suspendAuxiliaryWindowKeyFocus()
+ }
+
toggleMenuSurface {
openMenuSurfaceFromHotKey(on: targetScreen)
}
+
+ if opensMenuSurface {
+ scheduleAuxiliaryWindowKeyFocusRestore()
+ }
}
private func openMenuSurfaceFromHotKey(on targetScreen: NSScreen?) {
@@ -434,9 +702,16 @@ private final class StatusItemController: NSObject {
}
private func presentStatusItemMenu(_ menu: NSMenu, relativeTo button: NSStatusBarButton) {
+ pendingStatusItemMenuAction = nil
+ activeStatusItemMenu = menu
+ menu.delegate = self
statusItem.menu = menu
- defer { statusItem.menu = nil }
button.performClick(nil)
+ finishStatusItemMenuPresentation(menu)
+ }
+
+ func menuDidClose(_ menu: NSMenu) {
+ finishStatusItemMenuPresentation(menu)
}
private func makeContextMenu() -> NSMenu {
@@ -485,11 +760,55 @@ private final class StatusItemController: NSObject {
}
@objc private func openSettings() {
- settingsWindowController.open()
+ openAuxiliaryWindow { [weak self] in
+ self?.settingsWindowController.open()
+ }
}
@objc private func openLog() {
- logWindowController.open()
+ openAuxiliaryWindow { [weak self] in
+ self?.logWindowController.open()
+ }
+ }
+
+ private func openAuxiliaryWindow(_ open: @escaping @MainActor () -> Void) {
+ guard activeStatusItemMenu == nil else {
+ pendingStatusItemMenuAction = { [weak self] in
+ self?.openAuxiliaryWindow(open)
+ }
+ return
+ }
+
+ auxiliaryWindowFocusRestoreTask?.cancel()
+ auxiliaryWindowFocusRestoreTask = nil
+ setAuxiliaryWindowKeyFocus(true)
+ open()
+ }
+
+ private func runPendingStatusItemMenuAction() {
+ guard let pendingStatusItemMenuAction else {
+ return
+ }
+
+ self.pendingStatusItemMenuAction = nil
+ DispatchQueue.main.async {
+ pendingStatusItemMenuAction()
+ }
+ }
+
+ private func finishStatusItemMenuPresentation(_ menu: NSMenu) {
+ guard activeStatusItemMenu === menu else {
+ return
+ }
+
+ menu.delegate = nil
+ activeStatusItemMenu = nil
+
+ if statusItem.menu === menu {
+ statusItem.menu = nil
+ }
+
+ runPendingStatusItemMenuAction()
}
@objc private func quit() {
@@ -673,11 +992,37 @@ private final class StatusItemController: NSObject {
}
private enum Metrics {
+ static let normalStatusSymbolName = "person.fill.checkmark"
+ static let errorStatusSymbolName = "person.fill.xmark"
static let fadeInDuration: TimeInterval = 0.24
static let fadeOutDuration: TimeInterval = 0.18
static let auxiliaryWindowKeyFocusRestoreDelayMilliseconds: UInt64 = 120
static let minimumTrustedAnchorLength: CGFloat = 1
static let anchorScreenTolerance: CGFloat = 1
+ static let progressStatusSymbolSize = NSSize(width: 24, height: 17)
+ static let progressStatusExtraWidth: CGFloat = 3
+ static let progressStatusImageSize = NSSize(
+ width: progressStatusSymbolSize.width + progressStatusExtraWidth,
+ height: progressStatusSymbolSize.height
+ )
+ static let progressStatusSymbolRect = NSRect(
+ x: progressStatusExtraWidth,
+ y: 0,
+ width: progressStatusSymbolSize.width,
+ height: progressStatusSymbolSize.height
+ )
+ static let progressTrackRect = NSRect(x: 0.5, y: 1, width: 2, height: 15)
+ static let progressTrackCornerRadius: CGFloat = 1
+ static let progressTrackAlpha: CGFloat = 0.34
+ static let staleIconAlpha: CGFloat = 0.75
+ static let staleProgressAlpha: CGFloat = 0.55
+ static let statusIconProgressAnimationDuration: TimeInterval = 0.18
+ static let statusIconProgressAnimationFrameCount = 10
+ static let statusIconProgressAnimationFrameDelayNanoseconds = UInt64(
+ statusIconProgressAnimationDuration
+ / Double(statusIconProgressAnimationFrameCount)
+ * 1000000000
+ )
}
private enum MenuSurfaceState {
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index cd8fc25..d8bd4fb 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -24,6 +24,12 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
hasTrustedRateLimitsData || hasTrustedUsageData
}
+ var codexLimit: CodexQuotaLimitSnapshot? {
+ limits.first {
+ $0.limitId.compare("codex", options: [.caseInsensitive]) == .orderedSame
+ }
+ }
+
private var hasTrustedRateLimitsData: Bool {
!limits.isEmpty && !isRateLimitsStale
}
diff --git a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
new file mode 100644
index 0000000..d600046
--- /dev/null
+++ b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift
@@ -0,0 +1,133 @@
+import Combine
+import Foundation
+
+/// 菜单栏额度指示偏好
+@MainActor
+final class MenuBarQuotaSettings: ObservableObject {
+ @Published private(set) var selection: MenuBarQuotaSelection
+
+ private let defaults: UserDefaults
+ private var pendingSelection: MenuBarQuotaSelection?
+ private var publishSelectionTask: Task<Void, Never>?
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ selection = Self.loadSelection(from: defaults)
+ }
+
+ deinit {
+ publishSelectionTask?.cancel()
+ }
+
+ func refresh() {
+ publishSelection(Self.loadSelection(from: defaults))
+ }
+
+ func setSelection(_ selection: MenuBarQuotaSelection) {
+ guard selection != effectiveSelection else {
+ return
+ }
+
+ saveSelection(selection)
+ publishSelection(selection)
+ }
+
+ private var effectiveSelection: MenuBarQuotaSelection {
+ pendingSelection ?? selection
+ }
+
+ private func saveSelection(_ selection: MenuBarQuotaSelection) {
+ if selection == .off {
+ defaults.removeObject(forKey: Self.selectionKey)
+ } else {
+ defaults.set(selection.rawValue, forKey: Self.selectionKey)
+ }
+ }
+
+ private func publishSelection(_ selection: MenuBarQuotaSelection) {
+ publishSelectionTask?.cancel()
+ publishSelectionTask = nil
+ pendingSelection = nil
+
+ guard selection != self.selection else {
+ return
+ }
+
+ pendingSelection = selection
+ publishSelectionTask = Task { @MainActor [weak self] in
+ await Task.yield()
+ guard let self, !Task.isCancelled else {
+ return
+ }
+
+ self.selection = selection
+ pendingSelection = nil
+ publishSelectionTask = nil
+ }
+ }
+
+ private static func loadSelection(from defaults: UserDefaults) -> MenuBarQuotaSelection {
+ guard let rawValue = defaults.string(forKey: selectionKey),
+ let selection = MenuBarQuotaSelection(persistedValue: rawValue) else {
+ return .off
+ }
+
+ return selection
+ }
+
+ private static let selectionKey = "MenuBarQuota.selection"
+}
+
+nonisolated enum MenuBarQuotaSelection: String, CaseIterable, Identifiable {
+ case off
+ case primary
+ case secondary
+
+ var id: String {
+ rawValue
+ }
+
+ init?(persistedValue: String) {
+ switch persistedValue {
+ case "fiveHours":
+ self = .primary
+ case "sevenDays":
+ self = .secondary
+ default:
+ self.init(rawValue: persistedValue)
+ }
+ }
+
+ init?(windowId: String) {
+ switch windowId {
+ case "primary":
+ self = .primary
+ case "secondary":
+ self = .secondary
+ default:
+ return nil
+ }
+ }
+
+ var fallbackTitle: String {
+ switch self {
+ case .off:
+ "关闭"
+ case .primary:
+ "主额度"
+ case .secondary:
+ "次额度"
+ }
+ }
+
+ var windowId: String? {
+ switch self {
+ case .off:
+ nil
+ case .primary:
+ "primary"
+ case .secondary:
+ "secondary"
+ }
+ }
+}
diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
index 019f177..c36be28 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift
@@ -225,7 +225,7 @@ struct QuotaLimitsSection: View {
}
return groups.map { group in
- "过期时间: \(group.expirationText) • 可用: \(group.count)"
+ "过期: \(group.expirationText) • 可用: \(group.count)"
}
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index bb3343b..f69bcb4 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -7,9 +7,11 @@ struct AppSettingsView: View {
@EnvironmentObject private var appUpdater: AppUpdater
@StateObject private var loginItemSettings = LoginItemSettings()
@StateObject private var codexVersions = CodexCLIVersionViewModel()
+ @State private var lastMenuBarQuotaWindowSelection: MenuBarQuotaSelection = .primary
@ObservedObject var codexHookSettings: CodexHookSettings
@ObservedObject var syncSettings: WorkflowSyncSettings
@ObservedObject var globalHotKeySettings: GlobalHotKeySettings
+ @ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings
let onSyncChanged: (Bool) -> Void
var body: some View {
@@ -19,6 +21,8 @@ struct AppSettingsView: View {
LiquidGlassDivider()
automaticUpdateCheckRow
LiquidGlassDivider()
+ menuBarQuotaRow
+ LiquidGlassDivider()
codexHookRow
LiquidGlassDivider()
syncRow
@@ -56,15 +60,20 @@ struct AppSettingsView: View {
.onAppear {
loginItemSettings.refresh()
syncSettings.refresh()
+ refreshMenuBarQuotaSettings()
appUpdater.refreshAutomaticCheckSetting()
refreshCodexVersionSection()
}
.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
codexHookSettings.refresh()
syncSettings.refresh()
+ refreshMenuBarQuotaSettings()
codexHookSettings.verifyInstalledHooks()
refreshCodexVersionSection()
}
+ .onChange(of: menuBarQuotaSettings.selection) { _, selection in
+ rememberMenuBarQuotaSelection(selection)
+ }
}
}
@@ -78,6 +87,7 @@ private extension AppSettingsView {
static let surfaceCornerRadius: CGFloat = 16
static let panelCornerRadius: CGFloat = 10
static let iconWidth: CGFloat = 18
+ static let menuBarQuotaPickerWidth: CGFloat = 72
static let statusAnimation = Animation.codexStatus
}
@@ -108,6 +118,114 @@ private extension AppSettingsView {
HotKeyRecorderRow(settings: globalHotKeySettings)
}
+ var menuBarQuotaRow: some View {
+ let isEnabled = isMenuBarQuotaEnabled
+
+ return HStack(spacing: 10) {
+ Image(systemName: "gauge.with.dots.needle.50percent")
+ .frame(width: Metrics.iconWidth)
+ .foregroundStyle(.tint)
+
+ Text("菜单栏额度指示")
+
+ Spacer()
+
+ if isEnabled {
+ Picker(
+ "额度窗口",
+ selection: Binding(
+ get: { activeMenuBarQuotaSelection },
+ set: { setMenuBarQuotaWindowSelection($0) }
+ )
+ ) {
+ ForEach(menuBarQuotaWindowOptions) { option in
+ Text(option.title).tag(option.selection)
+ }
+ }
+ .labelsHidden()
+ .pickerStyle(.menu)
+ .controlSize(.small)
+ .frame(width: Metrics.menuBarQuotaPickerWidth)
+ .transition(.opacity.combined(with: .move(edge: .trailing)))
+ }
+
+ Toggle(
+ "菜单栏额度指示",
+ isOn: Binding(
+ get: { isMenuBarQuotaEnabled },
+ set: { setMenuBarQuotaEnabled($0) }
+ )
+ )
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ }
+ .animation(Metrics.statusAnimation, value: isEnabled)
+ }
+
+ var menuBarQuotaWindowOptions: [MenuBarQuotaOption] {
+ var options = (statusViewModel.snapshot?.codexLimit?.windows ?? [])
+ .compactMap { window -> MenuBarQuotaOption? in
+ guard let selection = MenuBarQuotaSelection(windowId: window.id) else {
+ return nil
+ }
+
+ return MenuBarQuotaOption(selection: selection, title: window.label)
+ }
+
+ let selectedWindow = activeMenuBarQuotaSelection
+ if !options.contains(where: { $0.selection == selectedWindow }) {
+ options.append(
+ MenuBarQuotaOption(
+ selection: selectedWindow,
+ title: selectedWindow.fallbackTitle
+ )
+ )
+ }
+
+ return options
+ }
+
+ var activeMenuBarQuotaSelection: MenuBarQuotaSelection {
+ let selection = menuBarQuotaSettings.selection
+ return selection == .off ? lastMenuBarQuotaWindowSelection : selection
+ }
+
+ var isMenuBarQuotaEnabled: Bool {
+ menuBarQuotaSettings.selection != .off
+ }
+
+ func setMenuBarQuotaWindowSelection(_ selection: MenuBarQuotaSelection) {
+ rememberMenuBarQuotaSelection(selection)
+ menuBarQuotaSettings.setSelection(selection)
+ }
+
+ func setMenuBarQuotaEnabled(_ enabled: Bool) {
+ if !enabled {
+ rememberMenuBarQuotaSelection(menuBarQuotaSettings.selection)
+ menuBarQuotaSettings.setSelection(.off)
+ return
+ }
+
+ setMenuBarQuotaWindowSelection(activeMenuBarQuotaSelection)
+ }
+
+ func refreshMenuBarQuotaSettings() {
+ menuBarQuotaSettings.refresh()
+ rememberMenuBarQuotaSelection()
+ }
+
+ func rememberMenuBarQuotaSelection(
+ _ selection: MenuBarQuotaSelection? = nil
+ ) {
+ let selection = selection ?? menuBarQuotaSettings.selection
+ guard selection != .off else {
+ return
+ }
+
+ lastMenuBarQuotaWindowSelection = selection
+ }
+
var codexHookRow: some View {
VStack(alignment: .leading, spacing: 4) {
SettingsToggleRow(
@@ -298,3 +416,12 @@ private struct SyncRowState {
isActive && (isSyncing || lastSyncText != nil)
}
}
+
+private struct MenuBarQuotaOption: Identifiable {
+ let selection: MenuBarQuotaSelection
+ let title: String
+
+ var id: String {
+ selection.id
+ }
+}
diff --git a/Docs/AppServer.md b/Docs/AppServer.md
index 460418f..98af040 100644
--- a/Docs/AppServer.md
+++ b/Docs/AppServer.md
@@ -60,7 +60,7 @@ codex app-server --listen stdio://
- `rateLimitsByLimitId` 优先于顶层 `rateLimits`; 为空时回退顶层 `rateLimits`。
- 顶层 `rateLimits.limitId` 指向主 limit, 缺省为 `codex`。
- `rateLimitResetCredits.availableCount` 是可用额度重置次数; 字段缺失时 UI 不显示重置次数。
-- `rateLimitResetCredits.availableCount > 0` 时, `CodexResetCreditsService` 使用真实用户 `CODEX_HOME/auth.json` 或 `HOME/.codex/auth.json` 中的 access token 请求 ChatGPT backend, 超时为 4 秒。401/403 时复用本轮认证刷新预算调用一次 `account/read(refreshToken:true)` 后重试; 其他失败静默降级。成功响应只保留 `status == "available"` 且未过期 credit 的 `expires_at`, 按时间升序展示在 `重置次数: N` 的 help text 中, 格式为 `过期时间: yyyy-MM-dd HH:mm:ss • 可用: N`; 相同展示时间合并数量, 单个显示 `可用: 1`。
+- `rateLimitResetCredits.availableCount > 0` 时, `CodexResetCreditsService` 使用真实用户 `CODEX_HOME/auth.json` 或 `HOME/.codex/auth.json` 中的 access token 请求 ChatGPT backend, 超时为 4 秒。401/403 时复用本轮认证刷新预算调用一次 `account/read(refreshToken:true)` 后重试; 其他失败静默降级。成功响应只保留 `status == "available"` 且未过期 credit 的 `expires_at`, 按时间升序展示在 `重置次数: N` 的 help text 中, 格式为 `过期: yyyy-MM-dd HH:mm:ss • 可用: N`; 相同展示时间合并数量, 单个显示 `可用: 1`。
认证失败时,同会话最多调用一次 `account/read(refreshToken:true)` 后重试原读取。
diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.md
index 481cf69..417fe24 100644
--- a/Docs/DevelopmentGuide.md
+++ b/Docs/DevelopmentGuide.md
@@ -77,7 +77,7 @@ sequenceDiagram
`StatusItemController.install()` 负责:
-- 配置菜单栏按钮图标, tooltip 和点击事件
+- 配置菜单栏按钮图标、可选额度进度条和点击事件
- 配置菜单面板的 SwiftUI 根视图
- 订阅状态变化并切换菜单栏图标
- 订阅 Hook、同步开关和同步可用性变化, 把维护/同步请求交给 `WorkflowSyncScheduler`
@@ -94,6 +94,8 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall
正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`
+设置页「菜单栏额度指示」默认关闭, 使用独立开关控制启用状态; 开启后在同一行显示额度窗口菜单, 可选择当前账号 Codex limit 返回的额度窗口, 当前保留选择不在返回窗口中时用 fallback 标题追加到菜单。关闭开关时, 设置页保留最后一个非关闭窗口值参与菜单淡出, 避免过渡期间回退到默认窗口。关闭时菜单栏只使用系统 template 图标; 开启后 `StatusItemController` 会把所选 Codex 窗口的剩余额度进度条绘制在图标左侧, 以竖条形式与 `person.fill.checkmark` / `person.fill.xmark` 合成为单个 `NSImage`, 并随 `CodexStatusViewModel` 自动刷新。合成图尺寸为 `27 x 17`, 图标本体保持原始 `24 x 17`, 左侧竖条轨道为 `2 x 15`。开启或关闭进度条时, `StatusItemController` 用逐帧重绘的方式对左侧竖条透明度做 0.18 秒过渡; 过渡期间合成图宽度和图标绘制坐标保持固定。
+
错误图标触发条件:
- `loadState` 是 `.notLoggedIn` 或 `.initializationFailed`
@@ -111,14 +113,16 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall
| 上下文菜单"日志" | 打开独立日志窗口 |
| 上下文菜单"退出" | 终止 App |
+上下文菜单由 `NSStatusBarButton.performClick(nil)` 触发。设置和日志菜单项的 action 可能在 `NSMenu` 仍处于 tracking 时被键盘等效键触发, 因此 `StatusItemController` 会先缓存打开请求, 等 `NSMenuDelegate.menuDidClose(_:)` 确认菜单结束、清空 `statusItem.menu` 后再真正打开辅助窗口, 确保鼠标点击和键盘等效键路径都能把目标窗口激活到最前面。
+
全局快捷键由 `GlobalHotKeySettings` 和 `GlobalHotKeyController` 管理。没有用户设置时默认注册 `⌘⇧W`; 用户清除后不注册快捷键。注册冲突时恢复到上一个已注册快捷键, 并把错误显示在设置窗口的快捷键行内。
-通过全局快捷键打开菜单面板前, `StatusItemController` 会先用鼠标所在屏幕作为目标屏幕, 找不到时回退主屏幕, 再校验当前 `NSStatusBarButton` 锚点是否可信: 按钮必须有 window 和有效 screen、未隐藏且 bounds 非空, 换算后的屏幕矩形必须是有限尺寸, 宽高至少 1 px, 并且与目标屏幕范围相交。锚点可信时使用 `NSPopover` 挂在 status item 下方; 锚点不可信时使用无箭头 fallback `NSPanel`, 放在目标屏幕顶部居中位置。已打开时仍允许快捷键关闭当前面板。鼠标点击路径不做这层 fallback, 因为点击 sender 本身就是当前锚点。
+通过全局快捷键打开菜单面板前, `StatusItemController` 会先用鼠标所在屏幕作为目标屏幕, 找不到时回退主屏幕, 再校验当前 `NSStatusBarButton` 锚点是否可信: 按钮必须有 window 和有效 screen、未隐藏且 bounds 非空, 换算后的屏幕矩形必须是有限尺寸, 宽高至少 1 px, 并且与目标屏幕范围相交。锚点可信时使用 `NSPopover` 挂在 status item 下方; 锚点不可信时使用无箭头 fallback `NSPanel`, 放在目标屏幕顶部居中位置。快捷键打开主面板时会短暂禁止设置窗口和日志窗口成为 key window, 避免 App 激活时把已有的设置/日志窗口一起带到前台。已打开时仍允许快捷键关闭当前面板。鼠标点击路径不做这层 fallback, 因为点击 sender 本身就是当前锚点。
打开菜单面板的顺序:
- 取消正在等待的延迟刷新和淡入淡出任务
-- 如果来自全局快捷键且当前状态需要打开菜单面板, 先用目标屏幕确认 status item 锚点可信; 不可信时改用同一屏幕顶部居中的 fallback `NSPanel`
+- 如果来自全局快捷键且当前状态需要打开菜单面板, 先临时禁止设置窗口和日志窗口成为 key window, 再用目标屏幕确认 status item 锚点可信; 不可信时改用同一屏幕顶部居中的 fallback `NSPanel`
- 设置状态为 `opening`, 准备透明度淡入
- 显示 `NSPopover` 或 fallback `NSPanel`, 把 `MenuSurfaceVisibilityState.isVisible` 设为 `true`
- 调用 `refreshWorkflowIfHookEnabled(performMaintenance: false)`, 只读取已有 `daily.jsonl`, 不做重维护
@@ -145,9 +149,9 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall
Command-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active 变化关闭逻辑, 避免 Spotlight 或系统搜索抢焦点时误关弹窗。
-设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。
+设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再 `orderFrontRegardless()`, `NSApplication.shared.activate()` 和 `makeKeyAndOrderFront(nil)`, 只做一次性置前, 不持续置顶。
-设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。通过快捷键打开或关闭菜单面板时, 只激活并置前当前面板, 不主动置前已有的设置窗口或日志窗口。
+设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。关闭菜单面板期间会临时禁止成为 key window, 避免菜单面板收起时抢焦点。通过快捷键打开或关闭菜单面板时, 只激活并置前当前面板, 不主动置前已有的设置窗口或日志窗口。
## 5. Codex 状态刷新流程
@@ -378,23 +382,23 @@ codex app-server --listen stdio://
app-server 与状态刷新错误:
-| 错误来源 | 检测位置 | 用户可见状态 | 日志或存储 | 重试或降级 |
-| -------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------- |
-| 找不到全局 Codex CLI 和 Codex APP 内置 CLI | `CodexCLIResolver.resolveAppServerCommand()` | `初始化失败` | `RequestLogStorage.recordFailure` 记录可读错误 | 不启动 app-server, 下轮刷新重新解析 |
-| app-server 进程启动失败 | `Process.run()` | `初始化失败` | 记录"app-server 启动失败" | 不复用本次进程, 下轮刷新重试 |
-| `initialize` 或首次 `account/read` 失败 | `CodexStatusService.openConnection` | `初始化失败` | 对应 JSON-RPC 请求进入日志 | 关闭本次 session, 不重复完整握手 |
-| 首次 `account/read` 返回 `account == nil` | `CodexStatusService.openConnection` | `未登录` | 请求响应进入日志 | 关闭本次 session, 不生成 snapshot |
-| 复用连接刷新 account 后返回 `account == nil` | `CodexStatusService.fetchData` | `未登录` | 请求响应进入日志 | 清空 supplemental cache, teardown connection |
-| JSON-RPC 认证失败 | `CodexStatusError.isAuthenticationRequired` | 取决于刷新后结果 | 失败响应进入日志 | 同一轮最多 `account/read(refreshToken:true)` 一次, 然后重试原读取 |
-| refresh token 后仍认证失败 | `ReadResult.resultAfterAuthAttempt` | `未登录` | 失败响应进入日志 | 清空 cache, teardown connection |
-| unsupported method | `CodexStatusError.isUnsupportedMethod` | 对应区域可能显示无数据 | 失败响应进入日志 | 当前 session 记住 method, 后续跳过, 不复用旧缓存 |
-| 非认证业务错误 | `CodexStatusError.isRetriableServerError` | 通常不改变整体状态 | 失败响应进入日志 | 同请求立即重试一次, 仍失败则 supplemental 读取按失败处理 |
-| rate limits 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无额度区 | 失败进入日志 | 同账号旧缓存复用并标记 `isRateLimitsStale` |
-| usage 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无用量区 | 失败进入日志 | 同账号旧缓存复用并标记 `isUsageStale` |
+| 错误来源 | 检测位置 | 用户可见状态 | 日志或存储 | 重试或降级 |
+| -------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------- |
+| 找不到全局 Codex CLI 和 Codex APP 内置 CLI | `CodexCLIResolver.resolveAppServerCommand()` | `初始化失败` | `RequestLogStorage.recordFailure` 记录可读错误 | 不启动 app-server, 下轮刷新重新解析 |
+| app-server 进程启动失败 | `Process.run()` | `初始化失败` | 记录"app-server 启动失败" | 不复用本次进程, 下轮刷新重试 |
+| `initialize` 或首次 `account/read` 失败 | `CodexStatusService.openConnection` | `初始化失败` | 对应 JSON-RPC 请求进入日志 | 关闭本次 session, 不重复完整握手 |
+| 首次 `account/read` 返回 `account == nil` | `CodexStatusService.openConnection` | `未登录` | 请求响应进入日志 | 关闭本次 session, 不生成 snapshot |
+| 复用连接刷新 account 后返回 `account == nil` | `CodexStatusService.fetchData` | `未登录` | 请求响应进入日志 | 清空 supplemental cache, teardown connection |
+| JSON-RPC 认证失败 | `CodexStatusError.isAuthenticationRequired` | 取决于刷新后结果 | 失败响应进入日志 | 同一轮最多 `account/read(refreshToken:true)` 一次, 然后重试原读取 |
+| refresh token 后仍认证失败 | `ReadResult.resultAfterAuthAttempt` | `未登录` | 失败响应进入日志 | 清空 cache, teardown connection |
+| unsupported method | `CodexStatusError.isUnsupportedMethod` | 对应区域可能显示无数据 | 失败响应进入日志 | 当前 session 记住 method, 后续跳过, 不复用旧缓存 |
+| 非认证业务错误 | `CodexStatusError.isRetriableServerError` | 通常不改变整体状态 | 失败响应进入日志 | 同请求立即重试一次, 仍失败则 supplemental 读取按失败处理 |
+| rate limits 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无额度区 | 失败进入日志 | 同账号旧缓存复用并标记 `isRateLimitsStale` |
+| usage 读取失败 | `CodexStatusService.cachedRead` | 有旧缓存时区域半透明, 无旧缓存时无用量区 | 失败进入日志 | 同账号旧缓存复用并标记 `isUsageStale` |
| 重置机会过期时间请求失败 | `CodexStatusService.fetchResetCreditExpirationDates` / `CodexResetCreditsService` | `重置次数: N` 保留, 不显示过期时间 help text | 不展示错误, 不保存原始响应 | 401/403 时复用本轮认证刷新预算重试, 其他失败静默降级为 `nil` |
-| 连接断开, 请求超时, 响应解析失败 | `CodexStatusError.isTransportFailure` | 复用连接重建失败后为 `初始化失败` | 请求标记为错误 | 复用连接只重建重试一次, 新连接失败不再重试 |
-| app-server 关闭超时 | `AppServerSession.close()` | 不直接改变 UI | 记录强制结束或仍在后台运行 | 先 terminate 等 1 秒, 再 SIGKILL 等 0.5 秒 |
-| snapshot 无可信 quota 和 usage | `CodexQuotaSnapshot.hasTrustedData` | 菜单栏切换错误图标 | 不新增日志 | 仍可展示 stale 数据或无数据面板 |
+| 连接断开, 请求超时, 响应解析失败 | `CodexStatusError.isTransportFailure` | 复用连接重建失败后为 `初始化失败` | 请求标记为错误 | 复用连接只重建重试一次, 新连接失败不再重试 |
+| app-server 关闭超时 | `AppServerSession.close()` | 不直接改变 UI | 记录强制结束或仍在后台运行 | 先 terminate 等 1 秒, 再 SIGKILL 等 0.5 秒 |
+| snapshot 无可信 quota 和 usage | `CodexQuotaSnapshot.hasTrustedData` | 菜单栏切换错误图标 | 不新增日志 | 仍可展示 stale 数据或无数据面板 |
日志错误处理:
@@ -471,6 +475,7 @@ Codex 版本探测错误:
- 优先读取 `rateLimitsByLimitId`, 为空时回退顶层 `rateLimits`
- 顶层 `rateLimits.limitId` 指向的主 limit 置顶, 缺省为 `codex`
+- `codexLimit` 返回 `limitId` 大小写不敏感等于 `codex` 的第一个 limit, 供菜单栏额度指示读取可选窗口
- 其他 limit 按 `limitName ?? limitId` localized standard 排序, 再按 `limitId` 稳定排序
- `rateLimitResetCredits.availableCount` 写入 `resetCreditsAvailableCount`, 缺失时不展示重置次数
- 如果 `resetCreditsAvailableCount > 0`, `CodexResetCreditsService` 会用真实用户 `CODEX_HOME/auth.json` 或 `HOME/.codex/auth.json` 中的 access token, 只读请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits`; 401/403 时复用本轮认证刷新预算, 尚未刷新过时通过当前 app-server 会话刷新一次 token 后重试。成功时将可用且未过期的 `credits[].expires_at` 按升序写入 `resetCreditExpirationDates`; 请求失败时为 `nil`
@@ -532,7 +537,7 @@ flowchart TD
额度区:
- 多个 limit 间用 `LiquidGlassDivider` 分隔
-- 如果 `resetCreditsAvailableCount` 有值, 只在置顶主 limit 标题右侧显示 `重置次数: N`; 如果 `resetCreditExpirationDates` 非空, 鼠标悬停时通过 help text 按 `过期时间: yyyy-MM-dd HH:mm:ss • 可用: N` 逐行展示过期时间, 相同展示时间合并数量, 单个显示 `可用: 1`
+- 如果 `resetCreditsAvailableCount` 有值, 只在置顶主 limit 标题右侧显示 `重置次数: N`; 如果 `resetCreditExpirationDates` 非空, 鼠标悬停时通过 help text 按 `过期: yyyy-MM-dd HH:mm:ss • 可用: N` 逐行展示过期时间, 相同展示时间合并数量, 单个显示 `可用: 1`
- 每个 quota window 展示标签, 50 个固定胶囊组成的电量条, 剩余百分比和重置时间
- 胶囊宽度为 `3.5`, 间距为 `2`, 高度为 `12`
- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到电量条间距 `12`, 电量条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`
@@ -846,11 +851,15 @@ UI 展示指标来自 `WorkflowDailyAggregate.metrics`:
- `CodexHookSettings.refresh()`
- `CodexHookSettings.verifyInstalledHooks()`
- `WorkflowSyncSettings.refresh()`
+- `MenuBarQuotaSettings.refresh()`
+
+设置窗口按 SwiftUI 内容 `fittingSize` 自适应高度, 但必须校验尺寸有限且夹紧到当前屏幕可见区域内的安全上限, 避免 SwiftUI 初始化或状态刷新重入时给出异常尺寸导致空白大窗口。`MenuBarQuotaSettings.refresh()` 可能被设置页 `onAppear` 和 `didBecomeActive` 调用, 发布 `selection` 时需要延后到下一轮 MainActor, 避免在 SwiftUI view update 中同步发布造成未定义布局行为。
`AppSettingsView.onAppear` 时刷新:
- `LoginItemSettings.refresh()`
- `WorkflowSyncSettings.refresh()`
+- `MenuBarQuotaSettings.refresh()`
- `AppUpdater.refreshAutomaticCheckSetting()`
- `CodexCLIVersionViewModel.refresh()`
- `CodexStatusViewModel.refreshCodexConnectionInfo()`
@@ -861,15 +870,16 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并
设置项:
-| 设置项 | 状态源 | 写入行为 |
-| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
-| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
-| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
-| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
-| 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 |
-| 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |
-| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
-| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
+| 设置项 | 状态源 | 写入行为 |
+| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
+| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` |
+| 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` |
+| 菜单栏额度指示 | `MenuBarQuotaSettings.selection` | 开关写入 `.off` 或当前保留窗口, 窗口菜单写入所选窗口; 标签优先来自当前账号 Codex limit 返回的额度窗口, 缺失时使用 fallback 标题 |
+| 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key |
+| 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 |
+| 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |
+| Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |
+| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |
错误显示:
diff --git a/README.md b/README.md
index 9c64af5..636f113 100644
--- a/README.md
+++ b/README.md
@@ -30,9 +30,11 @@ CodexBar 是一个无 Dock 图标的 macOS 菜单栏应用。
使用默认全局快捷键 `⌘ ⇧ W` 适合在任何工作区快速查看当前 Codex 状态。
+如果在设置中开启「菜单栏额度指示」,菜单栏图标左侧会以一条细竖向进度条显示当前账号 Codex 额度中所选窗口的剩余比例,未开启时菜单栏图标保持纯图标显示。
+
### 额度与重置时间一眼可见
-额度区用分段电量条展示不同时间窗口的剩余额度,并显示剩余百分比和重置时间。存在可用手动重置机会时,鼠标悬停在 `重置次数: N` 上会按 `过期时间: yyyy-MM-dd HH:mm:ss • 可用: N` 显示各重置机会的过期时间和数量。
+额度区用分段电量条展示不同时间窗口的剩余额度,并显示剩余百分比和重置时间。存在可用手动重置机会时,鼠标悬停在 `重置次数: N` 上会按 `过期: yyyy-MM-dd HH:mm:ss • 可用: N` 显示各重置机会的过期时间和数量。
### 近 30 周 Token 热力图
diff --git a/appcast.xml b/appcast.xml
index 5d898d4..af0cc69 100644
--- a/appcast.xml
+++ b/appcast.xml
@@ -7,6 +7,15 @@
<link>https://codexbar.zabrian.app/appcast.xml</link>
<description>CodexBar appcast feed</description>
<language>zh-CN</language>
+ <item>
+ <title>CodexBar.app 3.2.4</title>
+ <sparkle:version>32</sparkle:version>
+ <sparkle:shortVersionString>3.2.4</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.2.4</sparkle:releaseNotesLink>
+ <pubDate>Mon, 29 Jun 2026 20:09:25 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.2.4.dmg" sparkle:edSignature="d3YF/XAZ0Yx7MZzFaLzjScIrXk7waqYpK8lNWVfabcPWe/QMeMEVXp0U7x3S9fon6r8KxZtRBbkH4Hhi4TgqBA==" length="3421733" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.2.3</title>
<sparkle:version>31</sparkle:version>