CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 提升额度查询和设置窗口健壮性
Bobcdd7429a1d16
diff --git a/AGENTS.md b/AGENTS.mdindex 5a71a2e..738c9ca 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,107 +1,149 @@# AGENTS.md-此文件为 Codex 等代码代理在本仓库工作时提供上下文和约定。请优先遵循这里的项目事实、构建命令和实现边界。+此文件为 Codex 在本仓库工作时提供上下文和约定。请优先遵循这里的项目事实、构建命令和实现边界。## 项目概览-CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)→ `StatusItemController` 手动管理 `NSStatusItem` + `NSPopover`,SwiftUI 内容托管在 popover 中。唯一外部依赖是 Sparkle(SwiftPM)。+CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)启动,再由 `StatusItemController` 手动管理 `NSStatusItem`、`NSPopover` 和右键菜单。唯一外部依赖是 Sparkle(SwiftPM)。++Xcode target 关闭了 App Sandbox,因为应用需要启动本机 Codex CLI/App 内置 CLI,并读取当前 macOS 用户的 Codex 登录状态。最低系统版本已是 macOS 15.0,不要给 SF Symbols 或 SwiftUI API 增加低版本 fallback。## 构建验证-修改后运行以下命令,确保无 error 和 warning:+涉及 Swift/Xcode 工程的修改后运行:```bashxcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build```-SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索引滞后),以 `xcodebuild` 实际编译结果为准。+要求无 error 和 warning。SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索引滞后),以 `xcodebuild` 实际编译结果为准。文档、图片或发布元数据的纯修改可以不跑构建,但最终回复要说明未运行。++工程使用文件系统同步组(`PBXFileSystemSynchronizedRootGroup`):新增/删除 `CodexBar/` 下源码通常无需修改 `project.pbxproj`,只有依赖、target/build settings 或资源归属变更才需要改它。-工程使用文件系统同步组(`PBXFileSystemSynchronizedRootGroup`):新增/删除源文件无需修改 `project.pbxproj`,只有依赖变更才需要改它。+## 架构与文件分工-## 架构+数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标刷新)/`RateLimitsMenuView`(popover 弹窗)。-数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标,经 Combine 订阅 `objectWillChange` 刷新图标)/ `RateLimitsMenuView`(popover 弹窗)。+- `CodexBarApp.swift`:`@main`,仅声明占位 `Settings { EmptyView() }` Scene;真实 UI 由 `CodexBarAppDelegate` 驱动。同文件有 `nonisolated extension Bundle` 提供 `shortVersionString` 和 `displayVersionLabel`(`v1.2.3`,缺失回退 `--`)。+- `StatusItemController.swift`:`CodexBarAppDelegate` 持有 `RateLimitsViewModel` 和 `AppUpdater`。私有 `StatusItemController` 配置菜单栏按钮、popover、Combine 订阅和自动刷新;左键切换 popover,右键或 Control 点击弹出「设置 / 退出」菜单。popover 使用手写淡入淡出、`PopoverState` 状态机、本地/全局 mouse monitor 外部点击关闭,并在显示后延迟调用 `refreshIfNeeded()`。+- `SettingsWindowController.swift`:独立管理设置窗口生命周期,复用同一个 `NSWindow`,通过 status item 所在屏幕居中,内容为注入 `AppUpdater` 的 `AppSettingsView`。+- `RateLimitsViewModel.swift`:主线程 `ObservableObject`,只发布 `snapshot`、`isRefreshing`、`lastError`。错误状态单一来源是 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,不要增加并列错误布尔或重复错误字符串状态。+- `CodexRateLimitService.swift`:非 UI 服务,负责 app-server 进程、JSON-RPC 请求/响应、连接复用、认证重试和 usage 能力降级。+- `RateLimitModels.swift`:wire DTO 保持纯 `Decodable`,展示排序/兜底只放在业务快照转换里。核心模型是 `CodexQuotaSnapshot` → `CodexQuotaLimitSnapshot` → `QuotaWindow`,以及 `CodexUsageSnapshot`。+- `RateLimitsMenuView.swift`:popover 主 UI,负责登录提示、账号卡片、limit 分节、使用量卡片、更新时间和错误行。邮箱双击可模糊/取消模糊,账号图标双击触发手动刷新。+- `QuotaRow.swift`:单个 quota window 行和 `SegmentedQuotaBar`;条形图展示剩余额度而不是已用额度。+- `UsageHeatmap.swift` / `TokenCountText.swift`:token 汇总、30 列 × 7 行热力图、hover tooltip 和 K/M/B 紧凑数字格式。+- `AppSettingsView.swift` / `LoginItemSettings.swift`:设置窗口 UI 和 `SMAppService.mainApp` 开机自启。开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 刷新。+- `AppUpdater.swift`:Sparkle 封装和更新状态文案路由。+- `LiquidGlassStyle.swift`:Liquid Glass 视觉入口,包括 `.liquidGlassSurface(...)`、`.liquidGlassCapsule(...)` 和 `LiquidGlassDivider`。-- `CodexBarApp.swift`:`@main`,仅声明一个占位 `Settings { EmptyView() }` Scene(`LSUIElement` 无入口触发它);真实 UI 由 `@NSApplicationDelegateAdaptor` 注入的 `CodexBarAppDelegate` 驱动。同文件含 `nonisolated extension Bundle`(`shortVersionString`、`displayVersionLabel`)。-- `StatusItemController.swift`:`CodexBarAppDelegate`(持有 `RateLimitsViewModel`、`AppUpdater`)+ `StatusItemController`(私有)。后者 `install()` 时配置 `NSStatusItem`、popover、Combine 订阅,并调 `viewModel.startAutoRefresh()` 启动每分钟刷新;左键开关 popover(手写淡入淡出动画),右键弹 `NSMenu`(设置 / 退出),设置项打开独立 `NSWindow`(`makeSettingsWindow`,内嵌 `AppSettingsView`)。-- `AppSettingsView.swift`:设置窗口 UI(开机自启开关、自动检查更新开关、当前版本 + 立即更新、检查更新、退出),经 `environmentObject` 注入 `AppUpdater`;`onAppear` 时刷新开机自启与自动检查状态。两个开关行复用 `settingsToggleRow(icon:title:isOn:isEnabled:)`。-- `CodexRateLimitService.swift`:app-server 常驻连接管理 + JSON-RPC 请求/响应。-- `RateLimitModels.swift`:wire 响应模型(纯 Decodable,不含展示逻辑)、业务快照模型(`CodexQuotaSnapshot` → `limits: [CodexQuotaLimitSnapshot]` → `windows: [QuotaWindow]`,支持多 limit 多窗口)、`CodexRateLimitError`(含 `requiresLogin`、`isAuthenticationRequired` 分类属性)。-- `RateLimitsViewModel.swift`:错误状态单一来源——只发布 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,**不要再加并列的错误布尔**。-- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装;`LiquidGlassStyle.swift`:Liquid Glass 视觉(`liquidGlassSurface`/`liquidGlassCapsule` 修饰符、`LiquidGlassDivider`)。+## Codex app-server 连接-## Codex app-server 连接(核心逻辑)+启动命令为 `codex app-server --listen stdio://`。解析命令时优先找 PATH 中的全局 `codex`,但如果找到的路径等同于 `/Applications/Codex.app/Contents/Resources/codex`,则按内置 Codex.app CLI 处理;全局 CLI 不存在时回退 Codex.app 内置 CLI;两者都没有时展示「找不到 Codex CLI 或 Codex App」。-启动优先级:全局 `codex` CLI 优先,找不到则回退 `/Applications/Codex.app/Contents/Resources/codex`;两者都没有时弹窗展示「找不到 Codex CLI 或 Codex App」。启动命令:`codex app-server --listen stdio://`。+启动环境由 `CodexRateLimitService.appServerEnvironment()` 构造:保留当前环境,但 `HOME` 使用 `getpwuid(getuid())` 得到的真实用户 home,同步设置 `USER`、`LOGNAME`,合并 Homebrew、npm global、`.local`、Volta 和系统路径,并确保 `TERM` 有值。不要改回 Xcode sandbox/container 的 `HOME`,否则会读不到 `~/.codex/auth.json`。-应用维持**一条常驻连接**,首次握手顺序(必须在请求额度前完成,否则 app-server 拒绝请求):+应用维持一条常驻连接。首次握手必须在请求额度前完成:```json-{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"1.0.0"}}}+{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"<Bundle MARKETING_VERSION 或 1.0.0>"}}}{"method":"initialized"}{"method":"account/read","id":2,"params":{"refreshToken":false}}```-之后每分钟在同一会话上请求 `account/rateLimits/read` 和 `account/usage/read`。+之后同一会话上读取:-额度解析(`CodexQuotaSnapshot` 的转换 init,wire DTO 本身不做排序/兜底):优先读 `rateLimitsByLimitId`(多 limit),为空则回退顶层 `rateLimits`;顶层 `rateLimits.limitId` 指向的主 limit 置顶(缺省 `"codex"`),其余按名称排序;每个 limit 的 `primary`/`secondary` 窗口合成 `[QuotaWindow]`,无窗口的 limit 被过滤,全部为空才抛 `missingRateLimitWindow`。+- `account/rateLimits/read`:额度数据,认证失败时先同会话调用 `account/read`(`refreshToken: true`)再重试一次;仍失败抛 `authenticationRequired`。+- `account/usage/read`:token 统计,读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。如果 app-server 返回 method not found/unknown/unsupported/not supported,当前连接的 `isUsageReadAvailable` 置为 false,本连接后续不再请求 usage;其他 usage 错误也只隐藏 token 区域,额度信息仍正常显示。-连接重建规则(`CodexRateLimitService.ensureConnection`):+`requestTimeout` 是 20 秒。`JSONLineReader` 按行读取 stdout,只消费匹配请求 id 的响应;`PipeDrain` 持续排空 stderr 且不进入用户可见文案。-- 进程已退出 → 重建。-- 连接存活超过 `connectionMaxAge`(1 小时)→ 定期回收重建(覆盖 codex 全局升级、服务端状态漂移)。-- **复用的**连接上请求失败 → 丢弃重建一次再试;**全新**连接上的失败直接抛出,不做二次重试。-- 登录类错误(`requiresLogin`)→ 丢弃连接但不重试;下次轮询起新进程读取最新 `~/.codex/auth.json`,用户重新登录后最多一分钟自动恢复。+## 额度与使用量模型-认证重试:`account/rateLimits/read` 返回认证错误时,先在同一会话上调 `account/read`(`refreshToken: true`)再重试一次;仍失败抛 `authenticationRequired`。+`CodexQuotaSnapshot` 转换规则:-token 统计来自 `account/usage/read`(`summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`);本机 app-server 不支持该方法时,token 区域不展示,额度信息仍正常显示。+- 必须有 `AccountReadResponse.account`,否则抛 `notLoggedIn`。+- 优先读取 `rateLimitsByLimitId` 以支持多 limit;为空则回退顶层 `rateLimits`。+- 顶层 `rateLimits.limitId` 指向的主 limit 置顶,缺省 `"codex"`;其余按 `limitName ?? limitId` 做 localized standard 排序,再按 `limitId` 稳定排序。+- 每个 limit 的 `primary`/`secondary` 窗口合成 `[QuotaWindow]`;没有窗口的 limit 被过滤,全部为空才抛 `missingRateLimitWindow`。+- `QuotaWindow.remainingPercent = clamp(100 - usedPercent, 0...100)`,无 `usedPercent` 时视为无数据。+- `windowDurationMins` 动态生成标签:整天显示「N 天」,整小时显示「N 小时」,否则显示「N 分钟」,缺失或非正数显示「额度」。-## 并发约定+`CodexUsageSnapshot.recentDays(count:endingDaysAgo:)` 基于本地当天零点生成连续日期,按 `yyyy-MM-dd` 汇总 `dailyUsageBuckets`。UI 当前展示 `UsageHeatmap.Metrics.dayCount`(210 天)且 `endingDaysAgo: 1`,也就是默认不包含今天。热力图颜色按当前展示区间内的峰值缩放。-工程开启了 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未显式标注的类型一律推断为 MainActor 隔离。因此**所有非 UI 类型必须显式标 `nonisolated`**,否则会报「Call to main actor-isolated initializer in a synchronous nonisolated context」。+## 连接重建规则++`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`,连接状态只在私有串行 `DispatchQueue(label: "CodexBar.app-server")` 上读写。++- 进程已退出 → 重建。+- 连接存活超过 `connectionMaxAge`(1 小时)→ 关闭后重建,覆盖 Codex 升级或服务端状态漂移。+- 复用连接上的非登录类请求失败 → 丢弃连接,重建一次再试。+- 全新连接上的失败 → 直接抛出,避免故障时重复完整握手。+- 登录类错误(`requiresLogin`)→ 丢弃连接但不立即重试;下次轮询重新启动进程读取最新登录状态,用户重新登录后最多一分钟自动恢复。-`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`,连接状态只在私有串行 `DispatchQueue` 上读写,对外暴露 async 接口。+## 并发约定-## 认证和沙盒+工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未显式标注的类型会推断为 MainActor 隔离。因此非 UI 类型、DTO、模型、服务辅助类型和部分静态工具必须显式 `nonisolated`,否则容易出现「Call to main actor-isolated initializer in a synchronous nonisolated context」。-Xcode target 已关闭 App Sandbox(需要启动本机 Codex CLI 并读取用户登录状态)。服务层用真实用户 home(`getpwuid`)运行 app-server——Xcode 运行时 `HOME` 可能指向 app container,导致读不到 `~/.codex` 而报 "codex account authentication required"。+UI 层(`CodexBarAppDelegate`、`StatusItemController`、`SettingsWindowController`、`RateLimitsViewModel`、`AppUpdater`、`LoginItemSettings`)保持 `@MainActor` 或主线程使用。服务层对外暴露 async API,内部用 queue 串行化 Process/Pipe 状态。## UI 与错误展示约定-- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。+- 菜单栏正常图标是 `person.fill.checkmark`,错误图标是 `person.fill.xmark`;由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。- App 图标保持白底黑色 `timelapse`。-- 不要给 symbol API 加低版本 fallback,最低系统版本已是 macOS 15.0。-- 弹窗整体采用 Liquid Glass 风格(`LiquidGlassStyle.swift`):`.liquidGlassSurface(...)` 给各分区/外层加玻璃质感背景,`.liquidGlassCapsule` 给 plan 徽章,分隔线用 `LiquidGlassDivider`。plan 徽章颜色由 `planBadgeTint(for:)` 按计划名子串匹配(有序优先级:enterprise→team/business→pro→plus→edu→free→默认 cyan)。-- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `LiquidGlassDivider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`(更新时间行不展示版本号)。-- token 贡献墙为 30 列 × 7 行蓝色方块热力图,token 数按 `M`/`B` 紧凑单位展示。-- 设置走菜单栏图标**右键(或 Control 点击)菜单**的「设置」项,打开独立的 `AppSettingsView` 窗口;开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 时刷新。-- **错误文案不暴露内部细节**:`serverTimeout` 只携带 JSON-RPC 步骤名;子进程 stderr 由 `PipeDrain` 排空丢弃,不进入任何用户可见文案。-- 登录类错误(`requiresLogin`):弹窗顶部橙色提示「Codex 未登录」,旧快照置灰(opacity 0.4)保留,红色错误行被抑制。其他错误:红色小字展示 `errorDescription`,旧快照保持全亮度。-- 错误文案保持显示直到某次刷新成功(`refresh()` 开始时不清空 `lastError`);旧额度快照永远不清空。+- popover 宽度由 `RateLimitsMenuView.menuWidth` 绑定到热力图总宽度和 padding;修改热力图尺寸时同步检查弹窗宽度。+- 弹窗整体采用 Liquid Glass 风格:外层和分区使用 `.liquidGlassSurface(...)`,plan 徽章用 `.liquidGlassCapsule`,分隔线用 `LiquidGlassDivider`。不要把设置、额度、usage 区块改回普通卡片样式。+- plan 徽章颜色由 `planBadgeTint(for:)` 按子串匹配,优先级:enterprise → team/business → pro → plus → edu → free → 默认 cyan。+- 弹窗按 limit 分节展示,标题取 `limitName` 回退 `limitId` 并首字母大写;节之间用 `LiquidGlassDivider`。+- 额度条展示剩余百分比(`100 - usedPercent`),颜色阈值:剩余 50% 及以上绿色,25% 到 50% 橙色,低于 25% 红色;无数据使用占位色并显示 `--` / `暂无数据`。+- 重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`;更新时间行不展示应用版本号。+- token 区域显示「单日峰值」和「全时累计」,数字通过 `TokenCountText` 格式化为 K/M/B,下方是 30 × 7 蓝色热力图;hover tooltip 显示日期和单日 token。+- 设置走菜单栏图标右键或 Control 点击菜单的「设置」项,打开独立 `AppSettingsView` 窗口;不要恢复为 Option 点击或 popover 内设置区。+- 登录类错误(`requiresLogin`)时,popover 顶部显示橙色「Codex 未登录」,旧快照 opacity 0.4 置灰保留,红色错误行被抑制。+- 其他错误显示红色小字 `errorDescription`,旧快照保持全亮度。+- `refresh()` 开始时不要清空 `lastError`;错误文案保持到某次刷新成功才消失。旧额度快照永远不因失败而清空。+- app-server 相关用户可见错误通过 `CodexRateLimitError.errorDescription` 生成;不要把子进程 stderr 或原始日志拼进 UI 文案。## 自动更新(Sparkle)-`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,各操作文案显示「未配置更新资源」(Debug/未签名构建静默降级);`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。+`AppUpdater` 是 `@MainActor ObservableObject`。初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空);任一缺失则不创建 `SPUStandardUpdaterController`,所有更新操作文案显示「未配置更新资源」,Debug/未签名构建静默降级。`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。++更新文案按 UI 表面拆分,不要合并:++- `settingsStatusMessage`:设置窗版本行状态,默认 3 秒后由可取消 `Task` 清空;传 `autoDismissDelay: nil` 时常驻。+- `panelUpdateMessage`:popover 底栏被动提示,双击可触发 `startUpdate()`。+- `availableUpdateMessage`:发现新版的语义状态,驱动设置窗版本行和「立即更新」按钮。++`checkForUpdates()` 是设置窗手动检查,设置 `isManualCheckInProgress`;若已经有 `availableUpdateMessage`,只把该消息常驻显示到设置窗。`startUpdate()` 激活应用并调用 Sparkle 安装面板。`setAutomaticallyChecksForUpdates(_:)` 和 `refreshAutomaticCheckSetting()` 同步 Sparkle 开关状态。委托回调按 `isManualCheckInProgress` 路由:手动检查结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。++Info.plist 位于 `CodexBar/Resources/Info.plist`,当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,`SUScheduledCheckInterval = 3600`。++## 认证、隐私与沙盒++CodexBar 只与本机 app-server 进程通信,账号与额度数据不发往第三方服务。除 Sparkle appcast/DMG 下载外,应用自身不做网络请求。-按 UI 表面拆三个 `@Published` 文案,不要合并:`settingsStatusMessage`(设置窗版本行,默认 3 秒后由可取消 `Task` 清空,`autoDismissDelay: nil` 时常驻)、`panelUpdateMessage`(popover 底栏被动提示)、`availableUpdateMessage`(有新版的语义标志,驱动设置窗「立即更新」按钮)。`checkForUpdates()` 是设置窗的手动检查(置 `isManualCheckInProgress`),`startUpdate()` 拉起 Sparkle 安装面板,`setAutomaticallyChecksForUpdates(_:)`/`refreshAutomaticCheckSetting()` 同步开关状态。委托回调据 `isManualCheckInProgress` 路由:手动检查的结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。+App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`),否则无法可靠启动 Codex CLI 或读取当前用户登录状态。服务层必须用真实用户 home 运行 app-server,以免 Xcode 运行时 `HOME` 指向 app container 导致 "codex account authentication required"。## Git 提交规范-- 提交 message 使用 **Conventional Commits 前缀 + 中文描述**,格式:`<type>: <中文描述>`。+- 提交 message 使用 **Conventional Commits 前缀 + 中文标题 + 空行 + 缩进 bullet body**。+- 标题行格式:`<type>: <中文描述>`,描述简洁,不加句号。- 常用 type:`feat`(新功能)、`fix`(修复)、`chore`(杂项/发布)、`refactor`(重构)、`docs`(文档)。-- 描述简洁一行,不加句号。-- **提交后不要主动 push,必须等用户明确同意后才能推送。**+- 标题行后空一行再写 body;body 使用 4 个空格缩进的 `- ` 列表。+- body 每条 bullet 描述一个具体变更点,优先覆盖新增/修改的核心模块、用户可见行为、脚本/资源/配置变化;不要写泛泛总结。+- 简单文档或杂项改动如确实没有多个变更点,可以只写标题行;功能、修复、发布类提交必须写 body。+- 提交后不要主动 push,必须等用户明确同意后才能推送。### Tag 规范-- tag 名格式:`v{MARKETING_VERSION}`(如 `v1.2.1`),与 Xcode target 的 `MARKETING_VERSION` 保持一致。-- 使用**附注 tag**(`git tag -a`),message 格式:`Release v{version}`(如 `git tag -a v1.2.1 -m "Release v1.2.1"`)。+- tag 名格式:`v{MARKETING_VERSION}`(如 `v1.3.3`),与 Xcode target 的 `MARKETING_VERSION` 保持一致。+- 使用附注 tag(`git tag -a`),message 格式:`Release v{version}`(如 `git tag -a v1.3.3 -m "Release v1.3.3"`)。- tag 同样不要主动 push,等用户明确同意。## 发布流程1. 用 `Developer ID Application` 证书签名并 notarization,Xcode 导出 `CodexBar.app` 到项目根目录。-2. `Scripts/create-dmg.sh`:自动找到根目录唯一 `.app`,按 `MARKETING_VERSION` 生成 `CodexBar-v{version}.dmg`(含 Applications 快捷方式和 Finder 布局)。-3. `Scripts/update-appcast.sh [dmg]`:用 Sparkle `sign_update` 签名 DMG,从 build settings 读版本号,将 `<item>` 写入 `Updates/appcast.xml`(同版本去重,`xmllint` 校验)。常用环境变量:`DOWNLOAD_BASE_URL`、`INCLUDE_RELEASE_NOTES`、`MINIMUM_SYSTEM_VERSION` 等。-4. 上传 DMG 和更新后的 `appcast.xml` 到 `SUFeedURL` 对应站点。+2. `Scripts/create-dmg.sh [App.app] [Output.dmg]`:未传 app 时自动找到项目根目录唯一 `.app`;按 Xcode `MARKETING_VERSION` 生成默认 `CodexBar-v{version}.dmg`;DMG 内含 Applications 快捷方式和 Finder 布局。脚本依赖 `hdiutil`、`osascript`、`ditto`。+3. `Scripts/update-appcast.sh [CodexBar-vX.Y.Z.dmg]`:未传 DMG 时自动找项目根目录唯一 `.dmg`;用 Sparkle `sign_update` 签名,从 Release build settings 读取 `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION`,将同 build version 的旧 `<item>` 去重后写入 `Updates/appcast.xml`,有 `xmllint` 时校验。+4. 常用环境变量:`APPCAST_PATH`、`DOWNLOAD_BASE_URL`、`RELEASE_NOTES_BASE_URL`、`INCLUDE_RELEASE_NOTES`、`MINIMUM_SYSTEM_VERSION`、`SIGN_UPDATE`、`XCODE_PROJECT`、`XCODE_SCHEME`。+5. 上传 DMG 和更新后的 `appcast.xml` 到 `SUFeedURL` 对应站点。diff --git a/CLAUDE.md b/CLAUDE.mdindex 4d2979c..ff18a40 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,107 +1,149 @@# CLAUDE.md-This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.+此文件为 Claude Code 在本仓库工作时提供上下文和约定。请优先遵循这里的项目事实、构建命令和实现边界。## 项目概览-CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)→ `StatusItemController` 手动管理 `NSStatusItem` + `NSPopover`,SwiftUI 内容托管在 popover 中。唯一外部依赖是 Sparkle(SwiftPM)。+CodexBar 是一个 macOS 菜单栏应用(SwiftUI + MVVM,最低 macOS 15.0),通过本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。`LSUIElement` 纯菜单栏应用(无 Dock 图标、无应用菜单),入口经 `NSApplicationDelegateAdaptor`(`CodexBarAppDelegate`)启动,再由 `StatusItemController` 手动管理 `NSStatusItem`、`NSPopover` 和右键菜单。唯一外部依赖是 Sparkle(SwiftPM)。++Xcode target 关闭了 App Sandbox,因为应用需要启动本机 Codex CLI/App 内置 CLI,并读取当前 macOS 用户的 Codex 登录状态。最低系统版本已是 macOS 15.0,不要给 SF Symbols 或 SwiftUI API 增加低版本 fallback。## 构建验证-修改后运行以下命令,确保无 error 和 warning:+涉及 Swift/Xcode 工程的修改后运行:```bashxcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build```-SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索引滞后),以 `xcodebuild` 实际编译结果为准。+要求无 error 和 warning。SourceKit 经常对跨文件类型误报「Cannot find type ... in scope」(索引滞后),以 `xcodebuild` 实际编译结果为准。文档、图片或发布元数据的纯修改可以不跑构建,但最终回复要说明未运行。++工程使用文件系统同步组(`PBXFileSystemSynchronizedRootGroup`):新增/删除 `CodexBar/` 下源码通常无需修改 `project.pbxproj`,只有依赖、target/build settings 或资源归属变更才需要改它。-工程使用文件系统同步组(`PBXFileSystemSynchronizedRootGroup`):新增/删除源文件无需修改 `project.pbxproj`,只有依赖变更才需要改它。+## 架构与文件分工-## 架构+数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标刷新)/`RateLimitsMenuView`(popover 弹窗)。-数据流:`CodexRateLimitService`(JSON-RPC 常驻连接)→ `RateLimitsViewModel`(状态发布)→ `StatusItemController`(菜单栏图标,经 Combine 订阅 `objectWillChange` 刷新图标)/ `RateLimitsMenuView`(popover 弹窗)。+- `CodexBarApp.swift`:`@main`,仅声明占位 `Settings { EmptyView() }` Scene;真实 UI 由 `CodexBarAppDelegate` 驱动。同文件有 `nonisolated extension Bundle` 提供 `shortVersionString` 和 `displayVersionLabel`(`v1.2.3`,缺失回退 `--`)。+- `StatusItemController.swift`:`CodexBarAppDelegate` 持有 `RateLimitsViewModel` 和 `AppUpdater`。私有 `StatusItemController` 配置菜单栏按钮、popover、Combine 订阅和自动刷新;左键切换 popover,右键或 Control 点击弹出「设置 / 退出」菜单。popover 使用手写淡入淡出、`PopoverState` 状态机、本地/全局 mouse monitor 外部点击关闭,并在显示后延迟调用 `refreshIfNeeded()`。+- `SettingsWindowController.swift`:独立管理设置窗口生命周期,复用同一个 `NSWindow`,通过 status item 所在屏幕居中,内容为注入 `AppUpdater` 的 `AppSettingsView`。+- `RateLimitsViewModel.swift`:主线程 `ObservableObject`,只发布 `snapshot`、`isRefreshing`、`lastError`。错误状态单一来源是 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,不要增加并列错误布尔或重复错误字符串状态。+- `CodexRateLimitService.swift`:非 UI 服务,负责 app-server 进程、JSON-RPC 请求/响应、连接复用、认证重试和 usage 能力降级。+- `RateLimitModels.swift`:wire DTO 保持纯 `Decodable`,展示排序/兜底只放在业务快照转换里。核心模型是 `CodexQuotaSnapshot` → `CodexQuotaLimitSnapshot` → `QuotaWindow`,以及 `CodexUsageSnapshot`。+- `RateLimitsMenuView.swift`:popover 主 UI,负责登录提示、账号卡片、limit 分节、使用量卡片、更新时间和错误行。邮箱双击可模糊/取消模糊,账号图标双击触发手动刷新。+- `QuotaRow.swift`:单个 quota window 行和 `SegmentedQuotaBar`;条形图展示剩余额度而不是已用额度。+- `UsageHeatmap.swift` / `TokenCountText.swift`:token 汇总、30 列 × 7 行热力图、hover tooltip 和 K/M/B 紧凑数字格式。+- `AppSettingsView.swift` / `LoginItemSettings.swift`:设置窗口 UI 和 `SMAppService.mainApp` 开机自启。开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 刷新。+- `AppUpdater.swift`:Sparkle 封装和更新状态文案路由。+- `LiquidGlassStyle.swift`:Liquid Glass 视觉入口,包括 `.liquidGlassSurface(...)`、`.liquidGlassCapsule(...)` 和 `LiquidGlassDivider`。-- `CodexBarApp.swift`:`@main`,仅声明一个占位 `Settings { EmptyView() }` Scene(`LSUIElement` 无入口触发它);真实 UI 由 `@NSApplicationDelegateAdaptor` 注入的 `CodexBarAppDelegate` 驱动。同文件含 `nonisolated extension Bundle`(`shortVersionString`、`displayVersionLabel`)。-- `StatusItemController.swift`:`CodexBarAppDelegate`(持有 `RateLimitsViewModel`、`AppUpdater`)+ `StatusItemController`(私有)。后者 `install()` 时配置 `NSStatusItem`、popover、Combine 订阅,并调 `viewModel.startAutoRefresh()` 启动每分钟刷新;左键开关 popover(手写淡入淡出动画),右键弹 `NSMenu`(设置 / 退出),设置项打开独立 `NSWindow`(`makeSettingsWindow`,内嵌 `AppSettingsView`)。-- `AppSettingsView.swift`:设置窗口 UI(开机自启开关、自动检查更新开关、当前版本 + 立即更新、检查更新、退出),经 `environmentObject` 注入 `AppUpdater`;`onAppear` 时刷新开机自启与自动检查状态。两个开关行复用 `settingsToggleRow(icon:title:isOn:isEnabled:)`。-- `CodexRateLimitService.swift`:app-server 常驻连接管理 + JSON-RPC 请求/响应。-- `RateLimitModels.swift`:wire 响应模型(纯 Decodable,不含展示逻辑)、业务快照模型(`CodexQuotaSnapshot` → `limits: [CodexQuotaLimitSnapshot]` → `windows: [QuotaWindow]`,支持多 limit 多窗口)、`CodexRateLimitError`(含 `requiresLogin`、`isAuthenticationRequired` 分类属性)。-- `RateLimitsViewModel.swift`:错误状态单一来源——只发布 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是派生计算属性,**不要再加并列的错误布尔**。-- `QuotaRow.swift`:额度行和分段进度条;`LoginItemSettings.swift`:`SMAppService.mainApp` 开机自启;`AppUpdater.swift`:Sparkle 封装;`LiquidGlassStyle.swift`:Liquid Glass 视觉(`liquidGlassSurface`/`liquidGlassCapsule` 修饰符、`LiquidGlassDivider`)。+## Codex app-server 连接-## Codex app-server 连接(核心逻辑)+启动命令为 `codex app-server --listen stdio://`。解析命令时优先找 PATH 中的全局 `codex`,但如果找到的路径等同于 `/Applications/Codex.app/Contents/Resources/codex`,则按内置 Codex.app CLI 处理;全局 CLI 不存在时回退 Codex.app 内置 CLI;两者都没有时展示「找不到 Codex CLI 或 Codex App」。-启动优先级:全局 `codex` CLI 优先,找不到则回退 `/Applications/Codex.app/Contents/Resources/codex`;两者都没有时弹窗展示「找不到 Codex CLI 或 Codex App」。启动命令:`codex app-server --listen stdio://`。+启动环境由 `CodexRateLimitService.appServerEnvironment()` 构造:保留当前环境,但 `HOME` 使用 `getpwuid(getuid())` 得到的真实用户 home,同步设置 `USER`、`LOGNAME`,合并 Homebrew、npm global、`.local`、Volta 和系统路径,并确保 `TERM` 有值。不要改回 Xcode sandbox/container 的 `HOME`,否则会读不到 `~/.codex/auth.json`。-应用维持**一条常驻连接**,首次握手顺序(必须在请求额度前完成,否则 app-server 拒绝请求):+应用维持一条常驻连接。首次握手必须在请求额度前完成:```json-{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"1.0.0"}}}+{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"<Bundle MARKETING_VERSION 或 1.0.0>"}}}{"method":"initialized"}{"method":"account/read","id":2,"params":{"refreshToken":false}}```-之后每分钟在同一会话上请求 `account/rateLimits/read` 和 `account/usage/read`。+之后同一会话上读取:-额度解析(`CodexQuotaSnapshot` 的转换 init,wire DTO 本身不做排序/兜底):优先读 `rateLimitsByLimitId`(多 limit),为空则回退顶层 `rateLimits`;顶层 `rateLimits.limitId` 指向的主 limit 置顶(缺省 `"codex"`),其余按名称排序;每个 limit 的 `primary`/`secondary` 窗口合成 `[QuotaWindow]`,无窗口的 limit 被过滤,全部为空才抛 `missingRateLimitWindow`。+- `account/rateLimits/read`:额度数据,认证失败时先同会话调用 `account/read`(`refreshToken: true`)再重试一次;仍失败抛 `authenticationRequired`。+- `account/usage/read`:token 统计,读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。如果 app-server 返回 method not found/unknown/unsupported/not supported,当前连接的 `isUsageReadAvailable` 置为 false,本连接后续不再请求 usage;其他 usage 错误也只隐藏 token 区域,额度信息仍正常显示。-连接重建规则(`CodexRateLimitService.ensureConnection`):+`requestTimeout` 是 20 秒。`JSONLineReader` 按行读取 stdout,只消费匹配请求 id 的响应;`PipeDrain` 持续排空 stderr 且不进入用户可见文案。-- 进程已退出 → 重建。-- 连接存活超过 `connectionMaxAge`(1 小时)→ 定期回收重建(覆盖 codex 全局升级、服务端状态漂移)。-- **复用的**连接上请求失败 → 丢弃重建一次再试;**全新**连接上的失败直接抛出,不做二次重试。-- 登录类错误(`requiresLogin`)→ 丢弃连接但不重试;下次轮询起新进程读取最新 `~/.codex/auth.json`,用户重新登录后最多一分钟自动恢复。+## 额度与使用量模型-认证重试:`account/rateLimits/read` 返回认证错误时,先在同一会话上调 `account/read`(`refreshToken: true`)再重试一次;仍失败抛 `authenticationRequired`。+`CodexQuotaSnapshot` 转换规则:-token 统计来自 `account/usage/read`(`summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`);本机 app-server 不支持该方法时,token 区域不展示,额度信息仍正常显示。+- 必须有 `AccountReadResponse.account`,否则抛 `notLoggedIn`。+- 优先读取 `rateLimitsByLimitId` 以支持多 limit;为空则回退顶层 `rateLimits`。+- 顶层 `rateLimits.limitId` 指向的主 limit 置顶,缺省 `"codex"`;其余按 `limitName ?? limitId` 做 localized standard 排序,再按 `limitId` 稳定排序。+- 每个 limit 的 `primary`/`secondary` 窗口合成 `[QuotaWindow]`;没有窗口的 limit 被过滤,全部为空才抛 `missingRateLimitWindow`。+- `QuotaWindow.remainingPercent = clamp(100 - usedPercent, 0...100)`,无 `usedPercent` 时视为无数据。+- `windowDurationMins` 动态生成标签:整天显示「N 天」,整小时显示「N 小时」,否则显示「N 分钟」,缺失或非正数显示「额度」。-## 并发约定+`CodexUsageSnapshot.recentDays(count:endingDaysAgo:)` 基于本地当天零点生成连续日期,按 `yyyy-MM-dd` 汇总 `dailyUsageBuckets`。UI 当前展示 `UsageHeatmap.Metrics.dayCount`(210 天)且 `endingDaysAgo: 1`,也就是默认不包含今天。热力图颜色按当前展示区间内的峰值缩放。-工程开启了 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未显式标注的类型一律推断为 MainActor 隔离。因此**所有非 UI 类型必须显式标 `nonisolated`**,否则会报「Call to main actor-isolated initializer in a synchronous nonisolated context」。+## 连接重建规则++`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`,连接状态只在私有串行 `DispatchQueue(label: "CodexBar.app-server")` 上读写。++- 进程已退出 → 重建。+- 连接存活超过 `connectionMaxAge`(1 小时)→ 关闭后重建,覆盖 Codex 升级或服务端状态漂移。+- 复用连接上的非登录类请求失败 → 丢弃连接,重建一次再试。+- 全新连接上的失败 → 直接抛出,避免故障时重复完整握手。+- 登录类错误(`requiresLogin`)→ 丢弃连接但不立即重试;下次轮询重新启动进程读取最新登录状态,用户重新登录后最多一分钟自动恢复。-`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`,连接状态只在私有串行 `DispatchQueue` 上读写,对外暴露 async 接口。+## 并发约定-## 认证和沙盒+工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:未显式标注的类型会推断为 MainActor 隔离。因此非 UI 类型、DTO、模型、服务辅助类型和部分静态工具必须显式 `nonisolated`,否则容易出现「Call to main actor-isolated initializer in a synchronous nonisolated context」。-Xcode target 已关闭 App Sandbox(需要启动本机 Codex CLI 并读取用户登录状态)。服务层用真实用户 home(`getpwuid`)运行 app-server——Xcode 运行时 `HOME` 可能指向 app container,导致读不到 `~/.codex` 而报 "codex account authentication required"。+UI 层(`CodexBarAppDelegate`、`StatusItemController`、`SettingsWindowController`、`RateLimitsViewModel`、`AppUpdater`、`LoginItemSettings`)保持 `@MainActor` 或主线程使用。服务层对外暴露 async API,内部用 queue 串行化 Process/Pipe 状态。## UI 与错误展示约定-- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。+- 菜单栏正常图标是 `person.fill.checkmark`,错误图标是 `person.fill.xmark`;由 `StatusItemController.updateStatusImage()` 直接设置 `NSStatusItem.button.image`。菜单栏不展示额度数字,详情只在 popover 中展示。- App 图标保持白底黑色 `timelapse`。-- 不要给 symbol API 加低版本 fallback,最低系统版本已是 macOS 15.0。-- 弹窗整体采用 Liquid Glass 风格(`LiquidGlassStyle.swift`):`.liquidGlassSurface(...)` 给各分区/外层加玻璃质感背景,`.liquidGlassCapsule` 给 plan 徽章,分隔线用 `LiquidGlassDivider`。plan 徽章颜色由 `planBadgeTint(for:)` 按计划名子串匹配(有序优先级:enterprise→team/business→pro→plus→edu→free→默认 cyan)。-- 弹窗按 limit 分节展示(节标题取 `limitName` 回退 `limitId`,首字母大写,节之间 `LiquidGlassDivider`)。分段条展示**剩余**额度(`100 - usedPercent`);额度行标签由 `windowDurationMins` 动态生成(如 `300` → `5 小时`,`10080` → `7 天`)。重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`(更新时间行不展示版本号)。-- token 贡献墙为 30 列 × 7 行蓝色方块热力图,token 数按 `M`/`B` 紧凑单位展示。-- 设置走菜单栏图标**右键(或 Control 点击)菜单**的「设置」项,打开独立的 `AppSettingsView` 窗口;开机自启状态读取是同步 XPC,在设置窗口 `onAppear` 时刷新。-- **错误文案不暴露内部细节**:`serverTimeout` 只携带 JSON-RPC 步骤名;子进程 stderr 由 `PipeDrain` 排空丢弃,不进入任何用户可见文案。-- 登录类错误(`requiresLogin`):弹窗顶部橙色提示「Codex 未登录」,旧快照置灰(opacity 0.4)保留,红色错误行被抑制。其他错误:红色小字展示 `errorDescription`,旧快照保持全亮度。-- 错误文案保持显示直到某次刷新成功(`refresh()` 开始时不清空 `lastError`);旧额度快照永远不清空。+- popover 宽度由 `RateLimitsMenuView.menuWidth` 绑定到热力图总宽度和 padding;修改热力图尺寸时同步检查弹窗宽度。+- 弹窗整体采用 Liquid Glass 风格:外层和分区使用 `.liquidGlassSurface(...)`,plan 徽章用 `.liquidGlassCapsule`,分隔线用 `LiquidGlassDivider`。不要把设置、额度、usage 区块改回普通卡片样式。+- plan 徽章颜色由 `planBadgeTint(for:)` 按子串匹配,优先级:enterprise → team/business → pro → plus → edu → free → 默认 cyan。+- 弹窗按 limit 分节展示,标题取 `limitName` 回退 `limitId` 并首字母大写;节之间用 `LiquidGlassDivider`。+- 额度条展示剩余百分比(`100 - usedPercent`),颜色阈值:剩余 50% 及以上绿色,25% 到 50% 橙色,低于 25% 红色;无数据使用占位色并显示 `--` / `暂无数据`。+- 重置时间格式 `MM-dd HH:mm`,更新时间格式 `HH:mm:ss`;更新时间行不展示应用版本号。+- token 区域显示「单日峰值」和「全时累计」,数字通过 `TokenCountText` 格式化为 K/M/B,下方是 30 × 7 蓝色热力图;hover tooltip 显示日期和单日 token。+- 设置走菜单栏图标右键或 Control 点击菜单的「设置」项,打开独立 `AppSettingsView` 窗口;不要恢复为 Option 点击或 popover 内设置区。+- 登录类错误(`requiresLogin`)时,popover 顶部显示橙色「Codex 未登录」,旧快照 opacity 0.4 置灰保留,红色错误行被抑制。+- 其他错误显示红色小字 `errorDescription`,旧快照保持全亮度。+- `refresh()` 开始时不要清空 `lastError`;错误文案保持到某次刷新成功才消失。旧额度快照永远不因失败而清空。+- app-server 相关用户可见错误通过 `CodexRateLimitError.errorDescription` 生成;不要把子进程 stderr 或原始日志拼进 UI 文案。## 自动更新(Sparkle)-`AppUpdater`(`@MainActor`、`ObservableObject`)初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空),任一缺失则不创建 `SPUStandardUpdaterController`,各操作文案显示「未配置更新资源」(Debug/未签名构建静默降级);`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。+`AppUpdater` 是 `@MainActor ObservableObject`。初始化时先校验 Info.plist 的 `SUFeedURL`(http/https)和 `SUPublicEDKey`(非空);任一缺失则不创建 `SPUStandardUpdaterController`,所有更新操作文案显示「未配置更新资源」,Debug/未签名构建静默降级。`canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性,设置窗的「自动检查更新」开关据此禁用。++更新文案按 UI 表面拆分,不要合并:++- `settingsStatusMessage`:设置窗版本行状态,默认 3 秒后由可取消 `Task` 清空;传 `autoDismissDelay: nil` 时常驻。+- `panelUpdateMessage`:popover 底栏被动提示,双击可触发 `startUpdate()`。+- `availableUpdateMessage`:发现新版的语义状态,驱动设置窗版本行和「立即更新」按钮。++`checkForUpdates()` 是设置窗手动检查,设置 `isManualCheckInProgress`;若已经有 `availableUpdateMessage`,只把该消息常驻显示到设置窗。`startUpdate()` 激活应用并调用 Sparkle 安装面板。`setAutomaticallyChecksForUpdates(_:)` 和 `refreshAutomaticCheckSetting()` 同步 Sparkle 开关状态。委托回调按 `isManualCheckInProgress` 路由:手动检查结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。++Info.plist 位于 `CodexBar/Resources/Info.plist`,当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,`SUScheduledCheckInterval = 3600`。++## 认证、隐私与沙盒++CodexBar 只与本机 app-server 进程通信,账号与额度数据不发往第三方服务。除 Sparkle appcast/DMG 下载外,应用自身不做网络请求。-按 UI 表面拆三个 `@Published` 文案,不要合并:`settingsStatusMessage`(设置窗版本行,默认 3 秒后由可取消 `Task` 清空,`autoDismissDelay: nil` 时常驻)、`panelUpdateMessage`(popover 底栏被动提示)、`availableUpdateMessage`(有新版的语义标志,驱动设置窗「立即更新」按钮)。`checkForUpdates()` 是设置窗的手动检查(置 `isManualCheckInProgress`),`startUpdate()` 拉起 Sparkle 安装面板,`setAutomaticallyChecksForUpdates(_:)`/`refreshAutomaticCheckSetting()` 同步开关状态。委托回调据 `isManualCheckInProgress` 路由:手动检查的结果进 `settingsStatusMessage`,自动检查发现新版进 `panelUpdateMessage`。Info.plist 位于 `CodexBar/Resources/Info.plist`(`SUFeedURL = https://codexbar.zabrian.app/appcast.xml`,检查间隔 3600 秒)。+App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`),否则无法可靠启动 Codex CLI 或读取当前用户登录状态。服务层必须用真实用户 home 运行 app-server,以免 Xcode 运行时 `HOME` 指向 app container 导致 "codex account authentication required"。## Git 提交规范-- 提交 message 使用 **Conventional Commits 前缀 + 中文描述**,格式:`<type>: <中文描述>`。+- 提交 message 使用 **Conventional Commits 前缀 + 中文标题 + 空行 + 缩进 bullet body**。+- 标题行格式:`<type>: <中文描述>`,描述简洁,不加句号。- 常用 type:`feat`(新功能)、`fix`(修复)、`chore`(杂项/发布)、`refactor`(重构)、`docs`(文档)。-- 描述简洁一行,不加句号。-- **提交后不要主动 push,必须等用户明确同意后才能推送。**+- 标题行后空一行再写 body;body 使用 4 个空格缩进的 `- ` 列表。+- body 每条 bullet 描述一个具体变更点,优先覆盖新增/修改的核心模块、用户可见行为、脚本/资源/配置变化;不要写泛泛总结。+- 简单文档或杂项改动如确实没有多个变更点,可以只写标题行;功能、修复、发布类提交必须写 body。+- 提交后不要主动 push,必须等用户明确同意后才能推送。### Tag 规范-- tag 名格式:`v{MARKETING_VERSION}`(如 `v1.2.1`),与 Xcode target 的 `MARKETING_VERSION` 保持一致。-- 使用**附注 tag**(`git tag -a`),message 格式:`Release v{version}`(如 `git tag -a v1.2.1 -m "Release v1.2.1"`)。+- tag 名格式:`v{MARKETING_VERSION}`(如 `v1.3.3`),与 Xcode target 的 `MARKETING_VERSION` 保持一致。+- 使用附注 tag(`git tag -a`),message 格式:`Release v{version}`(如 `git tag -a v1.3.3 -m "Release v1.3.3"`)。- tag 同样不要主动 push,等用户明确同意。## 发布流程1. 用 `Developer ID Application` 证书签名并 notarization,Xcode 导出 `CodexBar.app` 到项目根目录。-2. `Scripts/create-dmg.sh`:自动找到根目录唯一 `.app`,按 `MARKETING_VERSION` 生成 `CodexBar-v{version}.dmg`(含 Applications 快捷方式和 Finder 布局)。-3. `Scripts/update-appcast.sh [dmg]`:用 Sparkle `sign_update` 签名 DMG,从 build settings 读版本号,将 `<item>` 写入 `Updates/appcast.xml`(同版本去重,`xmllint` 校验)。常用环境变量:`DOWNLOAD_BASE_URL`、`INCLUDE_RELEASE_NOTES`、`MINIMUM_SYSTEM_VERSION` 等。-4. 上传 DMG 和更新后的 `appcast.xml` 到 `SUFeedURL` 对应站点。+2. `Scripts/create-dmg.sh [App.app] [Output.dmg]`:未传 app 时自动找到项目根目录唯一 `.app`;按 Xcode `MARKETING_VERSION` 生成默认 `CodexBar-v{version}.dmg`;DMG 内含 Applications 快捷方式和 Finder 布局。脚本依赖 `hdiutil`、`osascript`、`ditto`。+3. `Scripts/update-appcast.sh [CodexBar-vX.Y.Z.dmg]`:未传 DMG 时自动找项目根目录唯一 `.dmg`;用 Sparkle `sign_update` 签名,从 Release build settings 读取 `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION`,将同 build version 的旧 `<item>` 去重后写入 `Updates/appcast.xml`,有 `xmllint` 时校验。+4. 常用环境变量:`APPCAST_PATH`、`DOWNLOAD_BASE_URL`、`RELEASE_NOTES_BASE_URL`、`INCLUDE_RELEASE_NOTES`、`MINIMUM_SYSTEM_VERSION`、`SIGN_UPDATE`、`XCODE_PROJECT`、`XCODE_SCHEME`。+5. 上传 DMG 和更新后的 `appcast.xml` 到 `SUFeedURL` 对应站点。diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 9791cef..c5c453a 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -275,7 +275,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 5;+ CURRENT_PROJECT_VERSION = 6;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -290,7 +290,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.3.2;+ MARKETING_VERSION = 1.3.3;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -312,7 +312,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 5;+ CURRENT_PROJECT_VERSION = 6;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -327,7 +327,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.3.2;+ MARKETING_VERSION = 1.3.3;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/AppSettingsView.swift b/CodexBar/AppSettingsView.swiftindex 2cdac95..80fe0d0 100644--- a/CodexBar/AppSettingsView.swift+++ b/CodexBar/AppSettingsView.swift@@ -11,7 +11,7 @@ import SwiftUIstruct AppSettingsView: View {@EnvironmentObject private var appUpdater: AppUpdater@StateObject private var loginItemSettings = LoginItemSettings()-+var body: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {@@ -23,7 +23,7 @@ struct AppSettingsView: View {}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)-+HStack(alignment: .center, spacing: 12) {quitButtonstatusText@@ -63,7 +63,7 @@ private extension AppSettingsView {static let panelCornerRadius: CGFloat = 10static let iconWidth: CGFloat = 18}-+var launchAtLoginRow: some View {settingsToggleRow(icon: "power",@@ -109,22 +109,22 @@ private extension AppSettingsView {.disabled(!isEnabled)}}-+var versionRow: some View {HStack(spacing: 10) {Image(systemName: "info.circle").frame(width: Metrics.iconWidth).foregroundStyle(.secondary)-+Text("当前 APP 版本")-+Spacer()-+Text(versionStatus.text).font(versionStatus.isVersionLabel ? .body.monospacedDigit() : .body).foregroundStyle(.secondary).lineLimit(1)-+if appUpdater.availableUpdateMessage != nil {Button {appUpdater.startUpdate()@@ -140,7 +140,7 @@ private extension AppSettingsView {}}}-+/// 版本行文案;无任何动态消息时回退到版本号(此时用等宽数字)var versionStatus: (text: String, isVersionLabel: Bool) {if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {@@ -148,7 +148,7 @@ private extension AppSettingsView {}return (Bundle.main.displayVersionLabel, true)}-+@ViewBuildervar statusText: some View {if let message = loginItemSettings.errorMessage {@@ -158,7 +158,7 @@ private extension AppSettingsView {.fixedSize(horizontal: false, vertical: true)}}-+var checkUpdateButton: some View {Button {appUpdater.checkForUpdates()@@ -166,7 +166,7 @@ private extension AppSettingsView {Label("检查更新", systemImage: "arrow.down.circle")}}-+var quitButton: some View {Button(role: .destructive) {NSApplication.shared.terminate(nil)diff --git a/CodexBar/AppUpdater.swift b/CodexBar/AppUpdater.swiftindex adb8629..4a18550 100644--- a/CodexBar/AppUpdater.swift+++ b/CodexBar/AppUpdater.swift@@ -22,14 +22,14 @@ final class AppUpdater: NSObject, ObservableObject {private var updaterController: SPUStandardUpdaterController?private var clearSettingsStatusMessageTask: Task<Void, Never>?private var isManualCheckInProgress = false-+init(bundle: Bundle = .main) {super.init()-+guard Self.hasUsableSparkleConfiguration(in: bundle) else {return}-+updaterController = SPUStandardUpdaterController(startingUpdater: true,updaterDelegate: self,@@ -37,61 +37,61 @@ final class AppUpdater: NSObject, ObservableObject {)refreshAutomaticCheckSetting()}-+func checkForUpdates() {guard let updaterController else {showSettingsStatusMessage("未配置更新资源")return}-+if let availableUpdateMessage {showSettingsStatusMessage(availableUpdateMessage, autoDismissDelay: nil)return}-+isManualCheckInProgress = trueshowSettingsStatusMessage("正在检查更新")updaterController.updater.checkForUpdateInformation()}-+func startUpdate() {guard let updaterController else {showSettingsStatusMessage("未配置更新资源")return}-+NSApplication.shared.activate()updaterController.checkForUpdates(nil)}-+func setAutomaticallyChecksForUpdates(_ isEnabled: Bool) {guard let updaterController else {automaticallyChecksForUpdates = falseshowSettingsStatusMessage("未配置更新资源")return}-+updaterController.updater.automaticallyChecksForUpdates = isEnabledrefreshAutomaticCheckSetting()}-+func refreshAutomaticCheckSetting() {automaticallyChecksForUpdates = updaterController?.updater.automaticallyChecksForUpdates ?? false}-+private func showSettingsStatusMessage(_ message: String, autoDismissDelay: Duration? = .seconds(3)) {clearSettingsStatusMessageTask?.cancel()settingsStatusMessage = message-+guard let autoDismissDelay else { return }-+clearSettingsStatusMessageTask = Task { [weak self] intry? await Task.sleep(for: autoDismissDelay)guard !Task.isCancelled else { return }self?.settingsStatusMessage = nil}}-+private static func hasUsableSparkleConfiguration(in bundle: Bundle) -> Bool {guardlet feedURLString = bundle.object(forInfoDictionaryKey: "SUFeedURL") as? String,@@ -101,7 +101,7 @@ final class AppUpdater: NSObject, ObservableObject {else {return false}-+return !publicKey.isEmpty}}@@ -110,24 +110,33 @@ extension AppUpdater: SPUUpdaterDelegate {func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {let message = "发现新版本: v\(item.displayVersionString)"availableUpdateMessage = message-+if isManualCheckInProgress {showSettingsStatusMessage(message, autoDismissDelay: nil)} else {panelUpdateMessage = message}-+isManualCheckInProgress = false}-+func updaterDidNotFindUpdate(_ updater: SPUUpdater, error: Error) {availableUpdateMessage = nilpanelUpdateMessage = nil-+if isManualCheckInProgress {- showSettingsStatusMessage("已是最新版本", autoDismissDelay: .milliseconds(1500))+ showSettingsStatusMessage("没有可用更新", autoDismissDelay: .milliseconds(1500))}-++ isManualCheckInProgress = false+ }++ func updater(_ updater: SPUUpdater, didAbortWithError error: Error) {+ guard isManualCheckInProgress else {+ return+ }++ showSettingsStatusMessage("检查更新失败")isManualCheckInProgress = false}}diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/CodexBarApp.swiftindex bbc7c5c..30aeb3e 100644--- a/CodexBar/CodexBarApp.swift+++ b/CodexBar/CodexBarApp.swift@@ -11,7 +11,7 @@ import SwiftUI@mainstruct CodexBarApp: App {@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate-+var body: some Scene {// 实际 UI 由 CodexBarAppDelegate 的 StatusItemController 驱动// App 仅需声明一个占位 Scene 设置窗口走右键菜单的 makeSettingsWindowdiff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swiftindex 0924bdd..221605a 100644--- a/CodexBar/CodexRateLimitService.swift+++ b/CodexBar/CodexRateLimitService.swift@@ -17,17 +17,17 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {private static let connectionMaxAge: TimeInterval = 1 * 60 * 60// 进程环境在应用启动后不会变化, 只构建一次private static let environment = appServerEnvironment()-+// 连接状态只在 queue 上读写private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)private var connection: AppServerConnection?-+init() {}-+deinit {connection?.session.close()}-+func fetchRateLimits() async throws -> CodexQuotaSnapshot {try await withCheckedThrowingContinuation { continuation inqueue.async {@@ -35,7 +35,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {}}}-+private func fetchRateLimitsOnQueue() throws -> CodexQuotaSnapshot {do {let (connection, reused) = try ensureConnection()@@ -53,15 +53,15 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {throw error}}-+private func ensureConnection() throws -> (connection: AppServerConnection, reused: Bool) {if let connection, connection.session.process.isRunning,Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {return (connection, reused: true)}-+teardownConnection()-+let command = try Self.resolveAppServerCommand(environment: Self.environment)let newConnection = try Self.openConnection(command: command,@@ -69,16 +69,16 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {clientVersion: Self.clientVersion(),timeout: Self.requestTimeout)-+connection = newConnectionreturn (newConnection, reused: false)}-+private func teardownConnection() {connection?.session.close()connection = nil}-+private static func fetchSnapshot(using connection: AppServerConnection) throws -> CodexQuotaSnapshot {func readRateLimits() throws -> AccountRateLimitsResponse {try connection.session.request(@@ -86,7 +86,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {as: AccountRateLimitsResponse.self)}-+let rateLimitsResponse: AccountRateLimitsResponsedo {rateLimitsResponse = try readRateLimits()@@ -96,26 +96,41 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {params: ["refreshToken": true],as: AccountReadResponse.self)-+do {rateLimitsResponse = try readRateLimits()} catch let retryError as CodexRateLimitError where retryError.isAuthenticationRequired {throw CodexRateLimitError.authenticationRequired}}-- let usageResponse = try? connection.session.request(- "account/usage/read",- as: AccountUsageResponse.self- )-++ let usageResponse = readUsageIfAvailable(using: connection)+return try CodexQuotaSnapshot(accountResponse: connection.accountResponse,rateLimitsResponse: rateLimitsResponse,usageResponse: usageResponse)}-++ private static func readUsageIfAvailable(using connection: AppServerConnection) -> AccountUsageResponse? {+ guard connection.isUsageReadAvailable else {+ return nil+ }++ do {+ return try connection.session.request(+ "account/usage/read",+ as: AccountUsageResponse.self+ )+ } catch let error as CodexRateLimitError where error.isUnsupportedUsageMethod {+ connection.isUsageReadAvailable = false+ return nil+ } catch {+ return nil+ }+ }+/// 启动 app-server 进程并完成 initialize、account/read 握手, 返回可复用的连接private static func openConnection(command: AppServerCommand,@@ -127,23 +142,23 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {process.executableURL = URL(fileURLWithPath: command.executablePath)process.arguments = command.argumentsprocess.environment = environment-+let standardInput = Pipe()let standardOutput = Pipe()let standardError = Pipe()let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)let errorReader = PipeDrain(fileHandle: standardError.fileHandleForReading)-+process.standardInput = standardInputprocess.standardOutput = standardOutputprocess.standardError = standardError-+do {try process.run()} catch {throw CodexRateLimitError.serverStartFailed(error.localizedDescription)}-+let session = AppServerSession(process: process,input: standardInput,@@ -151,7 +166,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {errorReader: errorReader,timeout: timeout)-+do {_ = try session.request("initialize",@@ -164,15 +179,15 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {],as: EmptyResponse.self)-+try session.notify("initialized")-+let accountResponse = try session.request("account/read",params: ["refreshToken": false],as: AccountReadResponse.self)-+return AppServerConnection(session: session,accountResponse: accountResponse@@ -182,7 +197,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {throw error}}-+private nonisolated static func appServerEnvironment() -> [String: String] {var environment = ProcessInfo.processInfo.environmentlet homeDirectory = realUserHomeDirectory()@@ -198,34 +213,34 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {"/usr/sbin","/sbin"]-+environment["HOME"] = homeDirectoryenvironment["USER"] = NSUserName()environment["LOGNAME"] = NSUserName()environment["PATH"] = mergedPath(path, fallbackPaths: fallbackPaths)environment["TERM"] = environment["TERM"] ?? "xterm-256color"-+return environment}-+private nonisolated static func resolveAppServerCommand(environment: [String: String]) throws -> AppServerCommand {let cliPath = findExecutable(named: "codex", environment: environment)-+if let cliPath, standardizedPath(cliPath) != standardizedPath(bundledExecutablePath) {return AppServerCommand(executablePath: cliPath)}-+if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {return AppServerCommand(executablePath: bundledExecutablePath)}-+if let cliPath {return AppServerCommand(executablePath: cliPath)}-+throw CodexRateLimitError.executableNotFound}-+private nonisolated static func findExecutable(named executableName: String,environment: [String: String]@@ -233,51 +248,51 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {guard let path = environment["PATH"] else {return nil}-+for directory in path.split(separator: ":") {let executablePath = "\(directory)/\(executableName)"if FileManager.default.isExecutableFile(atPath: executablePath) {return executablePath}}-+return nil}-+private nonisolated static func mergedPath(_ path: String, fallbackPaths: [String]) -> String {var components: [String] = []var seen = Set<String>()-+for component in path.split(separator: ":").map(String.init) + fallbackPaths {guard !component.isEmpty, !seen.contains(component) else {continue}-+components.append(component)seen.insert(component)}-+return components.joined(separator: ":")}-+private nonisolated static func standardizedPath(_ path: String) -> String {URL(fileURLWithPath: path).standardizedFileURL.path}-+private nonisolated static func clientVersion() -> String {guard let version = Bundle.main.shortVersionString, !version.isEmpty else {return "1.0.0"}-+return version}-+private nonisolated static func realUserHomeDirectory() -> String {guard let passwd = getpwuid(getuid()),let home = passwd.pointee.pw_dir else {return NSHomeDirectory()}-+return String(cString: home)}}@@ -286,7 +301,8 @@ private nonisolated final class AppServerConnection {let session: AppServerSessionlet openedAt = Date()var accountResponse: AccountReadResponse-+ var isUsageReadAvailable = true+init(session: AppServerSession, accountResponse: AccountReadResponse) {self.session = sessionself.accountResponse = accountResponse@@ -295,13 +311,13 @@ private nonisolated final class AppServerConnection {private nonisolated final class AppServerSession {let process: Process-+private let input: Pipeprivate let lineReader: JSONLineReaderprivate let errorReader: PipeDrainprivate let timeout: TimeIntervalprivate var nextId = 1-+init(process: Process,input: Pipe,@@ -315,21 +331,21 @@ private nonisolated final class AppServerSession {self.errorReader = errorReaderself.timeout = timeout}-+func close() {lineReader.stop()errorReader.stop()try? input.fileHandleForWriting.close()-+if process.isRunning {process.terminate()}}-+func notify(_ method: String, params: [String: Any]? = nil) throws {- try write(message(method: method, id: nil, params: params))+ try write(message(method: method, id: nil, params: params), step: method)}-+func request<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -337,10 +353,10 @@ private nonisolated final class AppServerSession {) throws -> Response {let id = nextIdnextId += 1- try write(message(method: method, id: id, params: params))+ try write(message(method: method, id: id, params: params), step: method)return try waitForResponse(id: id, step: method, decode: type)}-+private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {var object: [String: Any] = ["method": method]if let id {@@ -351,13 +367,18 @@ private nonisolated final class AppServerSession {}return object}-- private func write(_ object: [String: Any]) throws {++ private func write(_ object: [String: Any], step: String) throws {var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])data.append(0x0A)- input.fileHandleForWriting.write(data)++ do {+ try input.fileHandleForWriting.write(contentsOf: data)+ } catch {+ throw CodexRateLimitError.serverConnectionClosed(step)+ }}-+private func waitForResponse<Response: Decodable>(id: Int,step: String,@@ -365,31 +386,38 @@ private nonisolated final class AppServerSession {) throws -> Response {let deadline = Date().addingTimeInterval(timeout)let decoder = JSONDecoder()-+while Date() < deadline {guard let line = lineReader.nextLine(timeout: deadline.timeIntervalSinceNow) else {+ if lineReader.isClosed {+ throw CodexRateLimitError.serverConnectionClosed(step)+ }+continue}-+guard let data = line.data(using: .utf8) else {continue}-++ guard let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),+ idEnvelope.id == id else {+ continue+ }+if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: data),- errorEnvelope.id == id,let error = errorEnvelope.error {throw CodexRateLimitError.serverError(error.message)}-+guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: data),- envelope.id == id,let result = envelope.result else {- continue+ throw CodexRateLimitError.invalidServerResponse(step)}-+return result}-+throw CodexRateLimitError.serverTimeout(step)}}@@ -401,6 +429,10 @@ private nonisolated struct AppServerCommand: Sendable {private nonisolated struct EmptyResponse: Decodable {}+private nonisolated struct RPCIDEnvelope: Decodable {+ let id: Int?+}+private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {let id: Int?let result: Response?@@ -421,45 +453,59 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {private let fileHandle: FileHandleprivate var buffer = Data()private var lines: [String] = []-+ private var closed = false+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { [weak self] handle inself?.append(handle.availableData)}}-+func nextLine(timeout: TimeInterval) -> String? {if let line = popLine() {return line}-++ if isClosed {+ return nil+ }+let result = semaphore.wait(timeout: .now() + timeout)guard result == .success else {return nil}-+return popLine()}-+func stop() {fileHandle.readabilityHandler = nil+ markClosed()+ }++ var isClosed: Bool {+ lock.lock()+ defer { lock.unlock() }++ return closed && lines.isEmpty}-+private func append(_ data: Data) {guard !data.isEmpty else {+ markClosed()return}-+lock.lock()defer { lock.unlock() }-+buffer.append(data)-+while let newlineRange = buffer.firstRange(of: Data([0x0A])) {let lineData = buffer[..<newlineRange.lowerBound]buffer.removeSubrange(...newlineRange.lowerBound)-+if let line = String(data: lineData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),!line.isEmpty {@@ -468,27 +514,46 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {}}}-++ private func markClosed() {+ lock.lock()+ defer {+ lock.unlock()+ semaphore.signal()+ }++ if !buffer.isEmpty {+ if let line = String(data: buffer, encoding: .utf8)?+ .trimmingCharacters(in: .whitespacesAndNewlines),+ !line.isEmpty {+ lines.append(line)+ }+ buffer.removeAll()+ }++ closed = true+ }+private func popLine() -> String? {lock.lock()defer { lock.unlock() }-+guard !lines.isEmpty else {return nil}-+return lines.removeFirst()}}private nonisolated final class PipeDrain: @unchecked Sendable {private let fileHandle: FileHandle-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { _ = $0.availableData }}-+func stop() {fileHandle.readabilityHandler = nil}diff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/LoginItemSettings.swiftindex 848a6ec..b5bc6ec 100644--- a/CodexBar/LoginItemSettings.swift+++ b/CodexBar/LoginItemSettings.swift@@ -14,10 +14,6 @@ final class LoginItemSettings: ObservableObject {@Published private(set) var isEnabled = false@Published private(set) var errorMessage: String?- init() {- refresh()- }-func refresh() {isEnabled = SMAppService.mainApp.status == .enabled}diff --git a/CodexBar/QuotaRow.swift b/CodexBar/QuotaRow.swiftindex 4ee2c97..950d11f 100644--- a/CodexBar/QuotaRow.swift+++ b/CodexBar/QuotaRow.swift@@ -9,22 +9,22 @@ import SwiftUIstruct QuotaRow: View {let window: QuotaWindow-+var body: some View {HStack(alignment: .center, spacing: Metrics.spacing) {Text(window.label).font(.caption.weight(.semibold)).lineLimit(1).frame(width: Metrics.labelWidth, alignment: .leading)-- SegmentedQuotaBar(percent: window.remainingPercent)++ SegmentedQuotaBar(percent: window.hasData ? window.remainingPercent : nil).frame(height: Metrics.barHeight)-+Text(percentText).font(.caption.monospacedDigit().weight(.semibold)).lineLimit(1).frame(width: Metrics.percentWidth, alignment: .leading)-+Text(resetText).font(.caption2.monospacedDigit()).foregroundStyle(.secondary)@@ -42,27 +42,27 @@ private extension QuotaRow {static let percentWidth: CGFloat = 32static let resetWidth: CGFloat = 76}-+var resetText: String {guard window.hasData else {return "暂无数据"}-+guard let resetsAt = window.resetsAt else {return "--"}-+return Self.resetFormatter.string(from: resetsAt)}-+var percentText: String {guard window.hasData else {return "--"}-+return "\(window.remainingPercent)%"}-+static let resetFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")@@ -72,22 +72,22 @@ private extension QuotaRow {}private struct SegmentedQuotaBar: View {- let percent: Int-+ let percent: Int?+var body: some View {GeometryReader { proxy inlet segmentCount = segmentCount(for: proxy.size.width)let filledSegments = filledSegments(for: segmentCount)-+HStack(spacing: Metrics.spacing) {ForEach(0..<segmentCount, id: \.self) { index inCapsule(style: .continuous)- .fill(index < filledSegments ? fillStyle : emptyStyle)+ .fill(fillStyle(for: index, filledSegments: filledSegments)).frame(maxWidth: .infinity)}}}- .accessibilityLabel("剩余 \(percent)%")+ .accessibilityLabel(accessibilityLabel)}}@@ -96,16 +96,32 @@ private extension SegmentedQuotaBar {static let spacing: CGFloat = 2static let idealSegmentWidth: CGFloat = 6}-+func segmentCount(for width: CGFloat) -> Int {max(1, Int((width + Metrics.spacing) / (Metrics.idealSegmentWidth + Metrics.spacing)))}-+func filledSegments(for segmentCount: Int) -> Int {- Int((Double(percent) / 100.0 * Double(segmentCount)).rounded())+ guard let percent else {+ return 0+ }++ return Int((Double(percent) / 100.0 * Double(segmentCount)).rounded())+ }++ func fillStyle(for index: Int, filledSegments: Int) -> Color {+ guard percent != nil else {+ return placeholderStyle+ }++ return index < filledSegments ? filledStyle : emptyStyle}-- var fillStyle: Color {++ var filledStyle: Color {+ guard let percent else {+ return placeholderStyle+ }+switch percent {case 50...:return .green@@ -115,8 +131,20 @@ private extension SegmentedQuotaBar {return .red}}-+var emptyStyle: Color {Color.secondary.opacity(0.18)}++ var placeholderStyle: Color {+ Color.secondary.opacity(0.12)+ }++ var accessibilityLabel: String {+ guard let percent else {+ return "暂无额度数据"+ }++ return "剩余 \(percent)%"+ }}diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/RateLimitModels.swiftindex 69b3889..3131352 100644--- a/CodexBar/RateLimitModels.swift+++ b/CodexBar/RateLimitModels.swift@@ -13,11 +13,11 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let generatedAt: Datelet limits: [CodexQuotaLimitSnapshot]let usage: CodexUsageSnapshot?-+var accountLabel: String {account.displayName}-+var planLabel: String? {account.planType ?? planType}@@ -27,14 +27,14 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {let limitId: Stringlet limitName: String?let windows: [QuotaWindow]-+var id: String { limitId }-+var title: String {if let limitName, !limitName.isEmpty {return limitName.capitalizingFirstLetter()}-+return limitId.capitalizingFirstLetter()}}@@ -44,7 +44,7 @@ nonisolated private extension String {guard let first else {return self}-+return first.uppercased() + dropFirst()}}@@ -53,16 +53,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {let type: Stringlet email: String?let planType: String?-+var hasEmail: Bool {email?.isEmpty == false}-+var displayName: String {if let email, hasEmail {return email}-+switch type {case "apiKey":return "API Key"@@ -85,36 +85,36 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {let windowDurationMins: Int?let usedPercent: Int?let resetsAt: Date?-+var label: String {Self.windowLabel(for: windowDurationMins)}-+var remainingPercent: Int {guard let usedPercent else {return 0}-+return max(0, min(100, 100 - usedPercent))}-+var hasData: Bool {usedPercent != nil}-+private static func windowLabel(for minutes: Int?) -> String {guard let minutes, minutes > 0 else {return "额度"}-+if minutes.isMultiple(of: 1_440) {return "\(minutes / 1_440) 天"}-+if minutes.isMultiple(of: 60) {return "\(minutes / 60) 小时"}-+return "\(minutes) 分钟"}}@@ -133,10 +133,10 @@ nonisolated struct RateLimitSnapshot: Decodable {}nonisolated struct RateLimitWindow: Decodable {- let usedPercent: Int+ let usedPercent: Int?let resetsAt: Int?let windowDurationMins: Int?-+var resetDate: Date? {guard let resetsAt else { return nil }return Date(timeIntervalSince1970: TimeInterval(resetsAt))@@ -156,31 +156,31 @@ nonisolated struct UsageSummary: Decodable, Equatable {nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {let startDate: Stringlet tokens: Int-+var id: String { startDate }}nonisolated struct CodexUsageSnapshot: Equatable {let summary: UsageSummarylet dailyBuckets: [DailyUsageBucket]-+func recentDays(count: Int, endingDaysAgo: Int) -> [DailyUsageBucket] {let calendar = Calendar.currentlet today = calendar.startOfDay(for: Date())let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket inresult[bucket.startDate, default: 0] += bucket.tokens}-+return (0..<count).reversed().compactMap { offset inguard let date = calendar.date(byAdding: .day, value: -(offset + endingDaysAgo), to: today) else {return nil}-+let startDate = Self.dayFormatter.string(from: date)return DailyUsageBucket(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)}}-+private nonisolated static let dayFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")@@ -199,15 +199,15 @@ nonisolated extension CodexQuotaSnapshot {guard let account = accountResponse.account else {throw CodexRateLimitError.notLoggedIn}-+let limits = Self.orderedSnapshots(from: rateLimitsResponse).compactMap { entry inCodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)}-+guard !limits.isEmpty else {throw CodexRateLimitError.missingRateLimitWindow}-+self.init(account: account,planType: rateLimitsResponse.rateLimits.planType,@@ -218,24 +218,31 @@ nonisolated extension CodexQuotaSnapshot {})}-+/// 展示顺序: 顶层 rateLimits 指向的主 limit 置顶, 其余按名称排序private static func orderedSnapshots(from response: AccountRateLimitsResponse) -> [(limitId: String, snapshot: RateLimitSnapshot)] {let primaryLimitId = response.rateLimits.limitId ?? "codex"-+guard let byLimitId = response.rateLimitsByLimitId, !byLimitId.isEmpty else {return [(primaryLimitId, response.rateLimits)]}-+return byLimitId.map { (limitId: $0.key, snapshot: $0.value) }.sorted { lhs, rhs inif (lhs.limitId == primaryLimitId) != (rhs.limitId == primaryLimitId) {return lhs.limitId == primaryLimitId}-++ let lhsName = lhs.snapshot.limitName ?? lhs.limitId+ let rhsName = rhs.snapshot.limitName ?? rhs.limitId+ let nameOrder = lhsName.localizedStandardCompare(rhsName)+ if nameOrder != .orderedSame {+ return nameOrder == .orderedAscending+ }+return lhs.limitId.localizedStandardCompare(rhs.limitId) == .orderedAscending}}@@ -247,11 +254,11 @@ nonisolated extension CodexQuotaLimitSnapshot {.compactMap { id, window inwindow.map { QuotaWindow(id: id, window: $0) }}-+guard !windows.isEmpty else {return nil}-+self.init(limitId: limitId,limitName: snapshot.limitName,@@ -275,11 +282,13 @@ nonisolated enum CodexRateLimitError: LocalizedError {case executableNotFoundcase serverStartFailed(String)case serverTimeout(String)+ case serverConnectionClosed(String)+ case invalidServerResponse(String)case serverError(String)case missingRateLimitWindowcase notLoggedIncase authenticationRequired-+var errorDescription: String? {switch self {case .executableNotFound:@@ -288,17 +297,21 @@ nonisolated enum CodexRateLimitError: LocalizedError {return "Codex app-server 启动失败: \(message)"case .serverTimeout(let step):return "Codex app-server 响应超时: \(step)"+ case .serverConnectionClosed(let step):+ return "Codex app-server 连接断开: \(step)"+ case .invalidServerResponse(let step):+ return "Codex app-server 响应异常: \(step)"case .serverError(let message):return "Codex app-server 返回错误: \(message)"case .missingRateLimitWindow:- return "查询不到数据"+ return "暂未获取到数据"case .notLoggedIn:return "Codex 未登录"case .authenticationRequired:return "Codex 需要身份验证"}}-+var isAuthenticationRequired: Bool {switch self {case .serverError(let message):@@ -309,7 +322,19 @@ nonisolated enum CodexRateLimitError: LocalizedError {return false}}-++ var isUnsupportedUsageMethod: Bool {+ guard case .serverError(let message) = self else {+ return false+ }++ let normalizedMessage = message.lowercased()+ return normalizedMessage.contains("method not found")+ || normalizedMessage.contains("unknown method")+ || normalizedMessage.contains("unsupported")+ || normalizedMessage.contains("not supported")+ }+/// 凭证已失效或未登录, 需要用户在 Codex 中重新登录才能恢复var requiresLogin: Bool {switch self {diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swiftindex 125eed1..df0c867 100644--- a/CodexBar/RateLimitsMenuView.swift+++ b/CodexBar/RateLimitsMenuView.swift@@ -5,16 +5,15 @@// Created by Bob on 2026-06-10.//-import AppKitimport SwiftUIstruct RateLimitsMenuView: View {static let menuWidth: CGFloat = Metrics.padding * 2 + Metrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth-+@ObservedObject var viewModel: RateLimitsViewModel@EnvironmentObject private var appUpdater: AppUpdater@State private var isEmailBlurred = false-+var body: some View {VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {content@@ -39,13 +38,13 @@ private extension RateLimitsMenuView {static let accountIconSize: CGFloat = 14static let loadingVerticalPadding: CGFloat = 16}-+@ViewBuildervar content: some View {if viewModel.requiresLogin {loginRequiredNotice}-+if let snapshot = viewModel.snapshot {Group {accountCard(@@ -53,13 +52,13 @@ private extension RateLimitsMenuView {isEmail: snapshot.account.hasEmail,plan: snapshot.planLabel)-+quotaLimitsView(snapshot.limits)-+if let usage = snapshot.usage {UsageSummaryView(usage: usage)}-+updatedAtRow(for: snapshot).padding(.horizontal, Metrics.panelPadding).padding(.vertical, 7)@@ -74,42 +73,42 @@ private extension RateLimitsMenuView {.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)}}-+var loginRequiredNotice: some View {HStack(spacing: 8) {Image(systemName: "person.crop.circle.badge.exclamationmark").foregroundStyle(.orange)-+Text("Codex 未登录").font(.caption).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)-+Spacer()}}-+var emptyView: some View {Text("暂无数据").foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, Metrics.loadingVerticalPadding)}-+func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot]) -> some View {VStack(alignment: .leading, spacing: 8) {ForEach(limits) { limit inif limit.id != limits.first?.id {LiquidGlassDivider()}-+quotaLimitSection(limit)}}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .green)}-+func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {VStack(alignment: .leading, spacing: 6) {Text(limit.title)@@ -117,7 +116,7 @@ private extension RateLimitsMenuView {.foregroundStyle(.primary).lineLimit(1).truncationMode(.middle)-+VStack(spacing: 8) {ForEach(limit.windows) { window inQuotaRow(window: window)@@ -125,14 +124,14 @@ private extension RateLimitsMenuView {}}}-+func accountCard(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {accountRow(title: title, isEmail: isEmail, plan: plan).padding(.horizontal, Metrics.panelPadding).padding(.vertical, 8).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)}-+func accountRow(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {HStack(spacing: 8) {Image(systemName: "person.fill")@@ -141,7 +140,7 @@ private extension RateLimitsMenuView {.onTapGesture(count: 2) {viewModel.refresh()}-+Text(title).font(.caption.weight(.semibold)).lineLimit(1)@@ -152,18 +151,18 @@ private extension RateLimitsMenuView {guard isEmail else { return }isEmailBlurred.toggle()}-+if viewModel.isRefreshing {ProgressView().controlSize(.mini).padding(.leading, 2)}-+Spacer()-+if let plan {let tint = planBadgeTint(for: plan)-+Text(plan.uppercased()).font(.caption2).foregroundStyle(tint)@@ -174,15 +173,15 @@ private extension RateLimitsMenuView {}}}-+func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {HStack {- Text("更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)")+ Text("数据更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)").font(.caption2).foregroundStyle(.secondary)Spacer()-+if let message = appUpdater.panelUpdateMessage {Text(message).font(.caption2.monospacedDigit())@@ -194,7 +193,7 @@ private extension RateLimitsMenuView {}}}-+@ViewBuilderfunc errorView(_ message: String?) -> some View {if let message {@@ -205,37 +204,37 @@ private extension RateLimitsMenuView {.frame(maxWidth: .infinity, alignment: .leading)}}-+func planBadgeTint(for plan: String) -> Color {let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()-+if normalizedPlan.contains("enterprise") {return .green}-+if normalizedPlan.contains("team") || normalizedPlan.contains("business") {return .orange}-+if normalizedPlan.contains("pro") {return .purple}-+if normalizedPlan.contains("plus") {return .blue}-+if normalizedPlan.contains("edu") {return .teal}-+if normalizedPlan.contains("free") {return .secondary}-+return .cyan}-+static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")@@ -243,261 +242,3 @@ private extension RateLimitsMenuView {return formatter}()}--private struct UsageSummaryView: View {- let usage: CodexUsageSnapshot- private let days: [DailyUsageBucket]- @State private var hoveredDay: DailyUsageBucket?-- init(usage: CodexUsageSnapshot) {- self.usage = usage- self.days = usage.recentDays(count: UsageHeatmap.Metrics.dayCount, endingDaysAgo: 1)- }-- var body: some View {- VStack(alignment: .leading, spacing: 8) {- HStack(alignment: .firstTextBaseline) {- metric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .leading)- Spacer()- metric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .trailing)- }-- UsageHeatmap(days: days, hoveredDay: $hoveredDay)- }- .padding(10)- .liquidGlassSurface(cornerRadius: 8, tint: .blue)- .onAppear {- hoveredDay = nil- }- }-- private func metric(label: String, value: Int, alignment: Alignment) -> some View {- VStack(alignment: .leading, spacing: 2) {- Text(label)- .font(.caption2)- .foregroundStyle(.secondary)- .frame(maxWidth: .infinity, alignment: alignment)-- TokenCountText(tokens: value)- .frame(maxWidth: .infinity, alignment: alignment)- }- .frame(width: 96)- }-}--private struct UsageHeatmap: View {- let days: [DailyUsageBucket]- @Binding var hoveredDay: DailyUsageBucket?- @State private var hoverLocation: CGPoint = .zero- // hover 期间 body 频繁重算, 峰值只在构建时求一次- private let peakTokens: Int-- init(days: [DailyUsageBucket], hoveredDay: Binding<DailyUsageBucket?>) {- self.days = days- self._hoveredDay = hoveredDay- self.peakTokens = max(days.lazy.map(\.tokens).max() ?? 0, 1)- }-- var body: some View {- ZStack(alignment: .topLeading) {- heatmapGrid-- if let hoveredDay {- UsageHeatmapTooltip(day: hoveredDay)- .allowsHitTesting(false)- .offset(tooltipOffset)- .zIndex(1)- .transition(.opacity.combined(with: .scale(scale: 0.96, anchor: .topLeading)))- .transaction { transaction in- transaction.animation = nil- }- }- }- .frame(height: Metrics.height)- .coordinateSpace(name: Metrics.coordinateSpaceName)- .animation(.snappy(duration: 0.16), value: hoveredDay?.id)- }-- private var heatmapGrid: some View {- VStack(alignment: .leading, spacing: 6) {- HStack(alignment: .firstTextBaseline) {- Text("近 \(days.count) 天")- .font(.caption2.weight(.medium))- .foregroundStyle(.secondary)-- Spacer()-- if let firstDate = days.first?.startDate, let lastDate = days.last?.startDate {- Text("\(firstDate) ~ \(lastDate)")- .font(.caption2.monospacedDigit())- .foregroundStyle(.tertiary)- .lineLimit(1)- }- }-- HStack(alignment: .top, spacing: Metrics.squareSpacing) {- ForEach(0..<Metrics.columnCount, id: \.self) { column in- VStack(spacing: Metrics.squareSpacing) {- ForEach(0..<Metrics.rowCount, id: \.self) { row in- let index = column * Metrics.rowCount + row-- if days.indices.contains(index) {- let day = days[index]- UsageHeatmapSquare(- day: day,- percent: Double(day.tokens) / Double(peakTokens),- isHovered: hoveredDay?.id == day.id- ) { location in- hoveredDay = day- hoverLocation = location- } onEnded: {- if hoveredDay?.id == day.id {- hoveredDay = nil- }- }- } else {- Color.clear- .frame(width: Metrics.squareSize, height: Metrics.squareSize)- }- }- }- }- }- }- .frame(maxWidth: .infinity, alignment: .leading)- }-- private var tooltipOffset: CGSize {- CGSize(- width: min(max(hoverLocation.x + 10, 0), max(0, Metrics.totalWidth - Metrics.tooltipWidth)),- height: min(max(hoverLocation.y + 12, 0), max(0, Metrics.height - Metrics.tooltipHeight))- )- }-}--private extension UsageHeatmap {- enum Metrics {- static let coordinateSpaceName = "usageHeatmap"- static let columnCount = 30- static let rowCount = 7- static let squareSize: CGFloat = 12- static let squareSpacing: CGFloat = 3- static let height: CGFloat = 120- static let tooltipWidth: CGFloat = 78- static let tooltipHeight: CGFloat = 38-- static var dayCount: Int { columnCount * rowCount }-- static var totalWidth: CGFloat {- CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing- }- }-}--private struct UsageHeatmapSquare: View {- let day: DailyUsageBucket- let percent: Double- let isHovered: Bool- let onActive: (CGPoint) -> Void- let onEnded: () -> Void-- var body: some View {- GeometryReader { proxy in- RoundedRectangle(cornerRadius: 4, style: .continuous)- .fill(fillColor)- .overlay {- RoundedRectangle(cornerRadius: 4, style: .continuous)- .stroke(borderColor, lineWidth: isHovered ? 1.2 : 0.7)- }- .shadow(color: .blue.opacity(0.22), radius: isHovered ? 5 : 0, y: isHovered ? 2 : 0)- .scaleEffect(isHovered ? 1.08 : 1)- .onContinuousHover { phase in- switch phase {- case .active(let location):- let frame = proxy.frame(in: .named(UsageHeatmap.Metrics.coordinateSpaceName))- onActive(CGPoint(x: frame.minX + location.x, y: frame.minY + location.y))- case .ended:- onEnded()- }- }- }- .frame(width: UsageHeatmap.Metrics.squareSize, height: UsageHeatmap.Metrics.squareSize)- .contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous))- .animation(.snappy(duration: 0.14), value: isHovered)- }-- private var clampedPercent: Double {- min(max(percent, 0), 1)- }-- private var fillColor: Color {- guard day.tokens > 0 else {- return Color.blue.opacity(isHovered ? 0.16 : 0.08)- }-- let intensity = pow(clampedPercent, 0.62)- let opacity = 0.18 + intensity * 0.68- return Color.blue.opacity(isHovered ? min(opacity + 0.10, 1.0) : opacity)- }-- private var borderColor: Color {- if isHovered {- return Color.blue.opacity(0.78)- }-- return Color.blue.opacity(day.tokens > 0 ? 0.18 : 0.10)- }-}--private struct UsageHeatmapTooltip: View {- let day: DailyUsageBucket-- var body: some View {- VStack(alignment: .leading, spacing: 2) {- Text(day.startDate)- .font(.caption2.monospacedDigit())- .foregroundStyle(Color(nsColor: .secondaryLabelColor))-- TokenCountText(tokens: day.tokens)- .foregroundStyle(Color(nsColor: .labelColor))- }- .padding(.horizontal, 7)- .padding(.vertical, 5)- .frame(width: UsageHeatmap.Metrics.tooltipWidth, alignment: .leading)- .liquidGlassSurface(cornerRadius: 7, tint: .blue)- }-}--private struct TokenCountText: View {- let tokens: Int-- var body: some View {- Text(TokenCountFormatter.string(from: tokens))- .font(.caption.monospacedDigit().weight(.semibold))- .lineLimit(1)- .minimumScaleFactor(0.8)- }-}--private enum TokenCountFormatter {- static func string(from tokens: Int) -> String {- if tokens >= 1_000_000_000 {- return decimal(Double(tokens) / 1_000_000_000) + "B"- }-- return decimal(Double(tokens) / 1_000_000) + "M"- }- private static func decimal(_ value: Double) -> String {- let rounded = value >= 0.1 ? (value * 10).rounded() / 10 : (value * 100).rounded() / 100- return formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)- }-- private static let formatter: NumberFormatter = {- let formatter = NumberFormatter()- formatter.numberStyle = .decimal- formatter.locale = Locale(identifier: "en_US_POSIX")- formatter.minimumFractionDigits = 0- formatter.maximumFractionDigits = 2- return formatter- }()-}diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/RateLimitsViewModel.swiftindex ea866d1..b67ad39 100644--- a/CodexBar/RateLimitsViewModel.swift+++ b/CodexBar/RateLimitsViewModel.swift@@ -13,55 +13,58 @@ final class RateLimitsViewModel: ObservableObject {@Published private(set) var snapshot: CodexQuotaSnapshot?@Published private(set) var isRefreshing = false@Published private(set) var lastError: CodexRateLimitError?-+// UI 状态统一从 lastError 派生, 保证单一真相来源var errorMessage: String? { lastError?.errorDescription }var requiresLogin: Bool { lastError?.requiresLogin ?? false }var hasError: Bool { lastError != nil }-+private static let refreshInterval: TimeInterval = 60-+private let service: CodexRateLimitServiceprivate var autoRefreshTask: Task<Void, Never>?-+init(service: CodexRateLimitService = CodexRateLimitService()) {self.service = service}-+deinit {autoRefreshTask?.cancel()}-+func refreshIfNeeded() {guard Date().timeIntervalSince(snapshot?.generatedAt ?? .distantPast) > Self.refreshInterval else {return}-+refresh()}-+func startAutoRefresh() {guard autoRefreshTask == nil else {return}-+autoRefreshTask = Task { [weak self] inself?.refreshIfNeeded()-+while !Task.isCancelled {- try? await Task.sleep(nanoseconds: UInt64(Self.refreshInterval * 1_000_000_000))+ if (try? await Task.sleep(nanoseconds: UInt64(Self.refreshInterval * 1_000_000_000))) == nil {+ break+ }+self?.refresh()}}}-+func refresh() {guard !isRefreshing else {return}-+isRefreshing = true-+Task {do {let snapshot = try await service.fetchRateLimits()@@ -70,7 +73,7 @@ final class RateLimitsViewModel: ObservableObject {} catch {self.lastError = (error as? CodexRateLimitError) ?? .serverError(error.localizedDescription)}-+self.isRefreshing = false}}diff --git a/CodexBar/SettingsWindowController.swift b/CodexBar/SettingsWindowController.swiftnew file mode 100644index 0000000..e5cd89a--- /dev/null+++ b/CodexBar/SettingsWindowController.swift@@ -0,0 +1,87 @@+//+// SettingsWindowController.swift+// CodexBar+//+// Created by Bob on 2026-06-14.+//++import AppKit+import SwiftUI++@MainActor+final class SettingsWindowController {+ private let appUpdater: AppUpdater+ private let screenProvider: () -> NSScreen?+ private var window: NSWindow?++ init(appUpdater: AppUpdater, screenProvider: @escaping () -> NSScreen?) {+ self.appUpdater = appUpdater+ self.screenProvider = screenProvider+ }++ func open() {+ if window == nil {+ window = makeWindow()+ }++ guard let window else {+ return+ }++ NSApplication.shared.activate()+ prepareForDisplay(window)+ window.makeKeyAndOrderFront(nil)+ }++ private func makeWindow() -> NSWindow {+ let hostingController = NSHostingController(+ rootView: AppSettingsView()+ .environmentObject(appUpdater)+ )+ hostingController.sizingOptions = [.preferredContentSize]++ let window = NSWindow(contentViewController: hostingController)+ window.title = "CodexBar 设置"+ window.styleMask = [.titled, .closable, .miniaturizable]+ window.isReleasedWhenClosed = false+ window.contentMinSize = Metrics.minimumContentSize+ return window+ }++ private func prepareForDisplay(_ window: NSWindow) {+ 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)+ )+ )+ }++ center(window)+ }++ private func center(_ window: NSWindow) {+ guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {+ window.center()+ return+ }++ let visibleFrame = screen.visibleFrame+ let windowFrame = window.frame+ let origin = NSPoint(+ x: visibleFrame.midX - windowFrame.width / 2,+ y: visibleFrame.midY - windowFrame.height / 2+ )++ window.setFrameOrigin(origin)+ }++ private enum Metrics {+ static let minimumContentSize = NSSize(width: 420, height: 240)+ }+}diff --git a/CodexBar/StatusItemController.swift b/CodexBar/StatusItemController.swiftindex d11adbe..788bcd9 100644--- a/CodexBar/StatusItemController.swift+++ b/CodexBar/StatusItemController.swift@@ -13,15 +13,15 @@ import SwiftUIfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let viewModel = RateLimitsViewModel()let appUpdater = AppUpdater()-+private var statusItemController: StatusItemController?-+func applicationDidFinishLaunching(_ notification: Notification) {let controller = StatusItemController(viewModel: viewModel, appUpdater: appUpdater)controller.install()statusItemController = controller}-+func applicationWillTerminate(_ notification: Notification) {statusItemController?.uninstall()}@@ -33,8 +33,10 @@ private final class StatusItemController: NSObject {private let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()-- private var settingsWindow: NSWindow?++ private lazy var settingsWindowController = SettingsWindowController(appUpdater: appUpdater) { [weak self] in+ self?.statusItem.button?.window?.screen+ }private var deferredRefreshTask: Task<Void, Never>?private var popoverOpenTask: Task<Void, Never>?private var popoverCloseTask: Task<Void, Never>?@@ -47,13 +49,13 @@ private final class StatusItemController: NSObject {private static let normalImage = NSImage(systemSymbolName: "person.fill.checkmark", accessibilityDescription: nil)private static let errorImage = NSImage(systemSymbolName: "person.fill.xmark", accessibilityDescription: nil)-+init(viewModel: RateLimitsViewModel, appUpdater: AppUpdater) {self.viewModel = viewModelself.appUpdater = appUpdatersuper.init()}-+func install() {configureStatusButton()configurePopover()@@ -61,38 +63,38 @@ private final class StatusItemController: NSObject {updateStatusImage()viewModel.startAutoRefresh()}-+func uninstall() {closePopover(animated: false)cancellables.removeAll()NSStatusBar.system.removeStatusItem(statusItem)}-+private func configureStatusButton() {guard let button = statusItem.button else {return}-+button.target = selfbutton.action = #selector(statusItemClicked(_:))button.imagePosition = .imageOnlybutton.toolTip = "CodexBar"button.sendAction(on: [.leftMouseUp, .rightMouseUp])}-+private func configurePopover() {let rootView = RateLimitsMenuView(viewModel: viewModel).environmentObject(appUpdater).frame(width: RateLimitsMenuView.menuWidth)-+let hostingController = NSHostingController(rootView: rootView)hostingController.sizingOptions = [.preferredContentSize]-+popover.behavior = .applicationDefinedpopover.animates = falsepopover.contentViewController = hostingController}-+private func observeViewModel() {viewModel.objectWillChange.sink { [weak self] _ in@@ -102,7 +104,7 @@ private final class StatusItemController: NSObject {}.store(in: &cancellables)}-+private func updateStatusImage() {let hasError = viewModel.hasErrorguard hasError != lastHasError else {@@ -112,20 +114,20 @@ private final class StatusItemController: NSObject {lastHasError = hasErrorstatusItem.button?.image = hasError ? Self.errorImage : Self.normalImage}-+@objc private func statusItemClicked(_ sender: NSStatusBarButton) {guard let event = NSApplication.shared.currentEvent else {togglePopover(relativeTo: sender)return}-+if event.type == .rightMouseUp || event.modifierFlags.contains(.control) {showContextMenu(relativeTo: sender)} else {togglePopover(relativeTo: sender)}}-+private func togglePopover(relativeTo button: NSStatusBarButton) {switch popoverState {case .hidden:@@ -137,7 +139,7 @@ private final class StatusItemController: NSObject {openPopover(relativeTo: button)}}-+private func cancelPopoverTasks() {deferredRefreshTask?.cancel()deferredRefreshTask = nil@@ -153,32 +155,32 @@ private final class StatusItemController: NSObject {popoverAnimationGeneration += 1let generation = popoverAnimationGenerationpopoverState = .opening-+preparePopoverForFadeIn()popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)stabilizePopoverChromeAppearance()installPopoverDismissMonitors()fadePopover(to: 1, duration: Metrics.fadeInDuration)-+popoverOpenTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(Int(Metrics.fadeInDuration * 1000)))guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {return}-+self.resetPopoverAlpha()self.popoverState = .shownself.popoverOpenTask = nil}-+scheduleDeferredRefresh()}-+private func showContextMenu(relativeTo button: NSStatusBarButton) {closePopover(animated: false)-+let menu = NSMenu()-+let settingsItem = NSMenuItem(title: "设置",action: #selector(openSettings),@@ -187,9 +189,9 @@ private final class StatusItemController: NSObject {settingsItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)settingsItem.target = selfmenu.addItem(settingsItem)-+menu.addItem(.separator())-+let quitItem = NSMenuItem(title: "退出",action: #selector(quit),@@ -198,37 +200,27 @@ private final class StatusItemController: NSObject {quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil)quitItem.target = selfmenu.addItem(quitItem)-+menu.popUp(positioning: nil,at: NSPoint(x: 0, y: button.bounds.minY - 4),in: button)}-+@objc private func openSettings() {- if settingsWindow == nil {- settingsWindow = makeSettingsWindow()- }-- guard let settingsWindow else {- return- }-- NSApplication.shared.activate()- prepareSettingsWindowForDisplay(settingsWindow)- settingsWindow.makeKeyAndOrderFront(nil)+ settingsWindowController.open()}-+@objc private func quit() {NSApplication.shared.terminate(nil)}-+private func closePopover(animated: Bool = true) {if popoverState == .closing && animated {return}-+cancelPopoverTasks()removePopoverDismissMonitors()@@ -237,16 +229,16 @@ private final class StatusItemController: NSObject {popoverState = .hiddenreturn}-+guard animated, let contentView = popover.contentViewController?.view else {finishPopoverClose()return}-+popoverAnimationGeneration += 1let generation = popoverAnimationGenerationpopoverState = .closing-+let popoverWindow = contentView.windowfadePopover(to: 0, duration: Metrics.fadeOutDuration)popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in@@ -254,7 +246,7 @@ private final class StatusItemController: NSObject {guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {return}-+self.popover.performClose(nil)contentView?.alphaValue = 1popoverWindow?.alphaValue = 1@@ -262,125 +254,125 @@ private final class StatusItemController: NSObject {self.popoverCloseTask = nil}}-+private func finishPopoverClose() {cancelPopoverTasks()popoverAnimationGeneration += 1removePopoverDismissMonitors()-+if popover.isShown {popover.performClose(nil)}-+resetPopoverAlpha()popoverState = .hidden}-+private func installPopoverDismissMonitors() {removePopoverDismissMonitors()-+localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event inself?.closePopoverIfNeeded(for: event)self?.restabilizePopoverChromeAfterEvent()return event}-+globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] _ inself?.closePopover()}}-+private func removePopoverDismissMonitors() {if let localMouseEventMonitor {NSEvent.removeMonitor(localMouseEventMonitor)self.localMouseEventMonitor = nil}-+if let globalMouseEventMonitor {NSEvent.removeMonitor(globalMouseEventMonitor)self.globalMouseEventMonitor = nil}}-+private func restabilizePopoverChromeAfterEvent() {Task { @MainActor [weak self] inawait Task.yield()guard let self, self.popover.isShown else {return}-+self.stabilizePopoverChromeAppearance()}}-+private func stabilizePopoverChromeAppearance() {guard let rootView = popover.contentViewController?.view.window?.contentView else {return}-+stabilizeVisualEffectViews(in: rootView)}-+private func stabilizeVisualEffectViews(in view: NSView) {if let visualEffectView = view as? NSVisualEffectView {visualEffectView.state = .inactivevisualEffectView.isEmphasized = false}-+for subview in view.subviews {stabilizeVisualEffectViews(in: subview)}}-+private func closePopoverIfNeeded(for event: NSEvent) {guard popover.isShown else {return}-+if isEventInsidePopover(event) || isEventInsideStatusButton(event) {return}-+closePopover()}-+private func isEventInsidePopover(_ event: NSEvent) -> Bool {guard let contentView = popover.contentViewController?.view,event.window == contentView.window else {return false}-+let point = contentView.convert(event.locationInWindow, from: nil)return contentView.bounds.contains(point)}-+private func isEventInsideStatusButton(_ event: NSEvent) -> Bool {guard let button = statusItem.button,let buttonWindow = button.window else {return false}-+let eventScreenPoint = event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocationlet buttonRectInWindow = button.convert(button.bounds, to: nil)let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)return buttonScreenRect.contains(eventScreenPoint)}-+private func preparePopoverForFadeIn() {popover.contentViewController?.view.alphaValue = 0popover.contentViewController?.view.window?.alphaValue = 0}-+private func resetPopoverAlpha() {popover.contentViewController?.view.alphaValue = 1popover.contentViewController?.view.window?.alphaValue = 1}-+private func fadePopover(to alpha: CGFloat, duration: TimeInterval) {guard let contentView = popover.contentViewController?.view else {return}-+let popoverWindow = contentView.window// 淡入前窗口可能刚由 popover.show 懒创建,先把窗口 alpha 归零再动画if alpha == 1 {@@ -394,7 +386,7 @@ private final class StatusItemController: NSObject {contentView.animator().alphaValue = alpha}}-+private func scheduleDeferredRefresh() {deferredRefreshTask?.cancel()deferredRefreshTask = Task { @MainActor [weak self] in@@ -402,53 +394,11 @@ private final class StatusItemController: NSObject {guard let self, !Task.isCancelled, self.popover.isShown else {return}-+self.viewModel.refreshIfNeeded()}}-- private func makeSettingsWindow() -> NSWindow {- let hostingController = NSHostingController(- rootView: AppSettingsView()- .environmentObject(appUpdater)- )- hostingController.sizingOptions = [.preferredContentSize]-- let window = NSWindow(contentViewController: hostingController)- window.title = "CodexBar 设置"- window.styleMask = [.titled, .closable, .miniaturizable]- window.isReleasedWhenClosed = false- return window- }-- private func prepareSettingsWindowForDisplay(_ window: NSWindow) {- window.contentViewController?.view.layoutSubtreeIfNeeded()-- if let fittingSize = window.contentViewController?.view.fittingSize,- fittingSize.width > 0,- fittingSize.height > 0 {- window.setContentSize(fittingSize)- }-- centerSettingsWindow(window)- }-- private func centerSettingsWindow(_ window: NSWindow) {- guard let screen = statusItem.button?.window?.screen ?? window.screen ?? NSScreen.main else {- window.center()- return- }-- let visibleFrame = screen.visibleFrame- let windowFrame = window.frame- let origin = NSPoint(- x: visibleFrame.midX - windowFrame.width / 2,- y: visibleFrame.midY - windowFrame.height / 2- )-- window.setFrameOrigin(origin)- }-+private enum Metrics {static let dismissEventMask: NSEvent.EventTypeMask = [.leftMouseDown,@@ -458,7 +408,7 @@ private final class StatusItemController: NSObject {static let fadeInDuration: TimeInterval = 0.24static let fadeOutDuration: TimeInterval = 0.18}-+private enum PopoverState {case hiddencase openingdiff --git a/CodexBar/TokenCountText.swift b/CodexBar/TokenCountText.swiftnew file mode 100644index 0000000..5bfb73d--- /dev/null+++ b/CodexBar/TokenCountText.swift@@ -0,0 +1,46 @@+//+// TokenCountText.swift+// CodexBar+//+// Created by Bob on 2026-06-14.+//++import SwiftUI++struct TokenCountText: View {+ let tokens: Int++ var body: some View {+ Text(TokenCountFormatter.string(from: tokens))+ .font(.caption.monospacedDigit().weight(.semibold))+ .lineLimit(1)+ .minimumScaleFactor(0.8)+ }+}++private enum TokenCountFormatter {+ static func string(from tokens: Int) -> String {+ switch tokens {+ case 1_000_000_000...:+ return decimal(Double(tokens) / 1_000_000_000) + "B"+ case 1_000_000...:+ return decimal(Double(tokens) / 1_000_000) + "M"+ default:+ return decimal(Double(tokens) / 1_000) + "K"+ }+ }++ private static func decimal(_ value: Double) -> String {+ let rounded = value >= 0.1 ? (value * 10).rounded() / 10 : (value * 100).rounded() / 100+ return formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)+ }++ private static let formatter: NumberFormatter = {+ let formatter = NumberFormatter()+ formatter.numberStyle = .decimal+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.minimumFractionDigits = 0+ formatter.maximumFractionDigits = 2+ return formatter+ }()+}diff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/UsageHeatmap.swiftnew file mode 100644index 0000000..e8b4ec7--- /dev/null+++ b/CodexBar/UsageHeatmap.swift@@ -0,0 +1,257 @@+//+// UsageHeatmap.swift+// CodexBar+//+// Created by Bob on 2026-06-14.+//++import SwiftUI++struct UsageSummaryView: View {+ let usage: CodexUsageSnapshot+ private let days: [DailyUsageBucket]+ @State private var hoveredDay: DailyUsageBucket?++ init(usage: CodexUsageSnapshot) {+ self.usage = usage+ self.days = usage.recentDays(count: UsageHeatmap.Metrics.dayCount, endingDaysAgo: 1)+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ HStack(alignment: .firstTextBaseline) {+ metric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .leading)+ Spacer()+ metric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .trailing)+ }++ UsageHeatmap(days: days, hoveredDay: $hoveredDay)+ }+ .padding(10)+ .liquidGlassSurface(cornerRadius: 8, tint: .blue)+ .onAppear {+ hoveredDay = nil+ }+ }++ private func metric(label: String, value: Int, alignment: Alignment) -> some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(label)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: alignment)++ TokenCountText(tokens: value)+ .frame(maxWidth: .infinity, alignment: alignment)+ }+ .frame(width: 96)+ }+}++struct UsageHeatmap: View {+ let days: [DailyUsageBucket]+ @Binding var hoveredDay: DailyUsageBucket?+ @State private var hoveredSquareFrame: CGRect = .zero+ // hover 期间 body 频繁重算, 峰值只在构建时求一次+ private let peakTokens: Int++ init(days: [DailyUsageBucket], hoveredDay: Binding<DailyUsageBucket?>) {+ self.days = days+ self._hoveredDay = hoveredDay+ self.peakTokens = max(days.lazy.map(\.tokens).max() ?? 0, 1)+ }++ var body: some View {+ ZStack(alignment: .topLeading) {+ heatmapGrid++ if let hoveredDay {+ UsageHeatmapTooltip(day: hoveredDay)+ .id(hoveredDay.id)+ .allowsHitTesting(false)+ .offset(tooltipOffset)+ .zIndex(1)+ .transition(.opacity)+ }+ }+ .frame(height: Metrics.height)+ .coordinateSpace(name: Metrics.coordinateSpaceName)+ }++ private var heatmapGrid: some View {+ VStack(alignment: .leading, spacing: 6) {+ HStack(alignment: .firstTextBaseline) {+ Text("近 \(days.count) 天")+ .font(.caption2.weight(.medium))+ .foregroundStyle(.secondary)++ Spacer()++ if let firstDate = days.first?.startDate, let lastDate = days.last?.startDate {+ Text("\(firstDate) ~ \(lastDate)")+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.tertiary)+ .lineLimit(1)+ }+ }++ HStack(alignment: .top, spacing: Metrics.squareSpacing) {+ ForEach(0..<Metrics.columnCount, id: \.self) { column in+ VStack(spacing: Metrics.squareSpacing) {+ ForEach(0..<Metrics.rowCount, id: \.self) { row in+ let index = column * Metrics.rowCount + row++ if days.indices.contains(index) {+ let day = days[index]+ UsageHeatmapSquare(+ day: day,+ percent: Double(day.tokens) / Double(peakTokens),+ isHovered: hoveredDay?.id == day.id+ ) { frame in+ if hoveredDay?.id != day.id {+ withAnimation(.easeInOut(duration: Metrics.tooltipFadeDuration)) {+ hoveredDay = day+ hoveredSquareFrame = frame+ }+ } else if hoveredSquareFrame != frame {+ hoveredSquareFrame = frame+ }+ } onEnded: {+ if hoveredDay?.id == day.id {+ withAnimation(.easeInOut(duration: Metrics.tooltipFadeDuration)) {+ hoveredDay = nil+ }+ }+ }+ } else {+ Color.clear+ .frame(width: Metrics.squareSize, height: Metrics.squareSize)+ }+ }+ }+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }++ private var tooltipOffset: CGSize {+ let aboveY = hoveredSquareFrame.minY - Metrics.tooltipSquareSpacing - Metrics.tooltipHeight+ let tooltipY = aboveY >= 0 ? aboveY : hoveredSquareFrame.maxY + Metrics.tooltipSquareSpacing++ return CGSize(+ width: tooltipX(for: hoveredSquareFrame),+ height: min(max(tooltipY, 0), max(0, Metrics.height - Metrics.tooltipHeight))+ )+ }++ private func tooltipX(for squareFrame: CGRect) -> CGFloat {+ let trailingX = squareFrame.maxX + Metrics.tooltipSquareSpacing+ let leadingX = squareFrame.minX - Metrics.tooltipSquareSpacing - Metrics.tooltipWidth+ let maxX = max(0, Metrics.totalWidth - Metrics.tooltipWidth)++ if leadingX >= 0 {+ return leadingX+ }++ if trailingX + Metrics.tooltipWidth <= Metrics.totalWidth {+ return trailingX+ }++ return min(max(leadingX, 0), maxX)+ }+}++extension UsageHeatmap {+ enum Metrics {+ static let coordinateSpaceName = "usageHeatmap"+ static let columnCount = 30+ static let rowCount = 7+ static let squareSize: CGFloat = 12+ static let squareSpacing: CGFloat = 3+ static let height: CGFloat = 120+ static let tooltipWidth: CGFloat = 78+ static let tooltipHeight: CGFloat = 38+ static let tooltipSquareSpacing: CGFloat = 2+ static let tooltipFadeDuration: TimeInterval = 0.15++ static var dayCount: Int { columnCount * rowCount }++ static var totalWidth: CGFloat {+ CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing+ }+ }+}++private struct UsageHeatmapSquare: View {+ let day: DailyUsageBucket+ let percent: Double+ let isHovered: Bool+ let onActive: (CGRect) -> Void+ let onEnded: () -> Void++ var body: some View {+ GeometryReader { proxy in+ RoundedRectangle(cornerRadius: 4, style: .continuous)+ .fill(fillColor)+ .overlay {+ RoundedRectangle(cornerRadius: 4, style: .continuous)+ .stroke(borderColor, lineWidth: isHovered ? 1.2 : 0.7)+ }+ .shadow(color: .blue.opacity(0.22), radius: isHovered ? 5 : 0, y: isHovered ? 2 : 0)+ .scaleEffect(isHovered ? 1.08 : 1)+ .onContinuousHover { phase in+ switch phase {+ case .active:+ onActive(proxy.frame(in: .named(UsageHeatmap.Metrics.coordinateSpaceName)))+ case .ended:+ onEnded()+ }+ }+ }+ .frame(width: UsageHeatmap.Metrics.squareSize, height: UsageHeatmap.Metrics.squareSize)+ .contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous))+ .animation(.snappy(duration: 0.14), value: isHovered)+ }++ private var clampedPercent: Double {+ min(max(percent, 0), 1)+ }++ private var fillColor: Color {+ guard day.tokens > 0 else {+ return Color.blue.opacity(isHovered ? 0.16 : 0.08)+ }++ let intensity = pow(clampedPercent, 0.62)+ let opacity = 0.18 + intensity * 0.68+ return Color.blue.opacity(isHovered ? min(opacity + 0.10, 1.0) : opacity)+ }++ private var borderColor: Color {+ if isHovered {+ return Color.blue.opacity(0.78)+ }++ return Color.blue.opacity(day.tokens > 0 ? 0.18 : 0.10)+ }+}++private struct UsageHeatmapTooltip: View {+ let day: DailyUsageBucket++ var body: some View {+ VStack(alignment: .leading, spacing: 2) {+ Text(day.startDate)+ .font(.caption2.monospacedDigit())+ .foregroundStyle(Color(nsColor: .secondaryLabelColor))++ TokenCountText(tokens: day.tokens)+ .foregroundStyle(Color(nsColor: .labelColor))+ }+ .padding(.horizontal, 7)+ .padding(.vertical, 5)+ .frame(width: UsageHeatmap.Metrics.tooltipWidth, alignment: .leading)+ .liquidGlassSurface(cornerRadius: 7, tint: .blue)+ }+}diff --git a/Images/screenshot.png b/Images/screenshot.pngindex c81fff2..b9ffdee 100644Binary files a/Images/screenshot.png and b/Images/screenshot.png differdiff --git a/README.md b/README.mdindex db50ee1..00f0aa0 100644--- a/README.md+++ b/README.md@@ -13,7 +13,7 @@ CodexBar 是一个轻量级 macOS 菜单栏应用。它直接连接本机 Codex- **额度一目了然**: 分段电量条展示各时间窗口 (如 5 小时、7 天) 的剩余额度,附剩余百分比和重置时间- **token 贡献墙**: 30 周的每日 token 用量热力图,鼠标悬停查看单日明细,同时展示累计 token 和单日峰值- **自动刷新**: 每分钟后台刷新一次,弹窗未打开也保持最新;双击账号图标可手动刷新-- **开机自启**: 按住 Option 点击菜单栏图标打开设置区+- **自动更新**: 内置 Sparkle 更新检查,新版本自动更新- **本地优先**: 只与本机 Codex app-server 进程通信,不向任何第三方服务发送账号或额度数据## 安装@@ -27,8 +27,8 @@ CodexBar 是一个轻量级 macOS 菜单栏应用。它直接连接本机 Codex### 运行要求- macOS 15.0 或更高版本-- 已安装 [Codex CLI](https://github.com/openai/codex) (全局 `codex` 命令) 或 Codex.app-- 当前 macOS 用户已在 Codex 中完成登录+- 已安装 [Codex CLI](https://github.com/openai/codex) (全局 `codex` 命令或 `Codex.app`)+- 已在 Codex 中完成登录> 提示: 如果把应用移动到 `/Applications` 后才开启开机自启,建议重新开关一次「开机启动」让 macOS 记录最终路径。@@ -44,5 +44,6 @@ xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/pl## 隐私-CodexBar 只与本机 Codex app-server 进程通信。账号信息和额度数据不会被收集和发送到任何个人和服务-只有更新 App 会产生额外的网络请求仅包含 [appcast](https://codexbar.zabrian.app/appcast.xml) 和 appcast 中对应的 DMG 下载地址+CodexBar 只与本机 Codex app-server 进程通信。账号信息和额度数据不会被收集或发送给任何个人或服务。++只有检查和下载 App 更新时会产生额外网络请求,请求范围仅包含 [appcast](https://codexbar.zabrian.app/appcast.xml) 和 appcast 中对应的 DMG 下载地址。diff --git a/Updates/appcast.xml b/Updates/appcast.xmlindex cac59a6..549bd6b 100644--- a/Updates/appcast.xml+++ b/Updates/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 1.3.3</title>+ <sparkle:version>6</sparkle:version>+ <sparkle:shortVersionString>1.3.3</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes/1.3.3.html</sparkle:releaseNotesLink>+ <pubDate>Sun, 14 Jun 2026 22:10:39 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v1.3.3.dmg" sparkle:edSignature="1auvaT2F0dJ4GOQAN7CpC1cFWBRq+eZGzjj6lIFj0iI4vwMVuUl4QcY9usI9UpfSOPDyJniARYkEXrIJoJZYCQ==" length="1405208" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 1.3.2</title><sparkle:version>5</sparkle:version>