Skip to content

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

Replace polling spawns with persistent app-server connection

Bob01e49d6a81b4
diff --git a/AGENTS.md b/AGENTS.md
index 0937de4..b8f5c4c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,21 +8,19 @@ CodexBar 是一个 macOS 菜单栏应用,用来展示当前本机 Codex 账号
## 核心功能
-- 菜单栏只展示 `timelapse` SF Symbol,App 图标使用白底黑色 `timelapse`。
+- 菜单栏图标:正常时显示 `person.fill.checkmark`,任何错误(包括未登录)时显示 `person.fill.xmark`,切换使用 `.contentTransition(.symbolEffect(.replace))` 动画。App 图标使用白底黑色 `timelapse`。
- 弹窗第一行展示账号信息和套餐。
- 弹窗展示两行分段电量条,额度行标签根据 `windowDurationMins` 动态生成。
- 每行额度在进度条右侧展示剩余百分比和重置时间。
- 弹窗展示最近 14 个完整自然日的 token 柱状图、累计 token 和单日峰值 token。
- 鼠标划过 token 柱状图中的单日柱子时,展示对应日期和用量。
-- 更新时间显示在左侧。
- 应用运行时每分钟自动刷新,即使弹窗未打开也会刷新。
-- 收到 `account/rateLimits/updated` 后会重新查询额度,并在「额度通知」已开启时发送 macOS 本地通知。
- 双击账号图标可手动刷新。
-- 按住 Option/Alt 点击菜单栏图标时,才展示控制区。
-- Option/Alt 设置区左侧上下排列「开机启动」和「额度通知」开关,右下方展示「退出」按钮,不展示刷新按钮。
-- 弹窗错误只展示普通红色错误文案,不包含 Debug 明细或环境变量模拟入口。
+- 按住 Option/Alt 点击菜单栏图标时,才展示设置区。设置区为单行布局:左侧「开机自动启动」开关,右侧「退出」按钮,不展示刷新按钮。
+- 没有通知功能:不监听 `account/rateLimits/updated`,不发送 macOS 本地通知(该功能已整体移除,不要恢复)。
+- 弹窗错误只展示普通错误文案,不包含 Debug 明细或环境变量模拟入口。
-## Codex 数据来源
+## Codex 数据来源与常驻连接
应用通过本机 Codex app-server 读取数据。启动优先级:
@@ -38,24 +36,32 @@ codex app-server --listen stdio://
/Applications/Codex.app/Contents/Resources/codex app-server --listen stdio://
```
-连接后必须按顺序发送:
+应用与 app-server 维持**一条常驻连接**:首次拉取时启动进程,按顺序完成握手:
```json
{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"1.0.0"}}}
{"method":"initialized"}
{"method":"account/read","id":2,"params":{"refreshToken":false}}
-{"method":"account/rateLimits/read","id":3}
-{"method":"account/usage/read","id":4}
```
-注意:不能在 `initialize` 和 `initialized` 完成前请求额度,否则 Codex app-server 会拒绝请求。
+之后每分钟在同一会话上请求 `account/rateLimits/read` 和 `account/usage/read`。注意:不能在 `initialize` 和 `initialized` 完成前请求额度,否则 app-server 会拒绝请求。
-每日 token 统计使用 `account/usage/read`,读取 `summary.lifetimeTokens`、`summary.peakDailyTokens` 和 `dailyUsageBuckets`。
-如果本机 Codex app-server 不支持 `account/usage/read`,token 统计区域不展示,额度信息仍正常显示。
+连接重建规则(`CodexRateLimitService.ensureConnection`):
-`account/rateLimits/updated` 是 app-server notification,不是可请求方法。应用后台保留一个 app-server 连接监听该 notification;收到后重新调用 `account/rateLimits/read` 获取完整额度并更新 UI,在「额度通知」开启且系统通知权限已授权时发送本地通知。不要直接用 notification 中的稀疏 `rateLimits` payload 覆盖完整快照。
+- 进程已退出 → 重建。
+- 连接存活超过 `connectionMaxAge`(1 小时)→ 定期回收重建,覆盖 codex 全局升级后切换新二进制、服务端状态漂移等陈旧问题。
+- **复用的**连接上请求失败 → 丢弃重建一次再试;**全新**连接上的失败直接抛出,不做二次重试(避免故障时整套握手做两遍)。
+- 登录类错误(`requiresLogin`)→ 丢弃连接但不重试;下一次轮询起新进程读取最新 `~/.codex/auth.json`,用户重新登录后最多一分钟自动恢复。
-后台监听连接启动时也必须按 `account/read`、`account/rateLimits/read` 的顺序初始化额度路径;如果监听连接因为 app-server 退出、认证失败或响应超时而断开,应用会在 30 秒后重新启动监听连接。
+认证重试:`account/rateLimits/read` 返回认证错误时,先在同一会话上调 `account/read`(`refreshToken: true`)刷新 token 再重试一次;仍失败抛 `authenticationRequired`。
+
+每日 token 统计使用 `account/usage/read`,读取 `summary.lifetimeTokens`、`summary.peakDailyTokens` 和 `dailyUsageBuckets`。如果本机 app-server 不支持该方法,token 统计区域不展示,额度信息仍正常显示。
+
+## 并发约定
+
+工程开启了 `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`:没有显式标注的类型一律推断为 MainActor 隔离。因此**所有非 UI 类型必须显式标 `nonisolated`**(`CodexRateLimitService`、`AppServerSession`、模型类型等都已标注),否则会出现「Call to main actor-isolated initializer in a synchronous nonisolated context」一类的错误。
+
+`CodexRateLimitService` 是 `nonisolated final class` + `@unchecked Sendable`,连接状态只在私有串行 `DispatchQueue` 上读写,对外暴露 async 接口。
## 认证和沙盒
@@ -65,7 +71,7 @@ CodexBar 必须使用真实 macOS 用户的 Codex 登录数据。之前遇到过
codex account authentication required to read rate limits
```
-当前服务层会用真实用户 home 运行 app-server,避免读到沙盒容器路径。
+当前服务层会用真实用户 home(`getpwuid`)运行 app-server,避免读到沙盒容器路径。
Xcode target 已关闭 App Sandbox,因为应用需要启动本机 Codex CLI 并访问用户的 Codex 登录状态。
@@ -74,53 +80,48 @@ Xcode target 已关闭 App Sandbox,因为应用需要启动本机 Codex CLI
## 代码组织
- `CodexBarApp.swift`:应用入口,创建 `RateLimitsViewModel`,配置 `MenuBarExtra`。
-- `RateLimitsViewModel.swift`:视图模型,负责快照状态、刷新状态、自动刷新。
-- `CodexRateLimitService.swift`:启动 Codex app-server,并处理 JSON-RPC 请求/响应。
-- `RateLimitModels.swift`:Codex 响应模型、业务快照模型、错误文案。
-- `MenuBarStatusView.swift`:菜单栏常驻展示,只包含 `timelapse` 动画图标。
-- `RateLimitsMenuView.swift`:点击菜单栏后的弹窗内容。
+- `RateLimitsViewModel.swift`:视图模型。错误状态单一来源:只发布 `lastError: CodexRateLimitError?`,`errorMessage`、`requiresLogin`、`hasError` 都是从它派生的计算属性,不要再加并列的错误布尔。
+- `CodexRateLimitService.swift`:常驻 app-server 连接管理 + JSON-RPC 请求/响应。
+- `RateLimitModels.swift`:Codex 响应模型、业务快照模型、`CodexRateLimitError`(含 `requiresLogin`、`isAuthenticationRequired` 分类属性)。
+- `MenuBarStatusView.swift`:菜单栏常驻图标(checkmark/xmark 切换 + 动画),并在 `.task` 中启动自动刷新。
+- `RateLimitsMenuView.swift`:点击菜单栏后的弹窗内容,含未登录橙色提示和设置区。
- `QuotaRow.swift`:额度行和分段进度条。
- `LoginItemSettings.swift`:使用 `SMAppService.mainApp` 管理开机自启。
- `Assets.xcassets/AppIcon.appiconset`:App 图标资源,白底黑色中心符号使用 `timelapse`。
- `Scripts/create-dmg.sh`:将项目根目录下导出的 `.app` 打包成拖拽安装 DMG。
-## UI 约定
-
-- 菜单栏图标使用 `timelapse`。菜单栏图标直接使用:
+工程使用文件系统同步组(`PBXFileSystemSynchronizedRootGroup`),新增/删除源文件无需修改 `project.pbxproj`。
-```swift
-.symbolEffect(.variableColor.cumulative.hideInactiveLayers.nonReversing, options: .repeat(.continuous))
-```
+## UI 约定
-- 不要再给 `symbolEffect` 加低版本 fallback;最低系统版本已经定为 macOS 15.0。
+- 菜单栏正常图标 `person.fill.checkmark`,错误图标 `person.fill.xmark`,切换用 `.contentTransition(.symbolEffect(.replace))` + `.animation(.default, value:)`。
+- 不要给 symbol API 加低版本 fallback;最低系统版本已经定为 macOS 15.0。
- App 图标保持白底黑色 `timelapse`,不要恢复成蓝绿色图标。
- 菜单栏不展示额度数字、窗口标签或外层圈数;额度详情只在弹窗中展示。
- 弹窗账号图标使用 `person.fill`,双击该图标刷新数据。
- 弹窗字体要保持紧凑,避免菜单栏弹窗内容被截断。
- 分段条展示剩余额度,剩余额度计算方式是 `100 - usedPercent`。
- 额度行标签示例:`300` 分钟显示 `5 小时`,`10080` 分钟显示 `7 天`;缺少 `windowDurationMins` 时再回退到默认文案。
-- 重置时间格式使用 `MM-dd HH:mm`。
-- 更新时间格式使用 `HH:mm:ss`。
-- token 数按 `M`、`B` 紧凑单位展示。
-- token 柱状图使用橙色,单日用量越高颜色越浓。
+- 重置时间格式使用 `MM-dd HH:mm`;更新时间格式使用 `HH:mm:ss`。
+- token 数按 `M`、`B` 紧凑单位展示;token 柱状图使用橙色,单日用量越高颜色越浓。
-## 错误和调试
+## 错误展示约定
-- 当前代码不包含 Debug UI、Debug 详情展示或环境变量模拟错误入口。
-- Codex 交互错误会通过 `CodexRateLimitError.localizedDescription` 展示在弹窗中。
-- 每分钟自动刷新失败时,如果已有旧额度快照,旧快照不会被清空;弹窗继续显示上一次成功读取的数据和对应更新时间,同时展示错误文案。
-- `account/rateLimits/updated` 触发的刷新如果失败,不会更新 UI,也不会发送通知;只有当前没有旧快照时才会把错误展示到弹窗中。
-- 开机启动设置失败会展示 `设置开机启动失败: ...`。
+- 登录类错误(`requiresLogin` 为 true:`notLoggedIn`、`authenticationRequired`、消息含 "authentication required" 的 `serverError`):弹窗顶部橙色提示「Codex 未登录」+ 图标 `person.crop.circle.badge.exclamationmark`;旧快照置灰(opacity 0.4)保留展示;红色错误行被抑制,避免重复文案。
+- 其他错误:弹窗红色小字展示 `errorDescription`;旧快照保持全亮度。
+- 错误文案保持显示直到某次刷新成功(`refresh()` 开始时不清空 `lastError`)。
+- 旧额度快照永远不清空,弹窗继续显示上一次成功读取的数据和更新时间。
+- 开机启动设置失败会展示 `设置开机启动失败: ...`,属于 `LoginItemSettings` 的独立错误位,与额度错误互不影响。
## 构建验证
-修改后至少运行:
+修改后运行确保无 error 和 warning
```bash
xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
```
-当前已验证该命令可通过。
+SourceKit 经常对跨文件类型报「Cannot find type ... in scope」,属索引滞后误报,以 `xcodebuild` 实际编译结果为准。
## 分发备注
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..3cd7682
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,3 @@
+# CLAUDE.md
+
+完整项目记忆(架构、JSON-RPC 协议、UI 约定、错误展示规则)见 @AGENTS.md,两份文档以它为准,更新记忆时优先改它。
diff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swift
index 9110d72..cd35d03 100644
--- a/CodexBar/CodexRateLimitService.swift
+++ b/CodexBar/CodexRateLimitService.swift
@@ -8,212 +8,180 @@
import Darwin
import Foundation
-struct CodexRateLimitService: Sendable {
+/// 与 codex app-server 维持一条常驻连接: 首次拉取时启动进程并完成握手
+/// 之后所有额度读取复用同一会话; 进程退出或请求失败时自动重建连接
+nonisolated final class CodexRateLimitService: @unchecked Sendable {
private nonisolated static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"
-
- nonisolated init() {}
-
- nonisolated func fetchRateLimits() async throws -> CodexQuotaSnapshot {
- return try await Task.detached(priority: .utility) {
- let environment = Self.appServerEnvironment()
- let command = try Self.resolveAppServerCommand(environment: environment)
- let clientVersion = Self.clientVersion()
-
- return try Self.fetchRateLimitsSynchronously(
- command: command,
- environment: environment,
- clientVersion: clientVersion,
- timeout: 20
- )
- }.value
+ private static let requestTimeout: TimeInterval = 20
+ // 连接定期回收: 覆盖 codex 全局升级后换用新二进制
+ private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
+ // 进程环境在应用启动后不会变化, 只构建一次
+ private static let environment = appServerEnvironment()
+
+ // 连接状态只在 queue 上读写
+ private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)
+ private var connection: AppServerConnection?
+
+ init() {}
+
+ deinit {
+ connection?.session.close()
}
-
- nonisolated func observeRateLimitUpdates(onUpdate: @escaping @Sendable () -> Void) async {
- let environment = Self.appServerEnvironment()
- let clientVersion = Self.clientVersion()
-
- while !Task.isCancelled {
+
+ func fetchRateLimits() async throws -> CodexQuotaSnapshot {
+ try await withCheckedThrowingContinuation { continuation in
+ queue.async {
+ continuation.resume(with: Result { try self.fetchRateLimitsOnQueue() })
+ }
+ }
+ }
+
+ private func fetchRateLimitsOnQueue() throws -> CodexQuotaSnapshot {
+ do {
+ let (connection, reused) = try ensureConnection()
do {
- let command = try Self.resolveAppServerCommand(environment: environment)
- try Self.observeRateLimitUpdatesSynchronously(
- command: command,
- environment: environment,
- clientVersion: clientVersion,
- timeout: 20,
- onUpdate: onUpdate
- )
- } catch {
- guard !Task.isCancelled else {
- return
- }
-
- try? await Task.sleep(nanoseconds: 30_000_000_000)
+ 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 nonisolated static func fetchRateLimitsSynchronously(
- command: AppServerCommand,
- environment: [String: String],
- clientVersion: String,
- timeout: TimeInterval
- ) throws -> CodexQuotaSnapshot {
- try withRateLimitsSession(
+
+ private func ensureConnection() throws -> (connection: AppServerConnection, reused: Bool) {
+ if let connection, connection.session.process.isRunning,
+ Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {
+ return (connection, reused: true)
+ }
+
+ teardownConnection()
+
+ let command = try Self.resolveAppServerCommand(environment: Self.environment)
+ let newConnection = try Self.openConnection(
command: command,
- environment: environment,
- clientVersion: clientVersion,
- timeout: timeout
- ) { connection in
- let usageResponse = try? connection.session.request(
- "account/usage/read",
- as: AccountUsageResponse.self
+ environment: Self.environment,
+ clientVersion: Self.clientVersion(),
+ timeout: Self.requestTimeout
+ )
+
+ connection = newConnection
+ return (newConnection, reused: false)
+ }
+
+ private func teardownConnection() {
+ connection?.session.close()
+ connection = nil
+ }
+
+ private static func fetchSnapshot(using connection: AppServerConnection) throws -> CodexQuotaSnapshot {
+ let rateLimitsResponse: AccountRateLimitsResponse
+ do {
+ rateLimitsResponse = try connection.session.request(
+ "account/rateLimits/read",
+ as: AccountRateLimitsResponse.self
)
-
- return try CodexQuotaSnapshot(
- accountResponse: connection.accountResponse,
- rateLimitsResponse: connection.rateLimitsResponse,
- usageResponse: usageResponse
+ } catch let error as CodexRateLimitError where error.isAuthenticationRequired {
+ connection.accountResponse = try connection.session.request(
+ "account/read",
+ params: ["refreshToken": true],
+ as: AccountReadResponse.self
)
- }
- }
-
- private nonisolated static func observeRateLimitUpdatesSynchronously(
- command: AppServerCommand,
- environment: [String: String],
- clientVersion: String,
- timeout: TimeInterval,
- onUpdate: @escaping @Sendable () -> Void
- ) throws {
- try withRateLimitsSession(
- command: command,
- environment: environment,
- clientVersion: clientVersion,
- timeout: timeout
- ) { connection in
- let decoder = JSONDecoder()
- while !Task.isCancelled {
- guard let line = connection.lineReader.nextLine(timeout: 0.5) else {
- if !connection.process.isRunning {
- let stderr = connection.errorReader.text.trimmingCharacters(in: .whitespacesAndNewlines)
- throw CodexRateLimitError.serverTimeout(stderr.isEmpty ? "account/rateLimits/updated" : stderr)
- }
-
- continue
- }
-
- guard let data = line.data(using: .utf8),
- let notification = try? decoder.decode(RPCNotificationEnvelope.self, from: data),
- notification.method == "account/rateLimits/updated" else {
- continue
- }
-
- onUpdate()
+
+ do {
+ rateLimitsResponse = try connection.session.request(
+ "account/rateLimits/read",
+ as: AccountRateLimitsResponse.self
+ )
+ } catch let retryError as CodexRateLimitError where retryError.isAuthenticationRequired {
+ throw CodexRateLimitError.authenticationRequired
}
}
+
+ let usageResponse = try? connection.session.request(
+ "account/usage/read",
+ as: AccountUsageResponse.self
+ )
+
+ return try CodexQuotaSnapshot(
+ accountResponse: connection.accountResponse,
+ rateLimitsResponse: rateLimitsResponse,
+ usageResponse: usageResponse
+ )
}
-
- /// 启动 app-server 进程并完成 initialize、account/read、account/rateLimits/read
- /// (含认证失败重试)初始化序列,fetch 和监听两条路径共用,保证握手始终一致。
- private nonisolated static func withRateLimitsSession<T>(
+
+ /// 启动 app-server 进程并完成 initialize、account/read 握手, 返回可复用的连接
+ private static func openConnection(
command: AppServerCommand,
environment: [String: String],
clientVersion: String,
- timeout: TimeInterval,
- body: (AppServerConnection) throws -> T
- ) throws -> T {
+ 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 = PipeTextCollector(fileHandle: standardError.fileHandleForReading)
-
+
process.standardInput = standardInput
process.standardOutput = standardOutput
process.standardError = standardError
-
+
do {
try process.run()
} catch {
throw CodexRateLimitError.serverStartFailed(error.localizedDescription)
}
-
- defer {
- lineReader.stop()
- errorReader.stop()
- try? standardInput.fileHandleForWriting.close()
-
- if process.isRunning {
- process.terminate()
- }
- }
-
+
let session = AppServerSession(
+ process: process,
input: standardInput,
lineReader: lineReader,
errorReader: errorReader,
timeout: timeout
)
-
- _ = try session.request(
- "initialize",
- params: [
- "clientInfo": [
- "name": "codex_bar",
- "title": "Codex Bar",
- "version": clientVersion
- ]
- ],
- as: EmptyResponse.self
- )
-
- try session.notify("initialized")
-
- var accountResponse = try session.request(
- "account/read",
- params: ["refreshToken": false],
- as: AccountReadResponse.self
- )
-
- let rateLimitsResponse: AccountRateLimitsResponse
+
do {
- rateLimitsResponse = try session.request(
- "account/rateLimits/read",
- as: AccountRateLimitsResponse.self
+ _ = try session.request(
+ "initialize",
+ params: [
+ "clientInfo": [
+ "name": "codex_bar",
+ "title": "Codex Bar",
+ "version": clientVersion
+ ]
+ ],
+ as: EmptyResponse.self
)
- } catch let error as CodexRateLimitError where error.isAuthenticationRequired {
- accountResponse = try session.request(
+
+ try session.notify("initialized")
+
+ let accountResponse = try session.request(
"account/read",
- params: ["refreshToken": true],
+ params: ["refreshToken": false],
as: AccountReadResponse.self
)
-
- do {
- rateLimitsResponse = try session.request(
- "account/rateLimits/read",
- as: AccountRateLimitsResponse.self
- )
- } catch let retryError as CodexRateLimitError where retryError.isAuthenticationRequired {
- throw CodexRateLimitError.authenticationRequired
- }
- }
-
- return try body(
- AppServerConnection(
- process: process,
+
+ return AppServerConnection(
session: session,
- lineReader: lineReader,
- errorReader: errorReader,
- accountResponse: accountResponse,
- rateLimitsResponse: rateLimitsResponse
+ accountResponse: accountResponse
)
- )
+ } catch {
+ session.close()
+ throw error
+ }
}
-
+
private nonisolated static func appServerEnvironment() -> [String: String] {
var environment = ProcessInfo.processInfo.environment
let homeDirectory = realUserHomeDirectory()
@@ -229,34 +197,34 @@ struct CodexRateLimitService: Sendable {
"/usr/sbin",
"/sbin"
]
-
+
environment["HOME"] = homeDirectory
environment["USER"] = NSUserName()
environment["LOGNAME"] = NSUserName()
environment["PATH"] = mergedPath(path, fallbackPaths: fallbackPaths)
environment["TERM"] = environment["TERM"] ?? "xterm-256color"
-
+
return environment
}
-
+
private nonisolated static func resolveAppServerCommand(environment: [String: String]) throws -> AppServerCommand {
let cliPath = findExecutable(named: "codex", environment: environment)
-
+
if let cliPath, standardizedPath(cliPath) != standardizedPath(bundledExecutablePath) {
return AppServerCommand(executablePath: cliPath)
}
-
+
if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {
return AppServerCommand(executablePath: bundledExecutablePath)
}
-
+
if let cliPath {
return AppServerCommand(executablePath: cliPath)
}
-
+
throw CodexRateLimitError.executableNotFound
}
-
+
private nonisolated static func findExecutable(
named executableName: String,
environment: [String: String]
@@ -264,74 +232,104 @@ struct CodexRateLimitService: Sendable {
guard let path = environment["PATH"] else {
return nil
}
-
+
for directory in path.split(separator: ":") {
let executablePath = "\(directory)/\(executableName)"
if FileManager.default.isExecutableFile(atPath: executablePath) {
return executablePath
}
}
-
+
return nil
}
-
+
private nonisolated static func mergedPath(_ path: String, fallbackPaths: [String]) -> String {
var components: [String] = []
var seen = Set<String>()
-
+
for component in path.split(separator: ":").map(String.init) + fallbackPaths {
guard !component.isEmpty, !seen.contains(component) else {
continue
}
-
+
components.append(component)
seen.insert(component)
}
-
+
return components.joined(separator: ":")
}
-
+
private nonisolated static func standardizedPath(_ path: String) -> String {
URL(fileURLWithPath: path).standardizedFileURL.path
}
-
+
private nonisolated static func clientVersion() -> String {
guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String,
!version.isEmpty else {
return "1.0.0"
}
-
+
return version
}
-
+
private nonisolated static func realUserHomeDirectory() -> String {
guard let passwd = getpwuid(getuid()),
let home = passwd.pointee.pw_dir else {
return NSHomeDirectory()
}
-
+
return String(cString: home)
}
}
+private nonisolated final class AppServerConnection {
+ let session: AppServerSession
+ let openedAt = Date()
+ var accountResponse: AccountReadResponse
+
+ init(session: AppServerSession, accountResponse: AccountReadResponse) {
+ self.session = session
+ self.accountResponse = accountResponse
+ }
+}
+
private nonisolated final class AppServerSession {
+ let process: Process
+
private let input: Pipe
private let lineReader: JSONLineReader
private let errorReader: PipeTextCollector
private let timeout: TimeInterval
private var nextId = 1
-
- init(input: Pipe, lineReader: JSONLineReader, errorReader: PipeTextCollector, timeout: TimeInterval) {
+
+ init(
+ process: Process,
+ input: Pipe,
+ lineReader: JSONLineReader,
+ errorReader: PipeTextCollector,
+ 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))
}
-
+
func request<Response: Decodable>(
_ method: String,
params: [String: Any]? = nil,
@@ -342,7 +340,7 @@ private nonisolated final class AppServerSession {
try write(message(method: method, id: id, params: params))
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 {
@@ -353,13 +351,13 @@ private nonisolated final class AppServerSession {
}
return object
}
-
+
private func write(_ object: [String: Any]) throws {
var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])
data.append(0x0A)
input.fileHandleForWriting.write(data)
}
-
+
private func waitForResponse<Response: Decodable>(
id: Int,
step: String,
@@ -367,36 +365,36 @@ private nonisolated final class AppServerSession {
) throws -> Response {
let deadline = Date().addingTimeInterval(timeout)
let decoder = JSONDecoder()
-
+
while Date() < deadline {
guard let line = lineReader.nextLine(timeout: 0.2) else {
continue
}
-
+
guard let data = line.data(using: .utf8) else {
continue
}
-
+
if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: data),
errorEnvelope.id == id,
let error = errorEnvelope.error {
throw CodexRateLimitError.serverError(error.message)
}
-
+
guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: data),
envelope.id == id,
let result = envelope.result else {
continue
}
-
+
return result
}
-
+
let stderr = errorReader.text.trimmingCharacters(in: .whitespacesAndNewlines)
if stderr.isEmpty {
throw CodexRateLimitError.serverTimeout(step)
}
-
+
throw CodexRateLimitError.serverTimeout("\(step):\(stderr)")
}
}
@@ -406,15 +404,6 @@ private nonisolated struct AppServerCommand: Sendable {
let arguments = ["app-server", "--listen", "stdio://"]
}
-private nonisolated struct AppServerConnection {
- let process: Process
- let session: AppServerSession
- let lineReader: JSONLineReader
- let errorReader: PipeTextCollector
- let accountResponse: AccountReadResponse
- let rateLimitsResponse: AccountRateLimitsResponse
-}
-
private nonisolated struct EmptyResponse: Decodable {}
private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {
@@ -431,55 +420,51 @@ private nonisolated struct RPCError: Decodable {
let message: String
}
-private nonisolated struct RPCNotificationEnvelope: Decodable {
- let method: 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] = []
-
+
init(fileHandle: FileHandle) {
self.fileHandle = fileHandle
fileHandle.readabilityHandler = { [weak self] handle in
self?.append(handle.availableData)
}
}
-
+
func nextLine(timeout: TimeInterval) -> String? {
if let line = popLine() {
return line
}
-
+
let result = semaphore.wait(timeout: .now() + timeout)
guard result == .success else {
return nil
}
-
+
return popLine()
}
-
+
func stop() {
fileHandle.readabilityHandler = nil
}
-
+
private func append(_ data: Data) {
guard !data.isEmpty else {
return
}
-
+
lock.lock()
defer { lock.unlock() }
-
+
buffer.append(data)
-
+
while let newlineRange = buffer.firstRange(of: Data([0x0A])) {
let lineData = buffer[..<newlineRange.lowerBound]
buffer.removeSubrange(...newlineRange.lowerBound)
-
+
if let line = String(data: lineData, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!line.isEmpty {
@@ -488,52 +473,52 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {
}
}
}
-
+
private func popLine() -> String? {
lock.lock()
defer { lock.unlock() }
-
+
guard !lines.isEmpty else {
return nil
}
-
+
return lines.removeFirst()
}
}
private nonisolated final class PipeTextCollector: @unchecked Sendable {
- // 监听连接会随应用运行数小时甚至数天,stderr 只保留末尾,避免无界增长。
+ // 常驻连接 stderr 只保留末尾, 避免无界增长
private static let maxBytes = 16_384
-
+
private let lock = NSLock()
private let fileHandle: FileHandle
private var data = Data()
-
+
var text: String {
lock.lock()
defer { lock.unlock() }
return String(data: data, encoding: .utf8) ?? ""
}
-
+
init(fileHandle: FileHandle) {
self.fileHandle = fileHandle
fileHandle.readabilityHandler = { [weak self] handle in
self?.append(handle.availableData)
}
}
-
+
func stop() {
fileHandle.readabilityHandler = nil
}
-
+
private func append(_ newData: Data) {
guard !newData.isEmpty else {
return
}
-
+
lock.lock()
defer { lock.unlock() }
-
+
data.append(newData)
if data.count > Self.maxBytes {
data = Data(data.suffix(Self.maxBytes))
diff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/LoginItemSettings.swift
index 848a6ec..2fde233 100644
--- a/CodexBar/LoginItemSettings.swift
+++ b/CodexBar/LoginItemSettings.swift
@@ -35,7 +35,7 @@ final class LoginItemSettings: ObservableObject {
refresh()
} catch {
refresh()
- errorMessage = "设置开机启动失败: \(error.localizedDescription)"
+ errorMessage = "设置开机自动启动失败: \(error.localizedDescription)"
}
}
}
diff --git a/CodexBar/MenuBarStatusView.swift b/CodexBar/MenuBarStatusView.swift
index b3b61e0..7450f17 100644
--- a/CodexBar/MenuBarStatusView.swift
+++ b/CodexBar/MenuBarStatusView.swift
@@ -11,7 +11,9 @@ struct MenuBarStatusView: View {
@ObservedObject var viewModel: RateLimitsViewModel
var body: some View {
- Image(systemName: "timelapse")
+ Image(systemName: viewModel.hasError ? "person.fill.xmark" : "person.fill.checkmark")
+ .contentTransition(.symbolEffect(.replace))
+ .animation(.default, value: viewModel.hasError)
.task {
viewModel.startAutoRefresh()
}
diff --git a/CodexBar/NotificationSettings.swift b/CodexBar/NotificationSettings.swift
deleted file mode 100644
index 9fae6d3..0000000
--- a/CodexBar/NotificationSettings.swift
+++ /dev/null
@@ -1,135 +0,0 @@
-//
-// NotificationSettings.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-11.
-//
-
-import Combine
-import Foundation
-import UserNotifications
-
-@MainActor
-final class NotificationSettings: ObservableObject {
- @Published private(set) var isEnabled = NotificationSettingsStore.isEnabled
- @Published private(set) var errorMessage: String?
-
- init() {
- refresh()
- }
-
- func refresh() {
- Task {
- await refreshAuthorizationState()
- }
- }
-
- func setEnabled(_ enabled: Bool) {
- errorMessage = nil
-
- guard enabled else {
- NotificationSettingsStore.isEnabled = false
- isEnabled = false
- return
- }
-
- Task {
- await enable()
- }
- }
-
- private func enable() async {
- let center = UNUserNotificationCenter.current()
- let status = await center.notificationSettings().authorizationStatus
-
- if status.allowsNotifications {
- NotificationSettingsStore.isEnabled = true
- isEnabled = true
- return
- }
-
- if status == .notDetermined {
- let granted = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
- NotificationSettingsStore.isEnabled = granted
- isEnabled = granted
-
- if !granted {
- errorMessage = "系统通知权限未开启"
- }
-
- return
- }
-
- NotificationSettingsStore.isEnabled = false
- isEnabled = false
- errorMessage = status == .denied ? "系统通知权限被拒绝" : "系统通知权限不可用"
- }
-
- private func refreshAuthorizationState() async {
- let status = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
-
- if status.allowsNotifications {
- isEnabled = NotificationSettingsStore.isEnabled
- } else {
- if status != .notDetermined {
- NotificationSettingsStore.isEnabled = false
- }
-
- isEnabled = false
- }
- }
-}
-
-extension UNAuthorizationStatus {
- var allowsNotifications: Bool {
- switch self {
- case .authorized, .provisional, .ephemeral:
- return true
- case .notDetermined, .denied:
- return false
- @unknown default:
- return false
- }
- }
-}
-
-enum NotificationSettingsStore {
- private static let enabledKey = "rateLimitNotificationsEnabled"
-
- static var isEnabled: Bool {
- get {
- UserDefaults.standard.bool(forKey: enabledKey)
- }
- set {
- UserDefaults.standard.set(newValue, forKey: enabledKey)
- }
- }
-}
-
-struct QuotaNotificationService {
- func sendRateLimitUpdatedNotification() async {
- guard NotificationSettingsStore.isEnabled,
- await hasAuthorization else {
- return
- }
-
- let content = UNMutableNotificationContent()
- content.title = "Codex 额度已更新"
- content.sound = .default
-
- let request = UNNotificationRequest(
- identifier: "codex-rate-limits-updated-\(UUID().uuidString)",
- content: content,
- trigger: nil
- )
-
- try? await UNUserNotificationCenter.current().add(request)
- }
-
- private var hasAuthorization: Bool {
- get async {
- await UNUserNotificationCenter.current().notificationSettings().authorizationStatus.allowsNotifications
- }
- }
-
-}
diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/RateLimitModels.swift
index b64696c..d57d465 100644
--- a/CodexBar/RateLimitModels.swift
+++ b/CodexBar/RateLimitModels.swift
@@ -15,19 +15,19 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
let fiveHour: QuotaWindow
let weekly: QuotaWindow
let usage: CodexUsageSnapshot?
-
+
var title: String {
if let limitName, !limitName.isEmpty {
return limitName
}
-
+
return "Codex"
}
-
+
var accountLabel: String {
account?.displayName ?? "未登录"
}
-
+
var planLabel: String? {
account?.planType ?? planType
}
@@ -37,12 +37,12 @@ nonisolated struct CodexAccount: Decodable, Equatable {
let type: String
let email: String?
let planType: String?
-
+
var displayName: String {
if let email, !email.isEmpty {
return email
}
-
+
switch type {
case "apiKey":
return "API Key"
@@ -66,22 +66,22 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {
case fiveHour
case weekly
}
-
+
let kind: Kind
let label: String
let usedPercent: Int?
let resetsAt: Date?
-
+
var id: String { kind.rawValue }
-
+
var remainingPercent: Int {
guard let usedPercent else {
return 0
}
-
+
return max(0, min(100, 100 - usedPercent))
}
-
+
var hasData: Bool {
usedPercent != nil
}
@@ -90,7 +90,7 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {
nonisolated struct AccountRateLimitsResponse: Decodable {
let rateLimits: RateLimitSnapshot
let rateLimitsByLimitId: [String: RateLimitSnapshot]?
-
+
var codexSnapshot: RateLimitSnapshot {
rateLimitsByLimitId?["codex"] ?? rateLimits
}
@@ -107,7 +107,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))
@@ -133,30 +133,30 @@ nonisolated struct CodexUsageSnapshot: Equatable {
struct Day: Equatable, Identifiable {
let startDate: String
let tokens: Int
-
+
var id: String { startDate }
}
-
+
let summary: UsageSummary
let dailyBuckets: [DailyUsageBucket]
-
+
func recentDays(count: Int, endingDaysAgo: Int = 0) -> [Day] {
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket in
result[bucket.startDate, default: 0] += bucket.tokens
}
-
+
return (0..<count).reversed().compactMap { offset in
guard let date = calendar.date(byAdding: .day, value: -(offset + endingDaysAgo), to: today) else {
return nil
}
-
+
let startDate = Self.dayFormatter.string(from: date)
return Day(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)
}
}
-
+
private nonisolated static let dayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
@@ -175,9 +175,9 @@ nonisolated extension CodexQuotaSnapshot {
guard let account = accountResponse.account else {
throw CodexRateLimitError.notLoggedIn
}
-
+
let snapshot = rateLimitsResponse.codexSnapshot
-
+
try self.init(
account: account,
snapshot: snapshot,
@@ -185,7 +185,7 @@ nonisolated extension CodexQuotaSnapshot {
generatedAt: generatedAt
)
}
-
+
private init(
account: CodexAccount?,
snapshot: RateLimitSnapshot,
@@ -195,7 +195,7 @@ nonisolated extension CodexQuotaSnapshot {
guard let primary = snapshot.primary else {
throw CodexRateLimitError.missingRateLimitWindow("5 小时额度")
}
-
+
self.init(
account: account,
planType: snapshot.planType,
@@ -218,24 +218,24 @@ nonisolated extension CodexQuotaSnapshot {
}
)
}
-
+
private static func windowLabel(for minutes: Int?, fallback: String) -> String {
guard let minutes, minutes > 0 else {
return fallback
}
-
+
if minutes < 60 {
return "\(minutes) 分钟"
}
-
+
if minutes.isMultiple(of: 1_440) {
return "\(minutes / 1_440) 天"
}
-
+
if minutes.isMultiple(of: 60) {
return "\(minutes / 60) 小时"
}
-
+
return "\(minutes) 分钟"
}
}
@@ -248,7 +248,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {
case missingRateLimitWindow(String)
case notLoggedIn
case authenticationRequired
-
+
var errorDescription: String? {
switch self {
case .executableNotFound:
@@ -267,7 +267,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {
return "Codex 需要身份验证"
}
}
-
+
var isAuthenticationRequired: Bool {
switch self {
case .serverError(let message):
@@ -278,4 +278,14 @@ nonisolated enum CodexRateLimitError: LocalizedError {
return false
}
}
+
+ /// 凭证已失效或未登录, 需要用户在 Codex 中重新登录才能恢复
+ var requiresLogin: Bool {
+ switch self {
+ case .notLoggedIn:
+ return true
+ default:
+ return isAuthenticationRequired
+ }
+ }
}
diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swift
index e662ac9..c1a1866 100644
--- a/CodexBar/RateLimitsMenuView.swift
+++ b/CodexBar/RateLimitsMenuView.swift
@@ -10,25 +10,23 @@ import SwiftUI
struct RateLimitsMenuView: View {
static let menuWidth: CGFloat = 360
-
+
@ObservedObject var viewModel: RateLimitsViewModel
@StateObject private var loginItemSettings = LoginItemSettings()
- @StateObject private var notificationSettings = NotificationSettings()
@State private var showsControls = false
-
+
var body: some View {
VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {
content
- errorView(viewModel.errorMessage)
+ // 未登录已有专属橙色提示, 不再重复显示同文案的红色错误行
+ errorView(viewModel.requiresLogin ? nil : viewModel.errorMessage)
errorView(loginItemSettings.errorMessage)
- errorView(notificationSettings.errorMessage)
controls
}
.padding(Metrics.padding)
.onAppear {
viewModel.refreshIfNeeded()
loginItemSettings.refresh()
- notificationSettings.refresh()
showsControls = NSEvent.modifierFlags.contains(.option)
}
}
@@ -41,22 +39,30 @@ private extension RateLimitsMenuView {
static let accountIconSize: CGFloat = 14
static let loadingVerticalPadding: CGFloat = 16
}
-
+
@ViewBuilder
var content: some View {
+ if viewModel.requiresLogin {
+ loginRequiredNotice
+ }
+
if let snapshot = viewModel.snapshot {
- accountRow(title: snapshot.accountLabel, plan: snapshot.planLabel)
-
- VStack(spacing: 8) {
- QuotaRow(window: snapshot.fiveHour)
- QuotaRow(window: snapshot.weekly)
- }
-
- if let usage = snapshot.usage {
- UsageSummaryView(usage: usage)
+ Group {
+ accountRow(title: snapshot.accountLabel, plan: snapshot.planLabel)
+
+ VStack(spacing: 8) {
+ QuotaRow(window: snapshot.fiveHour)
+ QuotaRow(window: snapshot.weekly)
+ }
+
+ if let usage = snapshot.usage {
+ UsageSummaryView(usage: usage)
+ }
+
+ updatedAtRow(for: snapshot)
}
-
- updatedAtRow(for: snapshot)
+ // 未登录时旧数据已过期, 置灰提示不可信
+ .opacity(viewModel.requiresLogin ? 0.4 : 1)
} else if viewModel.isRefreshing {
accountRow(title: "Codex")
loadingView
@@ -65,7 +71,21 @@ private extension RateLimitsMenuView {
emptyView
}
}
-
+
+ var loginRequiredNotice: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "person.crop.circle.badge.exclamationmark")
+ .foregroundStyle(.orange)
+
+ Text("Codex 未登录")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Spacer()
+ }
+ }
+
@ViewBuilder
var controls: some View {
if showsControls {
@@ -73,26 +93,26 @@ private extension RateLimitsMenuView {
settingsView
}
}
-
+
var loadingView: some View {
HStack(spacing: 10) {
ProgressView()
.controlSize(.small)
-
+
Text("正在获取数据")
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, Metrics.loadingVerticalPadding)
}
-
+
var emptyView: some View {
Text("暂无数据")
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, Metrics.loadingVerticalPadding)
}
-
+
func accountRow(title: String, plan: String? = nil) -> some View {
HStack(spacing: 8) {
Image(systemName: "person.fill")
@@ -101,20 +121,20 @@ private extension RateLimitsMenuView {
.onTapGesture(count: 2) {
viewModel.refresh()
}
-
+
Text(title)
.font(.caption.weight(.semibold))
.lineLimit(1)
.truncationMode(.middle)
-
+
if viewModel.isRefreshing {
ProgressView()
.controlSize(.small)
.padding(.leading, 2)
}
-
+
Spacer()
-
+
if let plan {
Text(plan.uppercased())
.font(.caption2)
@@ -126,37 +146,31 @@ private extension RateLimitsMenuView {
}
}
}
-
+
func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {
HStack {
Text("更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)")
.font(.caption2)
.foregroundStyle(.secondary)
-
+
Spacer()
}
}
-
+
var settingsView: some View {
- VStack(spacing: 8) {
- VStack(alignment: .leading, spacing: 8) {
- loginItemToggle
- notificationToggle
- }
- .frame(maxWidth: .infinity, alignment: .leading)
-
- HStack {
- Spacer()
-
- Button("退出") {
- NSApplication.shared.terminate(nil)
- }
- .foregroundStyle(.red)
- .keyboardShortcut("q")
+ HStack {
+ loginItemToggle
+
+ Spacer()
+
+ Button("退出") {
+ NSApplication.shared.terminate(nil)
}
+ .foregroundStyle(.red)
+ .keyboardShortcut("q")
}
}
-
+
var loginItemToggle: some View {
settingsToggle(
"开机自动启动",
@@ -164,15 +178,7 @@ private extension RateLimitsMenuView {
setEnabled: { loginItemSettings.setEnabled($0) }
)
}
-
- var notificationToggle: some View {
- settingsToggle(
- "额度重置通知",
- isEnabled: notificationSettings.isEnabled,
- setEnabled: { notificationSettings.setEnabled($0) }
- )
- }
-
+
func settingsToggle(
_ title: String,
isEnabled: Bool,
@@ -183,7 +189,7 @@ private extension RateLimitsMenuView {
.controlSize(.small)
.font(.caption)
}
-
+
@ViewBuilder
func errorView(_ message: String?) -> some View {
if let message {
@@ -194,7 +200,7 @@ private extension RateLimitsMenuView {
.frame(maxWidth: .infinity, alignment: .leading)
}
}
-
+
static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
@@ -207,37 +213,37 @@ private struct UsageSummaryView: View {
let usage: CodexUsageSnapshot
private let recentDays: [CodexUsageSnapshot.Day]
@State private var hoveredDay: CodexUsageSnapshot.Day?
-
+
init(usage: CodexUsageSnapshot) {
self.usage = usage
self.recentDays = usage.recentDays(count: 14, endingDaysAgo: 1)
}
-
+
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Divider()
-
+
HStack(alignment: .firstTextBaseline) {
metric(label: "单日峰值", value: usage.summary.peakDailyTokens, alignment: .leading)
Spacer()
hoveredMetric
Spacer()
- metric(label: "累计 Token", value: usage.summary.lifetimeTokens, alignment: .trailing)
+ metric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .trailing)
}
-
+
UsageBarChart(days: recentDays, hoveredDay: $hoveredDay)
}
.onAppear {
hoveredDay = nil
}
}
-
+
var hoveredMetric: some View {
VStack(spacing: 2) {
Text(hoveredDateText)
.font(.caption2.monospacedDigit())
.foregroundStyle(.secondary)
-
+
Text(hoveredTokensText)
.font(.caption.monospacedDigit().weight(.semibold))
.lineLimit(1)
@@ -246,26 +252,26 @@ private struct UsageSummaryView: View {
.opacity(hoveredDay == nil ? 0 : 1)
.frame(width: 112, alignment: .center)
}
-
+
private var hoveredDateText: String {
hoveredDay?.startDate ?? " "
}
-
+
private var hoveredTokensText: String {
guard let hoveredDay else {
return " "
}
-
+
return TokenCountFormatter.string(from: hoveredDay.tokens)
}
-
+
private func metric(label: String, value: Int, alignment: Alignment) -> some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(.caption2)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: alignment)
-
+
Text(TokenCountFormatter.string(from: value))
.font(.caption.monospacedDigit().weight(.semibold))
.lineLimit(1)
@@ -279,11 +285,11 @@ private struct UsageSummaryView: View {
private struct UsageBarChart: View {
let days: [CodexUsageSnapshot.Day]
@Binding var hoveredDay: CodexUsageSnapshot.Day?
-
+
private var peakTokens: Int {
max(days.map(\.tokens).max() ?? 0, 1)
}
-
+
var body: some View {
HStack(alignment: .bottom, spacing: 5) {
ForEach(days) { day in
@@ -309,15 +315,15 @@ private struct UsageBar: View {
let day: CodexUsageSnapshot.Day
let percent: Double
let isHovered: Bool
-
+
var body: some View {
GeometryReader { proxy in
let barHeight = max(day.tokens > 0 ? 2 : 0, proxy.size.height * clampedPercent)
-
+
ZStack(alignment: .bottom) {
Rectangle()
.fill(.secondary.opacity(isHovered ? 0.20 : 0.12))
-
+
Rectangle()
.fill(Color.orange.opacity(day.tokens > 0 ? barOpacity : 0))
.frame(height: barHeight)
@@ -326,11 +332,11 @@ private struct UsageBar: View {
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
}
-
+
private var clampedPercent: Double {
min(max(percent, 0), 1)
}
-
+
private var barOpacity: Double {
let opacity = 0.28 + clampedPercent * 0.62
return isHovered ? min(opacity + 0.10, 1.0) : opacity
@@ -342,15 +348,15 @@ private enum TokenCountFormatter {
if tokens >= 1_000_000_000 {
return decimal(Double(tokens) / 1_000_000_000) + "B"
}
-
+
return decimal(Double(tokens) / 1_000_000) + "M"
}
-
+
private static func decimal(_ value: Double) -> String {
let rounded = value >= 0.1 ? (value * 10).rounded() / 10 : (value * 100).rounded() / 100
return formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)
}
-
+
private static let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/RateLimitsViewModel.swift
index eee80e0..3e5772f 100644
--- a/CodexBar/RateLimitsViewModel.swift
+++ b/CodexBar/RateLimitsViewModel.swift
@@ -12,115 +12,66 @@ import Foundation
final class RateLimitsViewModel: ObservableObject {
@Published private(set) var snapshot: CodexQuotaSnapshot?
@Published private(set) var isRefreshing = false
- @Published private(set) var errorMessage: String?
-
+ @Published private(set) var lastError: CodexRateLimitError?
+
+ // UI 状态统一从 lastError 派生, 保证单一真相来源
+ var errorMessage: String? { lastError?.errorDescription }
+ var requiresLogin: Bool { lastError?.requiresLogin ?? false }
+ var hasError: Bool { lastError != nil }
+
private static let refreshInterval: TimeInterval = 60
-
+
private let service: CodexRateLimitService
- private let notificationService: QuotaNotificationService
private var autoRefreshTask: Task<Void, Never>?
- private var rateLimitUpdateTask: Task<Void, Never>?
- private var isHandlingRateLimitUpdate = false
-
+
init(service: CodexRateLimitService = CodexRateLimitService()) {
self.service = service
- self.notificationService = QuotaNotificationService()
}
-
+
deinit {
autoRefreshTask?.cancel()
- rateLimitUpdateTask?.cancel()
}
-
+
func refreshIfNeeded() {
guard snapshot == nil || Date().timeIntervalSince(snapshot?.generatedAt ?? .distantPast) > Self.refreshInterval else {
return
}
-
+
refresh()
}
-
+
func startAutoRefresh() {
- startRateLimitUpdateObserver()
-
guard autoRefreshTask == nil else {
return
}
-
+
autoRefreshTask = Task { [weak self] in
self?.refreshIfNeeded()
-
+
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: UInt64(Self.refreshInterval * 1_000_000_000))
self?.refresh()
}
}
}
-
+
func refresh() {
guard !isRefreshing else {
return
}
-
+
isRefreshing = true
- errorMessage = nil
-
+
Task {
do {
let snapshot = try await service.fetchRateLimits()
self.snapshot = snapshot
+ self.lastError = nil
} catch {
- self.errorMessage = error.localizedDescription
+ self.lastError = (error as? CodexRateLimitError) ?? .serverError(error.localizedDescription)
}
-
+
self.isRefreshing = false
}
}
-
- private func startRateLimitUpdateObserver() {
- guard rateLimitUpdateTask == nil else {
- return
- }
-
- let viewModelBox = WeakRateLimitsViewModelBox(self)
- rateLimitUpdateTask = Task.detached(priority: .utility) { [service, viewModelBox] in
- await service.observeRateLimitUpdates {
- Task { @MainActor [viewModelBox] in
- await viewModelBox.value?.handleRateLimitUpdate()
- }
- }
- }
- }
-
- private func handleRateLimitUpdate() async {
- guard !isHandlingRateLimitUpdate else {
- return
- }
-
- isHandlingRateLimitUpdate = true
- defer {
- isHandlingRateLimitUpdate = false
- }
-
- do {
- let updatedSnapshot = try await service.fetchRateLimits()
- snapshot = updatedSnapshot
- errorMessage = nil
-
- await notificationService.sendRateLimitUpdatedNotification()
- } catch {
- if snapshot == nil {
- errorMessage = error.localizedDescription
- }
- }
- }
-}
-
-private final class WeakRateLimitsViewModelBox: @unchecked Sendable {
- weak var value: RateLimitsViewModel?
-
- @MainActor
- init(_ value: RateLimitsViewModel) {
- self.value = value
- }
}
diff --git a/README.md b/README.md
index 5ccfac8..c49e41e 100644
--- a/README.md
+++ b/README.md
@@ -2,11 +2,12 @@
CodexBar 是一个轻量级 macOS 菜单栏应用,用来查看当前本机 Codex 账号的额度使用情况。
-它会启动本机 Codex 的 app-server,完成 JSON-RPC 初始化流程后读取账号信息和额度信息,并在菜单栏弹窗中展示不同时间窗口的额度。
+它会启动本机 Codex 的 app-server 并维持一条常驻 JSON-RPC 连接,完成初始化握手后定期读取账号信息和额度信息,并在菜单栏弹窗中展示不同时间窗口的额度。
## 功能
-- 菜单栏使用 `timelapse` SF Symbol;App 图标是白底黑色 `timelapse`
+- 菜单栏图标:正常时显示 `person.fill.checkmark`,任何错误(包括未登录)时切换为 `person.fill.xmark`,切换带 symbol 替换动画
+- App 图标是白底黑色 `timelapse`
- 弹窗第一行展示账号信息和套餐
- 弹窗使用两行分段电量条展示额度窗口,标签根据 `windowDurationMins` 动态生成
- 每行额度在进度条右侧展示剩余百分比和重置时间
@@ -14,10 +15,10 @@ CodexBar 是一个轻量级 macOS 菜单栏应用,用来查看当前本机 Cod
- 鼠标划过 token 柱状图中的单日柱子时,展示对应日期和用量
- 更新时间显示在额度行下方,并使用 `HH:mm:ss` 格式
- 应用运行时每分钟自动刷新额度,即使弹窗未打开也会刷新
-- 收到 `account/rateLimits/updated` 后会重新查询额度,并在「额度通知」已开启时发送本地通知
- 双击账号图标可手动刷新
- 不按 Option/Alt 点击菜单栏图标时,只展示额度内容
-- 按住 Option/Alt 点击菜单栏图标时,才展示设置区;设置区包含「开机启动」「额度通知」开关和「退出」按钮
+- 按住 Option/Alt 点击菜单栏图标时,才展示设置区;设置区为单行布局,左侧「开机自动启动」开关,右侧「退出」按钮
+- 未登录或认证失效时,弹窗顶部展示橙色提示,旧额度数据置灰保留展示
## 运行要求
@@ -39,31 +40,44 @@ codex app-server --listen stdio://
如果两个入口都不可用,弹窗中会展示「找不到 Codex CLI 或 Codex App」的错误。
-连接后会先发送初始化请求,再读取账号和额度:
+## 连接与刷新
+
+应用与 app-server 维持一条常驻连接:首次拉取时启动进程并完成握手,之后所有额度读取复用同一会话。
+
+建立连接时按顺序发送:
```json
{"method":"initialize","id":1,"params":{"clientInfo":{"name":"codex_bar","title":"Codex Bar","version":"1.0.0"}}}
{"method":"initialized"}
{"method":"account/read","id":2,"params":{"refreshToken":false}}
+```
+
+之后每分钟在同一会话上读取额度和用量:
+
+```json
{"method":"account/rateLimits/read","id":3}
{"method":"account/usage/read","id":4}
```
+连接会在以下情况自动重建:
+
+- app-server 进程已退出
+- 连接存活超过 1 小时(定期回收,覆盖 codex 全局升级后切换新二进制、服务端状态漂移等陈旧问题)
+- 复用连接上的请求失败(重建一次再试;全新连接上的失败直接报错,不做二次重试)
+
+认证处理:`account/rateLimits/read` 返回认证错误时,会先用 `account/read`(`refreshToken: true`)刷新 token 再重试一次;仍然失败则按「需要重新登录」处理,丢弃当前连接——下一次轮询会起新进程读取最新的登录凭证,因此用户重新登录后最多一分钟自动恢复。
+
+## 额度数据
+
额度窗口来自 Codex app-server 返回的 `primary` 和 `secondary`:
- `usedPercent`:已用百分比
-- `windowDurationMins`:额度窗口分钟数,用来生成 `5 小时`、`7 天`、`5h`、`7d` 等标签
+- `windowDurationMins`:额度窗口分钟数,用来生成 `5 小时`、`7 天` 等标签
- `resetsAt`:秒级 Unix 时间戳,弹窗中显示为 `MM-dd HH:mm`
剩余额度统一按 `100 - usedPercent` 计算。
-应用会保留一个后台 app-server 连接监听 `account/rateLimits/updated` 通知。该通知是稀疏更新,收到后不会直接用通知 payload 更新 UI,而是重新调用 `account/rateLimits/read` 获取完整额度并更新 UI;如果「额度通知」开启且系统通知权限已授权,则发送 macOS 本地通知。
-
-后台监听连接启动时也会按 `account/read`、`account/rateLimits/read` 的顺序初始化额度路径。如果监听连接因为 app-server 退出、认证失败或响应超时而断开,应用会在 30 秒后重新启动监听连接。
-
-「额度通知」开关只在按住 Option/Alt 打开菜单栏弹窗时展示。开启该开关时会请求 macOS 通知权限;关闭后不再发送额度更新通知。
-
-token 使用量来自 Codex app-server 返回的 `account/usage/read`:
+token 使用量来自 `account/usage/read`:
- `summary.lifetimeTokens`:累计 token
- `summary.peakDailyTokens`:单日峰值 token
@@ -76,9 +90,12 @@ token 柱状图使用橙色,单日用量越高颜色越浓。
## 错误展示
-CodexBar 会在弹窗中用红色小字展示错误,例如未安装 Codex、app-server 启动失败、响应超时、当前未登录、需要重新验证身份、响应中缺少额度窗口等。应用不包含调试模拟入口,也不会在窗口里展示 Debug 明细。
+错误分为两类,展示方式不同:
+
+- **登录类错误**(未登录、认证失效):菜单栏图标切换为 `person.fill.xmark`;弹窗顶部展示橙色提示「Codex 未登录」;如果之前成功读取过额度,旧快照置灰保留展示,表示数据已过期。
+- **其他错误**(未安装 Codex、app-server 启动失败、响应超时、响应中缺少额度窗口等):菜单栏图标同样切换为 `person.fill.xmark`;弹窗中用红色小字展示错误文案;旧快照保持正常亮度展示,可通过更新时间判断数据新旧。
-如果应用运行期间 Codex 退出登录或认证失效,每分钟自动刷新会继续尝试读取额度;刷新失败时会展示对应错误。如果之前已经成功读取过额度,旧的额度快照不会被清空,弹窗会继续显示上一次成功读取的数据和对应更新时间,同时显示错误文案。收到 `account/rateLimits/updated` 后触发的刷新如果失败,不会更新 UI,也不会发送通知;只有在当前没有任何旧快照时才会把该错误展示到弹窗中。
+错误文案会保持显示,直到某次刷新成功才清除。应用不包含调试模拟入口,也不会在窗口里展示 Debug 明细。
## 构建