Skip to content

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

feat: 完善 Codex 状态与日志体验

Bobc63607e1e212
diff --git a/.gitignore b/.gitignore
index 87f12c0..1f030a4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -33,3 +33,7 @@ codesign2
# Logs
*.log
+
+# Agent Tools
+.agents/
+.specify/
diff --git a/AGENTS.md b/AGENTS.md
index 0aad579..cf828b5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,81 +1,107 @@
# AGENTS.md
-本文件是 Codex 在本仓库工作的持久指令。根目录范围内均适用;如果子目录未来出现更近的 `AGENTS.md`, 以更近文件为准。内容按 OpenAI Prompt Guidance(GPT-5.5) 的思路组织: 先定义可验证目标、成功标准、工具与上下文策略, 再列出 CodexBar 的代码事实和实现边界。
+本文件是 Codex 在本仓库工作的持久指令。根目录范围内均适用;如果子目录未来出现更近的 `AGENTS.md`, 以更近文件为准。
+
+本文件按 OpenAI GPT-5.5 prompt guidance 的思路组织: 结果优先、约束明确、上下文可追溯、验证轻量但必须执行。不要把它当成逐步脚本机械执行;遇到更直接、安全、可验证的路径时, 选择更高效的做法。
## 目标
-CodexBar 是一个 macOS 菜单栏应用, 用本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。你在本仓库中的目标是交付可验证、贴合现有 SwiftUI/MVVM 架构的修改, 并保护本地认证、隐私、菜单栏体验、Sparkle 更新和发布流程不被无意破坏。
+CodexBar 是一个 macOS 菜单栏应用, 通过本机 Codex app-server 展示当前 Codex 账号、额度、token 用量、Codex CLI/APP 版本和交互日志。你的目标是交付可验证、范围清晰、贴合现有 SwiftUI/AppKit/MVVM 架构的修改, 并保护本地认证、隐私、菜单栏体验、Sparkle 更新和发布流程。
## 成功标准
-- 用户请求已转成明确的结果: 代码、文档、脚本、诊断结论或发布操作。
-- 修改范围只覆盖完成目标所需的文件; 不顺手重构无关模块, 不回滚他人未提交改动。
-- Swift/Xcode 工程修改后运行本文件的构建命令, 结果无 error 和项目代码 warning。
-- 文档、图片或发布元数据的纯修改可以不构建, 但最终回复必须说明未运行构建的原因。
-- 最终回复说明改了什么、如何验证、还剩什么风险或未执行项。
+- 先明确用户要的结果: 代码修改、文档、诊断结论、review、构建验证或发布操作。
+- 修改范围只覆盖完成目标所需文件; 不顺手重构无关模块, 不回滚他人未提交改动。
+- 行为改变必须能用代码事实、工具输出或用户确认支撑。
+- 涉及 Swift/Xcode 工程、资源、build setting、Info.plist、SwiftPM、脚本行为或 UI 行为的改动后运行构建命令。
+- 纯文档改动可以不构建, 但最终说明实际做过的检查。
+- 最终回复简洁说明改了什么、如何验证、剩余风险或未执行项。
## 工作方式
-- 先读局部上下文, 再行动。优先用 `rg` / `rg --files`、当前文件和相邻模块定位事实; 只有依赖缺失时再扩大范围。
-- 多步骤或跨文件任务先给简短计划。计划写清关键文件/系统、验证命令、失败处理和真正会影响实现的开放问题。
-- 简单、低风险、可逆的请求直接执行。删除、发布、推送、生产写入、覆盖用户选择或会明显改变行为但缺少关键决策时, 先取得用户明确同意。
-- 独立的读取和检索可以并行; 有先后依赖、歧义会影响实现、或动作不可逆时必须顺序执行。
-- 工具调用前给一句短说明。长任务中持续同步进度, 但不要把中间状态当最终答复。
-- 遇到失败先做最小可行诊断和一次合理重试。仍无法完成时, 说明阻塞点、已验证事实和下一个最小检查。
-- 回复保持紧凑, 路径、命令、函数、类型和文件名用反引号。中文说明优先, 除非用户要求英文。
-- 修改 prompt、文档或 agent 指令时, 优先保留有效事实和行为边界; 删除或改写会改变执行行为的规则前, 确认它确实与当前目标冲突。
+- 默认中文回复, 除非用户要求英文。
+- 先读局部上下文再行动。优先用 `rg` / `rg --files`、当前文件和相邻模块定位事实。
+- 简单、低风险、可逆的请求直接执行。删除、发布、推送、生产写入、覆盖用户选择或行为不确定时先取得明确同意。
+- 独立读取可以并行; 有依赖、会改变文件、或动作不可逆时顺序执行。
+- 工具调用前用一句话说明意图。长任务中持续同步进度, 不把中间状态当最终结果。
+- 需要外部事实时使用可检索来源; 不猜测当前版本、API、文档或政策。若上下文缺失且无法检索, 问最小问题。
+- 修改 prompt、文档或 agent 指令时, 保留仍然准确的项目事实和边界; 删除会改变执行行为的规则前确认它确实过期或冲突。
+
+## 行动安全
+
+执行高影响动作前做轻量 pre-flight:
+
+- 说明将要做的动作和关键参数。
+- 通过工具执行。
+- post-flight 确认结果和验证。
+
+高影响动作包括: `git push`、tag、release、DMG/appcast 更新、删除文件、改 Xcode build settings、改 Sparkle 配置、改 sandbox/signing、改认证/隐私相关逻辑。
+
+## 验证
-## 验证命令
+Swift/Xcode 相关改动后运行:
-涉及 Swift/Xcode 工程、资源归属、build setting、Info.plist、SwiftPM 依赖或发布脚本行为的改动后运行:
+```bash
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination generic/platform=macOS -derivedDataPath /tmp/CodexBarDerivedData build
+```
+
+要求无 error。当前 Xcode 可能输出 `Metadata extraction skipped. No AppIntents.framework dependency found.` 的 metadata warning, 不作为项目代码 warning 处理。SourceKit 对跨文件类型偶尔误报时, 以 `xcodebuild` 为准。
+
+文档-only 修改至少运行:
```bash
-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+git diff --check
```
-要求无 error 和 warning。当前 Xcode 可能输出 `Metadata extraction skipped. No AppIntents.framework dependency found.` 的 metadata 阶段 warning, 不作为项目代码 warning 处理。SourceKit 对跨文件类型偶尔误报 `Cannot find type ... in scope`, 以 `xcodebuild` 为准。
+提交或发布前再检查:
-工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下源码通常无需修改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。
+```bash
+git status --short
+```
## 项目事实
- 平台: SwiftUI + AppKit + MVVM, 最低 macOS 15.0。
-- 应用形态: `LSUIElement` 纯菜单栏应用, 无 Dock 图标、无应用菜单。
-- 入口: `CodexBarApp` 只声明占位 `Settings { EmptyView() }`; 真实 UI 由 `CodexBarAppDelegate` 和 `StatusItemController` 驱动。
+- 应用形态: `LSUIElement` 菜单栏应用, 无 Dock 图标、无主窗口。
- 外部依赖: Sparkle(SwiftPM)。
-- App Sandbox 必须关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/App 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。
-- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 1.3.6`, `CURRENT_PROJECT_VERSION = 9`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`。
+- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 2.0.0`, `CURRENT_PROJECT_VERSION = 10`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`。
+- App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/APP 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。
+- 工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下 Swift 文件通常无需改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。
- 不要为 macOS 15 以下添加 SF Symbols 或 SwiftUI API fallback。
## 架构地图
-数据流:
+主要数据流:
```text
-CodexRateLimitService(JSON-RPC app-server)
- -> RateLimitsViewModel(@MainActor 状态发布)
- -> StatusItemController(菜单栏图标/Popover 生命周期)
- -> RateLimitsMenuView / AppSettingsView(SwiftUI 展示)
+CodexStatusService(JSON-RPC app-server)
+ -> CodexStatusViewModel(@MainActor 状态发布)
+ -> StatusItemController(菜单栏图标、popover、窗口入口)
+ -> CodexStatusMenuView / AppSettingsView / LogView
```
关键文件职责:
-- `CodexBarApp.swift`: `@main` 入口和 `Bundle.displayVersionLabel`(`v1.2.3`, 缺失回退 `--`)。
-- `StatusItemController.swift`: 创建 `NSStatusItem`、`NSPopover`、右键菜单、外部点击监控、淡入淡出状态机和自动刷新启动。左键切换 popover, 右键或 Control 点击显示「设置 / 退出」。
-- `SettingsWindowController.swift`: 复用单个设置窗口。首次显示或关闭后重开时按 status item 所在屏幕居中; 已可见时只 `deminiaturize`、激活并置顶, 不重新居中或新建窗口。
-- `RateLimitsViewModel.swift`: `@MainActor ObservableObject`, 发布 `snapshot`、`isRefreshing`、`lastError`、`codexConnectionInfo`、`autoRefreshCountdownStartedAt`。错误单一来源是 `lastError: CodexRateLimitError?`; `errorMessage`、`requiresLogin`、`hasError` 都从它派生。
-- `CodexRateLimitService.swift`: 非 UI 服务, 管理 app-server 进程、JSON-RPC、连接复用、认证重试、usage 降级和当前运行中的 Codex 来源/路径/版本。
-- `CodexCLIResolver.swift`: 解析全局 `codex` 与 `/Applications/Codex.app/Contents/Resources/codex`, 并构造 app-server 和版本探测共用的真实用户环境。
-- `CodexCLIVersionService.swift`: 并发探测全局 CLI 与 Codex App 内置 CLI 的 `--version`, 合成磁盘版本、当前运行版本和「已更新至」提示。
-- `RateLimitModels.swift`: wire DTO 保持纯 `Decodable`; 展示排序、兜底和派生文案放在业务快照转换里。
-- `RateLimitsMenuView.swift`: popover 主 UI, 包含登录提示、账号卡片、limit 分节、usage 卡片、更新时间倒计时和错误行。
-- `QuotaRow.swift`: 单个 quota window 行和 `SegmentedQuotaBar`, 条形图展示剩余额度。
+- `CodexBarApp.swift`: `@main` 入口、空 `Settings` scene、`Bundle.displayVersionLabel`。
+- `StatusItemController.swift`: `NSStatusItem`、`NSPopover`、右键菜单、设置/日志窗口入口、外部点击监控、淡入淡出状态机、自动刷新启动。
+- `HostingWindowController.swift`: 设置和日志窗口的懒创建、居中、置顶和跨桌面打开行为。
+- `SettingsWindowController.swift`: 独立设置窗口。
+- `LogWindowController.swift`: 独立日志窗口。
+- `CodexStatusViewModel.swift`: `@MainActor ObservableObject`, 发布 `snapshot`、`isRefreshing`、`loadState`、`codexConnectionInfo`、`autoRefreshCountdownStartedAt`。
+- `CodexStatusService.swift`: app-server 进程、JSON-RPC、连接复用、认证刷新、usage 降级、连接信息。
+- `RequestLog.swift`: 常驻交互日志存储, 记录请求、响应、错误和无响应请求。
+- `LogView.swift`: 日志窗口 UI, 状态标签为「进行」「完成」「错误」「请求」。
+- `CodexCLIResolver.swift`: 解析全局 `codex` 与 `/Applications/Codex.app/Contents/Resources/codex`, 并构造真实用户环境。
+- `CodexCLIVersionService.swift`: 并发探测全局 CLI 与 Codex APP 内置 CLI 的磁盘版本, 合成当前运行版本和「已更新至」提示。
+- `CodexQuotaModels.swift`: wire DTO、业务快照、limit/usage 转换、错误分类。
+- `CodexStatusMenuView.swift`: popover 主 UI, 包含账号卡片、状态卡片、额度、usage、更新时间倒计时和更新提示。
+- `QuotaRow.swift`: 单个 quota window 行和分段额度条。
- `UsageHeatmap.swift` / `TokenCountText.swift`: token 汇总、近 30 周热力图、hover tooltip 和 K/M/B 紧凑数字格式。
- `AppSettingsView.swift` / `LoginItemSettings.swift`: 设置窗口、开机自启、CodexBar 版本、Codex CLI/Codex APP 版本与路径复制。
-- `AppUpdater.swift`: Sparkle 封装, 更新状态文案按设置窗、popover 和可用更新三个表面拆分。
-- `LiquidGlassStyle.swift`: 自绘 Liquid Glass 视觉入口, 提供 `.liquidGlassSurface(...)`、`.liquidGlassCapsule(...)`、`LiquidGlassDivider`、`Animation.codexStatus` 和 `Color.codexLabel` / `Color.codexSecondaryLabel`。
+- `AppUpdater.swift`: Sparkle 封装, 更新状态按设置窗、popover 和可用更新拆分。
+- `LiquidGlassStyle.swift`: 自绘 Liquid Glass 视觉入口。
-## Codex app-server 合约
+## app-server 合约
启动命令统一是:
@@ -86,19 +112,20 @@ codex app-server --listen stdio://
必须通过 `CodexCLIResolver.resolveAppServerCommand()` 解析:
- 优先 PATH 中的全局 `codex`。
-- 如果 PATH 中解析到的路径等价于 `/Applications/Codex.app/Contents/Resources/codex`, 当作内置 Codex APP CLI, 不当作全局 CLI。
+- 如果 PATH 中的 `codex` 等价于 `/Applications/Codex.app/Contents/Resources/codex`, 当作内置 Codex APP CLI, 不当作全局 CLI。
- 全局 CLI 不存在时回退 Codex APP 内置 CLI。
-- 两者都不存在时展示「找不到 Codex CLI 或 Codex APP」。
+- 两者都不存在时返回 `CodexStatusError.executableNotFound`, UI 归为「初始化失败」, 日志记录具体错误。
启动环境由 `CodexCLIResolver.environment` 构造:
-- 保留当前环境, 但 `HOME` 必须用 `getpwuid(getuid())` 得到真实用户 home。
+- 保留当前环境。
+- `HOME` 必须来自 `getpwuid(getuid())` 的真实用户 home。
- 同步设置 `USER`、`LOGNAME`。
- 合并 Homebrew、npm global、`.local`、Volta 和系统路径。
- 确保 `TERM` 有值。
-- 不要改回 Xcode sandbox/container 的 `HOME`, 否则会读不到 `~/.codex/auth.json`。
+- 不要改回 Xcode sandbox/container 的 `HOME`, 否则会读不到真实 `~/.codex/auth.json`。
-首次连接必须先握手再读额度:
+首次连接流程:
```json
{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"<Bundle MARKETING_VERSION 或 1.0.0>"}}}
@@ -106,139 +133,153 @@ codex app-server --listen stdio://
{"method":"account/read","id":2,"params":{"refreshToken":false}}
```
+`initialized` 是无 id 请求, 不等待响应; 日志中记录为空响应请求, 不归为通知类型。
+
同一会话后续读取:
-- `account/rateLimits/read`: 额度数据。认证失败时同会话先调用 `account/read`(`refreshToken: true`) 再重试一次; 仍失败抛 `authenticationRequired`。
-- `account/usage/read`: token 统计。读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。如果返回 method not found / unknown / unsupported / not supported, 将当前连接的 `isUsageReadAvailable` 置为 false, 本连接后续不再请求 usage。其他 usage 错误只隐藏 token 区域, 额度仍正常展示。
+- `account/read` 每轮复用连接时用 `refreshToken: false` 更新账户状态。
+- `account/rateLimits/read` 读取额度。
+- `account/usage/read` 读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。
+- 认证失败时同会话最多调用一次 `account/read`(`refreshToken: true`) 后重试原读取。
+- usage 方法不支持时, 将当前连接的 `isUsageReadAvailable` 置为 false, 本连接后续不再请求 usage。
+- 非认证业务错误不阻断整轮刷新, 详情只进日志。
+- 传输/解析故障归为需要重建连接。
连接细节:
- `requestTimeout` 是 20 秒。
-- `initialize` 响应的 `userAgent` 首个 token 形如 `codex_bar/0.139.0 (...)`; `serverVersion(fromUserAgent:)` 取 `/` 后版本号作为当前运行版本。
-- 每条连接保存 `CodexCLIConnectionInfo(source, executablePath, version, openedAt)`, 设置页用它标记「当前使用」。
-- `JSONLineReader` 按行读取 stdout, 只消费匹配请求 id 的响应; stdout EOF 时标记关闭并唤醒等待中的请求。
-- `PipeDrain` 持续排空 stderr, stderr 不进入用户可见文案; stderr EOF 时停止 readability handler。
+- `connectionMaxAge` 是 1 小时。
+- `SIGPIPE` 已被忽略, 写入断管后应由 `write` 抛错并走重建。
+- 复用连接出现传输故障时只重建重试一次。
+- 全新连接初始化失败直接返回「初始化失败」, 不重复完整握手。
+- `initialize` 响应 `userAgent` 首个 token 形如 `codex_bar/0.139.0 (...)`; 取 `/` 后版本号作为当前运行版本。
+
+## UI 状态与日志
+
+`CodexLoadState` 只有四种:
-## 自动刷新与连接重建
+- `loading`
+- `loaded`
+- `notLoggedIn`
+- `initializationFailed`
-- `RateLimitsViewModel.refreshInterval` 是 60 秒。
-- `startAutoRefresh()` 启动一个 `Task`, 每轮按 `autoRefreshDelay`(距下次刷新的剩余秒数, 下限 1 秒; `autoRefreshCountdownStartedAt` 为空时取 `refreshInterval`)休眠后调用 `refreshIfNeeded()`, 不再每秒空转唤醒。
-- `refreshIfNeeded()` 只看 `autoRefreshCountdownStartedAt` 距当前是否超过 60 秒, 作为动态休眠的兜底判断。
-- `refresh()` 用 `isRefreshing` 合并并发触发; 开始时不要清空 `lastError`。
-- `refresh()` 成功后更新 `snapshot` 并清空 `lastError`; 失败时保留旧 `snapshot`, 写入 `lastError`。
-- 无论成功失败, 刷新结束都更新 `codexConnectionInfo`、重置 `autoRefreshCountdownStartedAt`, 并关闭 `isRefreshing`。
-- popover 显示后延迟调用 `refreshIfNeeded()`; 账号图标双击触发手动 `refresh()`。
+UI 只展示「未登录」和「初始化失败」两类特殊状态; 具体请求错误、启动错误、超时、断连、解析失败都进入日志。
-`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`, 连接状态只在 `DispatchQueue(label: "CodexBar.app-server")` 上读写:
+日志状态标签:
-- 进程已退出 -> 重建。
-- 连接存活超过 `connectionMaxAge`(1 小时) -> 关闭后重建, 覆盖 Codex 升级或服务端状态漂移。
-- 复用连接上的非登录类请求失败 -> 丢弃连接, 重建一次再试。
-- 全新连接上的失败 -> 直接抛出, 避免故障时重复完整握手。
-- 登录类错误(`requiresLogin`) -> 丢弃连接但不立即重试; 下次轮询重新启动进程读取最新登录状态。
+- `.pending` ->「进行」
+- `.response` ->「完成」
+- `.failure` ->「错误」
+- `.emptyResponse` ->「请求」
-## 数据模型规则
+日志规则:
+
+- 带 id 的 JSON-RPC 请求先记录为进行, 响应或错误到达后回填到同一条。
+- `initialized` 这类无 id 请求记录为空响应。
+- 日志容量上限 500 条, 单条详情上限 4000 字符。
+- 合法 JSON 通过 `JSONSerialization` 重新序列化, 使用 `.sortedKeys` 和 `.withoutEscapingSlashes`; 非 JSON 错误消息保持原样。
+- 不要把子进程 stderr 直接展示给用户。
+
+## 数据模型
`CodexQuotaSnapshot`:
-- 必须有 `AccountReadResponse.account`, 否则抛 `notLoggedIn`。
-- 优先读取 `rateLimitsByLimitId` 支持多 limit; 为空则回退顶层 `rateLimits`。
+- 必须有 `AccountReadResponse.account`, 否则视为未登录。
+- `rateLimitsResponse` 和 `usageResponse` 都可以为空; 账户有效时仍生成快照, UI 展示「暂无数据」。
+- 优先读取 `rateLimitsByLimitId`; 为空时回退顶层 `rateLimits`。
- 顶层 `rateLimits.limitId` 指向的主 limit 置顶, 缺省 `"codex"`。
- 其余 limit 按 `limitName ?? limitId` 做 localized standard 排序, 再按 `limitId` 稳定排序。
-- 每个 limit 的 `primary` / `secondary` 合成 `[QuotaWindow]`; 没有窗口的 limit 被过滤, 全部为空才抛 `missingRateLimitWindow`。
+- `primary` / `secondary` 合成 `[QuotaWindow]`; 没有窗口的 limit 被过滤。
- `QuotaWindow.remainingPercent = clamp(100 - usedPercent, 0...100)`; 无 `usedPercent` 视为无数据。
-- `windowDurationMins` 标签: 整天为「N 天」, 整小时为「N 小时」, 否则「N 分钟」, 缺失或非正数为「额度」。
+- `windowDurationMins` 标签: 整天「N 天」, 整小时「N 小时」, 否则「N 分钟」, 缺失或非正数为「额度」。
`CodexUsageSnapshot`:
-- `recentWeekGrid(columnCount:endingDaysAgo:today:)` 基于本地当天零点生成按周对齐的日期网格。
-- UI 使用 `UsageHeatmap.Metrics.columnCount = 30` 且 `endingDaysAgo = 1`, 默认不包含今天。
-- 最右列锚定最后一个可见日期所在的周日开头周, 避免今天是周日时出现整列空白。
-- 返回值中的 `nil` 表示今天、未来日期或不可生成日期; 热力图不绘制方块也不参与峰值计算。
-- 颜色按当前可见日期区间内峰值缩放。
+- `recentWeekGrid(columnCount:endingDaysAgo:today:)` 基于本地当天零点生成按周排列的日期网格, 每列从周日开始。
+- UI 使用 30 列、7 行, 默认 `endingDaysAgo = 1`, 不包含今天。
+- `nil` 表示未来日期或不可生成日期; 热力图不绘制方块也不参与峰值计算。
## 并发与隔离
工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; 未显式标注的类型会推断为 MainActor 隔离。
-- UI 层保持 `@MainActor` 或主线程使用: `CodexBarAppDelegate`、`StatusItemController`、`SettingsWindowController`、`RateLimitsViewModel`、`AppUpdater`、`LoginItemSettings`、`CodexCLIVersionViewModel`。
+- UI 层保持 `@MainActor`: app delegate、status item controller、window controllers、view models、settings/updater。
- 服务层对外暴露 async API, 内部用串行 queue 管理 `Process`、`Pipe` 和连接状态。
-- 非 UI 类型、DTO、模型、服务辅助类型和部分静态工具需要显式 `nonisolated`, 避免 `Call to main actor-isolated initializer in a synchronous nonisolated context`。
-- `CodexRateLimitService` 使用 `CodexBar.app-server` 队列。
+- 非 UI 类型、DTO、模型、服务辅助类型和静态工具需要显式 `nonisolated`, 避免 main actor 隔离泄漏到同步服务代码。
+- `CodexStatusService` 使用 `CodexBar.app-server` 队列。
- `CodexCLIVersionService` 使用 `CodexBar.codex-version` 队列, 全局和内置版本探测先并发启动再收集。
+- `RequestLogStore` 可从后台队列写入, storage 用锁保护, SwiftUI 通知切回主线程发送。
## UI 约束
菜单栏:
- 正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`。
-- `StatusItemController.updateStatusImage(hasError:)` 只随 `lastError` 的有无变化设置图标。
- 菜单栏不展示额度数字; 详情只在 popover 中展示。
-- App 图标保持白底黑色 `timelapse`。
+- 左键切换 popover; 右键或 Control 点击显示「设置 / 日志 / 退出」。
Popover:
-- `RateLimitsMenuView.menuWidth` 由热力图总宽度和 padding 推导; 修改热力图尺寸时同步检查弹窗宽度。
+- `CodexStatusMenuView.menuWidth` 由热力图宽度和 padding 推导; 改热力图尺寸时同步检查弹窗宽度。
- 外层和分区使用 `.liquidGlassSurface(...)`; 分隔线使用 `LiquidGlassDivider`; 小徽章可用 `.liquidGlassCapsule(...)`。
-- `LiquidGlassStyle.swift` 是自绘玻璃效果, 不是 macOS 26 原生 `.glassEffect`。没有明确设计要求时不要切换。
-- 账号行 plan 是右侧加粗纯文字, 不加胶囊底色或额外 padding。`planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。
-- 邮箱双击可模糊/取消模糊; 账号图标双击手动刷新。
-- limit 分节标题取 `limitName` 回退 `limitId`, 首字母大写; 节之间使用 `LiquidGlassDivider`。
-- 额度条展示剩余百分比, 颜色按 20% 一档: 0-19 红色, 20-39 橙色, 40-59 黄色, 60-79 薄荷色, 80-100 绿色。
-- 无 quota 数据时显示 `--` / `暂无数据`, 并用占位色。
-- 重置时间格式 `MM-dd HH:mm`。
-- 更新时间行显示顺时针自动刷新倒计时圆环、「数据更新时间」和 `HH:mm:ss`; 时间文本使用 `.contentTransition(.numericText())` 和 `Color.codexSecondaryLabel`, 不展示应用版本号。
-- 倒计时圆环(`AutoRefreshCountdownCircle`)用 `Circle().trim` 按秒离散跳格, 不做连续动画: `Shape.trim` 的长连续动画是逐帧 CPU 重绘, 比每秒采样更耗 CPU, 不要改成连续动画。每秒采样由 `AutoRefreshCountdownTimeline` 的 `TimelineView` 驱动, 且只在 popover 可见(`PopoverVisibilityState.isVisible`, 由 `StatusItemController` 在 popover show/close 时维护)时启用; 隐藏时静态渲染一次。仅 `startedAt` 变化(刷新重置)且可见时播放 0.2 秒恢复动画, 普通 tick 直接跳变。
+- `LiquidGlassStyle.swift` 是自绘玻璃效果, 不是 macOS 原生 `.glassEffect`; 没有明确设计要求时不要切换。
+- 账号图标双击触发刷新。邮箱文本双击切换模糊。
+- 计划名是右侧加粗纯文字; `planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。
+- 额度条展示剩余百分比, 颜色按 20% 一档: 红、橙、黄、薄荷、绿。
+- 无 quota 数据时显示 `--` / `暂无数据`, 并使用占位色。
+- 重置时间格式是 `MM-dd HH:mm`。
+- 更新时间行显示倒计时圆环、「数据更新时间」和 `HH:mm:ss`。
+- 倒计时只在 popover 可见时用 `TimelineView` 每秒 tick; 普通 tick 不做连续动画, 仅刷新起点变化时播放恢复动画。
- token 区域显示「单日峰值」和「全时累计」; `TokenCountText` 对 1K 以下显示完整整数, 1K 起显示 K/M/B。
-- 热力图是近 30 周、30 列 x 7 行、周日到周六排列、默认不包含今天; hover tooltip 显示日期和单日 token。
-
-错误展示:
-
-- 登录类错误(`requiresLogin`)时, popover 顶部显示橙色「Codex 未登录」。
-- 登录类错误会让旧快照 `opacity(0.4)` 置灰保留, 并抑制红色错误行。
-- 其他错误显示红色小字 `errorDescription`, 旧快照保持全亮度。
-- 旧额度快照永远不因失败而清空。
-- app-server 相关用户可见错误通过 `CodexRateLimitError.errorDescription` 生成; 不要把子进程 stderr 或原始日志拼进 UI。
+- 热力图是近 30 周、30 列 x 7 行、周日到周六排列、默认不包含今天。
设置窗口:
-- 通过菜单栏图标右键或 Control 点击菜单的「设置」打开独立 `AppSettingsView` 窗口。
+- 通过右键菜单「设置」打开独立 `AppSettingsView` 窗口。
- 不要恢复为 Option 点击或 popover 内设置区。
-- 设置页包含「CodexBar 版本」和「Codex 版本」两个版本区域。
+- 设置页包含「CodexBar 版本」和「Codex 版本」区域。
- `Codex CLI` 行图标用 `terminal`; `Codex APP` 行图标用 `app.badge`。
-- Codex CLI/Codex APP 子行相对标题缩进, 当前运行来源显示「当前使用」徽章。
-- 当前行优先展示 app-server 握手自报运行版本; 非当前行展示磁盘安装版本。
-- 如果当前运行版本与磁盘安装版本不同, 显示「已更新至 <version>」。
+- 当前运行来源显示「当前使用」。
+- 当前行优先展示 app-server 握手自报版本; 非当前行展示磁盘安装版本。
+- 当前运行版本与磁盘安装版本不同时, 显示「已更新至 <version>」。
- 路径点击复制到剪贴板, 对应来源显示「已复制」1.5 秒; 保留路径文本布局宽度避免跳动。
-- 设置页版本状态、Codex 版本值、复制提示、popover 更新提示和错误提示使用 `Animation.codexStatus` 做淡入淡出。
-## Sparkle 更新
+日志窗口:
+
+- 通过右键菜单「日志」打开。
+- 日志窗口应持续显示全局 `RequestLogStore.shared` 中的记录, 不因窗口关闭丢失。
+- 详情文本必须可选择, 长内容由存储层截断。
-`AppUpdater` 是 `@MainActor ObservableObject`。
+## Sparkle 更新
-- 初始化时先校验 `Info.plist` 的 `SUFeedURL`(http/https) 和 `SUPublicEDKey`(非空)。
+- `AppUpdater` 是 `@MainActor ObservableObject`。
+- 初始化时先校验 `SUFeedURL`(http/https) 和 `SUPublicEDKey`(非空)。
- 任一缺失时不创建 `SPUStandardUpdaterController`, 更新操作显示「未配置更新资源」。
-- `canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性; 设置窗「自动检查更新」开关据此禁用。
-- `settingsStatusMessage`: 设置窗版本行状态, 默认 3 秒后由可取消 `Task` 清空; `autoDismissDelay: nil` 时常驻。
-- `panelUpdateMessage`: popover 底栏被动提示, 双击可触发 `startUpdate()`。
-- `availableUpdateMessage`: 发现新版的语义状态, 驱动设置窗版本行和「立即更新」按钮。
-- `checkForUpdates()` 是设置窗手动检查, 设置 `isManualCheckInProgress`。
-- 如果已经有 `availableUpdateMessage`, 手动检查只把该消息常驻显示到设置窗。
-- `startUpdate()` 激活应用并调用 Sparkle 安装面板。
-- 委托回调按 `isManualCheckInProgress` 路由: 手动结果进 `settingsStatusMessage`, 自动发现新版进 `panelUpdateMessage`。
-- `Info.plist` 当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`, `SUScheduledCheckInterval = 3600`。
+- `canConfigureAutomaticChecks` 是 `updaterController != nil`。
+- `settingsStatusMessage` 用于设置窗版本行, 默认 3 秒后清空。
+- `panelUpdateMessage` 用于 popover 底栏被动提示, 双击触发 `startUpdate()`。
+- `availableUpdateMessage` 驱动设置窗版本行和「立即更新」按钮。
+- 手动检查结果进 `settingsStatusMessage`; 自动发现新版进 `panelUpdateMessage`。
+- 当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`, `SUScheduledCheckInterval = 3600`。
## 认证、隐私与沙盒
-- CodexBar 只与本机 Codex app-server 进程通信; 账号、额度和 token 使用量不发往第三方服务。
+- CodexBar 只与本机 Codex app-server 通信; 账号、额度和 token 使用量不发往第三方服务。
- 除 Sparkle appcast/DMG 下载外, 应用自身不做网络请求。
-- App Sandbox 必须保持关闭。开启沙盒会破坏 CLI 启动或真实用户登录状态读取。
-- app-server 和版本探测必须使用真实用户 home, 避免 Xcode 运行时 `HOME` 指向 app container 导致 `codex account authentication required`。
-- 不要把 Codex auth 文件、stderr、原始 RPC 响应或用户路径之外的敏感信息写入 UI、日志、文档或测试夹具。
+- App Sandbox 必须保持关闭。
+- app-server 和版本探测必须使用真实用户 home。
+- 不要把 Codex auth 文件、stderr、原始敏感 RPC 响应或用户路径之外的敏感信息写入 UI、文档或测试夹具。
+
+## 发布脚本
+
+- `Scripts/create-dmg.sh [App.app] [Output.dmg]` 创建带 `/Applications` 链接的 DMG, 会尝试写 Finder 布局。
+- `Scripts/update-appcast.sh [CodexBar-vX.Y.Z.dmg]` 更新 `Updates/appcast.xml`, 需要 Sparkle `sign_update`。
+- 改发布脚本后至少运行 `bash -n Scripts/create-dmg.sh` 和 `bash -n Scripts/update-appcast.sh`。
+- 更新 appcast、tag、push、上传 DMG 都必须先得到用户明确同意。
## Git 规则
-- 不要主动 push; 必须等用户明确同意。
+- 不要主动 push。
- 不要回滚或覆盖你没做的未提交改动。
- 提交 message 使用 Conventional Commits 前缀 + 中文标题 + 空行 + 4 空格缩进 bullet body。
- 标题格式: `<type>: <中文描述>`, 不加句号。
@@ -248,7 +289,7 @@ Popover:
示例:
```text
-fix: 修复 Codex 版本状态刷新
+fix: 修复 Codex 状态刷新
- 合并设置页 onAppear 和 didBecomeActive 的重复版本探测
- 保留当前运行版本与磁盘安装版本不一致时的更新提示
@@ -256,21 +297,20 @@ fix: 修复 Codex 版本状态刷新
Tag:
-- tag 名格式 `v{MARKETING_VERSION}`, 例如 `v1.3.6`。
-- 使用附注 tag: `git tag -a v1.3.6 -m "Release v1.3.6"`。
-- tag 不主动 push。
+- tag 名格式 `v{MARKETING_VERSION}`, 例如 `v2.0.0`。
+- 使用附注 tag: `git tag -a v2.0.0 -m "Release v2.0.0"`。
-## 发布流程
+## 最终检查
-1. 用 `Developer ID Application` 证书签名并 notarization, Xcode 导出 `CodexBar.app` 到项目根目录。
-2. 运行 `Scripts/create-dmg.sh [App.app] [Output.dmg]`。未传 app 时自动查找项目根目录唯一 `.app`; 默认输出 `CodexBar-v{MARKETING_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` 对应站点。
+返回最终答复或执行不可逆动作前, 快速确认:
-## 停止规则
+- 是否满足用户的所有明确要求。
+- 是否基于当前代码和工具输出, 没有使用过期文件名或旧架构名。
+- 是否运行了与改动匹配的验证命令。
+- 是否说明了未验证项和原因。
+- 是否避免泄露本机认证、路径之外的敏感信息或原始错误噪音。
-- 构建或验证失败时, 不要声称完成; 先定位可操作错误。若无法修复, 交代失败命令、关键输出和下一步。
-- 官方文档或外部事实会影响实现时, 先查官方来源; 不确定就说明不确定。
-- 用户要求的文件名与仓库事实冲突时, 采用仓库中的真实文件并在最终回复说明。例如本仓库使用 `AGENTS.md`, 不是 `AGENT.md`。
-- 发布、推送、删除、重置历史、覆盖未提交用户改动、写入仓库外路径或触发真实更新分发前, 必须得到明确同意。
+<!-- SPECKIT START -->
+For additional context about technologies to be used, project structure,
+shell commands, and other important information, read the current plan
+<!-- SPECKIT END -->
diff --git a/CLAUDE.md b/CLAUDE.md
deleted file mode 100644
index 64263bb..0000000
--- a/CLAUDE.md
+++ /dev/null
@@ -1,276 +0,0 @@
-# CLAUDE.md
-
-此文件为 Claude Code 在本仓库工作时提供上下文和约定。请优先遵循这里的项目事实、构建命令和实现边界。
-
-## 目标
-
-CodexBar 是一个 macOS 菜单栏应用, 用本机 Codex app-server 展示当前 Codex 账号的额度和 token 用量。你在本仓库中的目标是交付可验证、贴合现有 SwiftUI/MVVM 架构的修改, 并保护本地认证、隐私、菜单栏体验、Sparkle 更新和发布流程不被无意破坏。
-
-## 成功标准
-
-- 用户请求已转成明确的结果: 代码、文档、脚本、诊断结论或发布操作。
-- 修改范围只覆盖完成目标所需的文件; 不顺手重构无关模块, 不回滚他人未提交改动。
-- Swift/Xcode 工程修改后运行本文件的构建命令, 结果无 error 和项目代码 warning。
-- 文档、图片或发布元数据的纯修改可以不构建, 但最终回复必须说明未运行构建的原因。
-- 最终回复说明改了什么、如何验证、还剩什么风险或未执行项。
-
-## 工作方式
-
-- 先读局部上下文, 再行动。优先用 `rg` / `rg --files`、当前文件和相邻模块定位事实; 只有依赖缺失时再扩大范围。
-- 多步骤或跨文件任务先给简短计划。计划写清关键文件/系统、验证命令、失败处理和真正会影响实现的开放问题。
-- 简单、低风险、可逆的请求直接执行。删除、发布、推送、生产写入、覆盖用户选择或会明显改变行为但缺少关键决策时, 先取得用户明确同意。
-- 独立的读取和检索可以并行; 有先后依赖、歧义会影响实现、或动作不可逆时必须顺序执行。
-- 工具调用前给一句短说明。长任务中持续同步进度, 但不要把中间状态当最终答复。
-- 遇到失败先做最小可行诊断和一次合理重试。仍无法完成时, 说明阻塞点、已验证事实和下一个最小检查。
-- 回复保持紧凑, 路径、命令、函数、类型和文件名用反引号。中文说明优先, 除非用户要求英文。
-- 修改 prompt、文档或 agent 指令时, 优先保留有效事实和行为边界; 删除或改写会改变执行行为的规则前, 确认它确实与当前目标冲突。
-
-## 验证命令
-
-涉及 Swift/Xcode 工程、资源归属、build setting、Info.plist、SwiftPM 依赖或发布脚本行为的改动后运行:
-
-```bash
-xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
-```
-
-要求无 error 和 warning。当前 Xcode 可能输出 `Metadata extraction skipped. No AppIntents.framework dependency found.` 的 metadata 阶段 warning, 不作为项目代码 warning 处理。SourceKit 对跨文件类型偶尔误报 `Cannot find type ... in scope`, 以 `xcodebuild` 为准。
-
-工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下源码通常无需修改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。
-
-## 项目事实
-
-- 平台: SwiftUI + AppKit + MVVM, 最低 macOS 15.0。
-- 应用形态: `LSUIElement` 纯菜单栏应用, 无 Dock 图标、无应用菜单。
-- 入口: `CodexBarApp` 只声明占位 `Settings { EmptyView() }`; 真实 UI 由 `CodexBarAppDelegate` 和 `StatusItemController` 驱动。
-- 外部依赖: Sparkle(SwiftPM)。
-- App Sandbox 必须关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/App 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。
-- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 1.3.6`, `CURRENT_PROJECT_VERSION = 9`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`。
-- 不要为 macOS 15 以下添加 SF Symbols 或 SwiftUI API fallback。
-
-## 架构地图
-
-数据流:
-
-```text
-CodexRateLimitService(JSON-RPC app-server)
- -> RateLimitsViewModel(@MainActor 状态发布)
- -> StatusItemController(菜单栏图标/Popover 生命周期)
- -> RateLimitsMenuView / AppSettingsView(SwiftUI 展示)
-```
-
-关键文件职责:
-
-- `CodexBarApp.swift`: `@main` 入口和 `Bundle.displayVersionLabel`(`v1.2.3`, 缺失回退 `--`)。
-- `StatusItemController.swift`: 创建 `NSStatusItem`、`NSPopover`、右键菜单、外部点击监控、淡入淡出状态机和自动刷新启动。左键切换 popover, 右键或 Control 点击显示「设置 / 退出」。
-- `SettingsWindowController.swift`: 复用单个设置窗口。首次显示或关闭后重开时按 status item 所在屏幕居中; 已可见时只 `deminiaturize`、激活并置顶, 不重新居中或新建窗口。
-- `RateLimitsViewModel.swift`: `@MainActor ObservableObject`, 发布 `snapshot`、`isRefreshing`、`lastError`、`codexConnectionInfo`、`autoRefreshCountdownStartedAt`。错误单一来源是 `lastError: CodexRateLimitError?`; `errorMessage`、`requiresLogin`、`hasError` 都从它派生。
-- `CodexRateLimitService.swift`: 非 UI 服务, 管理 app-server 进程、JSON-RPC、连接复用、认证重试、usage 降级和当前运行中的 Codex 来源/路径/版本。
-- `CodexCLIResolver.swift`: 解析全局 `codex` 与 `/Applications/Codex.app/Contents/Resources/codex`, 并构造 app-server 和版本探测共用的真实用户环境。
-- `CodexCLIVersionService.swift`: 并发探测全局 CLI 与 Codex App 内置 CLI 的 `--version`, 合成磁盘版本、当前运行版本和「已更新至」提示。
-- `RateLimitModels.swift`: wire DTO 保持纯 `Decodable`; 展示排序、兜底和派生文案放在业务快照转换里。
-- `RateLimitsMenuView.swift`: popover 主 UI, 包含登录提示、账号卡片、limit 分节、usage 卡片、更新时间倒计时和错误行。
-- `QuotaRow.swift`: 单个 quota window 行和 `SegmentedQuotaBar`, 条形图展示剩余额度。
-- `UsageHeatmap.swift` / `TokenCountText.swift`: token 汇总、近 30 周热力图、hover tooltip 和 K/M/B 紧凑数字格式。
-- `AppSettingsView.swift` / `LoginItemSettings.swift`: 设置窗口、开机自启、CodexBar 版本、Codex CLI/Codex APP 版本与路径复制。
-- `AppUpdater.swift`: Sparkle 封装, 更新状态文案按设置窗、popover 和可用更新三个表面拆分。
-- `LiquidGlassStyle.swift`: 自绘 Liquid Glass 视觉入口, 提供 `.liquidGlassSurface(...)`、`.liquidGlassCapsule(...)`、`LiquidGlassDivider`、`Animation.codexStatus` 和 `Color.codexLabel` / `Color.codexSecondaryLabel`。
-
-## Codex app-server 合约
-
-启动命令统一是:
-
-```bash
-codex app-server --listen stdio://
-```
-
-必须通过 `CodexCLIResolver.resolveAppServerCommand()` 解析:
-
-- 优先 PATH 中的全局 `codex`。
-- 如果 PATH 中解析到的路径等价于 `/Applications/Codex.app/Contents/Resources/codex`, 当作内置 Codex APP CLI, 不当作全局 CLI。
-- 全局 CLI 不存在时回退 Codex APP 内置 CLI。
-- 两者都不存在时展示「找不到 Codex CLI 或 Codex APP」。
-
-启动环境由 `CodexCLIResolver.environment` 构造:
-
-- 保留当前环境, 但 `HOME` 必须用 `getpwuid(getuid())` 得到真实用户 home。
-- 同步设置 `USER`、`LOGNAME`。
-- 合并 Homebrew、npm global、`.local`、Volta 和系统路径。
-- 确保 `TERM` 有值。
-- 不要改回 Xcode sandbox/container 的 `HOME`, 否则会读不到 `~/.codex/auth.json`。
-
-首次连接必须先握手再读额度:
-
-```json
-{"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/read`(`refreshToken: true`) 再重试一次; 仍失败抛 `authenticationRequired`。
-- `account/usage/read`: token 统计。读取 `summary.lifetimeTokens`、`summary.peakDailyTokens`、`dailyUsageBuckets`。如果返回 method not found / unknown / unsupported / not supported, 将当前连接的 `isUsageReadAvailable` 置为 false, 本连接后续不再请求 usage。其他 usage 错误只隐藏 token 区域, 额度仍正常展示。
-
-连接细节:
-
-- `requestTimeout` 是 20 秒。
-- `initialize` 响应的 `userAgent` 首个 token 形如 `codex_bar/0.139.0 (...)`; `serverVersion(fromUserAgent:)` 取 `/` 后版本号作为当前运行版本。
-- 每条连接保存 `CodexCLIConnectionInfo(source, executablePath, version, openedAt)`, 设置页用它标记「当前使用」。
-- `JSONLineReader` 按行读取 stdout, 只消费匹配请求 id 的响应; stdout EOF 时标记关闭并唤醒等待中的请求。
-- `PipeDrain` 持续排空 stderr, stderr 不进入用户可见文案; stderr EOF 时停止 readability handler。
-
-## 自动刷新与连接重建
-
-- `RateLimitsViewModel.refreshInterval` 是 60 秒。
-- `startAutoRefresh()` 启动一个 `Task`, 每轮按 `autoRefreshDelay`(距下次刷新的剩余秒数, 下限 1 秒; `autoRefreshCountdownStartedAt` 为空时取 `refreshInterval`)休眠后调用 `refreshIfNeeded()`, 不再每秒空转唤醒。
-- `refreshIfNeeded()` 只看 `autoRefreshCountdownStartedAt` 距当前是否超过 60 秒, 作为动态休眠的兜底判断。
-- `refresh()` 用 `isRefreshing` 合并并发触发; 开始时不要清空 `lastError`。
-- `refresh()` 成功后更新 `snapshot` 并清空 `lastError`; 失败时保留旧 `snapshot`, 写入 `lastError`。
-- 无论成功失败, 刷新结束都更新 `codexConnectionInfo`、重置 `autoRefreshCountdownStartedAt`, 并关闭 `isRefreshing`。
-- popover 显示后延迟调用 `refreshIfNeeded()`; 账号图标双击触发手动 `refresh()`。
-
-`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`, 连接状态只在 `DispatchQueue(label: "CodexBar.app-server")` 上读写:
-
-- 进程已退出 -> 重建。
-- 连接存活超过 `connectionMaxAge`(1 小时) -> 关闭后重建, 覆盖 Codex 升级或服务端状态漂移。
-- 复用连接上的非登录类请求失败 -> 丢弃连接, 重建一次再试。
-- 全新连接上的失败 -> 直接抛出, 避免故障时重复完整握手。
-- 登录类错误(`requiresLogin`) -> 丢弃连接但不立即重试; 下次轮询重新启动进程读取最新登录状态。
-
-## 数据模型规则
-
-`CodexQuotaSnapshot`:
-
-- 必须有 `AccountReadResponse.account`, 否则抛 `notLoggedIn`。
-- 优先读取 `rateLimitsByLimitId` 支持多 limit; 为空则回退顶层 `rateLimits`。
-- 顶层 `rateLimits.limitId` 指向的主 limit 置顶, 缺省 `"codex"`。
-- 其余 limit 按 `limitName ?? limitId` 做 localized standard 排序, 再按 `limitId` 稳定排序。
-- 每个 limit 的 `primary` / `secondary` 合成 `[QuotaWindow]`; 没有窗口的 limit 被过滤, 全部为空才抛 `missingRateLimitWindow`。
-- `QuotaWindow.remainingPercent = clamp(100 - usedPercent, 0...100)`; 无 `usedPercent` 视为无数据。
-- `windowDurationMins` 标签: 整天为「N 天」, 整小时为「N 小时」, 否则「N 分钟」, 缺失或非正数为「额度」。
-
-`CodexUsageSnapshot`:
-
-- `recentWeekGrid(columnCount:endingDaysAgo:today:)` 基于本地当天零点生成按周对齐的日期网格。
-- UI 使用 `UsageHeatmap.Metrics.columnCount = 30` 且 `endingDaysAgo = 1`, 默认不包含今天。
-- 最右列锚定最后一个可见日期所在的周日开头周, 避免今天是周日时出现整列空白。
-- 返回值中的 `nil` 表示今天、未来日期或不可生成日期; 热力图不绘制方块也不参与峰值计算。
-- 颜色按当前可见日期区间内峰值缩放。
-
-## 并发与隔离
-
-工程开启 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; 未显式标注的类型会推断为 MainActor 隔离。
-
-- UI 层保持 `@MainActor` 或主线程使用: `CodexBarAppDelegate`、`StatusItemController`、`SettingsWindowController`、`RateLimitsViewModel`、`AppUpdater`、`LoginItemSettings`、`CodexCLIVersionViewModel`。
-- 服务层对外暴露 async API, 内部用串行 queue 管理 `Process`、`Pipe` 和连接状态。
-- 非 UI 类型、DTO、模型、服务辅助类型和部分静态工具需要显式 `nonisolated`, 避免 `Call to main actor-isolated initializer in a synchronous nonisolated context`。
-- `CodexRateLimitService` 使用 `CodexBar.app-server` 队列。
-- `CodexCLIVersionService` 使用 `CodexBar.codex-version` 队列, 全局和内置版本探测先并发启动再收集。
-
-## UI 约束
-
-菜单栏:
-
-- 正常图标是 `person.fill.checkmark`, 错误图标是 `person.fill.xmark`。
-- `StatusItemController.updateStatusImage(hasError:)` 只随 `lastError` 的有无变化设置图标。
-- 菜单栏不展示额度数字; 详情只在 popover 中展示。
-- App 图标保持白底黑色 `timelapse`。
-
-Popover:
-
-- `RateLimitsMenuView.menuWidth` 由热力图总宽度和 padding 推导; 修改热力图尺寸时同步检查弹窗宽度。
-- 外层和分区使用 `.liquidGlassSurface(...)`; 分隔线使用 `LiquidGlassDivider`; 小徽章可用 `.liquidGlassCapsule(...)`。
-- `LiquidGlassStyle.swift` 是自绘玻璃效果, 不是 macOS 26 原生 `.glassEffect`。没有明确设计要求时不要切换。
-- 账号行 plan 是右侧加粗纯文字, 不加胶囊底色或额外 padding。`planBadgeTint(for:)` 优先级: enterprise -> team/business -> pro -> plus -> edu -> free -> 默认 cyan。
-- 邮箱双击可模糊/取消模糊; 账号图标双击手动刷新。
-- limit 分节标题取 `limitName` 回退 `limitId`, 首字母大写; 节之间使用 `LiquidGlassDivider`。
-- 额度条展示剩余百分比, 颜色按 20% 一档: 0-19 红色, 20-39 橙色, 40-59 黄色, 60-79 薄荷色, 80-100 绿色。
-- 无 quota 数据时显示 `--` / `暂无数据`, 并用占位色。
-- 重置时间格式 `MM-dd HH:mm`。
-- 更新时间行显示顺时针自动刷新倒计时圆环、「数据更新时间」和 `HH:mm:ss`; 时间文本使用 `.contentTransition(.numericText())` 和 `Color.codexSecondaryLabel`, 不展示应用版本号。
-- 倒计时圆环(`AutoRefreshCountdownCircle`)用 `Circle().trim` 按秒离散跳格, 不做连续动画: `Shape.trim` 的长连续动画是逐帧 CPU 重绘, 比每秒采样更耗 CPU, 不要改成连续动画。每秒采样由 `AutoRefreshCountdownTimeline` 的 `TimelineView` 驱动, 且只在 popover 可见(`PopoverVisibilityState.isVisible`, 由 `StatusItemController` 在 popover show/close 时维护)时启用; 隐藏时静态渲染一次。仅 `startedAt` 变化(刷新重置)且可见时播放 0.2 秒恢复动画, 普通 tick 直接跳变。
-- token 区域显示「单日峰值」和「全时累计」; `TokenCountText` 对 1K 以下显示完整整数, 1K 起显示 K/M/B。
-- 热力图是近 30 周、30 列 x 7 行、周日到周六排列、默认不包含今天; hover tooltip 显示日期和单日 token。
-
-错误展示:
-
-- 登录类错误(`requiresLogin`)时, popover 顶部显示橙色「Codex 未登录」。
-- 登录类错误会让旧快照 `opacity(0.4)` 置灰保留, 并抑制红色错误行。
-- 其他错误显示红色小字 `errorDescription`, 旧快照保持全亮度。
-- 旧额度快照永远不因失败而清空。
-- app-server 相关用户可见错误通过 `CodexRateLimitError.errorDescription` 生成; 不要把子进程 stderr 或原始日志拼进 UI。
-
-设置窗口:
-
-- 通过菜单栏图标右键或 Control 点击菜单的「设置」打开独立 `AppSettingsView` 窗口。
-- 不要恢复为 Option 点击或 popover 内设置区。
-- 设置页包含「CodexBar 版本」和「Codex 版本」两个版本区域。
-- `Codex CLI` 行图标用 `terminal`; `Codex APP` 行图标用 `app.badge`。
-- Codex CLI/Codex APP 子行相对标题缩进, 当前运行来源显示「当前使用」徽章。
-- 当前行优先展示 app-server 握手自报运行版本; 非当前行展示磁盘安装版本。
-- 如果当前运行版本与磁盘安装版本不同, 显示「已更新至 <version>」。
-- 路径点击复制到剪贴板, 对应来源显示「已复制」1.5 秒; 保留路径文本布局宽度避免跳动。
-- 设置页版本状态、Codex 版本值、复制提示、popover 更新提示和错误提示使用 `Animation.codexStatus` 做淡入淡出。
-
-## Sparkle 更新
-
-`AppUpdater` 是 `@MainActor ObservableObject`。
-
-- 初始化时先校验 `Info.plist` 的 `SUFeedURL`(http/https) 和 `SUPublicEDKey`(非空)。
-- 任一缺失时不创建 `SPUStandardUpdaterController`, 更新操作显示「未配置更新资源」。
-- `canConfigureAutomaticChecks` 是 `updaterController != nil` 的计算属性; 设置窗「自动检查更新」开关据此禁用。
-- `settingsStatusMessage`: 设置窗版本行状态, 默认 3 秒后由可取消 `Task` 清空; `autoDismissDelay: nil` 时常驻。
-- `panelUpdateMessage`: popover 底栏被动提示, 双击可触发 `startUpdate()`。
-- `availableUpdateMessage`: 发现新版的语义状态, 驱动设置窗版本行和「立即更新」按钮。
-- `checkForUpdates()` 是设置窗手动检查, 设置 `isManualCheckInProgress`。
-- 如果已经有 `availableUpdateMessage`, 手动检查只把该消息常驻显示到设置窗。
-- `startUpdate()` 激活应用并调用 Sparkle 安装面板。
-- 委托回调按 `isManualCheckInProgress` 路由: 手动结果进 `settingsStatusMessage`, 自动发现新版进 `panelUpdateMessage`。
-- `Info.plist` 当前 `SUFeedURL = https://codexbar.zabrian.app/appcast.xml`, `SUScheduledCheckInterval = 3600`。
-
-## 认证、隐私与沙盒
-
-- CodexBar 只与本机 Codex app-server 进程通信; 账号、额度和 token 使用量不发往第三方服务。
-- 除 Sparkle appcast/DMG 下载外, 应用自身不做网络请求。
-- App Sandbox 必须保持关闭。开启沙盒会破坏 CLI 启动或真实用户登录状态读取。
-- app-server 和版本探测必须使用真实用户 home, 避免 Xcode 运行时 `HOME` 指向 app container 导致 `codex account authentication required`。
-- 不要把 Codex auth 文件、stderr、原始 RPC 响应或用户路径之外的敏感信息写入 UI、日志、文档或测试夹具。
-
-## Git 规则
-
-- 不要主动 push; 必须等用户明确同意。
-- 不要回滚或覆盖你没做的未提交改动。
-- 提交 message 使用 Conventional Commits 前缀 + 中文标题 + 空行 + 4 空格缩进 bullet body。
-- 标题格式: `<type>: <中文描述>`, 不加句号。
-- 常用 type: `feat`、`fix`、`chore`、`refactor`、`docs`。
-- 功能、修复、发布类提交必须写 body; 简单文档或杂项可只写标题行。
-
-示例:
-
-```text
-fix: 修复 Codex 版本状态刷新
-
- - 合并设置页 onAppear 和 didBecomeActive 的重复版本探测
- - 保留当前运行版本与磁盘安装版本不一致时的更新提示
-```
-
-Tag:
-
-- tag 名格式 `v{MARKETING_VERSION}`, 例如 `v1.3.6`。
-- 使用附注 tag: `git tag -a v1.3.6 -m "Release v1.3.6"`。
-- tag 不主动 push。
-
-## 发布流程
-
-1. 用 `Developer ID Application` 证书签名并 notarization, Xcode 导出 `CodexBar.app` 到项目根目录。
-2. 运行 `Scripts/create-dmg.sh [App.app] [Output.dmg]`。未传 app 时自动查找项目根目录唯一 `.app`; 默认输出 `CodexBar-v{MARKETING_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` 对应站点。
-
-## 停止规则
-
-- 构建或验证失败时, 不要声称完成; 先定位可操作错误。若无法修复, 交代失败命令、关键输出和下一步。
-- 官方文档或外部事实会影响实现时, 先查官方来源; 不确定就说明不确定。
-- 用户要求的文件名与仓库事实冲突时, 采用仓库中的真实文件并在最终回复说明。例如本仓库使用 `AGENTS.md`, 不是 `AGENT.md`。
-- 发布、推送、删除、重置历史、覆盖未提交用户改动、写入仓库外路径或触发真实更新分发前, 必须得到明确同意。
diff --git a/CodexBar/AppSettingsView.swift b/CodexBar/AppSettingsView.swift
index 68b74ac..04b8359 100644
--- a/CodexBar/AppSettingsView.swift
+++ b/CodexBar/AppSettingsView.swift
@@ -1,15 +1,8 @@
-//
-// AppSettingsView.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-14.
-//
-
import AppKit
import SwiftUI
struct AppSettingsView: View {
- @EnvironmentObject private var rateLimitsViewModel: RateLimitsViewModel
+ @EnvironmentObject private var statusViewModel: CodexStatusViewModel
@EnvironmentObject private var appUpdater: AppUpdater
@StateObject private var loginItemSettings = LoginItemSettings()
@StateObject private var codexVersions = CodexCLIVersionViewModel()
@@ -162,7 +155,7 @@ private extension AppSettingsView {
.animation(Metrics.statusAnimation, value: appUpdater.availableUpdateMessage != nil)
}
- /// 版本行文案;无任何动态消息时回退到版本号 (此时用等宽数字)
+ /// 版本行优先显示更新状态, 没有动态消息时回退到当前版本号
var versionStatus: (text: String, isVersionLabel: Bool) {
if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {
return (message, false)
@@ -195,13 +188,13 @@ private extension AppSettingsView {
}
func refreshCodexVersionSection() {
- // 版本探测是慢路径且自带并发合并; 连接信息只是一次缓存读取, 顺带刷新
+ // 版本探测较慢且内部会合并并发请求; 连接信息只是缓存读取
codexVersions.refresh()
- rateLimitsViewModel.refreshCodexConnectionInfo()
+ statusViewModel.refreshCodexConnectionInfo()
}
func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {
- let row = CodexCLIVersionDisplay(item: item, connection: rateLimitsViewModel.codexConnectionInfo)
+ let row = CodexCLIVersionDisplay(item: item, connection: statusViewModel.codexConnectionInfo)
let isPathCopied = copiedPathResetTasks[item.source] != nil
return HStack(alignment: .top, spacing: 10) {
diff --git a/CodexBar/AppUpdater.swift b/CodexBar/AppUpdater.swift
index 09d424c..45c878f 100644
--- a/CodexBar/AppUpdater.swift
+++ b/CodexBar/AppUpdater.swift
@@ -1,10 +1,3 @@
-//
-// AppUpdater.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-11.
-//
-
import Combine
import AppKit
import Sparkle
@@ -28,6 +21,7 @@ final class AppUpdater: NSObject, ObservableObject {
init(bundle: Bundle = .main) {
super.init()
+ // 开发环境可能没有 Sparkle feed 或公钥, 此时保留设置 UI, 但禁用更新能力
guard Self.hasUsableSparkleConfiguration(in: bundle) else {
return
}
diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/CodexBarApp.swift
index cb2fb68..7cc30e5 100644
--- a/CodexBar/CodexBarApp.swift
+++ b/CodexBar/CodexBarApp.swift
@@ -1,10 +1,3 @@
-//
-// CodexBarApp.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import AppKit
import SwiftUI
@@ -13,8 +6,7 @@ struct CodexBarApp: App {
@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate
var body: some Scene {
- // 实际 UI 由 CodexBarAppDelegate 的 StatusItemController 驱动
- // App 仅需声明一个占位 Scene 设置窗口走右键菜单的 makeSettingsWindow
+ // 菜单栏 UI 由 AppDelegate 驱动; 空 Settings scene 仅用于保留系统设置入口
Settings {
EmptyView()
}
@@ -26,7 +18,7 @@ nonisolated extension Bundle {
object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
- /// `v1.2.3` 形式的版本文案,缺失时回退 `--`(不带 v 前缀)
+ /// `v1.2.3` 形式的版本文案; 缺失时回退 `--`
var displayVersionLabel: String {
guard let version = shortVersionString else { return "--" }
return "v\(version)"
diff --git a/CodexBar/CodexCLIResolver.swift b/CodexBar/CodexCLIResolver.swift
index 2b748ce..ba94139 100644
--- a/CodexBar/CodexCLIResolver.swift
+++ b/CodexBar/CodexCLIResolver.swift
@@ -1,10 +1,3 @@
-//
-// CodexCLIResolver.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-15.
-//
-
import Darwin
import Foundation
@@ -29,7 +22,7 @@ nonisolated struct AppServerCommand: Sendable, Equatable {
nonisolated struct CodexCLIConnectionInfo: Sendable, Equatable {
let source: CodexCLIExecutableSource
let executablePath: String
- // initialize 握手里 app-server 自报的运行版本, 反映当前进程真实在跑的二进制
+ // 来自 initialize 握手, 代表当前 app-server 进程真实运行的版本
let version: String?
let openedAt: Date
}
@@ -38,7 +31,7 @@ nonisolated struct CodexCLIInstallations: Sendable, Equatable {
let globalPath: String?
let bundledPath: String?
- /// 当前会被启动的来源, 与 resolveAppServerCommand 优先级一致: 全局优先, 回退内置
+ /// 与启动优先级一致: 全局优先, 回退内置
var activeSource: CodexCLIExecutableSource? {
if globalPath != nil { return .global }
if bundledPath != nil { return .bundled }
@@ -61,11 +54,11 @@ nonisolated enum CodexCLIResolver {
try command(from: resolveInstallations(environment: environment))
}
- /// 从一份已解析的安装信息派生启动命令, 避免重复扫描 PATH
+ /// 从已解析的安装信息派生命令, 避免重复扫描 PATH
static func command(from installations: CodexCLIInstallations) throws -> AppServerCommand {
guard let source = installations.activeSource,
let path = installations.path(for: source) else {
- throw CodexRateLimitError.executableNotFound
+ throw CodexStatusError.executableNotFound
}
return AppServerCommand(source: source, executablePath: path)
@@ -92,6 +85,7 @@ nonisolated enum CodexCLIResolver {
var environment = ProcessInfo.processInfo.environment
let homeDirectory = realUserHomeDirectory()
let path = environment["PATH"] ?? ""
+ // 菜单栏应用通常拿不到用户 shell PATH, 需要补上常见 CLI 安装目录
let fallbackPaths = [
"/opt/homebrew/bin",
"/usr/local/bin",
diff --git a/CodexBar/CodexCLIVersionService.swift b/CodexBar/CodexCLIVersionService.swift
index b15a7c3..3da1588 100644
--- a/CodexBar/CodexCLIVersionService.swift
+++ b/CodexBar/CodexCLIVersionService.swift
@@ -1,10 +1,3 @@
-//
-// CodexCLIVersionService.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-15.
-//
-
import Combine
import Foundation
@@ -13,7 +6,7 @@ nonisolated struct CodexCLIVersionSnapshot: Equatable, Sendable {
let bundled: CodexCLIVersionItem
let refreshedAt: Date
- // distantPast 让首个 refresh 一定通过新鲜度门槛
+ // 让首次 refresh 不受节流限制
static let empty = CodexCLIVersionSnapshot(
global: CodexCLIVersionItem(source: .global),
bundled: CodexCLIVersionItem(source: .bundled),
@@ -50,19 +43,19 @@ nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {
}
}
-/// 把磁盘探测(item)与连接握手(connection)两路版本信息合成为一行可直接渲染的展示数据
+/// 合并磁盘探测版本和当前 app-server 握手版本
nonisolated struct CodexCLIVersionDisplay: Equatable {
let source: CodexCLIExecutableSource
let isCurrent: Bool
let displayVersion: String
let hasVersion: Bool
let path: String?
- /// 运行版本落后于磁盘已安装版本时(后台升级尚未重连)的新版本号, 否则 nil
+ /// 当前会话尚未重连到新安装版本时显示的新版本号
let newerInstalledVersion: String?
init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {
let isCurrent = connection?.source == item.source
- // 当前来源优先用正在运行的版本(连接握手自报), 其余用磁盘安装版本
+ // 当前来源优先显示正在运行的版本, 避免后台升级后误报已生效
let runningVersion = isCurrent ? connection?.version : nil
let version = runningVersion ?? item.version
@@ -100,7 +93,7 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {
let environment = CodexCLIResolver.environment
let installations = CodexCLIResolver.resolveInstallations(environment: environment)
- // 两个探测互不依赖, 先并发启动子进程, 再分别收集, 避免串行叠加超时
+ // 两个安装源互不依赖, 先并发启动再收集, 避免两个超时串行叠加
let globalProbe = startProbe(
source: .global,
path: installations.globalPath,
@@ -121,7 +114,6 @@ nonisolated final class CodexCLIVersionService: @unchecked Sendable {
)
}
- /// 一个已启动、等待收集的版本探测子进程
private struct RunningProbe {
let source: CodexCLIExecutableSource
let path: String
@@ -235,7 +227,7 @@ final class CodexCLIVersionViewModel: ObservableObject {
@Published private(set) var snapshot = CodexCLIVersionSnapshot.empty
@Published private(set) var isRefreshing = false
- // 版本几乎不变, 短时间内重复触发(didBecomeActive 频繁到达)直接复用上次结果
+ // onAppear 和 didBecomeActive 常连发, 版本探测需要节流以避免频繁启动子进程
private static let refreshThrottle: TimeInterval = 60
private let service: CodexCLIVersionService
@@ -250,7 +242,6 @@ final class CodexCLIVersionViewModel: ObservableObject {
}
func refresh() {
- // 合并并发触发与短时重复触发(onAppear 与 didBecomeActive 常同时/频繁到达), 避免重复启动子进程
guard !isRefreshing,
Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {
return
diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/CodexQuotaModels.swift
similarity index 76%
rename from CodexBar/RateLimitModels.swift
rename to CodexBar/CodexQuotaModels.swift
index 8812d7c..3cf7136 100644
--- a/CodexBar/RateLimitModels.swift
+++ b/CodexBar/CodexQuotaModels.swift
@@ -1,10 +1,3 @@
-//
-// RateLimitModels.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import Foundation
nonisolated struct CodexQuotaSnapshot: Equatable {
@@ -13,11 +6,11 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
let generatedAt: Date
let limits: [CodexQuotaLimitSnapshot]
let usage: CodexUsageSnapshot?
-
+
var accountLabel: String {
account.displayName
}
-
+
var planLabel: String? {
account.planType ?? planType
}
@@ -27,14 +20,14 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
let limitId: String
let 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 +37,7 @@ nonisolated private extension String {
guard let first else {
return self
}
-
+
return first.uppercased() + dropFirst()
}
}
@@ -53,16 +46,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {
let type: String
let 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 +78,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) 分钟"
}
}
@@ -136,7 +129,7 @@ nonisolated struct RateLimitWindow: Decodable {
let usedPercent: Int?
let resetsAt: Int?
let windowDurationMins: Int?
-
+
var resetDate: Date? {
guard let resetsAt else { return nil }
return Date(timeIntervalSince1970: TimeInterval(resetsAt))
@@ -149,26 +142,30 @@ nonisolated struct AccountUsageResponse: Decodable {
}
nonisolated struct UsageSummary: Decodable, Equatable {
+ let currentStreakDays: Int?
let lifetimeTokens: Int
+ let longestRunningTurnSec: Int?
+ let longestStreakDays: Int?
let peakDailyTokens: Int
}
nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
let startDate: String
let tokens: Int
-
+
var id: String { startDate }
}
nonisolated struct CodexUsageSnapshot: Equatable {
let summary: UsageSummary
let dailyBuckets: [DailyUsageBucket]
-
+
+ /// 给热力图生成按周排列的最近日期网格, 每列从周日开始
func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {
guard columnCount > 0 else {
return []
}
-
+
let calendar = Calendar.current
let todayStart = calendar.startOfDay(for: today)
let lastVisibleDate = calendar.date(
@@ -184,37 +181,37 @@ nonisolated struct CodexUsageSnapshot: Equatable {
) else {
return []
}
-
+
let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket in
result[bucket.startDate, default: 0] += bucket.tokens
}
-
+
return (0..<columnCount).flatMap { column -> [DailyUsageBucket?] in
guard let weekStart = calendar.date(byAdding: .weekOfYear, value: column, to: firstWeekStart) else {
return Array(repeating: nil, count: 7)
}
-
+
return (0..<7).map { weekdayOffset -> DailyUsageBucket? in
guard let date = calendar.date(byAdding: .day, value: weekdayOffset, to: weekStart) else {
return nil
}
-
+
guard date <= lastVisibleDate else {
return nil
}
-
+
let startDate = Self.dayFormatter.string(from: date)
return DailyUsageBucket(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)
}
}
}
-
+
private static func sundayStartOfWeek(containing date: Date, calendar: Calendar) -> Date {
let weekday = calendar.component(.weekday, from: date)
let daysSinceSunday = weekday - 1
return calendar.date(byAdding: .day, value: -daysSinceSunday, to: date) ?? date
}
-
+
private nonisolated static let dayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
@@ -226,57 +223,58 @@ nonisolated struct CodexUsageSnapshot: Equatable {
nonisolated extension CodexQuotaSnapshot {
init(
accountResponse: AccountReadResponse,
- rateLimitsResponse: AccountRateLimitsResponse,
+ rateLimitsResponse: AccountRateLimitsResponse?,
usageResponse: AccountUsageResponse? = nil,
generatedAt: Date = Date()
) throws {
guard let account = accountResponse.account else {
- throw CodexRateLimitError.notLoggedIn
- }
-
- let limits = Self.orderedSnapshots(from: rateLimitsResponse).compactMap { entry in
- CodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)
+ throw CodexStatusError.notLoggedIn
}
-
- guard !limits.isEmpty else {
- throw CodexRateLimitError.missingRateLimitWindow
+
+ let limits = rateLimitsResponse.map { response in
+ Self.orderedSnapshots(from: response).compactMap { entry in
+ CodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)
+ }
+ } ?? []
+
+ let usage = usageResponse.map {
+ CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)
}
-
+
+ // rateLimits/usage 可同时为空, 账户有效时仍生成快照给 UI 展示"暂无数据"
self.init(
account: account,
- planType: rateLimitsResponse.rateLimits.planType,
+ planType: rateLimitsResponse?.rateLimits.planType,
generatedAt: generatedAt,
limits: limits,
- usage: usageResponse.map {
- CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)
- }
+ usage: usage
)
}
-
+
/// 展示顺序: 顶层 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 in
if (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
}
}
@@ -288,11 +286,11 @@ nonisolated extension CodexQuotaLimitSnapshot {
.compactMap { id, window in
window.map { QuotaWindow(id: id, window: $0) }
}
-
+
guard !windows.isEmpty else {
return nil
}
-
+
self.init(
limitId: limitId,
limitName: snapshot.limitName,
@@ -312,70 +310,51 @@ nonisolated extension QuotaWindow {
}
}
-nonisolated enum CodexRateLimitError: LocalizedError {
+nonisolated enum CodexStatusError: LocalizedError {
case executableNotFound
- case serverStartFailed(String)
- case serverTimeout(String)
- case serverConnectionClosed(String)
- case invalidServerResponse(String)
+ case serverTimeout
+ case serverConnectionClosed
+ case invalidServerResponse
case serverError(String)
- case missingRateLimitWindow
case notLoggedIn
- case authenticationRequired
-
+
var errorDescription: String? {
switch self {
case .executableNotFound:
return "找不到 Codex CLI 或 Codex APP"
- case .serverStartFailed(let message):
- 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 "暂未获取到数据"
- case .notLoggedIn:
- return "Codex 未登录"
- case .authenticationRequired:
- return "Codex 需要身份验证"
+ default:
+ return nil
}
}
-
+
+ /// codex app-server 目前通过 serverError 文案表示认证失败
var isAuthenticationRequired: Bool {
+ serverErrorMessageContains("authentication required")
+ }
+
+ var isUnsupportedUsageMethod: Bool {
+ serverErrorMessageContains("unknown variant")
+ || serverErrorMessageContains("method not found")
+ || serverErrorMessageContains("unknown method")
+ || serverErrorMessageContains("unsupported")
+ || serverErrorMessageContains("not supported")
+ }
+
+ /// 连接断开、超时、无法解析都需要重建 app-server 会话
+ var isTransportFailure: Bool {
switch self {
- case .serverError(let message):
- return message.localizedCaseInsensitiveContains("authentication required")
- case .authenticationRequired:
+ case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:
return true
default:
return false
}
}
-
- var isUnsupportedUsageMethod: Bool {
+
+ private func serverErrorMessageContains(_ keyword: String) -> 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 {
- case .notLoggedIn:
- return true
- default:
- return isAuthenticationRequired
- }
+
+ return message.range(of: keyword, options: .caseInsensitive) != nil
}
}
diff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swift
deleted file mode 100644
index 2c88e98..0000000
--- a/CodexBar/CodexRateLimitService.swift
+++ /dev/null
@@ -1,514 +0,0 @@
-//
-// CodexRateLimitService.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
-import Foundation
-
-/// 与 codex app-server 维持一条常驻连接: 首次拉取时启动进程并完成握手
-/// 之后所有额度读取复用同一会话; 进程退出或请求失败时自动重建连接
-nonisolated final class CodexRateLimitService: @unchecked Sendable {
- private static let requestTimeout: TimeInterval = 20
- // 连接定期回收: 覆盖 codex 全局升级后换用新二进制
- private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
- // 进程环境在应用启动后不会变化, 只构建一次
- private static let environment = CodexCLIResolver.environment
-
- // 连接状态只在 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 in
- queue.async {
- continuation.resume(with: Result { try self.fetchRateLimitsOnQueue() })
- }
- }
- }
-
- func currentConnectionInfo() async -> CodexCLIConnectionInfo? {
- await withCheckedContinuation { continuation in
- queue.async {
- continuation.resume(returning: self.currentConnectionInfoOnQueue())
- }
- }
- }
-
- private func fetchRateLimitsOnQueue() throws -> CodexQuotaSnapshot {
- do {
- let (connection, reused) = try ensureConnection()
- do {
- return try Self.fetchSnapshot(using: connection)
- } catch where reused && !((error as? CodexRateLimitError)?.requiresLogin ?? false) {
- // 复用的连接可能已失效 (进程退出、管道断开), 重建一次再试;
- // 全新连接上的失败直接抛出, 避免故障时整套握手做两遍
- teardownConnection()
- return try Self.fetchSnapshot(using: ensureConnection().connection)
- }
- } catch let error as CodexRateLimitError where error.requiresLogin {
- // 凭证失效/已登出: 丢弃旧连接, 用户重新登录后下次轮询起新进程读取最新凭证
- teardownConnection()
- 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 CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)
- let newConnection = try Self.openConnection(
- command: command,
- environment: Self.environment,
- clientVersion: Self.clientVersion(),
- timeout: Self.requestTimeout
- )
-
- connection = newConnection
- return (newConnection, reused: false)
- }
-
- private func teardownConnection() {
- connection?.session.close()
- connection = nil
- }
-
- private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {
- guard let connection, connection.session.process.isRunning else {
- return nil
- }
-
- return connection.commandInfo
- }
-
- private static func fetchSnapshot(using connection: AppServerConnection) throws -> CodexQuotaSnapshot {
- func readRateLimits() throws -> AccountRateLimitsResponse {
- try connection.session.request(
- "account/rateLimits/read",
- as: AccountRateLimitsResponse.self
- )
- }
-
- let rateLimitsResponse: AccountRateLimitsResponse
- do {
- rateLimitsResponse = try readRateLimits()
- } catch let error as CodexRateLimitError where error.isAuthenticationRequired {
- connection.accountResponse = try connection.session.request(
- "account/read",
- params: ["refreshToken": true],
- as: AccountReadResponse.self
- )
-
- do {
- rateLimitsResponse = try readRateLimits()
- } catch let retryError as CodexRateLimitError where retryError.isAuthenticationRequired {
- throw CodexRateLimitError.authenticationRequired
- }
- }
-
- 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,
- environment: [String: String],
- clientVersion: String,
- timeout: TimeInterval
- ) throws -> AppServerConnection {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: command.executablePath)
- process.arguments = command.arguments
- process.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 = standardInput
- process.standardOutput = standardOutput
- process.standardError = standardError
-
- do {
- try process.run()
- } catch {
- throw CodexRateLimitError.serverStartFailed(error.localizedDescription)
- }
- let openedAt = Date()
-
- let session = AppServerSession(
- process: process,
- input: standardInput,
- lineReader: lineReader,
- errorReader: errorReader,
- timeout: timeout
- )
-
- do {
- let initializeResult = try session.request(
- "initialize",
- params: [
- "clientInfo": [
- "name": "codex_bar",
- "title": "Codex Bar",
- "version": clientVersion
- ]
- ],
- as: InitializeResult.self
- )
-
- try session.notify("initialized")
-
- let accountResponse = try session.request(
- "account/read",
- params: ["refreshToken": false],
- as: AccountReadResponse.self
- )
-
- let commandInfo = CodexCLIConnectionInfo(
- source: command.source,
- executablePath: command.executablePath,
- version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),
- openedAt: openedAt
- )
-
- return AppServerConnection(
- session: session,
- accountResponse: accountResponse,
- commandInfo: commandInfo
- )
- } catch {
- session.close()
- throw error
- }
- }
-
- private nonisolated static func clientVersion() -> String {
- guard let version = Bundle.main.shortVersionString, !version.isEmpty else {
- return "1.0.0"
- }
-
- return version
- }
-
- /// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号
- private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {
- guard let firstToken = userAgent?.split(separator: " ").first,
- let slashIndex = firstToken.firstIndex(of: "/") else {
- return nil
- }
-
- let version = firstToken[firstToken.index(after: slashIndex)...]
- return version.isEmpty ? nil : String(version)
- }
-}
-
-private nonisolated final class AppServerConnection {
- let session: AppServerSession
- let commandInfo: CodexCLIConnectionInfo
- var accountResponse: AccountReadResponse
- var isUsageReadAvailable = true
-
- var openedAt: Date { commandInfo.openedAt }
-
- init(
- session: AppServerSession,
- accountResponse: AccountReadResponse,
- commandInfo: CodexCLIConnectionInfo
- ) {
- self.session = session
- self.accountResponse = accountResponse
- self.commandInfo = commandInfo
- }
-}
-
-private nonisolated final class AppServerSession {
- let process: Process
-
- private let input: Pipe
- private let lineReader: JSONLineReader
- private let errorReader: PipeDrain
- private let timeout: TimeInterval
- private var nextId = 1
-
- init(
- process: Process,
- input: Pipe,
- lineReader: JSONLineReader,
- errorReader: PipeDrain,
- timeout: TimeInterval
- ) {
- self.process = process
- self.input = input
- self.lineReader = lineReader
- self.errorReader = errorReader
- self.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), step: method)
- }
-
- func request<Response: Decodable>(
- _ method: String,
- params: [String: Any]? = nil,
- as type: Response.Type
- ) throws -> Response {
- let id = nextId
- nextId += 1
- 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 {
- object["id"] = id
- }
- if let params {
- object["params"] = params
- }
- return object
- }
-
- private func write(_ object: [String: Any], step: String) throws {
- var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
- data.append(0x0A)
-
- do {
- try input.fileHandleForWriting.write(contentsOf: data)
- } catch {
- throw CodexRateLimitError.serverConnectionClosed(step)
- }
- }
-
- private func waitForResponse<Response: Decodable>(
- id: Int,
- step: String,
- decode type: Response.Type
- ) 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),
- let error = errorEnvelope.error {
- throw CodexRateLimitError.serverError(error.message)
- }
-
- guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: data),
- let result = envelope.result else {
- throw CodexRateLimitError.invalidServerResponse(step)
- }
-
- return result
- }
-
- throw CodexRateLimitError.serverTimeout(step)
- }
-}
-
-private nonisolated struct InitializeResult: Decodable {
- let userAgent: String?
-}
-
-private nonisolated struct RPCIDEnvelope: Decodable {
- let id: Int?
-}
-
-private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
- let id: Int?
- let result: Response?
-}
-
-private nonisolated struct RPCErrorEnvelope: Decodable {
- let id: Int?
- let error: RPCError?
-}
-
-private nonisolated struct RPCError: Decodable {
- let message: String
-}
-
-private nonisolated final class JSONLineReader: @unchecked Sendable {
- private let lock = NSLock()
- private let semaphore = DispatchSemaphore(value: 0)
- private let fileHandle: FileHandle
- private var buffer = Data()
- private var lines: [String] = []
- private var closed = false
-
- init(fileHandle: FileHandle) {
- self.fileHandle = fileHandle
- fileHandle.readabilityHandler = { [weak self] handle in
- let data = handle.availableData
- guard !data.isEmpty else {
- handle.readabilityHandler = nil
- self?.markClosed()
- return
- }
- self?.append(data)
- }
- }
-
- 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) {
- 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 {
- lines.append(line)
- semaphore.signal()
- }
- }
- }
-
- 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 = fileHandle
- fileHandle.readabilityHandler = { handle in
- guard !handle.availableData.isEmpty else {
- handle.readabilityHandler = nil
- return
- }
- }
- }
-
- func stop() {
- fileHandle.readabilityHandler = nil
- }
-}
diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/CodexStatusMenuView.swift
similarity index 71%
rename from CodexBar/RateLimitsMenuView.swift
rename to CodexBar/CodexStatusMenuView.swift
index 0814206..4dcdc82 100644
--- a/CodexBar/RateLimitsMenuView.swift
+++ b/CodexBar/CodexStatusMenuView.swift
@@ -1,10 +1,3 @@
-//
-// RateLimitsMenuView.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import Combine
import SwiftUI
@@ -13,31 +6,28 @@ final class PopoverVisibilityState: ObservableObject {
@Published var isVisible = false
}
-struct RateLimitsMenuView: View {
+struct CodexStatusMenuView: View {
static let menuWidth: CGFloat = Metrics.padding * 2 + Metrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth
-
- @ObservedObject var viewModel: RateLimitsViewModel
+
+ @ObservedObject var viewModel: CodexStatusViewModel
@ObservedObject var popoverVisibility: PopoverVisibilityState
@EnvironmentObject private var appUpdater: AppUpdater
@State private var isEmailBlurred = false
-
+
var body: some View {
VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {
content
- // 未登录已有专属橙色提示, 不再重复显示同文案的红色错误行
- errorView(viewModel.requiresLogin ? nil : viewModel.errorMessage)
}
.padding(Metrics.padding)
.liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, tint: .cyan, isOuterSurface: true)
- .animation(Metrics.statusAnimation, value: viewModel.requiresLogin)
- .animation(Metrics.statusAnimation, value: viewModel.errorMessage)
+ .animation(Metrics.statusAnimation, value: viewModel.loadState)
.onChange(of: viewModel.snapshot?.account.email) { _, _ in
isEmailBlurred = false
}
}
}
-private extension RateLimitsMenuView {
+private extension CodexStatusMenuView {
enum Metrics {
static let padding: CGFloat = 12
static let panelPadding: CGFloat = 10
@@ -48,78 +38,110 @@ private extension RateLimitsMenuView {
static let loadingVerticalPadding: CGFloat = 16
static let statusAnimation = Animation.codexStatus
}
-
+
@ViewBuilder
var content: some View {
- if viewModel.requiresLogin {
- loginRequiredNotice
- .transition(.opacity)
- }
-
if let snapshot = viewModel.snapshot {
- Group {
- accountCard(
- title: snapshot.accountLabel,
- 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)
- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .mint)
- }
- // 未登录时旧数据已过期, 置灰提示不可信
- .opacity(viewModel.requiresLogin ? 0.4 : 1)
+ accountCard(
+ title: snapshot.accountLabel,
+ isEmail: snapshot.account.hasEmail,
+ plan: snapshot.planLabel
+ )
+
+ dataSection(snapshot)
} else {
- accountCard(title: "")
+ // 仅展示未登录 / 初始化失败两种特殊状态, 其余错误只进日志
+ statusAccountCard
emptyView
.padding(Metrics.panelPadding)
.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
}
}
-
- var loginRequiredNotice: some View {
+
+ @ViewBuilder
+ func dataSection(_ snapshot: CodexQuotaSnapshot) -> some View {
+ if snapshot.limits.isEmpty, snapshot.usage == nil {
+ emptyView
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+ } else {
+ if !snapshot.limits.isEmpty {
+ quotaLimitsView(snapshot.limits)
+ }
+
+ if let usage = snapshot.usage {
+ UsageSummaryView(usage: usage)
+ }
+ }
+
+ updatedAtRow(for: snapshot)
+ .padding(.horizontal, Metrics.panelPadding)
+ .padding(.vertical, 7)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .mint)
+ }
+
+ var statusAccountCard: 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)
-
+ Image(systemName: "person.fill")
+ .font(.system(size: Metrics.accountIconSize, weight: .medium))
+ .foregroundStyle(statusDisplay.color)
+ .onTapGesture(count: 2) {
+ viewModel.refresh()
+ }
+
+ if let text = statusDisplay.text {
+ Text(text)
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(statusDisplay.color)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+
+ if viewModel.isRefreshing {
+ ProgressView()
+ .controlSize(.mini)
+ .padding(.leading, 2)
+ }
+
Spacer()
}
+ .padding(.horizontal, Metrics.panelPadding)
+ .padding(.vertical, 8)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
}
-
+
+ var statusDisplay: (text: String?, color: Color) {
+ switch viewModel.loadState {
+ case .notLoggedIn:
+ return ("未登录", .orange)
+ case .initializationFailed:
+ return ("初始化失败", .red)
+ case .loading, .loaded:
+ return (nil, .accentColor)
+ }
+ }
+
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 in
if 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)
@@ -127,7 +149,7 @@ private extension RateLimitsMenuView {
.foregroundStyle(.primary)
.lineLimit(1)
.truncationMode(.middle)
-
+
VStack(spacing: 8) {
ForEach(limit.windows) { window in
QuotaRow(window: window)
@@ -135,14 +157,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")
@@ -151,7 +173,7 @@ private extension RateLimitsMenuView {
.onTapGesture(count: 2) {
viewModel.refresh()
}
-
+
Text(title)
.font(.caption.weight(.semibold))
.lineLimit(1)
@@ -162,18 +184,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.weight(.bold))
.foregroundStyle(tint)
@@ -181,7 +203,7 @@ private extension RateLimitsMenuView {
}
}
}
-
+
func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {
HStack {
HStack(spacing: 5) {
@@ -191,10 +213,10 @@ private extension RateLimitsMenuView {
isActive: popoverVisibility.isVisible,
color: .blue
)
-
+
Text("数据更新时间")
.foregroundStyle(Self.secondaryTextColor)
-
+
Text(Self.timeFormatter.string(from: snapshot.generatedAt))
.monospacedDigit()
.contentTransition(.numericText())
@@ -202,9 +224,9 @@ private extension RateLimitsMenuView {
}
.font(.caption2)
.animation(Metrics.statusAnimation, value: snapshot.generatedAt)
-
+
Spacer()
-
+
if let message = appUpdater.panelUpdateMessage {
Text(message)
.font(.caption2.monospacedDigit())
@@ -219,57 +241,30 @@ private extension RateLimitsMenuView {
}
.animation(Metrics.statusAnimation, value: appUpdater.panelUpdateMessage)
}
-
- @ViewBuilder
- func errorView(_ message: String?) -> some View {
- if let message {
- Text(message)
- .font(.caption)
- .foregroundStyle(.red)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- .contentTransition(.opacity)
- .transition(.opacity)
- }
- }
-
+
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
+ return Self.planTintRules.first { rule in
+ rule.keywords.contains { normalizedPlan.contains($0) }
+ }?.tint ?? .cyan
}
-
+
+ static let planTintRules: [(keywords: [String], tint: Color)] = [
+ (["enterprise"], .green),
+ (["team", "business"], .orange),
+ (["pro"], .purple),
+ (["plus"], .blue),
+ (["edu"], .teal),
+ (["free"], .secondary)
+ ]
+
static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "HH:mm:ss"
return formatter
}()
-
+
static let secondaryTextColor = Color.codexSecondaryLabel
}
@@ -278,7 +273,7 @@ private struct AutoRefreshCountdownTimeline: View {
let interval: TimeInterval
let isActive: Bool
let color: Color
-
+
var body: some View {
if isActive {
TimelineView(.periodic(from: .now, by: 1)) { timeline in
@@ -288,7 +283,7 @@ private struct AutoRefreshCountdownTimeline: View {
circle(now: Date())
}
}
-
+
private func circle(now: Date) -> AutoRefreshCountdownCircle {
AutoRefreshCountdownCircle(
startedAt: startedAt,
@@ -306,21 +301,21 @@ private struct AutoRefreshCountdownCircle: View {
let now: Date
let isActive: Bool
let color: Color
-
+
private var progress: Double {
guard interval > 0 else {
return 0
}
-
+
let elapsed = max(0, now.timeIntervalSince(startedAt))
return max(0, 1 - elapsed / interval)
}
-
+
var body: some View {
ZStack {
Circle()
.stroke(color.opacity(0.15), lineWidth: 1.4)
-
+
Circle()
.trim(from: 1 - progress, to: 1)
.stroke(
@@ -330,11 +325,10 @@ private struct AutoRefreshCountdownCircle: View {
.rotationEffect(.degrees(-90))
}
.frame(width: 8, height: 8)
- // 仅在 startedAt 变化(刷新重置)时播放恢复动画; 普通 tick 只改 now/progress, 直接跳变。
- // popover 隐藏(isActive == false)时不开启动画事务, 避免不可见状态下的无谓渲染。
+ // 只让刷新起点变化触发动画, 避免每秒 tick 被补间
.animation(isActive ? .linear(duration: Metrics.resetAnimationDuration) : nil, value: startedAt)
}
-
+
private enum Metrics {
static let resetAnimationDuration: TimeInterval = 0.50
}
diff --git a/CodexBar/CodexStatusService.swift b/CodexBar/CodexStatusService.swift
new file mode 100644
index 0000000..71db524
--- /dev/null
+++ b/CodexBar/CodexStatusService.swift
@@ -0,0 +1,707 @@
+import Foundation
+
+/// UI 只关心可展示数据、未登录、初始化失败; 更细的错误保留在交互日志中
+nonisolated enum CodexFetchOutcome {
+ case data(CodexQuotaSnapshot)
+ case notLoggedIn
+ case initializationFailed
+}
+
+private enum ConnectionResolution {
+ case ready(connection: AppServerConnection, reused: Bool)
+ case notLoggedIn
+ case initializationFailed
+}
+
+/// 单接口读取结果按后续动作分类: 跳过、刷新认证、重建连接
+private enum ReadResult<Value> {
+ case value(Value)
+ case skipped
+ case authRequired
+ case broken
+}
+
+private enum FetchFailure: Error {
+ case notLoggedIn
+ case needsRebuild
+}
+
+nonisolated private extension ReadResult {
+ var isAuthenticationRequired: Bool {
+ if case .authRequired = self {
+ return true
+ }
+ return false
+ }
+
+ func valueAfterAuthAttempt() throws -> Value? {
+ switch self {
+ case .value(let value):
+ return value
+ case .skipped:
+ return nil
+ case .authRequired:
+ throw FetchFailure.notLoggedIn
+ case .broken:
+ throw FetchFailure.needsRebuild
+ }
+ }
+}
+
+/// 维持一条 codex app-server stdio 会话, 复用失败后按需重建
+nonisolated final class CodexStatusService: @unchecked Sendable {
+ private static let requestTimeout: TimeInterval = 20
+ // 定期回收连接, 让后台升级后的 codex 二进制有机会生效
+ private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
+ private static let environment = CodexCLIResolver.environment
+
+ // connection 只在这个队列上访问
+ private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)
+ private var connection: AppServerConnection?
+
+ // app-server 退出后继续写管道会触发 SIGPIPE; 忽略信号, 让 write 抛错后走重建
+ private static let ignoreBrokenPipeSignal: Void = {
+ signal(SIGPIPE, SIG_IGN)
+ }()
+
+ init() {
+ _ = Self.ignoreBrokenPipeSignal
+ }
+
+ deinit {
+ connection?.session.close()
+ }
+
+ func fetchOutcome() async -> CodexFetchOutcome {
+ await withCheckedContinuation { continuation in
+ queue.async {
+ continuation.resume(returning: self.resolveOutcomeOnQueue(allowRebuild: true))
+ }
+ }
+ }
+
+ func currentConnectionInfo() async -> CodexCLIConnectionInfo? {
+ await withCheckedContinuation { continuation in
+ queue.async {
+ continuation.resume(returning: self.currentConnectionInfoOnQueue())
+ }
+ }
+ }
+
+ /// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
+ private func resolveOutcomeOnQueue(allowRebuild: Bool) -> CodexFetchOutcome {
+ switch ensureConnection() {
+ case .notLoggedIn:
+ return .notLoggedIn
+ case .initializationFailed:
+ return .initializationFailed
+ case .ready(let connection, let reused):
+ do {
+ let snapshot = try Self.fetchData(using: connection, refreshAccountInfo: reused)
+ return .data(snapshot)
+ } catch FetchFailure.notLoggedIn {
+ teardownConnection()
+ return .notLoggedIn
+ } catch FetchFailure.needsRebuild {
+ teardownConnection()
+ if reused && allowRebuild {
+ return resolveOutcomeOnQueue(allowRebuild: false)
+ }
+ return .initializationFailed
+ } catch {
+ teardownConnection()
+ return .initializationFailed
+ }
+ }
+ }
+
+ private func ensureConnection() -> ConnectionResolution {
+ if let connection, connection.session.process.isRunning,
+ Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {
+ return .ready(connection: connection, reused: true)
+ }
+
+ teardownConnection()
+
+ let command: AppServerCommand
+ do {
+ command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)
+ } catch {
+ RequestLogStore.shared.recordFailure(message: error.localizedDescription)
+ return .initializationFailed
+ }
+
+ let resolution = Self.openConnection(
+ command: command,
+ environment: Self.environment,
+ clientVersion: Self.clientVersion(),
+ timeout: Self.requestTimeout
+ )
+ if case .ready(let newConnection, _) = resolution {
+ connection = newConnection
+ }
+ return resolution
+ }
+
+ private func teardownConnection() {
+ connection?.session.close()
+ connection = nil
+ }
+
+ private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {
+ guard let connection, connection.session.process.isRunning else {
+ return nil
+ }
+
+ return connection.commandInfo
+ }
+
+ /// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接
+ private static func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {
+ var didRefresh = false
+
+ func refreshTokenIfNeeded() throws {
+ guard !didRefresh else { throw FetchFailure.notLoggedIn }
+ didRefresh = true
+ try refreshAccount(using: connection)
+ }
+
+ func readWithAuthRefresh<Value>(_ read: () -> ReadResult<Value>) throws -> Value? {
+ let firstAttempt = read()
+ guard firstAttempt.isAuthenticationRequired else {
+ return try firstAttempt.valueAfterAuthAttempt()
+ }
+
+ try refreshTokenIfNeeded()
+ return try read().valueAfterAuthAttempt()
+ }
+
+ // 新建连接已读过 account; 复用连接才刷新账户状态
+ if refreshAccountInfo {
+ if let response: AccountReadResponse = try readWithAuthRefresh({
+ read("account/read", params: ["refreshToken": false], using: connection, as: AccountReadResponse.self)
+ }) {
+ guard response.account != nil else { throw FetchFailure.notLoggedIn }
+ connection.accountResponse = response
+ }
+ }
+
+ let rateLimits: AccountRateLimitsResponse? = try readWithAuthRefresh({
+ read("account/rateLimits/read", using: connection, as: AccountRateLimitsResponse.self)
+ })
+
+ let usage: AccountUsageResponse? = try readWithAuthRefresh {
+ readUsage(using: connection)
+ }
+
+ // rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"
+ guard let snapshot = try? CodexQuotaSnapshot(
+ accountResponse: connection.accountResponse,
+ rateLimitsResponse: rateLimits,
+ usageResponse: usage
+ ) else {
+ throw FetchFailure.notLoggedIn
+ }
+
+ return snapshot
+ }
+
+ private static func read<Value: Decodable>(
+ _ method: String,
+ params: [String: Any]? = nil,
+ using connection: AppServerConnection,
+ as type: Value.Type
+ ) -> ReadResult<Value> {
+ do {
+ return .value(try connection.session.request(method, params: params, as: type))
+ } catch let error as CodexStatusError {
+ return classify(error)
+ } catch {
+ return .broken
+ }
+ }
+
+ private static func readUsage(using connection: AppServerConnection) -> ReadResult<AccountUsageResponse> {
+ guard connection.isUsageReadAvailable else {
+ return .skipped
+ }
+
+ do {
+ return .value(try connection.session.request("account/usage/read", as: AccountUsageResponse.self))
+ } catch let error as CodexStatusError where error.isUnsupportedUsageMethod {
+ // 老版本 codex 不支持该方法时, 后续轮询不再请求 usage
+ connection.isUsageReadAvailable = false
+ return .skipped
+ } catch let error as CodexStatusError {
+ return classify(error)
+ } catch {
+ return .broken
+ }
+ }
+
+ private static func classify<Value>(_ error: CodexStatusError) -> ReadResult<Value> {
+ if error.isAuthenticationRequired {
+ return .authRequired
+ }
+ // 非认证的业务错误不阻断整轮刷新, 详情只保留在日志中
+ return error.isTransportFailure ? .broken : .skipped
+ }
+
+ private static func refreshAccount(using connection: AppServerConnection) throws {
+ let response: AccountReadResponse
+ do {
+ response = try connection.session.request(
+ "account/read",
+ params: ["refreshToken": true],
+ as: AccountReadResponse.self
+ )
+ } catch let error as CodexStatusError {
+ throw error.isTransportFailure ? FetchFailure.needsRebuild : FetchFailure.notLoggedIn
+ } catch {
+ throw FetchFailure.needsRebuild
+ }
+
+ connection.accountResponse = response
+ if response.account == nil {
+ throw FetchFailure.notLoggedIn
+ }
+ }
+
+ /// 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程
+ private static func openConnection(
+ command: AppServerCommand,
+ environment: [String: String],
+ clientVersion: String,
+ timeout: TimeInterval
+ ) -> ConnectionResolution {
+ let process = Process()
+ process.executableURL = URL(fileURLWithPath: command.executablePath)
+ process.arguments = command.arguments
+ process.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 = standardInput
+ process.standardOutput = standardOutput
+ process.standardError = standardError
+
+ do {
+ try process.run()
+ } catch {
+ RequestLogStore.shared.recordFailure(message: "app-server 启动失败: \(error.localizedDescription)")
+ return .initializationFailed
+ }
+ let openedAt = Date()
+
+ let session = AppServerSession(
+ process: process,
+ input: standardInput,
+ lineReader: lineReader,
+ errorReader: errorReader,
+ timeout: timeout
+ )
+
+ do {
+ let initializeResult = try session.request(
+ "initialize",
+ params: [
+ "clientInfo": [
+ "name": "codex_bar",
+ "title": "Codex Bar",
+ "version": clientVersion
+ ]
+ ],
+ as: InitializeResult.self
+ )
+
+ try session.notify("initialized")
+
+ let accountResponse = try session.request(
+ "account/read",
+ params: ["refreshToken": false],
+ as: AccountReadResponse.self
+ )
+
+ guard accountResponse.account != nil else {
+ session.close()
+ return .notLoggedIn
+ }
+
+ let commandInfo = CodexCLIConnectionInfo(
+ source: command.source,
+ executablePath: command.executablePath,
+ version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),
+ openedAt: openedAt
+ )
+
+ return .ready(
+ connection: AppServerConnection(
+ session: session,
+ accountResponse: accountResponse,
+ commandInfo: commandInfo
+ ),
+ reused: false
+ )
+ } catch {
+ session.close()
+ return .initializationFailed
+ }
+ }
+
+ private nonisolated static func clientVersion() -> String {
+ guard let version = Bundle.main.shortVersionString, !version.isEmpty else {
+ return "1.0.0"
+ }
+
+ return version
+ }
+
+ /// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号
+ private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {
+ guard let firstToken = userAgent?.split(separator: " ").first,
+ let slashIndex = firstToken.firstIndex(of: "/") else {
+ return nil
+ }
+
+ let version = firstToken[firstToken.index(after: slashIndex)...]
+ return version.isEmpty ? nil : String(version)
+ }
+}
+
+private nonisolated final class AppServerConnection {
+ let session: AppServerSession
+ let commandInfo: CodexCLIConnectionInfo
+ var accountResponse: AccountReadResponse
+ var isUsageReadAvailable = true
+
+ var openedAt: Date { commandInfo.openedAt }
+
+ init(
+ session: AppServerSession,
+ accountResponse: AccountReadResponse,
+ commandInfo: CodexCLIConnectionInfo
+ ) {
+ self.session = session
+ self.accountResponse = accountResponse
+ self.commandInfo = commandInfo
+ }
+}
+
+private nonisolated final class AppServerSession {
+ let process: Process
+
+ private typealias EncodedMessage = (data: Data, text: String)
+ private typealias ResponseLine = (text: String, data: Data)
+
+ private static let writeFailureMessage = "连接断开, 无法写入请求"
+ private static let responseConnectionClosedMessage = "连接断开, 等待响应失败"
+ private static let responseTimeoutMessage = "响应超时"
+
+ private let input: Pipe
+ private let lineReader: JSONLineReader
+ private let errorReader: PipeDrain
+ private let timeout: TimeInterval
+ private var nextId = 1
+
+ init(
+ process: Process,
+ input: Pipe,
+ lineReader: JSONLineReader,
+ errorReader: PipeDrain,
+ timeout: TimeInterval
+ ) {
+ self.process = process
+ self.input = input
+ self.lineReader = lineReader
+ self.errorReader = errorReader
+ self.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 {
+ let encoded = try encodeMessage(method: method, id: nil, params: params)
+
+ try writeEncoded(encoded) {
+ RequestLogStore.shared.recordFailure(method: method, message: Self.writeFailureMessage)
+ }
+ RequestLogStore.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)
+ }
+
+ func request<Response: Decodable>(
+ _ method: String,
+ params: [String: Any]? = nil,
+ as type: Response.Type
+ ) throws -> Response {
+ let id = nextId
+ nextId += 1
+ let encoded = try encodeMessage(method: method, id: id, params: params)
+ let token = RequestLogStore.shared.beginRequest(method: method, payload: encoded.text)
+
+ try writeEncoded(encoded) {
+ RequestLogStore.shared.failRequest(token, message: Self.writeFailureMessage)
+ }
+
+ return try waitForResponse(id: id, token: token, decode: type)
+ }
+
+ private func encodeMessage(method: String, id: Int?, params: [String: Any]?) throws -> EncodedMessage {
+ try encode(message(method: method, id: id, params: params))
+ }
+
+ private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {
+ var object: [String: Any] = ["method": method]
+ if let id {
+ object["id"] = id
+ }
+ if let params {
+ object["params"] = params
+ }
+ return object
+ }
+
+ private func encode(_ object: [String: Any]) throws -> EncodedMessage {
+ let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])
+ return (data, String(decoding: data, as: UTF8.self))
+ }
+
+ private func writeEncoded(_ encoded: EncodedMessage, onFailure: () -> Void) throws {
+ do {
+ try writeData(encoded.data)
+ } catch {
+ onFailure()
+ throw CodexStatusError.serverConnectionClosed
+ }
+ }
+
+ private func writeData(_ data: Data) throws {
+ var payload = data
+ payload.append(0x0A)
+ try input.fileHandleForWriting.write(contentsOf: payload)
+ }
+
+ private func waitForResponse<Response: Decodable>(
+ id: Int,
+ token: UUID,
+ decode type: Response.Type
+ ) throws -> Response {
+ let deadline = Date().addingTimeInterval(timeout)
+ let decoder = JSONDecoder()
+
+ while Date() < deadline {
+ guard let line = try nextResponseLine(
+ matching: id,
+ before: deadline,
+ token: token,
+ decoder: decoder
+ ) else {
+ continue
+ }
+
+ let result = try decodeResponse(line, as: type, token: token, decoder: decoder)
+ RequestLogStore.shared.finishRequest(token, response: line.text)
+ return result
+ }
+
+ try failRequest(token, message: Self.responseTimeoutMessage, error: .serverTimeout)
+ }
+
+ private func nextResponseLine(
+ matching id: Int,
+ before deadline: Date,
+ token: UUID,
+ decoder: JSONDecoder
+ ) throws -> ResponseLine? {
+ guard let text = lineReader.nextLine(timeout: max(0, deadline.timeIntervalSinceNow)) else {
+ if lineReader.isClosed {
+ try failRequest(token, message: Self.responseConnectionClosedMessage, error: .serverConnectionClosed)
+ }
+
+ return nil
+ }
+
+ guard let data = text.data(using: .utf8),
+ let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),
+ idEnvelope.id == id else {
+ return nil
+ }
+
+ return (text, data)
+ }
+
+ private func decodeResponse<Response: Decodable>(
+ _ line: ResponseLine,
+ as type: Response.Type,
+ token: UUID,
+ decoder: JSONDecoder
+ ) throws -> Response {
+ if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: line.data),
+ let error = errorEnvelope.error {
+ try failRequest(token, message: line.text, error: .serverError(error.message))
+ }
+
+ guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data),
+ let result = envelope.result else {
+ try failRequest(token, message: line.text, error: .invalidServerResponse)
+ }
+
+ return result
+ }
+
+ private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {
+ RequestLogStore.shared.failRequest(token, message: message)
+ throw error
+ }
+}
+
+private nonisolated struct InitializeResult: Decodable {
+ let userAgent: String?
+}
+
+private nonisolated struct RPCIDEnvelope: Decodable {
+ let id: Int?
+}
+
+private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
+ let id: Int?
+ let result: Response?
+}
+
+private nonisolated struct RPCErrorEnvelope: Decodable {
+ let id: Int?
+ let error: RPCError?
+}
+
+private nonisolated struct RPCError: Decodable {
+ let message: String
+}
+
+private nonisolated final class JSONLineReader: @unchecked Sendable {
+ private let lock = NSLock()
+ private let semaphore = DispatchSemaphore(value: 0)
+ private let fileHandle: FileHandle
+ private var buffer = Data()
+ private var lines: [String] = []
+ private var closed = false
+
+ init(fileHandle: FileHandle) {
+ self.fileHandle = fileHandle
+ fileHandle.readabilityHandler = { [weak self] handle in
+ let data = handle.availableData
+ guard !data.isEmpty else {
+ handle.readabilityHandler = nil
+ self?.markClosed()
+ return
+ }
+ self?.append(data)
+ }
+ }
+
+ 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) {
+ 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 {
+ lines.append(line)
+ semaphore.signal()
+ }
+ }
+ }
+
+ 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 = fileHandle
+ fileHandle.readabilityHandler = { handle in
+ guard !handle.availableData.isEmpty else {
+ handle.readabilityHandler = nil
+ return
+ }
+ }
+ }
+
+ func stop() {
+ fileHandle.readabilityHandler = nil
+ }
+}
diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/CodexStatusViewModel.swift
similarity index 67%
rename from CodexBar/RateLimitsViewModel.swift
rename to CodexBar/CodexStatusViewModel.swift
index d0f09c3..626bfc1 100644
--- a/CodexBar/RateLimitsViewModel.swift
+++ b/CodexBar/CodexStatusViewModel.swift
@@ -1,99 +1,104 @@
-//
-// RateLimitsViewModel.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import Combine
import Foundation
+/// UI 级状态; 更细的连接和接口错误由服务层归并到日志
+nonisolated enum CodexLoadState: Equatable {
+ case loading
+ case loaded
+ case notLoggedIn
+ case initializationFailed
+
+ var isError: Bool { self == .notLoggedIn || self == .initializationFailed }
+}
+
@MainActor
-final class RateLimitsViewModel: ObservableObject {
+final class CodexStatusViewModel: ObservableObject {
@Published private(set) var snapshot: CodexQuotaSnapshot?
@Published private(set) var isRefreshing = false
- @Published private(set) var lastError: CodexRateLimitError?
+ @Published private(set) var loadState: CodexLoadState = .loading
@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?
@Published private(set) var autoRefreshCountdownStartedAt: Date?
-
- // UI 状态统一从 lastError 派生, 保证单一真相来源
- var errorMessage: String? { lastError?.errorDescription }
- var requiresLogin: Bool { lastError?.requiresLogin ?? false }
- var hasError: Bool { lastError != nil }
+
+ var hasError: Bool { loadState.isError }
var autoRefreshInterval: TimeInterval { Self.refreshInterval }
-
+
private static let refreshInterval: TimeInterval = 60
-
- private let service: CodexRateLimitService
+
+ private let service: CodexStatusService
private var autoRefreshTask: Task<Void, Never>?
-
- init(service: CodexRateLimitService = CodexRateLimitService()) {
+
+ init(service: CodexStatusService = CodexStatusService()) {
self.service = service
}
-
+
deinit {
autoRefreshTask?.cancel()
}
-
+
func refreshIfNeeded() {
guard Date().timeIntervalSince(autoRefreshCountdownStartedAt ?? .distantPast) > Self.refreshInterval else {
return
}
-
+
refresh()
}
-
+
func startAutoRefresh() {
guard autoRefreshTask == nil else {
return
}
-
+
autoRefreshTask = Task { [weak self] in
self?.refreshIfNeeded()
-
+
while !Task.isCancelled {
let delay = self?.autoRefreshDelay ?? Self.refreshInterval
if (try? await Task.sleep(for: .seconds(delay))) == nil {
break
}
-
+
self?.refreshIfNeeded()
}
}
}
-
+
func refresh() {
guard !isRefreshing else {
return
}
-
+
isRefreshing = true
-
+
Task {
- do {
- self.snapshot = try await service.fetchRateLimits()
- self.lastError = nil
- } catch {
- self.lastError = (error as? CodexRateLimitError) ?? .serverError(error.localizedDescription)
+ switch await service.fetchOutcome() {
+ case .data(let snapshot):
+ self.snapshot = snapshot
+ self.loadState = .loaded
+ case .notLoggedIn:
+ self.snapshot = nil
+ self.loadState = .notLoggedIn
+ case .initializationFailed:
+ self.snapshot = nil
+ self.loadState = .initializationFailed
}
-
+
self.codexConnectionInfo = await service.currentConnectionInfo()
self.autoRefreshCountdownStartedAt = Date()
self.isRefreshing = false
}
}
-
+
func refreshCodexConnectionInfo() {
Task {
self.codexConnectionInfo = await service.currentConnectionInfo()
}
}
-
+
private var autoRefreshDelay: TimeInterval {
guard let autoRefreshCountdownStartedAt else {
return Self.refreshInterval
}
-
+
let remaining = Self.refreshInterval - Date().timeIntervalSince(autoRefreshCountdownStartedAt)
return max(1, remaining)
}
diff --git a/CodexBar/HostingWindowController.swift b/CodexBar/HostingWindowController.swift
new file mode 100644
index 0000000..0cb3a87
--- /dev/null
+++ b/CodexBar/HostingWindowController.swift
@@ -0,0 +1,65 @@
+import AppKit
+
+/// 承载 SwiftUI 内容的单窗口控制器基类, 统一懒创建、居中与置顶逻辑
+@MainActor
+class HostingWindowController {
+ let screenProvider: () -> NSScreen?
+ private(set) var window: NSWindow?
+
+ init(screenProvider: @escaping () -> NSScreen?) {
+ self.screenProvider = screenProvider
+ }
+
+ func open() {
+ let target: NSWindow
+ if let window {
+ target = window
+ } else {
+ target = makeWindow()
+ target.isReleasedWhenClosed = false
+ // 重新打开时跟随到当前桌面, 避免把用户切回窗口旧桌面
+ target.collectionBehavior.insert(.moveToActiveSpace)
+ window = target
+ }
+
+ if !target.isVisible {
+ prepareForDisplay(target)
+ }
+
+ bringToFront(target)
+ }
+
+ func makeWindow() -> NSWindow {
+ fatalError("subclass must override makeWindow()")
+ }
+
+ func prepareForDisplay(_ window: NSWindow) {
+ center(window)
+ }
+
+ func bringToFront(_ window: NSWindow) {
+ if window.isMiniaturized {
+ window.deminiaturize(nil)
+ }
+
+ NSApplication.shared.activate()
+ window.makeKeyAndOrderFront(nil)
+ window.orderFrontRegardless()
+ }
+
+ func center(_ window: NSWindow) {
+ guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {
+ window.center()
+ return
+ }
+
+ let visibleFrame = screen.visibleFrame
+ let windowFrame = window.frame
+ window.setFrameOrigin(
+ NSPoint(
+ x: visibleFrame.midX - windowFrame.width / 2,
+ y: visibleFrame.midY - windowFrame.height / 2
+ )
+ )
+ }
+}
diff --git a/CodexBar/LiquidGlassStyle.swift b/CodexBar/LiquidGlassStyle.swift
index 994690d..b0dfaf1 100644
--- a/CodexBar/LiquidGlassStyle.swift
+++ b/CodexBar/LiquidGlassStyle.swift
@@ -1,21 +1,12 @@
-//
-// LiquidGlassStyle.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-14.
-//
-
import SwiftUI
extension Animation {
- /// 状态文案/徽章等淡入淡出的统一过渡动画
static let codexStatus = Animation.easeInOut(duration: 0.18)
}
extension Color {
- /// 主要文字色 (AppKit label),用于需要具体 Color 值而非 ShapeStyle 的场景
+ // 某些自定义 View 需要具体 Color, 不能直接使用 .primary/.secondary 这类 ShapeStyle
static let codexLabel = Color(nsColor: .labelColor)
- /// 次要文字色 (AppKit secondaryLabel)
static let codexSecondaryLabel = Color(nsColor: .secondaryLabelColor)
}
diff --git a/CodexBar/LogView.swift b/CodexBar/LogView.swift
new file mode 100644
index 0000000..35d8386
--- /dev/null
+++ b/CodexBar/LogView.swift
@@ -0,0 +1,229 @@
+import SwiftUI
+
+struct LogView: View {
+ @ObservedObject var store: RequestLogStore
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider()
+
+ if store.entries.isEmpty {
+ emptyState
+ } else {
+ logList
+ }
+ }
+ .frame(minWidth: 640, minHeight: 480)
+ }
+
+ private var header: some View {
+ HStack(spacing: 10) {
+ Image(systemName: "doc.text.magnifyingglass")
+ .foregroundStyle(.tint)
+
+ Text("Codex 日志")
+ .font(.headline)
+
+ Text("\(store.entries.count)")
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 7)
+ .padding(.vertical, 2)
+ .background(Capsule().fill(.quaternary))
+
+ Spacer()
+
+ Button {
+ store.clear()
+ } label: {
+ Label("清空", systemImage: "trash")
+ }
+ .controlSize(.small)
+ .disabled(store.entries.isEmpty)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 10)
+ }
+
+ private var emptyState: some View {
+ VStack(spacing: 8) {
+ Image(systemName: "tray")
+ .font(.largeTitle)
+ .foregroundStyle(.tertiary)
+
+ Text("暂无日志")
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+
+ private var logList: some View {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(store.entries) { entry in
+ LogRow(entry: entry)
+ Divider()
+ }
+ }
+ }
+ .background(Color(nsColor: .textBackgroundColor))
+ }
+}
+
+private struct LogRow: View {
+ let entry: RequestLogEntry
+ @State private var isExpanded = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Button {
+ withAnimation(.snappy(duration: 0.18)) {
+ isExpanded.toggle()
+ }
+ } label: {
+ summary
+ }
+ .buttonStyle(.plain)
+
+ if isExpanded {
+ VStack(alignment: .leading, spacing: 8) {
+ if let request = entry.request {
+ payloadBlock(caption: requestCaption, time: entry.requestedAt, text: request, color: .primary)
+ }
+
+ if let detail = entry.detail {
+ payloadBlock(
+ caption: detailCaption,
+ time: entry.respondedAt,
+ text: detail,
+ color: entry.kind == .failure ? .red : .primary
+ )
+ } else if entry.kind == .pending {
+ Text("等待响应…")
+ .font(.caption.monospaced())
+ .foregroundStyle(.secondary)
+ }
+ }
+ .padding(.top, 6)
+ .padding(.leading, 20)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 8)
+ }
+
+ private var summary: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "chevron.right")
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(.secondary)
+ .rotationEffect(.degrees(isExpanded ? 90 : 0))
+ .frame(width: 12)
+
+ Text(Self.timeFormatter.string(from: entry.requestedAt))
+ .font(.caption.monospaced())
+ .foregroundStyle(.secondary)
+
+ Text(entry.kind.label)
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(entry.kind.tint)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 1)
+ .background(
+ RoundedRectangle(cornerRadius: 4, style: .continuous)
+ .fill(entry.kind.tint.opacity(0.14))
+ )
+
+ if let method = entry.method {
+ Text(method)
+ .font(.caption.weight(.medium).monospaced())
+ .foregroundStyle(.primary)
+ } else if let detail = entry.detail {
+ // 无方法名的记录(信息/进程级错误)直接预览正文, 避免标签后留空
+ Text(detail)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .truncationMode(.tail)
+ }
+
+ Spacer(minLength: 0)
+ }
+ .contentShape(Rectangle())
+ }
+
+ private func payloadBlock(caption: String, time: Date?, text: String, color: Color) -> some View {
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(caption)
+ .font(.caption2.weight(.semibold))
+ .foregroundStyle(.tertiary)
+
+ if let time {
+ Text(Self.timeFormatter.string(from: time))
+ .font(.caption2.monospaced())
+ .foregroundStyle(.tertiary)
+ }
+ }
+
+ Text(text)
+ .font(.caption.monospaced())
+ .foregroundStyle(color)
+ .textSelection(.enabled)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+
+ private var requestCaption: String {
+ "请求"
+ }
+
+ private var detailCaption: String {
+ switch entry.kind {
+ case .response, .emptyResponse:
+ return "响应"
+ case .failure:
+ return "错误"
+ default:
+ return "详情"
+ }
+ }
+
+ private static let timeFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.dateFormat = "HH:mm:ss.SSS"
+ return formatter
+ }()
+}
+
+private extension RequestLogEntry.Kind {
+ var label: String {
+ switch self {
+ case .pending:
+ return "进行"
+ case .response:
+ return "完成"
+ case .failure:
+ return "错误"
+ case .emptyResponse:
+ return "请求"
+ }
+ }
+
+ var tint: Color {
+ switch self {
+ case .pending:
+ return .orange
+ case .response:
+ return .green
+ case .failure:
+ return .red
+ case .emptyResponse:
+ return .blue
+ }
+ }
+}
diff --git a/CodexBar/LogWindowController.swift b/CodexBar/LogWindowController.swift
new file mode 100644
index 0000000..9e432d9
--- /dev/null
+++ b/CodexBar/LogWindowController.swift
@@ -0,0 +1,31 @@
+import AppKit
+import SwiftUI
+
+@MainActor
+final class LogWindowController: HostingWindowController {
+ private let store: RequestLogStore
+
+ init(
+ store: RequestLogStore = .shared,
+ screenProvider: @escaping () -> NSScreen?
+ ) {
+ self.store = store
+ super.init(screenProvider: screenProvider)
+ }
+
+ override func makeWindow() -> NSWindow {
+ let hostingController = NSHostingController(rootView: LogView(store: store))
+
+ let window = NSWindow(contentViewController: hostingController)
+ window.title = "CodexBar 日志"
+ window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
+ window.contentMinSize = Metrics.minimumContentSize
+ window.setContentSize(Metrics.defaultContentSize)
+ return window
+ }
+
+ private enum Metrics {
+ static let minimumContentSize = NSSize(width: 640, height: 480)
+ static let defaultContentSize = NSSize(width: 900, height: 680)
+ }
+}
diff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/LoginItemSettings.swift
index b5bc6ec..a03dce0 100644
--- a/CodexBar/LoginItemSettings.swift
+++ b/CodexBar/LoginItemSettings.swift
@@ -1,10 +1,3 @@
-//
-// LoginItemSettings.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import Combine
import Foundation
import ServiceManagement
diff --git a/CodexBar/QuotaRow.swift b/CodexBar/QuotaRow.swift
index 42c8f8a..18a33e2 100644
--- a/CodexBar/QuotaRow.swift
+++ b/CodexBar/QuotaRow.swift
@@ -1,10 +1,3 @@
-//
-// QuotaRow.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
import SwiftUI
struct QuotaRow: View {
diff --git a/CodexBar/RequestLog.swift b/CodexBar/RequestLog.swift
new file mode 100644
index 0000000..d39bebe
--- /dev/null
+++ b/CodexBar/RequestLog.swift
@@ -0,0 +1,170 @@
+import Combine
+import Foundation
+
+/// JSON-RPC 交互日志: 带 id 的请求先记录为进行, 响应或错误到达后回填到同一条
+/// `initialized` 这类无 id 请求没有响应可等, 单独记录为空响应
+nonisolated struct RequestLogEntry: Identifiable, Equatable {
+ enum Kind {
+ case pending
+ case response
+ case failure
+ case emptyResponse
+ }
+
+ let id: UUID
+ let requestedAt: Date
+ var respondedAt: Date?
+ var kind: Kind
+ let method: String?
+ let request: String?
+ var detail: String?
+}
+
+/// 常驻日志存储, 写入来自后台队列, storage 用锁保护, SwiftUI 通知切回主线程发送
+nonisolated final class RequestLogStore: ObservableObject, @unchecked Sendable {
+ static let shared = RequestLogStore()
+
+ // nonisolated 存储不能用 @Published 包装可变数组, 这里手动发送变更
+ let objectWillChange = ObservableObjectPublisher()
+
+ // 环形上限避免长时间运行后日志无限增长
+ private static let capacity = 500
+ private static let maxDetailLength = 4000
+
+ private let lock = NSLock()
+ // 最新在前, 既方便渲染也让刚发出的请求更快被回填
+ private var storage: [RequestLogEntry] = []
+
+ var entries: [RequestLogEntry] {
+ lock.lock()
+ defer { lock.unlock() }
+ return storage
+ }
+
+ private init() {}
+
+ func beginRequest(method: String, payload: String) -> UUID {
+ let id = UUID()
+ append(
+ RequestLogEntry(
+ id: id,
+ requestedAt: Date(),
+ respondedAt: nil,
+ kind: .pending,
+ method: method,
+ request: Self.normalized(payload),
+ detail: nil
+ )
+ )
+ return id
+ }
+
+ func finishRequest(_ id: UUID, response: String) {
+ update(id) { entry in
+ entry.kind = .response
+ entry.detail = Self.normalized(response)
+ entry.respondedAt = Date()
+ }
+ }
+
+ func failRequest(_ id: UUID, message: String) {
+ update(id) { entry in
+ entry.kind = .failure
+ entry.detail = Self.normalized(message)
+ entry.respondedAt = Date()
+ }
+ }
+
+ func recordRequestWithEmptyResponse(method: String, payload: String) {
+ append(
+ RequestLogEntry(
+ id: UUID(),
+ requestedAt: Date(),
+ respondedAt: nil,
+ kind: .emptyResponse,
+ method: method,
+ request: Self.normalized(payload),
+ detail: ""
+ )
+ )
+ }
+
+ func recordFailure(method: String? = nil, message: String) {
+ append(
+ RequestLogEntry(
+ id: UUID(),
+ requestedAt: Date(),
+ respondedAt: nil,
+ kind: .failure,
+ method: method,
+ request: nil,
+ detail: Self.normalized(message)
+ )
+ )
+ }
+
+ func clear() {
+ lock.lock()
+ storage.removeAll()
+ lock.unlock()
+
+ notifyChange()
+ }
+
+ private func append(_ entry: RequestLogEntry) {
+ lock.lock()
+ storage.insert(entry, at: 0)
+ if storage.count > Self.capacity {
+ storage.removeLast(storage.count - Self.capacity)
+ }
+ lock.unlock()
+
+ notifyChange()
+ }
+
+ private func update(_ id: UUID, _ mutate: (inout RequestLogEntry) -> Void) {
+ lock.lock()
+ guard let index = storage.firstIndex(where: { $0.id == id }) else {
+ lock.unlock()
+ return
+ }
+ mutate(&storage[index])
+ lock.unlock()
+
+ notifyChange()
+ }
+
+ private func notifyChange() {
+ if Thread.isMainThread {
+ objectWillChange.send()
+ } else {
+ DispatchQueue.main.async { [weak self] in
+ self?.objectWillChange.send()
+ }
+ }
+ }
+
+ /// 合法 JSON 重新序列化为稳定、未转义斜杠的日志文本; 非 JSON 错误消息保持原样
+ private static func normalized(_ text: String) -> String {
+ let readableText = jsonNormalized(text) ?? text
+ guard readableText.count > maxDetailLength else {
+ return readableText
+ }
+
+ return String(readableText.prefix(maxDetailLength)) + "…"
+ }
+
+ private static func jsonNormalized(_ text: String) -> String? {
+ guard let data = text.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data),
+ JSONSerialization.isValidJSONObject(object),
+ let output = try? JSONSerialization.data(
+ withJSONObject: object,
+ options: [.sortedKeys, .withoutEscapingSlashes]
+ ) else {
+ return nil
+ }
+
+ return String(decoding: output, as: UTF8.self)
+ }
+}
diff --git a/CodexBar/SettingsWindowController.swift b/CodexBar/SettingsWindowController.swift
index d9a4935..281fb77 100644
--- a/CodexBar/SettingsWindowController.swift
+++ b/CodexBar/SettingsWindowController.swift
@@ -1,57 +1,22 @@
-//
-// SettingsWindowController.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-14.
-//
-
import AppKit
import SwiftUI
@MainActor
-final class SettingsWindowController {
- private let viewModel: RateLimitsViewModel
+final class SettingsWindowController: HostingWindowController {
+ private let viewModel: CodexStatusViewModel
private let appUpdater: AppUpdater
- private let screenProvider: () -> NSScreen?
- private var window: NSWindow?
init(
- viewModel: RateLimitsViewModel,
+ viewModel: CodexStatusViewModel,
appUpdater: AppUpdater,
screenProvider: @escaping () -> NSScreen?
) {
self.viewModel = viewModel
self.appUpdater = appUpdater
- self.screenProvider = screenProvider
- }
-
- func open() {
- if window == nil {
- window = makeWindow()
- }
-
- guard let window else {
- return
- }
-
- if !window.isVisible {
- prepareForDisplay(window)
- }
-
- bringToFront(window)
+ super.init(screenProvider: screenProvider)
}
- private func bringToFront(_ window: NSWindow) {
- if window.isMiniaturized {
- window.deminiaturize(nil)
- }
-
- NSApplication.shared.activate()
- window.makeKeyAndOrderFront(nil)
- window.orderFrontRegardless()
- }
-
- private func makeWindow() -> NSWindow {
+ override func makeWindow() -> NSWindow {
let hostingController = NSHostingController(
rootView: AppSettingsView()
.environmentObject(viewModel)
@@ -62,12 +27,11 @@ final class SettingsWindowController {
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) {
+ override func prepareForDisplay(_ window: NSWindow) {
window.contentViewController?.view.layoutSubtreeIfNeeded()
if let fittingSize = window.contentViewController?.view.fittingSize,
@@ -81,23 +45,7 @@ final class SettingsWindowController {
)
}
- 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)
+ super.prepareForDisplay(window)
}
private enum Metrics {
diff --git a/CodexBar/StatusItemController.swift b/CodexBar/StatusItemController.swift
index 8914161..cce5932 100644
--- a/CodexBar/StatusItemController.swift
+++ b/CodexBar/StatusItemController.swift
@@ -1,27 +1,20 @@
-//
-// StatusItemController.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-14.
-//
-
import AppKit
import Combine
import SwiftUI
@MainActor
final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
- let viewModel = RateLimitsViewModel()
+ let viewModel = CodexStatusViewModel()
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()
}
@@ -29,18 +22,21 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
@MainActor
private final class StatusItemController: NSObject {
- private let viewModel: RateLimitsViewModel
+ private let viewModel: CodexStatusViewModel
private let appUpdater: AppUpdater
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let popover = NSPopover()
private let popoverVisibility = PopoverVisibilityState()
-
+
private lazy var settingsWindowController = SettingsWindowController(
viewModel: viewModel,
appUpdater: appUpdater
) { [weak self] in
self?.statusItem.button?.window?.screen
}
+ private lazy var logWindowController = LogWindowController { [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>?
@@ -50,16 +46,16 @@ private final class StatusItemController: NSObject {
private var globalMouseEventMonitor: Any?
private var cancellables = Set<AnyCancellable>()
private var lastHasError: Bool?
-
+
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) {
+
+ init(viewModel: CodexStatusViewModel, appUpdater: AppUpdater) {
self.viewModel = viewModel
self.appUpdater = appUpdater
super.init()
}
-
+
func install() {
configureStatusButton()
configurePopover()
@@ -67,77 +63,77 @@ 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 = self
button.action = #selector(statusItemClicked(_:))
button.imagePosition = .imageOnly
button.toolTip = "CodexBar"
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
-
+
private func configurePopover() {
- let rootView = RateLimitsMenuView(
+ let rootView = CodexStatusMenuView(
viewModel: viewModel,
popoverVisibility: popoverVisibility
)
.environmentObject(appUpdater)
- .frame(width: RateLimitsMenuView.menuWidth)
-
+ .frame(width: CodexStatusMenuView.menuWidth)
+
let hostingController = NSHostingController(rootView: rootView)
hostingController.sizingOptions = [.preferredContentSize]
-
+
popover.behavior = .applicationDefined
popover.animates = false
popover.contentViewController = hostingController
}
-
+
private func observeViewModel() {
- viewModel.$lastError
- .map { $0 != nil }
+ viewModel.$loadState
+ .map(\.isError)
.removeDuplicates()
.sink { [weak self] hasError in
self?.updateStatusImage(hasError: hasError)
}
.store(in: &cancellables)
}
-
+
private func updateStatusImage() {
updateStatusImage(hasError: viewModel.hasError)
}
-
+
private func updateStatusImage(hasError: Bool) {
guard hasError != lastHasError else {
return
}
-
+
lastHasError = hasError
statusItem.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:
@@ -149,7 +145,7 @@ private final class StatusItemController: NSObject {
openPopover(relativeTo: button)
}
}
-
+
private func cancelPopoverTasks() {
deferredRefreshTask?.cancel()
deferredRefreshTask = nil
@@ -158,40 +154,40 @@ private final class StatusItemController: NSObject {
popoverCloseTask?.cancel()
popoverCloseTask = nil
}
-
+
private func openPopover(relativeTo button: NSStatusBarButton) {
cancelPopoverTasks()
-
+
popoverAnimationGeneration += 1
let generation = popoverAnimationGeneration
popoverState = .opening
-
+
preparePopoverForFadeIn()
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
popoverVisibility.isVisible = true
stabilizePopoverChromeAppearance()
installPopoverDismissMonitors()
fadePopover(to: 1, duration: Metrics.fadeInDuration)
-
+
popoverOpenTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .milliseconds(Int(Metrics.fadeInDuration * 1000)))
guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
return
}
-
+
self.resetPopoverAlpha()
self.popoverState = .shown
self.popoverOpenTask = nil
}
-
+
scheduleDeferredRefresh()
}
-
+
private func showContextMenu(relativeTo button: NSStatusBarButton) {
closePopover(animated: false)
-
+
let menu = NSMenu()
-
+
let settingsItem = NSMenuItem(
title: "设置",
action: #selector(openSettings),
@@ -200,9 +196,18 @@ private final class StatusItemController: NSObject {
settingsItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)
settingsItem.target = self
menu.addItem(settingsItem)
-
+
+ let logItem = NSMenuItem(
+ title: "日志",
+ action: #selector(openLog),
+ keyEquivalent: "l"
+ )
+ logItem.image = NSImage(systemSymbolName: "doc.text.magnifyingglass", accessibilityDescription: nil)
+ logItem.target = self
+ menu.addItem(logItem)
+
menu.addItem(.separator())
-
+
let quitItem = NSMenuItem(
title: "退出",
action: #selector(quit),
@@ -211,46 +216,50 @@ private final class StatusItemController: NSObject {
quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil)
quitItem.target = self
menu.addItem(quitItem)
-
+
menu.popUp(
positioning: nil,
at: NSPoint(x: 0, y: button.bounds.minY - 4),
in: button
)
}
-
+
@objc private func openSettings() {
settingsWindowController.open()
}
-
+
+ @objc private func openLog() {
+ logWindowController.open()
+ }
+
@objc private func quit() {
NSApplication.shared.terminate(nil)
}
-
+
private func closePopover(animated: Bool = true) {
if popoverState == .closing && animated {
return
}
-
+
cancelPopoverTasks()
removePopoverDismissMonitors()
popoverVisibility.isVisible = false
-
+
guard popover.isShown else {
resetPopoverAlpha()
popoverState = .hidden
return
}
-
+
guard animated, let contentView = popover.contentViewController?.view else {
finishPopoverClose()
return
}
-
+
popoverAnimationGeneration += 1
let generation = popoverAnimationGeneration
popoverState = .closing
-
+
let popoverWindow = contentView.window
fadePopover(to: 0, duration: Metrics.fadeOutDuration)
popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in
@@ -258,7 +267,7 @@ private final class StatusItemController: NSObject {
guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
return
}
-
+
self.popover.performClose(nil)
contentView?.alphaValue = 1
popoverWindow?.alphaValue = 1
@@ -266,132 +275,132 @@ private final class StatusItemController: NSObject {
self.popoverCloseTask = nil
}
}
-
+
private func finishPopoverClose() {
cancelPopoverTasks()
popoverAnimationGeneration += 1
removePopoverDismissMonitors()
-
+
if popover.isShown {
popover.performClose(nil)
}
-
+
popoverVisibility.isVisible = false
resetPopoverAlpha()
popoverState = .hidden
}
-
+
private func installPopoverDismissMonitors() {
removePopoverDismissMonitors()
-
+
localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event in
self?.closePopoverIfNeeded(for: event)
self?.restabilizePopoverChromeAfterEvent()
return event
}
-
+
globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] _ in
self?.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] in
await 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
}
-
+
+ // NSPopover 会在点击后重新强调 NSVisualEffectView, 这里固定为 inactive 避免背景明暗跳变
stabilizeVisualEffectViews(in: rootView)
}
-
+
private func stabilizeVisualEffectViews(in view: NSView) {
if let visualEffectView = view as? NSVisualEffectView {
visualEffectView.state = .inactive
visualEffectView.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.mouseLocation
let buttonRectInWindow = button.convert(button.bounds, to: nil)
let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)
return buttonScreenRect.contains(eventScreenPoint)
}
-
+
private func preparePopoverForFadeIn() {
popover.contentViewController?.view.alphaValue = 0
popover.contentViewController?.view.window?.alphaValue = 0
}
-
+
private func resetPopoverAlpha() {
popover.contentViewController?.view.alphaValue = 1
popover.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 {
popoverWindow?.alphaValue = 0
}
-
+
NSAnimationContext.runAnimationGroup { context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
@@ -399,7 +408,7 @@ private final class StatusItemController: NSObject {
contentView.animator().alphaValue = alpha
}
}
-
+
private func scheduleDeferredRefresh() {
deferredRefreshTask?.cancel()
deferredRefreshTask = Task { @MainActor [weak self] in
@@ -407,11 +416,11 @@ private final class StatusItemController: NSObject {
guard let self, !Task.isCancelled, self.popover.isShown else {
return
}
-
+
self.viewModel.refreshIfNeeded()
}
}
-
+
private enum Metrics {
static let dismissEventMask: NSEvent.EventTypeMask = [
.leftMouseDown,
@@ -421,7 +430,7 @@ private final class StatusItemController: NSObject {
static let fadeInDuration: TimeInterval = 0.24
static let fadeOutDuration: TimeInterval = 0.18
}
-
+
private enum PopoverState {
case hidden
case opening
diff --git a/CodexBar/TokenCountText.swift b/CodexBar/TokenCountText.swift
index ee412a2..ca8c223 100644
--- a/CodexBar/TokenCountText.swift
+++ b/CodexBar/TokenCountText.swift
@@ -1,10 +1,3 @@
-//
-// TokenCountText.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-14.
-//
-
import SwiftUI
struct TokenCountText: View {
diff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/UsageHeatmap.swift
index 54dde51..dd5b7c3 100644
--- a/CodexBar/UsageHeatmap.swift
+++ b/CodexBar/UsageHeatmap.swift
@@ -1,30 +1,19 @@
-//
-// 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.recentWeekGrid(columnCount: UsageHeatmap.Metrics.columnCount, 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)
- }
-
+ metricsGrid
+
UsageHeatmap(days: days, hoveredDay: $hoveredDay)
}
.padding(10)
@@ -33,18 +22,85 @@ struct UsageSummaryView: View {
hoveredDay = nil
}
}
-
- private func metric(label: String, value: Int, alignment: Alignment) -> some View {
+
+ private var metricsGrid: some View {
+ HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {
+ tokenMetric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .center)
+ tokenMetric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .center)
+ textMetric(label: "当前连胜", value: Self.dayText(usage.summary.currentStreakDays))
+ textMetric(label: "最长连胜", value: Self.dayText(usage.summary.longestStreakDays))
+ textMetric(label: "最长任务", value: Self.durationText(seconds: usage.summary.longestRunningTurnSec))
+ }
+ }
+
+ private func tokenMetric(label: String, value: Int, alignment: Alignment) -> some View {
+ metric(label: label, alignment: alignment) {
+ TokenCountText(tokens: value)
+ }
+ }
+
+ private func textMetric(label: String, value: String) -> some View {
+ metric(label: label, alignment: .center) {
+ Text(value)
+ .font(.caption.monospacedDigit().weight(.semibold))
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ }
+ }
+
+ private func metric<Content: View>(
+ label: String,
+ alignment: Alignment,
+ @ViewBuilder value: () -> Content
+ ) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(.caption2)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: alignment)
-
- TokenCountText(tokens: value)
+
+ value()
.frame(maxWidth: .infinity, alignment: alignment)
}
- .frame(width: 96)
+ .frame(maxWidth: .infinity)
+ }
+
+ private static func dayText(_ days: Int?) -> String {
+ guard let days else {
+ return "--"
+ }
+
+ return "\(max(days, 0))天"
+ }
+
+ private static func durationText(seconds: Int?) -> String {
+ guard let seconds else {
+ return "--"
+ }
+
+ let duration = max(seconds, 0)
+ let days = duration / 86_400
+ let hours = duration % 86_400 / 3_600
+ let minutes = duration % 3_600 / 60
+ let remainingSeconds = duration % 60
+
+ if days > 0 {
+ return "\(days) 天 \(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"
+ }
+
+ if hours > 0 {
+ return "\(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"
+ }
+
+ if minutes > 0 {
+ return "\(minutes) 分 \(remainingSeconds) 秒"
+ }
+
+ return "\(remainingSeconds) 秒"
+ }
+
+ private enum Metrics {
+ static let metricSpacing: CGFloat = 8
}
}
@@ -54,17 +110,17 @@ struct UsageHeatmap: View {
@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.compactMap { $0?.tokens }.max() ?? 0, 1)
}
-
+
var body: some View {
ZStack(alignment: .topLeading) {
heatmapGrid
-
+
if let hoveredDay {
UsageHeatmapTooltip(day: hoveredDay)
.id(hoveredDay.id)
@@ -77,16 +133,16 @@ struct UsageHeatmap: View {
.frame(height: Metrics.height)
.coordinateSpace(name: Metrics.coordinateSpaceName)
}
-
+
private var heatmapGrid: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline) {
Text("近 \(Metrics.columnCount) 周")
.font(.caption2.weight(.medium))
.foregroundStyle(.secondary)
-
+
Spacer()
-
+
if let firstDate = visibleDays.first?.startDate, let lastDate = visibleDays.last?.startDate {
Text("\(firstDate) ~ \(lastDate)")
.font(.caption2.monospacedDigit())
@@ -94,13 +150,13 @@ struct UsageHeatmap: View {
.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,
@@ -133,34 +189,34 @@ struct UsageHeatmap: View {
}
.frame(maxWidth: .infinity, alignment: .leading)
}
-
+
private var visibleDays: [DailyUsageBucket] {
days.compactMap { $0 }
}
-
+
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)
}
}
@@ -177,7 +233,7 @@ extension UsageHeatmap {
static let tooltipHeight: CGFloat = 38
static let tooltipSquareSpacing: CGFloat = 2
static let tooltipFadeDuration: TimeInterval = 0.15
-
+
static var totalWidth: CGFloat {
CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing
}
@@ -190,7 +246,7 @@ private struct UsageHeatmapSquare: View {
let isHovered: Bool
let onActive: (CGRect) -> Void
let onEnded: () -> Void
-
+
var body: some View {
GeometryReader { proxy in
RoundedRectangle(cornerRadius: 4, style: .continuous)
@@ -214,39 +270,39 @@ private struct UsageHeatmapSquare: View {
.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.codexSecondaryLabel)
-
+
TokenCountText(tokens: day.tokens)
.foregroundStyle(Color.codexLabel)
}