CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 更新菜单栏额度详情
Bobd5cd53c0d06f
diff --git a/AGENTS.md b/AGENTS.mdindex dabff4e..8134929 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -64,7 +64,7 @@ git status --short- 平台: SwiftUI + AppKit + MVVM, 最低 macOS 15.0。- 应用形态: `LSUIElement` 菜单栏应用, 无 Dock 图标、无主窗口。- 外部依赖: Sparkle(SwiftPM)。-- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 3.2.0`, `CURRENT_PROJECT_VERSION = 28`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, `SWIFT_VERSION = 6.0`。+- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 3.2.6`, `CURRENT_PROJECT_VERSION = 34`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, `SWIFT_VERSION = 6.0`。- App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/APP 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。- 工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下 Swift 文件通常无需改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。- Swift 源码按目录组织: `App/`、`Controllers/`、`Models/`、`Services/`、`Views/`。不要把新 Swift 文件直接放回 `CodexBar/` 根层。@@ -133,7 +133,7 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m- `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。+- `resetCreditsAvailableCount > 0` 时, 主 App 可使用本机 Codex OAuth token 请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits`; 401/403 时复用本轮认证刷新预算重试; 只保留可用且未过期的 `credits[].expires_at` 到 `resetCreditExpirationDates`, 请求失败时为 `nil`, 重置次数侧边详情面板显示未知过期时间。- `primary` / `secondary` 合成 `[QuotaWindow]`; 没有窗口的 limit 被过滤。- `QuotaWindow.remainingPercent = clamp(100 - usedPercent, 0...100)`; 无 `usedPercent` 视为无数据。- `windowDurationMins` 标签: 整天 `ND`, 整小时 `NH`, 否则 `NM`, 缺失或非正数为「额度」。@@ -170,9 +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 点击显示「设置 / 日志 / 退出」。+- 设置页「菜单栏额度指示」默认开启, 使用独立开关控制启用状态; 缺失持久化选择时默认使用 `.primary`, 关闭时必须显式持久化 `.off`。开启后同一行显示额度窗口菜单, 选项来自当前账号 Codex limit 返回的窗口, 当前保留选择不在返回窗口中时用 fallback 标题追加到菜单。关闭开关时设置页保留最后一个非关闭窗口值参与菜单淡出, 避免过渡期间回退到默认窗口。关闭时菜单栏只展示原图标, 开启时将所选 Codex 窗口剩余额度进度条绘制在 `person.fill.checkmark` / `person.fill.xmark` 图标左侧, 以竖条形式作为单个菜单栏图像自动随状态刷新; 合成图尺寸为 `27 x 17`, 图标本体保持原始 `24 x 17`, 左侧竖条轨道为 `2 x 15`; 开启或关闭时竖条透明度做 0.18 秒过渡, 过渡期间合成图宽度和图标绘制坐标保持固定。+- 左键或全局快捷键切换菜单面板; 右键或 Control 点击显示「设置 / 日志 / 退出」; 系统应用设置命令 `⌘,` 转交给自定义设置窗口。- 上下文菜单由 `NSStatusBarButton.performClick(nil)` 触发; 设置和日志菜单项 action 需要等 `NSMenuDelegate.menuDidClose(_:)` 确认菜单结束并清空 `statusItem.menu` 后再打开窗口, 避免键盘等效键在 `NSMenu` tracking 期间打开窗口导致无法激活到最前。+- 菜单面板打开时按 `⌘L` 会立即关闭菜单面板并打开日志窗口; 只响应精确 Command-L, 不响应额外修饰键组合。- 全局快捷键打开菜单面板前必须短暂禁止设置窗口和日志窗口成为 key window, 避免已有设置/日志窗口被 App 激活一起带到前台; 随后校验当前 status item 锚点可信。锚点无 window、无有效 screen、按钮隐藏、bounds 为空、屏幕矩形异常, 或屏幕矩形没有落在目标屏幕范围内时, 使用无箭头 fallback `NSPanel` 在目标屏幕顶部居中打开。目标屏幕优先取鼠标所在屏幕, 找不到时取主屏幕。快捷键关闭已打开的菜单面板不受此校验影响。- 设置和日志辅助窗口为 `.normal` level, 打开时先恢复 key focus, 再 `orderFrontRegardless()`, `NSRunningApplication.current.activate(options: [])` 和 `makeKeyAndOrderFront(nil)` 一次性置前; 不改用 `NSApplication.shared.activate()`, 避免 LSUIElement App 首次懒创建窗口时无法稳定拉到最前。@@ -183,7 +184,8 @@ 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 > 0` 时, 只在置顶主 limit 标题右侧显示 `重置次数: N`; 该控件是 plain button, 点击后通过 `ResetCreditsPanelController` 切换重置次数侧边详情面板。面板按升序逐行展示 `yyyy-MM-dd HH:mm:ss` 和 `可用: N`, 相同展示时间合并数量, 单个显示 `可用: 1`; 没有过期时间时显示「未知过期时间」。+- 重置次数侧边详情面板是菜单面板的 borderless nonactivating child panel, 可接收鼠标事件但不能成为 key/main window; 与菜单面板 gap 为 `4`, 屏幕边缘保留 `8` px, 内容宽 `147`, 最小高 `62`, 最大高 `260`, 圆角 `12`; 展开 `0.18` 秒、收起 `0.12` 秒。点击面板内部不关闭菜单面板, 点击外部关闭; 与热力图详情面板互斥, 任一面板显示时会立即隐藏另一面板。- 额度条展示剩余百分比, 固定为 50 个胶囊, 每个胶囊宽 `3.5`, 间距 `2`, 高 `12`; 颜色按 20% 一档: 红、橙、黄、薄荷、绿。- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到额度条间距 `12`, 额度条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`; 不通过加宽菜单面板解决额度行溢出。- 无 quota 数据时显示 `--` / `暂无数据`, 并使用占位色。@@ -195,7 +197,7 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m- token 区域显示「单日峰值」和「全时累计」; `TokenCountText` 对 1K 以下显示完整整数, 1K 起显示 K/M/B。- token 区域还显示「当前连胜」、「最长连胜」和「最长任务」。- 热力图是近 30 周、30 列 x 7 行、周日到周六排列; Codex Hook 开启时包含今天, Hook 关闭时仅在 app-server 已返回当天 token bucket 时包含今天。-- 热力图 hover 使用 `HeatmapDetailPanelController` 展示侧边详情面板, 不是菜单面板内 tooltip; 面板作为菜单面板 child window, 不接收鼠标事件, 左右贴边展示并在屏幕可见区域内夹紧。+- 热力图 hover 使用 `HeatmapDetailPanelController` 展示侧边详情面板, 不是菜单面板内 tooltip; 面板作为菜单面板 child window, 不接收鼠标事件, 左右贴边展示并在屏幕可见区域内夹紧。热力图详情面板和重置次数详情面板都被 `MenuSurfaceDismissMonitor` 视为允许点击区域。- 详情面板内容更新时保留 `NSPanel` / `NSHostingController`, 但每次替换 `hostingController.rootView` 并同步 `setContentSize`; 不用常驻 `ObservableObject` model 推送 hover context, 避免 Hook 开关切换 token-only / workflow 布局后触发 AppKit 递归布局。- Hook 关闭时详情面板显示日期、token 数和「用量强度」分段条, 尺寸 `212 x 84`。- Hook 开启时详情面板首行左侧显示日期、右侧显示 token 数, 当天 token 数显示 `--`; 后续显示「用量强度」、「会话总数」、「对话轮次」、「子智能体」、「工具调用」、「权限请求」、「上下文压缩」, 尺寸 `212 x 189`。@@ -204,7 +206,7 @@ Hook 统计的配置、存储、保留策略和统计口径见 [Docs/CodexHook.m设置窗口:-- 通过右键菜单「设置」打开独立 `AppSettingsView` 窗口。+- 通过右键菜单「设置」或系统应用设置命令 `⌘,` 打开独立 `AppSettingsView` 窗口。- 不要恢复为 Option 点击或菜单面板内设置区。- 设置页包含「菜单栏额度指示」、「使用快捷键」行、「CodexBar 版本」和「Codex 版本」区域。- 设置窗口按 SwiftUI 内容自适应高度时必须校验 `fittingSize` 有限并夹紧到安全上限; 设置页 `onAppear` / `didBecomeActive` 中触发的设置刷新不得同步发布 `@Published` 变化。diff --git a/CLAUDE.md b/CLAUDE.mdindex 3535fcf..070e09e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -55,10 +55,10 @@ WorkflowHookEventRecorder (--hook-event stdin hook_event_name 子进程)- Hook 命令写入当前 CodexBar 可执行文件路径和 `--hook-event` 参数,事件名来自 Codex 传入的 stdin payload 顶层 `hook_event_name`。- 开启 Hook 前必须通过当前 app-server 会话调用 `config/read`,如果全局配置禁用了 Hook,则不写入 `hooks.json`,并在 Hook 选项下方提示。-- 开启 Hook 写入后必须通过当前 app-server 会话调用 `hooks/list` 验证 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`warnings` 和 `errors`;未信任时提示用户去 Codex `/hooks` 信任。+- 开启 Hook 写入后必须通过当前 app-server 会话调用 `hooks/list` 验证 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`warnings` 和 `errors`;未信任或已修改时, 只对来源为全局 `hooks.json` 且 command 属于当前 CodexBar 的 Hook 通过 `config/batchWrite` 自动写入 `hooks.state` 的 `trusted_hash`, 再重新验证。- 设置开关只能追加/移除 `command` 同时包含当前 CodexBar 可执行路径和 `--hook-event` 参数的 Hook 处理器,绝不破坏其他用户 Hook。若用户自定义 Hook 命令也同时包含当前可执行路径和 `--hook-event` 参数,会被视为当前 CodexBar 处理器。- Hook 写入可能由多个 Codex 进程并发触发,追加 `events/YYYY-MM-DD.jsonl` 并更新 `maintenance.json` 必须经 `stats.lock` + `flock` 加锁;`daily.jsonl` 由主 App 刷新维护流程写回。-- iCloud 跨设备同步只上传去掉 `sessionIds` / `turnIds` 的 daily 聚合副本;iCloud 不可用时设置页禁用「跨设备同步」并显示「iCloud 不可用」。+- iCloud 跨设备同步只上传去掉 `sessionIds` / `turnIds` 的 daily 聚合副本;同步账号不可用时设置页禁用「跨设备同步」并显示「同步不可用」。- 字段兼容、保留策略、统计口径见 `Docs/CodexHook.md`;跨设备同步完整链路见 `Docs/CrossDeviceSync.md`。## 并发分工diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 4c7609c..6a6a8c6 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 = 33;+ CURRENT_PROJECT_VERSION = 34;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.5;+ MARKETING_VERSION = 3.2.6;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 = 33;+ CURRENT_PROJECT_VERSION = 34;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.5;+ MARKETING_VERSION = 3.2.6;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/App/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftindex 2b6676c..be3982a 100644--- a/CodexBar/App/CodexBarApp.swift+++ b/CodexBar/App/CodexBarApp.swift@@ -17,10 +17,18 @@ struct CodexBarApp: App {}var body: some Scene {- // 菜单栏 UI 由 AppDelegate 驱动; 空 Settings scene 仅用于保留系统设置入口+ // 菜单栏 UI 由 AppDelegate 驱动; 系统设置命令转交给自定义设置窗口Settings {EmptyView()}+ .commands {+ CommandGroup(replacing: .appSettings) {+ Button("设置...") {+ appDelegate.openSettingsFromCommand()+ }+ .keyboardShortcut(",", modifiers: .command)+ }+ }}}diff --git a/CodexBar/Controllers/HeatmapDetailPanelController.swift b/CodexBar/Controllers/HeatmapDetailPanelController.swiftindex 9e6d23a..feb4ffd 100644--- a/CodexBar/Controllers/HeatmapDetailPanelController.swift+++ b/CodexBar/Controllers/HeatmapDetailPanelController.swift@@ -25,6 +25,14 @@ final class HeatmapDetailPanelController {private var pendingSideSwitchRequest: PanelRequest?private weak var menuSurfaceWindow: NSWindow?+ func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {+ guard let panel, panel.isVisible else {+ return false+ }++ return panel.frame.contains(screenPoint)+ }+func update(context: UsageHeatmapHoverContext?,relativeTo menuSurfaceWindow: NSWindow?,diff --git a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swiftindex b948d37..162a185 100644--- a/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift+++ b/CodexBar/Controllers/MenuSurfaceDismissMonitor.swift@@ -6,6 +6,7 @@ final class MenuSurfaceDismissMonitor {private let isPresented: () -> Boolprivate let windowProvider: () -> NSWindow?private let statusButtonProvider: () -> NSStatusBarButton?+ private let isPointInExtraSurface: (NSPoint) -> Boolprivate var localEventMonitor: Any?private var globalMouseEventMonitor: Any?private var appResignActiveObserver: NSObjectProtocol?@@ -15,20 +16,27 @@ final class MenuSurfaceDismissMonitor {private var suppressActivationDismissTask: Task<Void, Never>?private var suppressesActivationDismiss = falseprivate var onDismiss: (() -> Void)?+ private var onLogShortcut: (() -> Void)?init(isPresented: @escaping () -> Bool,windowProvider: @escaping () -> NSWindow?,- statusButtonProvider: @escaping () -> NSStatusBarButton?+ statusButtonProvider: @escaping () -> NSStatusBarButton?,+ isPointInExtraSurface: @escaping (NSPoint) -> Bool = { _ in false }) {self.isPresented = isPresentedself.windowProvider = windowProviderself.statusButtonProvider = statusButtonProvider+ self.isPointInExtraSurface = isPointInExtraSurface}- func install(onDismiss: @escaping () -> Void) {+ func install(+ onDismiss: @escaping () -> Void,+ onLogShortcut: (() -> Void)? = nil+ ) {remove()self.onDismiss = onDismiss+ self.onLogShortcut = onLogShortcutlocalEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event inguard let self else {@@ -88,6 +96,7 @@ final class MenuSurfaceDismissMonitor {func remove() {onDismiss = nil+ onLogShortcut = nildeferredWindowFocusTask?.cancel()deferredWindowFocusTask = nilsuppressActivationDismissTask?.cancel()@@ -194,6 +203,11 @@ final class MenuSurfaceDismissMonitor {return true}+ if isExactCommandShortcut(event, keyCode: Metrics.logKeyCode) {+ onLogShortcut?()+ return true+ }+if isCommandShortcut(event, keyCode: Metrics.tabKeyCode) {dismiss()} else if isCommandShortcut(event, keyCode: Metrics.spaceKeyCode) {@@ -208,6 +222,11 @@ final class MenuSurfaceDismissMonitor {return modifierFlags.contains(.command) && event.keyCode == keyCode}+ private func isExactCommandShortcut(_ event: NSEvent, keyCode: UInt16) -> Bool {+ let shortcutModifiers = event.modifierFlags.intersection(Metrics.shortcutModifierMask)+ return shortcutModifiers == .command && event.keyCode == keyCode+ }+private func suppressNextActivationDismiss() {// Command-Space 会切换系统搜索焦点// 需要短暂抑制失活关闭避免误关面板@@ -237,7 +256,7 @@ final class MenuSurfaceDismissMonitor {return}- if isScreenPointInsideActiveMenuSurface(screenPoint) || isScreenPointInsideStatusButton(screenPoint) {+ if isPointAllowed(screenPoint) {return}@@ -245,6 +264,12 @@ final class MenuSurfaceDismissMonitor {dismiss()}+ private func isPointAllowed(_ screenPoint: NSPoint) -> Bool {+ isPointInMenuSurface(screenPoint)+ || isPointInStatusButton(screenPoint)+ || isPointInExtraSurface(screenPoint)+ }+private func isMouseDismissEvent(_ event: NSEvent) -> Bool {switch event.type {case .leftMouseDown, .rightMouseDown, .otherMouseDown:@@ -290,7 +315,7 @@ final class MenuSurfaceDismissMonitor {event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocation}- private func isScreenPointInsideActiveMenuSurface(_ screenPoint: NSPoint) -> Bool {+ private func isPointInMenuSurface(_ screenPoint: NSPoint) -> Bool {guard let activeMenuSurfaceWindow = windowProvider() else {return false}@@ -298,7 +323,7 @@ final class MenuSurfaceDismissMonitor {return activeMenuSurfaceWindow.frame.contains(screenPoint)}- private func isScreenPointInsideStatusButton(_ screenPoint: NSPoint) -> Bool {+ private func isPointInStatusButton(_ screenPoint: NSPoint) -> Bool {guard let button = statusButtonProvider(),let buttonWindow = button.window else {return false@@ -319,6 +344,13 @@ final class MenuSurfaceDismissMonitor {static let escapeKeyCode: UInt16 = 53static let tabKeyCode: UInt16 = 48static let spaceKeyCode: UInt16 = 49+ static let logKeyCode: UInt16 = 37+ static let shortcutModifierMask: NSEvent.ModifierFlags = [+ .command,+ .control,+ .option,+ .shift+ ]static let activationDismissSuppressionMilliseconds: UInt64 = 600}}diff --git a/CodexBar/Controllers/ResetCreditsPanelController.swift b/CodexBar/Controllers/ResetCreditsPanelController.swiftnew file mode 100644index 0000000..76aa163--- /dev/null+++ b/CodexBar/Controllers/ResetCreditsPanelController.swift@@ -0,0 +1,464 @@+import AppKit+import QuartzCore+import SwiftUI++/// 重置次数详情面板不接收焦点, 只作为菜单面板的跟随子窗口+private final class ResetCreditsPanel: NSPanel {+ override var canBecomeKey: Bool {+ false+ }++ override var canBecomeMain: Bool {+ false+ }+}++/// 重置次数详情控制器, 复用热力图详情的侧边抽屉动效+@MainActor+final class ResetCreditsPanelController {+ private var panel: NSPanel?+ private var hostingController: NSHostingController<ResetCreditsPanelView>?+ private var visibilityGeneration = 0+ private var currentSide = UsageHeatmapDetailSide.right+ private weak var menuSurfaceWindow: NSWindow?++ var isVisible: Bool {+ panel?.isVisible == true+ }++ func containsScreenPoint(_ screenPoint: NSPoint) -> Bool {+ guard let panel, panel.isVisible else {+ return false+ }++ return panel.frame.contains(screenPoint)+ }++ func toggle(+ context: ResetCreditsPanelContext,+ relativeTo menuSurfaceWindow: NSWindow?,+ contentView: NSView?+ ) {+ if isVisible {+ hide()+ return+ }++ show(+ context: context,+ relativeTo: menuSurfaceWindow,+ contentView: contentView+ )+ }++ func hide(immediate: Bool = false) {+ visibilityGeneration += 1++ guard let panel, panel.isVisible else {+ return+ }++ guard !immediate else {+ resetDrawerVisualState(for: panel)+ orderOut(panel)+ return+ }++ let generation = visibilityGeneration+ let side = currentSide+ let hidden = drawerHiddenTranslation(for: side, panelWidth: panel.frame.width)+ animateContentTranslation(+ to: hidden,+ duration: Metrics.drawerExitDuration,+ timing: .easeIn+ ) {+ Task { @MainActor [weak self] in+ guard let self,+ generation == visibilityGeneration else {+ return+ }++ orderOut(panel)+ setContentTranslation(0)+ }+ }+ }++ private func show(+ context: ResetCreditsPanelContext,+ relativeTo menuSurfaceWindow: NSWindow?,+ contentView: NSView?+ ) {+ guard let menuSurfaceWindow else {+ hide(immediate: true)+ return+ }++ let panel = ensurePanel()+ let panelSize = ResetCreditsPanelView.panelSize(for: context)+ let position = panelPosition(+ for: panelSize,+ relativeTo: menuSurfaceWindow,+ contentView: contentView,+ alignmentScreenFrame: context.alignmentScreenFrame,+ preferredSide: context.preferredSide+ )++ panel.level = menuSurfaceWindow.level+ defer {+ restoreMenuSurfaceKeyWindow(menuSurfaceWindow)+ }++ visibilityGeneration += 1+ apply(context: context, panelSize: panelSize, position: position, to: panel)+ showPanelWithDrawerAnimation(panel, relativeTo: menuSurfaceWindow)+ }++ private func ensurePanel() -> NSPanel {+ if let panel {+ return panel+ }++ let panel = ResetCreditsPanel(+ contentRect: NSRect(+ origin: .zero,+ size: ResetCreditsPanelView.initialPanelSize+ ),+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered,+ defer: false+ )+ panel.backgroundColor = .clear+ panel.collectionBehavior = [.transient, .canJoinAllSpaces, .fullScreenAuxiliary]+ panel.hasShadow = true+ panel.hidesOnDeactivate = false+ panel.ignoresMouseEvents = false+ panel.isFloatingPanel = true+ panel.isOpaque = false+ panel.isReleasedWhenClosed = false+ panel.animationBehavior = .none+ self.panel = panel+ return panel+ }++ private func updateContent(_ context: ResetCreditsPanelContext, size: CGSize) {+ let rootView = ResetCreditsPanelView(context: context)++ if let hostingController {+ hostingController.rootView = rootView+ } else {+ let hostingController = NSHostingController(rootView: rootView)+ hostingController.sizingOptions = [.preferredContentSize]+ panel?.contentViewController = hostingController+ self.hostingController = hostingController+ }++ configurePanelLayers()+ panel?.setContentSize(size)+ }++ private func apply(+ context: ResetCreditsPanelContext,+ panelSize: CGSize,+ position: PanelPosition,+ to panel: NSPanel+ ) {+ updateContent(context, size: panelSize)+ panel.setFrame(position.frame, display: true)+ panel.alphaValue = 1+ currentSide = position.side+ }++ private func showPanelWithDrawerAnimation(_ panel: NSPanel, relativeTo menuSurfaceWindow: NSWindow) {+ let generation = visibilityGeneration+ let hidden = drawerHiddenTranslation(for: currentSide, panelWidth: panel.frame.width)+ setContentTranslation(hidden)+ panel.alphaValue = 0+ attach(panel, to: menuSurfaceWindow)+ panel.order(.above, relativeTo: menuSurfaceWindow.windowNumber)+ animateContentTranslationAfterInitialLayout(+ from: hidden,+ panel: panel,+ generation: generation+ )+ }++ private func attach(_ panel: NSPanel, to parentWindow: NSWindow) {+ menuSurfaceWindow = parentWindow+ guard panel.parent !== parentWindow else {+ return+ }++ panel.parent?.removeChildWindow(panel)+ parentWindow.addChildWindow(panel, ordered: .above)+ }++ private func orderOut(_ panel: NSPanel) {+ let parentWindow = panel.parent ?? menuSurfaceWindow+ panel.orderOut(nil)+ parentWindow?.removeChildWindow(panel)+ restoreMenuSurfaceKeyWindow(parentWindow)+ }++ private func restoreMenuSurfaceKeyWindow(_ menuSurfaceWindow: NSWindow?) {+ guard NSApplication.shared.isActive else {+ return+ }++ menuSurfaceWindow?.makeKey()+ }++ private func configurePanelLayers() {+ if let hostingView = hostingController?.view {+ configurePanelLayer(for: hostingView)+ }++ if let contentView = panel?.contentView {+ configurePanelLayer(for: contentView)+ if let frameView = contentView.superview {+ configurePanelLayer(for: frameView)+ }+ }+ }++ private func configurePanelLayer(for view: NSView) {+ view.wantsLayer = true+ view.layer?.backgroundColor = NSColor.clear.cgColor+ view.layer?.masksToBounds = true+ view.layer?.cornerRadius = ResetCreditsPanelView.panelCornerRadius+ view.layer?.cornerCurve = .continuous+ }++ private func panelPosition(+ for panelSize: CGSize,+ relativeTo menuSurfaceWindow: NSWindow,+ contentView: NSView?,+ alignmentScreenFrame: CGRect?,+ preferredSide: UsageHeatmapDetailSide+ ) -> PanelPosition {+ let menuSurfaceFrame = contentScreenFrame(for: contentView, in: menuSurfaceWindow) ?? menuSurfaceWindow.frame+ let visibleFrame = (menuSurfaceWindow.screen ?? NSScreen.main)?.visibleFrame ?? menuSurfaceFrame+ let leftX = menuSurfaceFrame.minX - Metrics.panelGap - panelSize.width+ let rightX = menuSurfaceFrame.maxX + Metrics.panelGap+ let horizontal = horizontalPlacement(+ preferredSide: preferredSide,+ left: HorizontalPlacement(+ x: leftX,+ side: .left,+ isAvailable: leftX >= visibleFrame.minX + Metrics.screenPadding+ ),+ right: HorizontalPlacement(+ x: rightX,+ side: .right,+ isAvailable: rightX + panelSize.width <= visibleFrame.maxX - Metrics.screenPadding+ )+ )++ let x = clamped(+ horizontal.x,+ lower: visibleFrame.minX + Metrics.screenPadding,+ upper: visibleFrame.maxX - panelSize.width - Metrics.screenPadding+ )+ let y = clamped(+ proposedY(+ for: panelSize,+ menuSurfaceFrame: menuSurfaceFrame,+ alignmentScreenFrame: alignmentScreenFrame+ ),+ lower: max(visibleFrame.minY + Metrics.screenPadding, menuSurfaceFrame.minY),+ upper: visibleFrame.maxY - panelSize.height - Metrics.screenPadding+ )+ let frame = NSRect(x: x, y: y, width: panelSize.width, height: panelSize.height)++ return PanelPosition(+ frame: frame,+ side: actualSide(+ forX: x,+ panelWidth: panelSize.width,+ menuSurfaceFrame: menuSurfaceFrame,+ fallback: horizontal.side+ )+ )+ }++ private func proposedY(+ for panelSize: CGSize,+ menuSurfaceFrame: CGRect,+ alignmentScreenFrame: CGRect?+ ) -> CGFloat {+ if let alignmentScreenFrame {+ return alignmentScreenFrame.maxY - panelSize.height+ }++ return menuSurfaceFrame.midY - panelSize.height / 2+ }++ private func horizontalPlacement(+ preferredSide: UsageHeatmapDetailSide,+ left: HorizontalPlacement,+ right: HorizontalPlacement+ ) -> HorizontalPlacement {+ let primary = preferredSide == .left ? left : right+ let fallback = preferredSide == .left ? right : left++ if primary.isAvailable {+ return primary+ }+ return fallback.isAvailable ? fallback : primary+ }++ private func actualSide(+ forX x: CGFloat,+ panelWidth: CGFloat,+ menuSurfaceFrame: CGRect,+ fallback: UsageHeatmapDetailSide+ ) -> UsageHeatmapDetailSide {+ if x + panelWidth <= menuSurfaceFrame.minX {+ return .left+ }+ if x >= menuSurfaceFrame.maxX {+ return .right+ }+ return fallback+ }++ private func drawerHiddenTranslation(for side: UsageHeatmapDetailSide, panelWidth: CGFloat) -> CGFloat {+ let distance = panelWidth + Metrics.drawerOverscan+ switch side {+ case .left:+ return distance+ case .right:+ return -distance+ }+ }++ private func setContentTranslation(_ translationX: CGFloat) {+ guard let layer = hostingController?.view.layer else {+ return+ }++ CATransaction.begin()+ CATransaction.setDisableActions(true)+ layer.removeAnimation(forKey: Metrics.drawerTransformAnimationKey)+ layer.transform = CATransform3DMakeTranslation(translationX, 0, 0)+ CATransaction.commit()+ }++ private func animateContentTranslation(+ from fromTranslationX: CGFloat? = nil,+ to translationX: CGFloat,+ duration: TimeInterval,+ timing: CAMediaTimingFunctionName,+ completion: (() -> Void)? = nil+ ) {+ guard let layer = hostingController?.view.layer else {+ completion?()+ return+ }++ let targetTransform = CATransform3DMakeTranslation(translationX, 0, 0)+ CATransaction.begin()+ CATransaction.setCompletionBlock(completion)++ let animation = CABasicAnimation(keyPath: "transform")+ animation.fromValue = fromTranslationX.map { CATransform3DMakeTranslation($0, 0, 0) }+ ?? layer.presentation()?.transform+ ?? layer.transform+ animation.toValue = targetTransform+ animation.duration = duration+ animation.timingFunction = CAMediaTimingFunction(name: timing)+ layer.add(animation, forKey: Metrics.drawerTransformAnimationKey)+ layer.transform = targetTransform++ CATransaction.commit()+ }++ private func animateContentTranslationAfterInitialLayout(+ from hiddenTranslationX: CGFloat,+ panel: NSPanel,+ generation: Int+ ) {+ panel.contentView?.layoutSubtreeIfNeeded()+ panel.displayIfNeeded()+ CATransaction.flush()++ Task { @MainActor [weak self, weak panel] in+ await Task.yield()+ guard let self,+ let panel,+ panel.isVisible,+ generation == visibilityGeneration else {+ return+ }++ setContentTranslation(hiddenTranslationX)+ panel.contentView?.layoutSubtreeIfNeeded()+ panel.displayIfNeeded()+ CATransaction.flush()+ panel.alphaValue = 1+ animateContentTranslation(+ from: hiddenTranslationX,+ to: 0,+ duration: Metrics.drawerEnterDuration,+ timing: .easeOut+ ) {+ Task { @MainActor [weak self] in+ guard let self,+ generation == visibilityGeneration else {+ return+ }++ setContentTranslation(0)+ }+ }+ }+ }++ private func resetDrawerVisualState(for panel: NSPanel) {+ setContentTranslation(0)+ panel.alphaValue = 1+ }++ private func contentScreenFrame(for contentView: NSView?, in window: NSWindow) -> CGRect? {+ guard let contentView else {+ return nil+ }++ contentView.layoutSubtreeIfNeeded()+ let frameInWindow = contentView.convert(contentView.bounds, to: nil)+ let screenFrame = window.convertToScreen(frameInWindow)+ guard screenFrame.width > 0, screenFrame.height > 0 else {+ return nil+ }++ return screenFrame+ }++ private func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {+ guard lower <= upper else {+ return lower+ }++ return min(max(value, lower), upper)+ }++ private enum Metrics {+ static let panelGap: CGFloat = 4+ static let screenPadding: CGFloat = 8+ static let drawerEnterDuration: TimeInterval = 0.18+ static let drawerExitDuration: TimeInterval = 0.12+ static let drawerOverscan: CGFloat = 1+ static let drawerTransformAnimationKey = "CodexBar.resetCreditsDrawerTransform"+ }++ private struct PanelPosition {+ let frame: NSRect+ let side: UsageHeatmapDetailSide+ }++ private struct HorizontalPlacement {+ let x: CGFloat+ let side: UsageHeatmapDetailSide+ let isAvailable: Bool+ }+}diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 0b5221a..b4b913c 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -33,6 +33,10 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {func applicationWillTerminate(_: Notification) {statusItemController?.uninstall()}++ func openSettingsFromCommand() {+ statusItemController?.openSettingsFromCommand()+ }}/// 菜单栏入口控制器, 统一管理状态图标, 菜单面板, 右键菜单和全局快捷键@@ -49,6 +53,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private let popover = NSPopover()private let menuSurfaceVisibility = MenuSurfaceVisibilityState()private let heatmapDetailPanelController = HeatmapDetailPanelController()+ private let resetCreditsPanelController = ResetCreditsPanelController()private var activeMenuSurface = ActiveMenuSurface.noneprivate lazy var globalHotKeyController = GlobalHotKeyController { [weak self] inself?.toggleMenuSurfaceFromHotKey()@@ -99,6 +104,9 @@ private final class StatusItemController: NSObject, NSMenuDelegate {},statusButtonProvider: { [weak self] inself?.statusItem.button+ },+ isPointInExtraSurface: { [weak self] screenPoint in+ self?.isPointInDetailPanel(screenPoint) == true})private var delayedStatusRefreshTask: Task<Void, Never>?@@ -325,6 +333,11 @@ private final class StatusItemController: NSObject, NSMenuDelegate {NSStatusBar.system.removeStatusItem(statusItem)}+ func openSettingsFromCommand() {+ closeMenuSurface(animated: false)+ openSettings()+ }+private func configureStatusButton() {guard let button = statusItem.button else {return@@ -354,6 +367,9 @@ private final class StatusItemController: NSObject, NSMenuDelegate {menuSurfaceVisibility: menuSurfaceVisibility,onUsageHeatmapHoverChange: { [weak self] context inself?.updateHeatmapDetailPanel(context)+ },+ onResetCreditsTap: { [weak self] context in+ self?.toggleResetCreditsPanel(context)}).environmentObject(appUpdater)@@ -690,9 +706,14 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private func completeMenuSurfaceOpen() {menuSurfaceVisibility.isVisible = truerefreshWorkflowIfHookEnabled(performMaintenance: false)- menuSurfaceDismissMonitor.install { [weak self] in- self?.closeMenuSurface()- }+ menuSurfaceDismissMonitor.install(+ onDismiss: { [weak self] in+ self?.closeMenuSurface()+ },+ onLogShortcut: { [weak self] in+ self?.openLogFromShortcut()+ }+ )menuSurfaceFadeCoordinator.fadeIn(duration: Metrics.fadeInDuration) { [weak self] inself?.menuSurfaceState = .shown@@ -776,6 +797,11 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}}+ private func openLogFromShortcut() {+ closeMenuSurface(animated: false)+ openLog()+ }+private func openAuxiliaryWindow(_ open: @escaping @MainActor () -> Void) {guard activeStatusItemMenu == nil else {pendingStatusItemMenuAction = { [weak self] in@@ -826,7 +852,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}cancelMenuSurfaceTasks()- heatmapDetailPanelController.hide(immediate: true, delayed: false)+ hideSideDetailPanels()menuSurfaceDismissMonitor.remove()menuSurfaceVisibility.isVisible = false@@ -860,7 +886,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private func completeMenuSurfaceClose(hidesDetailPanel: Bool = true) {cancelMenuSurfaceTasks()if hidesDetailPanel {- heatmapDetailPanelController.hide(immediate: true)+ hideSideDetailPanels()}menuSurfaceDismissMonitor.remove()@@ -873,6 +899,16 @@ private final class StatusItemController: NSObject, NSMenuDelegate {scheduleAuxiliaryWindowKeyFocusRestore()}+ private func hideSideDetailPanels() {+ heatmapDetailPanelController.hide(immediate: true, delayed: false)+ resetCreditsPanelController.hide(immediate: true)+ }++ private func isPointInDetailPanel(_ screenPoint: NSPoint) -> Bool {+ heatmapDetailPanelController.containsScreenPoint(screenPoint)+ || resetCreditsPanelController.containsScreenPoint(screenPoint)+ }+private func suspendAuxiliaryWindowKeyFocus() {auxiliaryWindowFocusRestoreTask?.cancel()auxiliaryWindowFocusRestoreTask = nil@@ -946,6 +982,10 @@ private final class StatusItemController: NSObject, NSMenuDelegate {return}+ if context != nil {+ resetCreditsPanelController.hide(immediate: true)+ }+heatmapDetailPanelController.update(context: context,relativeTo: menuSurfaceWindow,@@ -953,6 +993,22 @@ private final class StatusItemController: NSObject, NSMenuDelegate {)}+ private func toggleResetCreditsPanel(_ context: ResetCreditsPanelContext) {+ guard isActiveMenuSurfaceVisible,+ let menuSurfaceContentView = activeMenuSurfaceContentView,+ let menuSurfaceWindow = activeMenuSurfaceWindow else {+ resetCreditsPanelController.hide(immediate: true)+ return+ }++ heatmapDetailPanelController.hide(immediate: true)+ resetCreditsPanelController.toggle(+ context: context,+ relativeTo: menuSurfaceWindow,+ contentView: menuSurfaceContentView+ )+ }+private var isActiveMenuSurfaceVisible: Bool {switch activeMenuSurface {case .none:diff --git a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift b/CodexBar/Services/Settings/MenuBarQuotaSettings.swiftindex d600046..e815ee2 100644--- a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift+++ b/CodexBar/Services/Settings/MenuBarQuotaSettings.swift@@ -37,11 +37,7 @@ final class MenuBarQuotaSettings: ObservableObject {}private func saveSelection(_ selection: MenuBarQuotaSelection) {- if selection == .off {- defaults.removeObject(forKey: Self.selectionKey)- } else {- defaults.set(selection.rawValue, forKey: Self.selectionKey)- }+ defaults.set(selection.rawValue, forKey: Self.selectionKey)}private func publishSelection(_ selection: MenuBarQuotaSelection) {@@ -68,8 +64,8 @@ final class MenuBarQuotaSettings: ObservableObject {private static func loadSelection(from defaults: UserDefaults) -> MenuBarQuotaSelection {guard let rawValue = defaults.string(forKey: selectionKey),- let selection = MenuBarQuotaSelection(persistedValue: rawValue) else {- return .off+ let selection = MenuBarQuotaSelection(rawValue: rawValue) else {+ return .primary}return selection@@ -87,17 +83,6 @@ nonisolated enum MenuBarQuotaSelection: String, CaseIterable, Identifiable {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":@@ -114,9 +99,9 @@ nonisolated enum MenuBarQuotaSelection: String, CaseIterable, Identifiable {case .off:"关闭"case .primary:- "主额度"+ "主要额度"case .secondary:- "次额度"+ "次要额度"}}diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex c36be28..d8f5d96 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -139,6 +139,8 @@ struct QuotaLimitsSection: View {let resetCreditsAvailableCount: Int?let resetCreditExpirationDates: [Date]?let isStale: Bool+ let onResetCreditsTap: (ResetCreditsPanelContext) -> Void+ @State private var sectionScreenFrame: CGRect?var body: some View {VStack(alignment: .leading, spacing: 8) {@@ -153,6 +155,11 @@ struct QuotaLimitsSection: View {.markStale(isStale).padding(MenuMetrics.panelPadding).liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ .background {+ ScreenFrameReader { frame in+ sectionScreenFrame = frame+ }+ }}private func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot, showsResetCredits: Bool) -> some View {@@ -166,8 +173,8 @@ struct QuotaLimitsSection: View {Spacer(minLength: 8)- if showsResetCredits, let resetCreditsText {- resetCreditsLabel(resetCreditsText)+ if showsResetCredits, let resetCreditsAvailableCount, resetCreditsAvailableCount > 0 {+ resetCreditsButton(count: resetCreditsAvailableCount)}}@@ -183,59 +190,28 @@ struct QuotaLimitsSection: View {limits.first?.id}- private var resetCreditsText: String? {- resetCreditsAvailableCount.map { "重置次数: \($0)" }- }-- @ViewBuilder- private func resetCreditsLabel(_ text: String) -> some View {- let label = Text(text)- .font(.caption2.weight(.semibold))- .foregroundStyle(.secondary)- .lineLimit(1)- .fixedSize(horizontal: true, vertical: false)-- if let helpText = resetCreditsHelpText {- label.help(helpText)- } else {- label- }- }-- private var resetCreditsHelpText: String? {- guard let resetCreditExpirationDates, !resetCreditExpirationDates.isEmpty else {- return nil- }-- return groupedResetCreditExpirationLines(from: resetCreditExpirationDates)- .joined(separator: "\n")- }-- private func groupedResetCreditExpirationLines(from dates: [Date]) -> [String] {- let expirationTexts = dates- .sorted()- .map { Self.resetCreditExpirationFormatter.string(from: $0) }-- let groups = expirationTexts.reduce(into: [(expirationText: String, count: Int)]()) { groups, expirationText in- if let lastIndex = groups.indices.last, groups[lastIndex].expirationText == expirationText {- groups[lastIndex].count += 1- } else {- groups.append((expirationText: expirationText, count: 1))- }- }-- return groups.map { group in- "过期: \(group.expirationText) • 可用: \(group.count)"+ private func resetCreditsButton(count: Int) -> some View {+ Button {+ onResetCreditsTap(+ ResetCreditsPanelContext(+ expirationDates: resetCreditExpirationDates ?? [],+ alignmentScreenFrame: sectionScreenFrame,+ preferredSide: .right+ )+ )+ } 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)}+ .buttonStyle(.plain)}- private static let resetCreditExpirationFormatter: DateFormatter = {- let formatter = DateFormatter()- formatter.locale = Locale(identifier: "en_US_POSIX")- formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"- return formatter- }()-private func isPrimaryLimit(_ limit: CodexQuotaLimitSnapshot) -> Bool {limit.id == primaryLimitId}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 91fdbe0..7e1d31f 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -17,6 +17,7 @@ struct CodexStatusMenuView: View {@ObservedObject var syncSettings: WorkflowSyncSettings@ObservedObject var menuSurfaceVisibility: MenuSurfaceVisibilityStatelet onUsageHeatmapHoverChange: (UsageHeatmapHoverContext?) -> Void+ let onResetCreditsTap: (ResetCreditsPanelContext) -> Void@EnvironmentObject private var appUpdater: AppUpdatervar body: some View {@@ -76,7 +77,8 @@ private extension CodexStatusMenuView {limits: snapshot.limits,resetCreditsAvailableCount: snapshot.resetCreditsAvailableCount,resetCreditExpirationDates: snapshot.resetCreditExpirationDates,- isStale: snapshot.isRateLimitsStale+ isStale: snapshot.isRateLimitsStale,+ onResetCreditsTap: onResetCreditsTap)}diff --git a/CodexBar/Views/Menu/ResetCreditsPanelView.swift b/CodexBar/Views/Menu/ResetCreditsPanelView.swiftnew file mode 100644index 0000000..8ae6bad--- /dev/null+++ b/CodexBar/Views/Menu/ResetCreditsPanelView.swift@@ -0,0 +1,184 @@+import SwiftUI++/// 重置次数侧边面板需要的数据和锚点信息+nonisolated struct ResetCreditsPanelContext: Equatable {+ let expirationDates: [Date]+ let alignmentScreenFrame: CGRect?+ let preferredSide: UsageHeatmapDetailSide+}++/// 重置次数侧边详情, 按过期时间从近到远展示+struct ResetCreditsPanelView: View {+ let context: ResetCreditsPanelContext+ @Environment(\.colorScheme) private var colorScheme++ var body: some View {+ let groups = expirationGroups+ let panelSize = Self.panelSize(forGroupCount: groups.count)++ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ if groups.isEmpty {+ emptyMessage+ } else {+ ScrollView(.vertical) {+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ ForEach(groups) { group in+ row(for: group)+ }+ }+ .frame(maxWidth: .infinity, alignment: .center)+ }+ .scrollIndicators(.never)+ }+ }+ .padding(.horizontal, Metrics.horizontalPadding)+ .padding(.vertical, Metrics.verticalPadding)+ .frame(width: panelSize.width, height: panelSize.height, alignment: .topLeading)+ .liquidGlassSurface(cornerRadius: Metrics.cornerRadius, isOuterSurface: true)+ .background {+ RoundedRectangle(cornerRadius: Metrics.cornerRadius, style: .continuous)+ .fill(panelBackingFill)+ }+ .overlay {+ RoundedRectangle(cornerRadius: Metrics.cornerRadius, style: .continuous)+ .strokeBorder(panelBoundaryColor, lineWidth: Metrics.boundaryLineWidth)+ }+ .clipShape(RoundedRectangle(cornerRadius: Metrics.cornerRadius, style: .continuous))+ .animation(Metrics.statusAnimation, value: context)+ }++ static var panelCornerRadius: CGFloat {+ Metrics.cornerRadius+ }++ static var initialPanelSize: CGSize {+ panelSize(forGroupCount: 0)+ }++ static func panelSize(for context: ResetCreditsPanelContext) -> CGSize {+ panelSize(forGroupCount: ResetCreditExpirationGroup.grouped(from: context.expirationDates).count)+ }++ private static func panelSize(forGroupCount rowCount: Int) -> CGSize {+ let rowHeight = CGFloat(max(rowCount, 1)) * Metrics.rowHeight+ let rowSpacing = CGFloat(max(rowCount - 1, 0)) * Metrics.rowSpacing+ let rawHeight = Metrics.baseHeight + rowHeight + rowSpacing+ return CGSize(+ width: Metrics.panelWidth,+ height: min(max(rawHeight, Metrics.minimumPanelHeight), Metrics.maximumPanelHeight)+ )+ }++ private var emptyMessage: some View {+ Text("未知过期时间")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, minHeight: Metrics.rowHeight, alignment: .leading)+ }++ private var expirationGroups: [ResetCreditExpirationGroup] {+ ResetCreditExpirationGroup.grouped(from: context.expirationDates)+ }++ private func row(for group: ResetCreditExpirationGroup) -> some View {+ VStack(alignment: .leading, spacing: 5) {+ rowHeader(for: group)++ expirationText(group.expirationText)+ }+ .fixedSize(horizontal: true, vertical: false)+ .frame(maxWidth: .infinity, alignment: .center)+ .frame(height: Metrics.rowHeight)+ }++ private func rowHeader(for group: ResetCreditExpirationGroup) -> some View {+ expirationText(group.expirationText)+ .hidden()+ .overlay {+ HStack(alignment: .center, spacing: 8) {+ Text("过期时间")+ .font(.caption2.weight(.medium))+ .foregroundStyle(.secondary)+ .lineLimit(1)++ Spacer(minLength: 8)++ availableValue(count: group.count)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ }++ private func expirationText(_ text: String) -> some View {+ Text(text)+ .font(.caption2.monospacedDigit().weight(.semibold))+ .foregroundStyle(Color.codexLabel)+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ }++ private func availableValue(count: Int) -> some View {+ Text("可用: \(count)")+ .font(.caption2.monospacedDigit().weight(.semibold))+ .foregroundStyle(.green)+ .lineLimit(1)+ .fixedSize(horizontal: true, vertical: false)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .liquidGlassCapsule(tint: .green)+ }++ private var panelBackingFill: Color {+ Color(nsColor: .windowBackgroundColor)+ .opacity(colorScheme == .dark ? 0.90 : 0.86)+ }++ private var panelBoundaryColor: Color {+ colorScheme == .dark+ ? .white.opacity(0.18)+ : .black.opacity(0.14)+ }++ private enum Metrics {+ static let expirationTextWidth: CGFloat = 123+ static let horizontalPadding: CGFloat = 12+ static let panelWidth: CGFloat = expirationTextWidth + horizontalPadding * 2+ static let minimumPanelHeight: CGFloat = 62+ static let maximumPanelHeight: CGFloat = 260+ static let baseHeight: CGFloat = verticalPadding * 2+ static let rowHeight: CGFloat = 42+ static let rowSpacing: CGFloat = 7+ static let verticalPadding: CGFloat = 10+ static let cornerRadius: CGFloat = 12+ static let boundaryLineWidth: CGFloat = 0.8+ static let statusAnimation = Animation.codexStatus+ }+}++private struct ResetCreditExpirationGroup: Identifiable, Equatable {+ let expirationText: String+ var count: Int++ var id: String {+ expirationText+ }++ static func grouped(from dates: [Date]) -> [Self] {+ dates.sorted().reduce(into: [Self]()) { groups, date in+ let expirationText = expirationFormatter.string(from: date)++ if let lastIndex = groups.indices.last, groups[lastIndex].expirationText == expirationText {+ groups[lastIndex].count += 1+ } else {+ groups.append(Self(expirationText: expirationText, count: 1))+ }+ }+ }++ private static let expirationFormatter: DateFormatter = {+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"+ return formatter+ }()+}diff --git a/CodexBar/Views/Menu/ScreenFrameReader.swift b/CodexBar/Views/Menu/ScreenFrameReader.swiftnew file mode 100644index 0000000..c583c2e--- /dev/null+++ b/CodexBar/Views/Menu/ScreenFrameReader.swift@@ -0,0 +1,72 @@+import AppKit+import SwiftUI++/// 通过 NSView 桥接读取 SwiftUI 视图在屏幕坐标系中的 frame+struct ScreenFrameReader: NSViewRepresentable {+ let onChange: (CGRect?) -> Void++ func makeNSView(context _: Context) -> ScreenFrameReportingView {+ let view = ScreenFrameReportingView()+ view.onChange = onChange+ return view+ }++ func updateNSView(_ nsView: ScreenFrameReportingView, context _: Context) {+ nsView.onChange = onChange+ nsView.scheduleReport()+ }+}++/// 只在 SwiftUI 布局稳定后上报 frame, 避免重渲染期间反复触发无效定位+@MainActor+final class ScreenFrameReportingView: NSView {+ var onChange: ((CGRect?) -> Void)?+ private var lastReportedFrame: CGRect?+ private var reportScheduled = false++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ scheduleReport()+ }++ override func layout() {+ super.layout()+ reportFrame()+ }++ func scheduleReport() {+ // updateNSView 每次 SwiftUI 重渲染都会调到这里+ // 合并掉重复的待执行 report, 至多保留一个+ guard !reportScheduled else {+ return+ }+ reportScheduled = true+ Task { @MainActor [weak self] in+ await Task.yield()+ guard let self else {+ return+ }+ reportScheduled = false+ reportFrame()+ }+ }++ private func reportFrame() {+ guard let window else {+ updateFrame(nil)+ return+ }++ let frameInWindow = convert(bounds, to: nil)+ updateFrame(window.convertToScreen(frameInWindow))+ }++ private func updateFrame(_ frame: CGRect?) {+ guard frame != lastReportedFrame else {+ return+ }++ lastReportedFrame = frame+ onChange?(frame)+ }+}diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex 48df7d8..e39d78b 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -311,7 +311,7 @@ struct UsageHeatmap: View {}}.background {- HeatmapScreenFrameReader(onChange: onScreenFrameChange)+ ScreenFrameReader(onChange: onScreenFrameChange)}}.frame(maxWidth: .infinity, alignment: .leading)@@ -477,77 +477,6 @@ private struct UsageHeatmapSquare: View {}}-/// 通过 NSView 桥接读取热力图在屏幕坐标系中的 frame-private struct HeatmapScreenFrameReader: NSViewRepresentable {- let onChange: (CGRect?) -> Void-- func makeNSView(context _: Context) -> HeatmapScreenFrameReportingView {- let view = HeatmapScreenFrameReportingView()- view.onChange = onChange- return view- }-- func updateNSView(_ nsView: HeatmapScreenFrameReportingView, context _: Context) {- nsView.onChange = onChange- nsView.scheduleReport()- }-}--/// 只在布局稳定后上报 frame, 避免 hover 期间反复触发无效定位-@MainActor-private final class HeatmapScreenFrameReportingView: NSView {- var onChange: ((CGRect?) -> Void)?- private var lastReportedFrame: CGRect?- private var reportScheduled = false-- override func viewDidMoveToWindow() {- super.viewDidMoveToWindow()- scheduleReport()- }-- override func layout() {- super.layout()- reportFrame()- }-- func scheduleReport() {- // updateNSView 每次 hover 重渲染都会调到这里- // 合并掉重复的待执行 report, 至多保留一个-- guard !reportScheduled else {- return- }- reportScheduled = true- Task { @MainActor [weak self] in- await Task.yield()- guard let self else {- return- }- reportScheduled = false- reportFrame()- }- }-- private func reportFrame() {- guard let window else {- updateFrame(nil)- return- }-- let frameInWindow = convert(bounds, to: nil)- updateFrame(window.convertToScreen(frameInWindow))- }-- private func updateFrame(_ frame: CGRect?) {- guard frame != lastReportedFrame else {- return- }-- lastReportedFrame = frame- onChange?(frame)- }-}-struct UsageHeatmapDayDetailView: View {let context: UsageHeatmapHoverContext@Environment(\.colorScheme) private var colorSchemediff --git a/Docs/AppServer.md b/Docs/AppServer.mdindex 98af040..5a00fba 100644--- a/Docs/AppServer.md+++ b/Docs/AppServer.md@@ -49,7 +49,7 @@ codex app-server --listen stdio://同一会话后续读取:- `account/read` 每轮复用连接时用 `refreshToken: false` 更新账户状态。-- `account/rateLimits/read` 读取额度, 包括可选的 `rateLimitResetCredits.availableCount`。当可用重置次数大于 0 时, 主 App 会通过 `CodexResetCreditsService` 额外读取本机 Codex OAuth token, 只读请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 获取各重置机会的 `expires_at`; 这条请求不走 app-server 日志, 失败时只是不展示过期时间 tooltip。+- `account/rateLimits/read` 读取额度, 包括可选的 `rateLimitResetCredits.availableCount`。当可用重置次数大于 0 时, 主 App 会通过 `CodexResetCreditsService` 额外读取本机 Codex OAuth token, 只读请求 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 获取各重置机会的 `expires_at`; 这条请求不走 app-server 日志, 失败时重置次数按钮仍可显示, 但侧边详情面板只展示未知过期时间。- `account/usage/read` 读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。- `config/read` 在开启 Codex Hook 前读取有效配置,用于判断 `[features] hooks = false` 或兼容旧名 `codex_hooks = false` 是否禁用了 Hook;关闭清理时也读取 `hooks.state` 以保留其他 Hook 的信任状态。- `hooks/list` 在写入 Hook 后或设置页刷新时验证 Codex 实际识别到的 Hook,检查 `command`、`eventName`、`enabled`、`sourcePath`、`trustStatus`、`key`、`currentHash`、`warnings` 和 `errors`。@@ -59,8 +59,8 @@ 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 时 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` 后在侧边详情面板中按时间升序展示 `yyyy-MM-dd HH:mm:ss` 和 `可用: N`; 相同展示时间合并数量, 单个显示 `可用: 1`。认证失败时,同会话最多调用一次 `account/read(refreshToken:true)` 后重试原读取。diff --git a/Docs/CodexHook.md b/Docs/CodexHook.mdindex 578141d..8b8506b 100644--- a/Docs/CodexHook.md+++ b/Docs/CodexHook.md@@ -294,6 +294,8 @@ UI 不直接展示所有原始字段,而是先生成 `WorkflowDailyMetrics`:热力图 hover 时不在菜单面板内绘制旧式 tooltip, 而是通过 `UsageHeatmapHoverContext` 通知 `HeatmapDetailPanelController` 展示侧边详情面板。指针会吸附到最近方块, 离开热力图后延迟 160 ms 清除选中状态。+热力图详情面板和额度区的重置次数详情面板互斥。hover 热力图时会隐藏重置次数详情面板; 点击重置次数按钮时会立即隐藏热力图详情面板。+详情面板是菜单面板的 borderless nonactivating child panel:- 不接收鼠标事件, 不抢走菜单面板 key windowdiff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.mdindex 575bb8d..3e9d9e9 100644--- a/Docs/DevelopmentGuide.md+++ b/Docs/DevelopmentGuide.md@@ -66,13 +66,14 @@ sequenceDiagramend```-普通启动时, `CodexBarAppDelegate` 创建六个长期对象:+普通启动时, `CodexBarAppDelegate` 创建七个长期对象:- `CodexStatusViewModel`: app-server 刷新状态- `WorkflowViewModel`: Hook 工作流统计快照- `CodexHookSettings`: Hook 配置状态和写入操作- `WorkflowSyncSettings`: 跨设备同步偏好、账号可用性、同步中和失败状态- `GlobalHotKeySettings`: 全局快捷键配置和错误状态+- `MenuBarQuotaSettings`: 菜单栏额度指示偏好和窗口选择- `AppUpdater`: Sparkle 更新状态`StatusItemController.install()` 负责:@@ -94,7 +95,7 @@ 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 秒过渡; 过渡期间合成图宽度和图标绘制坐标保持固定。+设置页「菜单栏额度指示」默认开启, 使用独立开关控制启用状态; 缺失持久化选择时默认使用 `.primary`, 关闭时显式持久化 `.off`。开启后在同一行显示额度窗口菜单, 可选择当前账号 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 秒过渡; 过渡期间合成图宽度和图标绘制坐标保持固定。错误图标触发条件:@@ -109,12 +110,16 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall| 右键点击 | 打开上下文菜单 || Control + 点击 | 打开上下文菜单 || 全局快捷键 | 切换菜单面板 |+| 系统 `⌘,` | 打开独立设置窗口 |+| 菜单面板内 `⌘L` | 打开独立日志窗口 || 上下文菜单"设置" | 打开独立设置窗口 || 上下文菜单"日志" | 打开独立日志窗口 || 上下文菜单"退出" | 终止 App |上下文菜单由 `NSStatusBarButton.performClick(nil)` 触发。设置和日志菜单项的 action 可能在 `NSMenu` 仍处于 tracking 时被键盘等效键触发, 因此 `StatusItemController` 会先缓存打开请求, 等 `NSMenuDelegate.menuDidClose(_:)` 确认菜单结束、清空 `statusItem.menu` 后再真正打开辅助窗口, 确保鼠标点击和键盘等效键路径都能把目标窗口激活到最前面。+系统应用设置命令由 `CodexBarApp` 的 `CommandGroup(replacing: .appSettings)` 接管, `⌘,` 不打开空 Settings scene, 而是调用 `StatusItemController.openSettingsFromCommand()` 关闭菜单面板并打开自定义设置窗口。菜单面板打开时, `MenuSurfaceDismissMonitor` 只对精确 `⌘L` 调用日志快捷入口; 带 Shift、Option 或 Control 的组合键不触发该路径。+全局快捷键由 `GlobalHotKeySettings` 和 `GlobalHotKeyController` 管理。没有用户设置时默认注册 `⌘⇧W`; 用户清除后不注册快捷键。注册冲突时恢复到上一个已注册快捷键, 并把错误显示在设置窗口的快捷键行内。通过全局快捷键打开菜单面板前, `StatusItemController` 会先用鼠标所在屏幕作为目标屏幕, 找不到时回退主屏幕, 再校验当前 `NSStatusBarButton` 锚点是否可信: 按钮必须有 window 和有效 screen、未隐藏且 bounds 非空, 换算后的屏幕矩形必须是有限尺寸, 宽高至少 1 px, 并且与目标屏幕范围相交。锚点可信时使用 `NSPopover` 挂在 status item 下方; 锚点不可信时使用无箭头 fallback `NSPanel`, 放在目标屏幕顶部居中位置。快捷键打开主面板时会短暂禁止设置窗口和日志窗口成为 key window, 避免 App 激活时把已有的设置/日志窗口一起带到前台。已打开时仍允许快捷键关闭当前面板。鼠标点击路径不做这层 fallback, 因为点击 sender 本身就是当前锚点。@@ -126,12 +131,13 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall- 设置状态为 `opening`, 准备透明度淡入- 显示 `NSPopover` 或 fallback `NSPanel`, 把 `MenuSurfaceVisibilityState.isVisible` 设为 `true`- 调用 `refreshWorkflowIfHookEnabled(performMaintenance: false)`, 只读取已有 `daily.jsonl`, 不做重维护-- 安装 `MenuSurfaceDismissMonitor`, 监听当前菜单面板 window 并只将当前菜单面板 window 置前和设为 key window+- 安装 `MenuSurfaceDismissMonitor`, 监听当前菜单面板 window、面板内日志快捷键和已打开的侧边详情面板区域, 并只将当前菜单面板 window 置前和设为 key window- 执行 0.24 秒淡入- 延迟 160 ms 后调用 `viewModel.refreshIfNeeded()`关闭菜单面板的顺序:+- 立即隐藏热力图详情面板和重置次数详情面板- 移除本地和全局事件监听- 将 `isVisible` 设为 `false`, 让倒计时停止 `TimelineView` 每秒 tick- 临时禁止设置窗口和日志窗口成为 key window, 避免关闭菜单面板时 AppKit 把这些辅助窗口提到前面@@ -140,7 +146,7 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall`MenuSurfaceDismissMonitor` 监听这些 dismiss 条件:-- 菜单面板外部鼠标点击+- 菜单面板、状态栏按钮和已打开侧边详情面板外部的鼠标点击- Escape- Command-Tab- App 失去 active@@ -149,6 +155,8 @@ App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstallCommand-Space 不直接关闭菜单面板, 只短暂抑制 600 ms 内的 active 变化关闭逻辑, 避免 Spotlight 或系统搜索抢焦点时误关弹窗。+热力图详情面板和重置次数详情面板都会通过 `containsScreenPoint(_:)` 告诉关闭监听器自己的屏幕区域, 因此点击这些 child panel 内部不会触发主菜单面板关闭。重置次数详情面板可接收鼠标事件用于滚动; 热力图详情面板不接收鼠标事件。+设置窗口和日志窗口都继承 `HostingWindowController` 的行为: 懒创建, 关闭后不释放, 重新打开复用, 按当前屏幕居中, 重新打开对应入口时只移动和置前对应窗口。窗口 level 保持 `.normal`; 置前时先恢复 `AuxiliaryHostingWindow.allowsKeyFocus`, 再 `orderFrontRegardless()`, `NSRunningApplication.current.activate(options: [])` 和 `makeKeyAndOrderFront(nil)`, 只做一次性置前, 不持续置顶。CodexBar 是 `LSUIElement` 菜单栏 App, 首次懒创建辅助窗口时需要通过当前运行中应用激活, 避免设置或日志窗口第一次打开时没有稳定拉到最前。设置窗口和日志窗口使用 `AuxiliaryHostingWindow`; 窗口可以成为 key window, 但不能成为 main window。关闭菜单面板期间会临时禁止成为 key window, 避免菜单面板收起时抢焦点。通过快捷键打开或关闭菜单面板时, 只激活并置前当前面板, 不主动置前已有的设置窗口或日志窗口。@@ -376,29 +384,29 @@ codex app-server --listen stdio://- 菜单面板只展示"未登录"和"初始化失败"两类特殊状态- 具体启动失败, 请求失败, 超时, 断连, 解析失败和业务错误进入日志窗口- 账户有效时, rate limits 和 usage 可以单独失败, 失败区域按缓存或无数据处理-- 登录项错误显示在设置窗口中部的独立错误组; Hook 写入/验证错误显示在 Hook 开关下方; 同步账号不可用显示在「跨设备同步」开关下方; 同步运行失败显示在主面板更新时间行同步图标 tooltip 中+- 登录项错误显示在设置组与底部按钮组之间的独立错误组; Hook 写入/验证错误显示在 Hook 开关下方; 同步账号不可用显示在「跨设备同步」开关下方; 同步运行失败显示在主面板更新时间行同步图标 tooltip 中- 全局快捷键录制, 校验和注册错误显示在快捷键行内- Hook 子进程尽量快速退出, 事件记录失败不会阻断 Codex 自身流程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` |-| 重置机会过期时间请求失败 | `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 数据或无数据面板 |+| 错误来源 | 检测位置 | 用户可见状态 | 日志或存储 | 重试或降级 |+| -------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------ | ---------------------------------------------- | ----------------------------------------------------------------- |+| 找不到全局 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` 保留, 侧边详情面板显示未知过期时间 | 不展示错误, 不保存原始响应 | 401/403 时复用本轮认证刷新预算重试, 其他失败静默降级为 `nil` |+| 连接断开, 请求超时, 响应解析失败 | `CodexStatusError.isTransportFailure` | 复用连接重建失败后为 `初始化失败` | 请求标记为错误 | 复用连接只重建重试一次, 新连接失败不再重试 |+| app-server 关闭超时 | `AppServerSession.close()` | 不直接改变 UI | 记录强制结束或仍在后台运行 | 先 terminate 等 1 秒, 再 SIGKILL 等 0.5 秒 |+| snapshot 无可信 quota 和 usage | `CodexQuotaSnapshot.hasTrustedData` | 菜单栏切换错误图标 | 不新增日志 | 仍可展示 stale 数据或无数据面板 |日志错误处理:@@ -537,7 +545,7 @@ flowchart TD额度区:- 多个 limit 间用 `LiquidGlassDivider` 分隔-- 如果 `resetCreditsAvailableCount` 有值, 只在置顶主 limit 标题右侧显示 `重置次数: N`; 如果 `resetCreditExpirationDates` 非空, 鼠标悬停时通过 help text 按 `过期: yyyy-MM-dd HH:mm:ss • 可用: N` 逐行展示过期时间, 相同展示时间合并数量, 单个显示 `可用: 1`+- 如果 `resetCreditsAvailableCount > 0`, 只在置顶主 limit 标题右侧显示 `重置次数: N`; 该控件是 plain button, 点击后通过重置次数侧边详情面板展示过期时间。`resetCreditExpirationDates` 非空时按 `yyyy-MM-dd HH:mm:ss` 升序逐行展示, 相同展示时间合并数量, 单个显示 `可用: 1`; 没有过期时间时显示「未知过期时间」- 每个 quota window 展示标签, 50 个固定胶囊组成的电量条, 剩余百分比和重置时间- 胶囊宽度为 `3.5`, 间距为 `2`, 高度为 `12`- 额度行标签列宽 `34`, 居中显示, 标签允许最小缩放到 `0.75`, 标签到电量条间距 `12`, 电量条到百分比间距 `8`, 百分比列宽 `37`, 百分比到重置时间最小间距 `6`, 重置时间列宽 `75`@@ -545,6 +553,18 @@ flowchart TD- 无数据时百分比和重置时间显示 `--`, 电量条用占位色- stale 数据通过 `.markStale(true)` 降低透明度到 0.55+`QuotaLimitsSection` 通过 `ScreenFrameReader` 记录额度区在屏幕坐标系中的 frame, 作为重置次数详情面板顶部对齐锚点。`ScreenFrameReader` 是通用 `NSViewRepresentable`, 同时服务额度区和热力图, 会在 SwiftUI 布局稳定后上报 frame 并去重, 避免重渲染期间反复触发无效定位。++重置次数详情面板由 `ResetCreditsPanelController` 管理:++- 面板是菜单面板的 borderless nonactivating child panel, 可接收鼠标事件但不能成为 key/main window+- 默认显示在菜单面板右侧, 空间不足时尝试左侧, 最终夹紧到当前屏幕可见区域内并保留 `8` px 边距+- 与菜单面板之间保留 `4` px gap; 纵向优先对齐额度区顶部, 没有锚点时居中对齐菜单面板+- 内容宽 `147`, 高度按过期时间行数在 `62...260` 之间夹紧, 圆角为 `12`+- 过期时间行高 `42`, 行间距 `7`, 横向 padding `12`, 纵向 padding `10`+- 展开使用 `0.18` 秒抽屉动画, 收起使用 `0.12` 秒抽屉动画+- 与热力图详情面板互斥: 点击重置次数会隐藏热力图详情面板, hover 热力图会隐藏重置次数详情面板+用量区:- 指标行展示"全时累计", "单日峰值", "当前连胜", "最长连胜", "最长任务"@@ -553,7 +573,7 @@ flowchart TD- hover 时通过 `UsageHeatmapHoverContext` 通知 `HeatmapDetailPanelController` 展示侧边详情面板- 指针会吸附到最近方块, 吸附动画 0.12 秒; 离开热力图后延迟 160 ms 清除选中状态-热力图详情面板是菜单面板的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在菜单面板左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。+热力图详情面板是菜单面板的 borderless nonactivating child panel, 不接收鼠标事件, 按悬停列优先显示在菜单面板左侧或右侧; 左右空间不足时尝试另一侧, 最终在当前屏幕可见区域内保留 8 px 边距。侧边切换时先以 0.12 秒抽屉动画收起, 再以 0.18 秒展开。热力图详情面板和重置次数详情面板互斥, hover 热力图会立即隐藏重置次数详情面板。`HeatmapDetailPanelController` 会复用同一个 `NSPanel` 和 `NSHostingController`, 但每次 hover 内容变化时必须替换 `hostingController.rootView` 并同步 `setContentSize`。不要用常驻 `ObservableObject` model 持续推送 `UsageHeatmapHoverContext`; Hook 开关会让详情面板在 `212 x 84` 和 `212 x 189` 两种布局之间切换, 复用同一棵 SwiftUI 布局树容易触发 AppKit constraint/layout 递归。相关回归路径是: 先 hover 出详情面板, 打开设置切换 Hook, 再回到主面板 hover 热力图。diff --git a/README.md b/README.mdindex 636f113..855dd4e 100644--- a/README.md+++ b/README.md@@ -16,7 +16,7 @@ Codex 的额度、Token 用量和使用情况通常分散在终端、App 或 Ses- 跟踪不同时间窗口的额度剩余比例和下一次重置时间- 用 30 周热力图回顾每日 Token 用量- 在开启 Codex Hook 后在 30 周热力图中可查看会话、对话轮次、工具调用、权限请求、上下文压缩和子智能体统计 (仅在开启后可记录查看,无法查看到历史数据)-- 通过可选 iCloud 私有数据库同步实现跨平台数据合并+- 通过可选 iCloud 私有数据库同步实现跨设备数据合并## 有什么功能@@ -30,11 +30,13 @@ CodexBar 是一个无 Dock 图标的 macOS 菜单栏应用。使用默认全局快捷键 `⌘ ⇧ W` 适合在任何工作区快速查看当前 Codex 状态。-如果在设置中开启「菜单栏额度指示」,菜单栏图标左侧会以一条细竖向进度条显示当前账号 Codex 额度中所选窗口的剩余比例,未开启时菜单栏图标保持纯图标显示。+系统设置快捷键 `⌘,` 会打开 CodexBar 的自定义设置窗口;菜单面板打开时按 `⌘L` 会直接打开日志窗口。++「菜单栏额度指示」默认开启,菜单栏图标左侧会以一条细竖向进度条显示当前账号 Codex 额度中所选窗口的剩余比例;关闭后菜单栏图标保持纯图标显示。### 额度与重置时间一眼可见-额度区用分段电量条展示不同时间窗口的剩余额度,并显示剩余百分比和重置时间。存在可用手动重置机会时,鼠标悬停在 `重置次数: N` 上会按 `过期: yyyy-MM-dd HH:mm:ss • 可用: N` 显示各重置机会的过期时间和数量。+额度区用分段电量条展示不同时间窗口的剩余额度,并显示剩余百分比和重置时间。存在可用手动重置机会时,主 limit 标题右侧会显示 `重置次数: N`,点击后通过侧边详情面板按过期时间展示各重置机会的数量。### 近 30 周 Token 热力图@@ -90,7 +92,7 @@ CodexBar 使用 Sparkle 检查更新。安装后,新版本会通过内置更## 隐私-CodexBar 默认通过本机 Codex app-server 读取账号、额度和 Token 用量。若 app-server 返回可用手动重置机会,CodexBar 会使用本机 Codex OAuth token 向 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 发起只读请求,用于读取这些重置机会的过期时间;请求失败时不会展示过期时间,也不会保留原始响应。+CodexBar 默认通过本机 Codex app-server 读取账号、额度和 Token 用量。若 app-server 返回可用手动重置机会,CodexBar 会使用本机 Codex OAuth token 向 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 发起只读请求,用于读取这些重置机会的过期时间;请求失败时不展示具体过期时间,重置次数侧边详情面板显示「未知过期时间」,也不会保留原始响应。Codex Hook 工作流数据默认只保存在本机:diff --git a/appcast.xml b/appcast.xmlindex ad26d77..890b856 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.6</title>+ <sparkle:version>34</sparkle:version>+ <sparkle:shortVersionString>3.2.6</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.2.6</sparkle:releaseNotesLink>+ <pubDate>Tue, 30 Jun 2026 12:40:30 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.2.6.dmg" sparkle:edSignature="Nj+fF98ifI/Jgf04s1UT6Yv/brvj2Ik4izOAwQN32BmMvjgvaB+IC/9P9ViqO2LZlO9aC/avpoPdPYRlNOl/DA==" length="3462024" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.2.5</title><sparkle:version>33</sparkle:version>