Skip to content

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

feat: implement Codex quota menu bar app

Bob537f836b90a4
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..2cce999
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,34 @@
+# macOS
+.DS_Store
+
+# Xcode
+DerivedData/
+build/
+*.xcarchive
+*.xcresult
+*.dSYM
+*.moved-aside
+
+# User-specific Xcode state
+xcuserdata/
+*.xcuserstate
+*.xcscmblueprint
+
+# Swift Package Manager
+.build/
+.swiftpm/
+Package.resolved
+
+# Code signing inspection output
+codesign0
+codesign1
+codesign2
+
+# Archives and exported apps
+*.ipa
+*.pkg
+*.dmg
+*.zip
+
+# Logs
+*.log
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..e8cfc20
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,128 @@
+# CodexBar 项目记忆
+
+## 项目概览
+
+CodexBar 是一个 macOS 菜单栏应用,用来展示当前本机 Codex 账号的额度信息。应用使用 SwiftUI + MVVM,主入口是 `MenuBarExtra`,弹窗使用 `.menuBarExtraStyle(.window)`。
+
+当前最低系统版本是 macOS 15.0。
+
+## 核心功能
+
+- 菜单栏只展示 `timelapse` SF Symbol,App 图标使用白底黑色 `timelapse`。
+- 弹窗第一行展示账号信息和套餐。
+- 弹窗展示两行分段电量条,额度行标签根据 `windowDurationMins` 动态生成。
+- 每行额度在进度条右侧展示剩余百分比和重置时间。
+- 更新时间显示在左侧。
+- 应用运行时每分钟自动刷新,即使弹窗未打开也会刷新。
+- 双击账号图标可手动刷新。
+- 按住 Option/Alt 点击菜单栏图标时,才展示控制区。
+- Option/Alt 控制区包含「开机启动」开关和「退出」按钮,不展示刷新按钮。
+- 弹窗错误只展示普通红色错误文案,不包含 Debug 明细或环境变量模拟入口。
+
+## Codex 数据来源
+
+应用通过本机 Codex app-server 读取数据。启动优先级:
+
+1. 如果全局 Codex CLI 可用,优先使用:
+
+```bash
+codex app-server --listen stdio://
+```
+
+2. 如果找不到全局 CLI,则回退到 Codex.app 内置二进制:
+
+```bash
+/Applications/Codex.app/Contents/Resources/codex app-server --listen stdio://
+```
+
+连接后必须按顺序发送:
+
+```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}
+```
+
+注意:不能在 `initialize` 和 `initialized` 完成前请求额度,否则 Codex app-server 会拒绝请求。
+
+## 认证和沙盒
+
+CodexBar 必须使用真实 macOS 用户的 Codex 登录数据。之前遇到过 Xcode 运行时 `HOME` 指向 app container,导致 app-server 读取不到 `/Users/{username}/.codex`,报错:
+
+```text
+codex account authentication required to read rate limits
+```
+
+当前服务层会用真实用户 home 运行 app-server,避免读到沙盒容器路径。
+
+Xcode target 已关闭 App Sandbox,因为应用需要启动本机 Codex CLI 并访问用户的 Codex 登录状态。
+
+如果既找不到全局 Codex CLI,也找不到 Codex.app 内置二进制,弹窗会展示 `找不到 Codex CLI 或 Codex App` 错误。
+
+## 代码组织
+
+- `CodexBarApp.swift`:应用入口,创建 `RateLimitsViewModel`,配置 `MenuBarExtra`。
+- `RateLimitsViewModel.swift`:视图模型,负责快照状态、刷新状态、自动刷新。
+- `CodexRateLimitService.swift`:启动 Codex app-server,并处理 JSON-RPC 请求/响应。
+- `RateLimitModels.swift`:Codex 响应模型、业务快照模型、错误文案。
+- `MenuBarStatusView.swift`:菜单栏常驻展示,只包含 `timelapse` 动画图标。
+- `RateLimitsMenuView.swift`:点击菜单栏后的弹窗内容。
+- `QuotaRow.swift`:额度行和分段进度条。
+- `LoginItemSettings.swift`:使用 `SMAppService.mainApp` 管理开机自启。
+- `Assets.xcassets/AppIcon.appiconset`:App 图标资源,白底黑色中心符号使用 `timelapse`。
+- `Scripts/create-dmg.sh`:将项目根目录下导出的 `.app` 打包成拖拽安装 DMG。
+
+## UI 约定
+
+- 菜单栏图标使用 `timelapse`。菜单栏图标直接使用:
+
+```swift
+.symbolEffect(.variableColor.cumulative.hideInactiveLayers.nonReversing, options: .repeat(.continuous))
+```
+
+- 不要再给 `symbolEffect` 加低版本 fallback;最低系统版本已经定为 macOS 15.0。
+- App 图标保持白底黑色 `timelapse`,不要恢复成蓝绿色图标。
+- 菜单栏不展示额度数字、窗口标签或外层圈数;额度详情只在弹窗中展示。
+- 弹窗账号图标使用 `person.fill`,双击该图标刷新数据。
+- 弹窗字体要保持紧凑,避免菜单栏弹窗内容被截断。
+- 分段条展示剩余额度,剩余额度计算方式是 `100 - usedPercent`。
+- 额度行标签示例:`300` 分钟显示 `5 小时`,`10080` 分钟显示 `7 天`;缺少 `windowDurationMins` 时再回退到默认文案。
+- 重置时间格式使用 `MM-dd HH:mm`。
+- 更新时间格式使用 `HH:mm:ss`。
+
+## 错误和调试
+
+- 当前代码不包含 Debug UI、Debug 详情展示或环境变量模拟错误入口。
+- Codex 交互错误会通过 `CodexRateLimitError.localizedDescription` 展示在弹窗中。
+- 开机启动设置失败会展示 `设置开机启动失败: ...`。
+
+## 构建验证
+
+修改后至少运行:
+
+```bash
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+```
+
+当前已验证该命令可通过。
+
+## 分发备注
+
+项目用于直接分发时,应使用 `Developer ID Application` 证书签名,并进行 notarization。
+
+Xcode 导出 `CodexBar.app` 到项目根目录后,可以运行:
+
+```bash
+Scripts/create-dmg.sh
+```
+
+脚本会自动查找当前目录下唯一的 `.app`,根据 Xcode target 的 `MARKETING_VERSION` 生成 `CodexBar-v{version}.dmg`。脚本会在 DMG 中放入 `CodexBar.app` 和 `Applications -> /Applications` 快捷方式,并写入 Finder 布局:app 在左侧,Applications 在右侧。若有多个工程或 scheme,可用 `XCODE_PROJECT`、`XCODE_SCHEME` 环境变量指定。
+
+## Git 远端
+
+当前远端仓库:
+
+```text
[email protected]:bob-zebedy/CodexBar.git
+```
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 3468bf2..c1b7d0d 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -179,7 +179,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -237,7 +237,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
@@ -250,22 +250,26 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4KJ362VJW5;
- ENABLE_APP_SANDBOX = YES;
+ ENABLE_APP_SANDBOX = NO;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
- ENABLE_USER_SELECTED_FILES = readonly;
+ ENABLE_USER_SELECTED_FILES = NO;
GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_CFBundleDisplayName = CodexBar;
+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
+ INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 1.0;
- PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.CodexBar;
+ MARKETING_VERSION = 1.0.0;
+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
REGISTER_APP_GROUPS = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
@@ -282,23 +286,29 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
+ CODE_SIGN_IDENTITY = "Apple Development";
+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
DEVELOPMENT_TEAM = 4KJ362VJW5;
- ENABLE_APP_SANDBOX = YES;
+ ENABLE_APP_SANDBOX = NO;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
- ENABLE_USER_SELECTED_FILES = readonly;
+ ENABLE_USER_SELECTED_FILES = NO;
GENERATE_INFOPLIST_FILE = YES;
+ INFOPLIST_KEY_CFBundleDisplayName = CodexBar;
+ INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";
+ INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 1.0;
- PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.CodexBar;
+ MARKETING_VERSION = 1.0.0;
+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
+ PROVISIONING_PROFILE_SPECIFIER = "";
REGISTER_APP_GROUPS = YES;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_APPROACHABLE_CONCURRENCY = YES;
diff --git a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme
new file mode 100644
index 0000000..5e96fbb
--- /dev/null
+++ b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+ LastUpgradeVersion = "2650"
+ version = "1.7">
+ <BuildAction
+ parallelizeBuildables = "YES"
+ buildImplicitDependencies = "YES"
+ buildArchitectures = "Automatic">
+ <BuildActionEntries>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "C4A0FD942FD9302E000263A7"
+ BuildableName = "CodexBar.app"
+ BlueprintName = "CodexBar"
+ ReferencedContainer = "container:CodexBar.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
+ </BuildActionEntries>
+ </BuildAction>
+ <TestAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ shouldAutocreateTestPlan = "YES">
+ </TestAction>
+ <LaunchAction
+ buildConfiguration = "Debug"
+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+ launchStyle = "0"
+ useCustomWorkingDirectory = "NO"
+ ignoresPersistentStateOnLaunch = "NO"
+ debugDocumentVersioning = "YES"
+ debugServiceExtension = "internal"
+ allowLocationSimulation = "YES"
+ queueDebuggingEnableBacktraceRecording = "Yes">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "C4A0FD942FD9302E000263A7"
+ BuildableName = "CodexBar.app"
+ BlueprintName = "CodexBar"
+ ReferencedContainer = "container:CodexBar.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </LaunchAction>
+ <ProfileAction
+ buildConfiguration = "Release"
+ shouldUseLaunchSchemeArgsEnv = "YES"
+ savedToolIdentifier = ""
+ useCustomWorkingDirectory = "NO"
+ debugDocumentVersioning = "YES">
+ <BuildableProductRunnable
+ runnableDebuggingMode = "0">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "C4A0FD942FD9302E000263A7"
+ BuildableName = "CodexBar.app"
+ BlueprintName = "CodexBar"
+ ReferencedContainer = "container:CodexBar.xcodeproj">
+ </BuildableReference>
+ </BuildableProductRunnable>
+ </ProfileAction>
+ <AnalyzeAction
+ buildConfiguration = "Debug">
+ </AnalyzeAction>
+ <ArchiveAction
+ buildConfiguration = "Release"
+ revealArchiveInOrganizer = "YES">
+ </ArchiveAction>
+</Scheme>
diff --git a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist
index 0f05ed1..e815e2c 100644
--- a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist
+++ b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist
@@ -10,5 +10,13 @@
<integer>0</integer>
</dict>
</dict>
+ <key>SuppressBuildableAutocreation</key>
+ <dict>
+ <key>C4A0FD942FD9302E000263A7</key>
+ <dict>
+ <key>primary</key>
+ <true/>
+ </dict>
+ </dict>
</dict>
</plist>
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/Contents.json b/CodexBar/Assets.xcassets/AppIcon.appiconset/Contents.json
index 3f00db4..64dc11e 100644
--- a/CodexBar/Assets.xcassets/AppIcon.appiconset/Contents.json
+++ b/CodexBar/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -1,51 +1,61 @@
{
"images" : [
{
+ "filename" : "icon_16x16.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
+ "filename" : "[email protected]",
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
+ "filename" : "icon_32x32.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
+ "filename" : "[email protected]",
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
+ "filename" : "icon_128x128.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
+ "filename" : "[email protected]",
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
+ "filename" : "icon_256x256.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
+ "filename" : "[email protected]",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
+ "filename" : "icon_512x512.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
+ "filename" : "[email protected]",
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_128x128.png b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_128x128.png
new file mode 100644
index 0000000..803f1b9
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_128x128.png differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..acd342f
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_16x16.png b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_16x16.png
new file mode 100644
index 0000000..c9d1d06
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_16x16.png differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..12ef8cd
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_256x256.png b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_256x256.png
new file mode 100644
index 0000000..acd342f
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_256x256.png differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..13e950f
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_32x32.png b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_32x32.png
new file mode 100644
index 0000000..12ef8cd
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_32x32.png differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..4c5486a
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_512x512.png b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_512x512.png
new file mode 100644
index 0000000..13e950f
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/icon_512x512.png differ
diff --git a/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected]
new file mode 100644
index 0000000..ea684e7
Binary files /dev/null and b/CodexBar/Assets.xcassets/AppIcon.appiconset/[email protected] differ
diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/CodexBarApp.swift
index 63a6bc7..82d0f8e 100644
--- a/CodexBar/CodexBarApp.swift
+++ b/CodexBar/CodexBarApp.swift
@@ -9,9 +9,15 @@ import SwiftUI
@main
struct CodexBarApp: App {
+ @StateObject private var viewModel = RateLimitsViewModel()
+
var body: some Scene {
- WindowGroup {
- ContentView()
+ MenuBarExtra {
+ RateLimitsMenuView(viewModel: viewModel)
+ .frame(width: RateLimitsMenuView.menuWidth)
+ } label: {
+ MenuBarStatusView(viewModel: viewModel)
}
+ .menuBarExtraStyle(.window)
}
}
diff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swift
new file mode 100644
index 0000000..8368878
--- /dev/null
+++ b/CodexBar/CodexRateLimitService.swift
@@ -0,0 +1,430 @@
+//
+// CodexRateLimitService.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import Darwin
+import Foundation
+
+struct CodexRateLimitService: 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 nonisolated static func fetchRateLimitsSynchronously(
+ command: AppServerCommand,
+ environment: [String: String],
+ clientVersion: String,
+ timeout: TimeInterval
+ ) throws -> CodexQuotaSnapshot {
+ 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(
+ 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
+ )
+ } catch let error as CodexRateLimitError where error.isAuthenticationRequired {
+ accountResponse = try session.request(
+ "account/read",
+ params: ["refreshToken": true],
+ 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 CodexQuotaSnapshot(
+ accountResponse: accountResponse,
+ rateLimitsResponse: rateLimitsResponse
+ )
+ }
+
+ private nonisolated static func appServerEnvironment() -> [String: String] {
+ var environment = ProcessInfo.processInfo.environment
+ let homeDirectory = realUserHomeDirectory()
+ let path = environment["PATH"] ?? ""
+ let fallbackPaths = [
+ "/opt/homebrew/bin",
+ "/usr/local/bin",
+ "\(homeDirectory)/.npm-global/bin",
+ "\(homeDirectory)/.local/bin",
+ "\(homeDirectory)/.volta/bin",
+ "/usr/bin",
+ "/bin",
+ "/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]
+ ) -> String? {
+ 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 AppServerSession {
+ 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) {
+ self.input = input
+ self.lineReader = lineReader
+ self.errorReader = errorReader
+ self.timeout = timeout
+ }
+
+ 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,
+ as type: Response.Type
+ ) throws -> Response {
+ let id = nextId
+ nextId += 1
+ 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 {
+ object["id"] = id
+ }
+ if let params {
+ object["params"] = params
+ }
+ 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,
+ decode type: Response.Type
+ ) 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)")
+ }
+}
+
+private nonisolated struct AppServerCommand: Sendable {
+ let executablePath: String
+ let arguments = ["app-server", "--listen", "stdio://"]
+}
+
+private nonisolated struct EmptyResponse: Decodable {}
+
+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] = []
+
+ 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 {
+ lines.append(line)
+ semaphore.signal()
+ }
+ }
+ }
+
+ 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 {
+ 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)
+ }
+}
diff --git a/CodexBar/ContentView.swift b/CodexBar/ContentView.swift
deleted file mode 100644
index 38d4dbd..0000000
--- a/CodexBar/ContentView.swift
+++ /dev/null
@@ -1,24 +0,0 @@
-//
-// ContentView.swift
-// CodexBar
-//
-// Created by Bob on 2026-06-10.
-//
-
-import SwiftUI
-
-struct ContentView: View {
- var body: some View {
- VStack {
- Image(systemName: "globe")
- .imageScale(.large)
- .foregroundStyle(.tint)
- Text("Hello, world!")
- }
- .padding()
- }
-}
-
-#Preview {
- ContentView()
-}
diff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/LoginItemSettings.swift
new file mode 100644
index 0000000..848a6ec
--- /dev/null
+++ b/CodexBar/LoginItemSettings.swift
@@ -0,0 +1,41 @@
+//
+// LoginItemSettings.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import Combine
+import Foundation
+import ServiceManagement
+
+@MainActor
+final class LoginItemSettings: ObservableObject {
+ @Published private(set) var isEnabled = false
+ @Published private(set) var errorMessage: String?
+
+ init() {
+ refresh()
+ }
+
+ func refresh() {
+ isEnabled = SMAppService.mainApp.status == .enabled
+ }
+
+ func setEnabled(_ enabled: Bool) {
+ errorMessage = nil
+
+ do {
+ if enabled {
+ try SMAppService.mainApp.register()
+ } else {
+ try SMAppService.mainApp.unregister()
+ }
+
+ refresh()
+ } catch {
+ refresh()
+ errorMessage = "设置开机启动失败: \(error.localizedDescription)"
+ }
+ }
+}
diff --git a/CodexBar/MenuBarStatusView.swift b/CodexBar/MenuBarStatusView.swift
new file mode 100644
index 0000000..b3b61e0
--- /dev/null
+++ b/CodexBar/MenuBarStatusView.swift
@@ -0,0 +1,19 @@
+//
+// MenuBarStatusView.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import SwiftUI
+
+struct MenuBarStatusView: View {
+ @ObservedObject var viewModel: RateLimitsViewModel
+
+ var body: some View {
+ Image(systemName: "timelapse")
+ .task {
+ viewModel.startAutoRefresh()
+ }
+ }
+}
diff --git a/CodexBar/QuotaRow.swift b/CodexBar/QuotaRow.swift
new file mode 100644
index 0000000..f8fb8f7
--- /dev/null
+++ b/CodexBar/QuotaRow.swift
@@ -0,0 +1,137 @@
+//
+// QuotaRow.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import SwiftUI
+
+struct QuotaRow: View {
+ let window: QuotaWindow
+
+ var body: some View {
+ HStack(alignment: .center, spacing: Metrics.spacing) {
+ Text(window.label)
+ .font(.caption.weight(.semibold))
+ .lineLimit(1)
+ .frame(width: Metrics.labelWidth, alignment: .leading)
+
+ SegmentedQuotaBar(percent: window.remainingPercent)
+ .frame(height: Metrics.barHeight)
+
+ Text(percentText)
+ .font(.caption.monospacedDigit().weight(.semibold))
+ .lineLimit(1)
+ .frame(width: Metrics.percentWidth, alignment: .leading)
+
+ Text(resetText)
+ .font(.caption2.monospacedDigit())
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .frame(width: Metrics.resetWidth, alignment: .trailing)
+ }
+ }
+}
+
+private extension QuotaRow {
+ enum Metrics {
+ static let spacing: CGFloat = 8
+ static let labelWidth: CGFloat = 52
+ static let barHeight: CGFloat = 12
+ static let percentWidth: CGFloat = 32
+ static let resetWidth: CGFloat = 76
+ }
+
+ var resetText: String {
+ guard window.hasData else {
+ return "暂无数据"
+ }
+
+ guard let resetsAt = window.resetsAt else {
+ return "--"
+ }
+
+ return Self.resetFormatter.string(from: resetsAt)
+ }
+
+ var percentText: String {
+ guard window.hasData else {
+ return "--"
+ }
+
+ return "\(window.remainingPercent)%"
+ }
+
+ static let resetFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "zh_CN")
+ formatter.dateFormat = "MM-dd HH:mm"
+ return formatter
+ }()
+}
+
+private struct SegmentedQuotaBar: View {
+ let percent: Int
+
+ var body: some View {
+ HStack(spacing: Metrics.spacing) {
+ ForEach(0..<Metrics.segmentCount, id: \.self) { index in
+ Capsule(style: .continuous)
+ .fill(index < filledSegments ? fillStyle : emptyStyle)
+ .frame(maxWidth: .infinity)
+ }
+ }
+ .accessibilityLabel("剩余 \(percent)%")
+ }
+}
+
+private extension SegmentedQuotaBar {
+ enum Metrics {
+ static let spacing: CGFloat = 2
+ static let segmentCount = 20
+ }
+
+ var filledSegments: Int {
+ Int((Double(percent) / 100.0 * Double(Metrics.segmentCount)).rounded())
+ }
+
+ var fillStyle: Color {
+ switch percent {
+ case 50...:
+ return .green
+ case 25..<50:
+ return .orange
+ default:
+ return .red
+ }
+ }
+
+ var emptyStyle: Color {
+ Color.secondary.opacity(0.18)
+ }
+}
+
+#Preview {
+ VStack {
+ QuotaRow(
+ window: QuotaWindow(
+ kind: .fiveHour,
+ label: "5 小时",
+ usedPercent: 24,
+ resetsAt: Date().addingTimeInterval(3600)
+ )
+ )
+
+ QuotaRow(
+ window: QuotaWindow(
+ kind: .weekly,
+ label: "7 天",
+ usedPercent: 50,
+ resetsAt: Date().addingTimeInterval(86400)
+ )
+ )
+ }
+ .padding()
+ .frame(width: RateLimitsMenuView.menuWidth)
+}
diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/RateLimitModels.swift
new file mode 100644
index 0000000..52d81fa
--- /dev/null
+++ b/CodexBar/RateLimitModels.swift
@@ -0,0 +1,223 @@
+//
+// RateLimitModels.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import Foundation
+
+nonisolated struct CodexQuotaSnapshot: Equatable {
+ let account: CodexAccount?
+ let planType: String?
+ let limitName: String?
+ let generatedAt: Date
+ let fiveHour: QuotaWindow
+ let weekly: QuotaWindow
+
+ var title: String {
+ if let limitName, !limitName.isEmpty {
+ return limitName
+ }
+
+ return "Codex"
+ }
+
+ var accountLabel: String {
+ account?.displayName ?? "未登录"
+ }
+
+ var planLabel: String? {
+ account?.planType ?? planType
+ }
+}
+
+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"
+ case "chatgpt":
+ return "ChatGPT"
+ case "amazonBedrock":
+ return "Amazon Bedrock"
+ default:
+ return type
+ }
+ }
+}
+
+nonisolated struct AccountReadResponse: Decodable {
+ let account: CodexAccount?
+ let requiresOpenaiAuth: Bool
+}
+
+nonisolated struct QuotaWindow: Equatable, Identifiable {
+ enum Kind: String {
+ 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
+ }
+}
+
+nonisolated struct AccountRateLimitsResponse: Decodable {
+ let rateLimits: RateLimitSnapshot
+ let rateLimitsByLimitId: [String: RateLimitSnapshot]?
+
+ var codexSnapshot: RateLimitSnapshot {
+ rateLimitsByLimitId?["codex"] ?? rateLimits
+ }
+}
+
+nonisolated struct RateLimitSnapshot: Decodable {
+ let limitName: String?
+ let planType: String?
+ let primary: RateLimitWindow?
+ let secondary: RateLimitWindow?
+}
+
+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))
+ }
+}
+
+nonisolated extension CodexQuotaSnapshot {
+ init(
+ accountResponse: AccountReadResponse,
+ rateLimitsResponse: AccountRateLimitsResponse,
+ generatedAt: Date = Date()
+ ) throws {
+ guard let account = accountResponse.account else {
+ throw CodexRateLimitError.notLoggedIn
+ }
+
+ let snapshot = rateLimitsResponse.codexSnapshot
+
+ try self.init(
+ account: account,
+ snapshot: snapshot,
+ generatedAt: generatedAt
+ )
+ }
+
+ private init(
+ account: CodexAccount?,
+ snapshot: RateLimitSnapshot,
+ generatedAt: Date
+ ) throws {
+ guard let primary = snapshot.primary else {
+ throw CodexRateLimitError.missingRateLimitWindow("5 小时额度")
+ }
+
+ self.init(
+ account: account,
+ planType: snapshot.planType,
+ limitName: snapshot.limitName,
+ generatedAt: generatedAt,
+ fiveHour: QuotaWindow(
+ kind: .fiveHour,
+ label: Self.windowLabel(for: primary.windowDurationMins, fallback: "5 小时"),
+ usedPercent: primary.usedPercent,
+ resetsAt: primary.resetDate
+ ),
+ weekly: QuotaWindow(
+ kind: .weekly,
+ label: Self.windowLabel(for: snapshot.secondary?.windowDurationMins, fallback: "7 天"),
+ usedPercent: snapshot.secondary?.usedPercent,
+ resetsAt: snapshot.secondary?.resetDate
+ )
+ )
+ }
+
+ 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) 分钟"
+ }
+}
+
+nonisolated enum CodexRateLimitError: LocalizedError {
+ case executableNotFound
+ case serverStartFailed(String)
+ case serverTimeout(String)
+ case serverError(String)
+ case missingRateLimitWindow(String)
+ 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 .serverError(let message):
+ return "Codex app-server 返回错误: \(message)"
+ case .missingRateLimitWindow(let name):
+ return "查询不到 \(name)"
+ case .notLoggedIn:
+ return "Codex 未登录"
+ case .authenticationRequired:
+ return "Codex 需要身份验证"
+ }
+ }
+
+ var isAuthenticationRequired: Bool {
+ switch self {
+ case .serverError(let message):
+ return message.localizedCaseInsensitiveContains("authentication required")
+ case .authenticationRequired:
+ return true
+ default:
+ return false
+ }
+ }
+}
diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swift
new file mode 100644
index 0000000..2a39956
--- /dev/null
+++ b/CodexBar/RateLimitsMenuView.swift
@@ -0,0 +1,182 @@
+//
+// RateLimitsMenuView.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import AppKit
+import SwiftUI
+
+struct RateLimitsMenuView: View {
+ static let menuWidth: CGFloat = 360
+
+ @ObservedObject var viewModel: RateLimitsViewModel
+ @StateObject private var loginItemSettings = LoginItemSettings()
+ @State private var showsControls = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {
+ content
+ errorView(viewModel.errorMessage)
+ errorView(loginItemSettings.errorMessage)
+ controls
+ }
+ .padding(Metrics.padding)
+ .onAppear {
+ viewModel.refreshIfNeeded()
+ loginItemSettings.refresh()
+ showsControls = NSEvent.modifierFlags.contains(.option)
+ }
+ }
+}
+
+private extension RateLimitsMenuView {
+ enum Metrics {
+ static let padding: CGFloat = 12
+ static let verticalSpacing: CGFloat = 10
+ static let accountIconSize: CGFloat = 14
+ static let loadingVerticalPadding: CGFloat = 16
+ }
+
+ @ViewBuilder
+ var content: some View {
+ if let snapshot = viewModel.snapshot {
+ accountRow(title: snapshot.accountLabel, plan: snapshot.planLabel)
+
+ VStack(spacing: 8) {
+ QuotaRow(window: snapshot.fiveHour)
+ QuotaRow(window: snapshot.weekly)
+ }
+
+ updatedAtRow(for: snapshot)
+ } else if viewModel.isRefreshing {
+ accountRow(title: "Codex")
+ loadingView
+ } else {
+ accountRow(title: "Codex")
+ emptyView
+ }
+ }
+
+ @ViewBuilder
+ var controls: some View {
+ if showsControls {
+ Divider()
+ controlsRow
+ }
+ }
+
+ 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")
+ .font(.system(size: Metrics.accountIconSize, weight: .medium))
+ .foregroundStyle(.tint)
+ .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)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 2)
+ .background(.secondary.opacity(0.12), in: Capsule())
+ }
+ }
+ }
+
+ func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {
+ HStack {
+ Text("更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+ }
+ }
+
+ var controlsRow: some View {
+ HStack {
+ loginItemToggle
+
+ Spacer()
+
+ Button("退出") {
+ NSApplication.shared.terminate(nil)
+ }
+ .keyboardShortcut("q")
+ }
+ }
+
+ var loginItemToggle: some View {
+ Toggle(
+ "开机启动",
+ isOn: Binding(
+ get: { loginItemSettings.isEnabled },
+ set: { loginItemSettings.setEnabled($0) }
+ )
+ )
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ .font(.caption)
+ }
+
+ @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)
+ }
+ }
+
+ static let timeFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "zh_CN")
+ formatter.dateFormat = "HH:mm:ss"
+ return formatter
+ }()
+}
+
+#Preview {
+ let viewModel = RateLimitsViewModel()
+ return RateLimitsMenuView(viewModel: viewModel)
+ .frame(width: RateLimitsMenuView.menuWidth)
+}
diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/RateLimitsViewModel.swift
new file mode 100644
index 0000000..8b434dc
--- /dev/null
+++ b/CodexBar/RateLimitsViewModel.swift
@@ -0,0 +1,68 @@
+//
+// RateLimitsViewModel.swift
+// CodexBar
+//
+// Created by Bob on 2026-06-10.
+//
+
+import Combine
+import Foundation
+
+@MainActor
+final class RateLimitsViewModel: ObservableObject {
+ @Published private(set) var snapshot: CodexQuotaSnapshot?
+ @Published private(set) var isRefreshing = false
+ @Published private(set) var errorMessage: String?
+
+ private static let refreshInterval: TimeInterval = 60
+
+ private let service: CodexRateLimitService
+ private var autoRefreshTask: Task<Void, Never>?
+
+ init(service: CodexRateLimitService = CodexRateLimitService()) {
+ self.service = service
+ }
+
+ func refreshIfNeeded() {
+ guard snapshot == nil || Date().timeIntervalSince(snapshot?.generatedAt ?? .distantPast) > Self.refreshInterval else {
+ return
+ }
+
+ refresh()
+ }
+
+ func startAutoRefresh() {
+ 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
+ } catch {
+ self.errorMessage = error.localizedDescription
+ }
+
+ self.isRefreshing = false
+ }
+ }
+}
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..fe44f69
--- /dev/null
+++ b/README.md
@@ -0,0 +1,103 @@
+# CodexBar
+
+CodexBar 是一个轻量级 macOS 菜单栏应用,用来查看当前本机 Codex 账号的额度使用情况。
+
+它会启动本机 Codex 的 app-server,完成 JSON-RPC 初始化流程后读取账号信息和额度信息,并在菜单栏弹窗中展示不同时间窗口的额度。
+
+## 功能
+
+- 菜单栏使用 `timelapse` SF Symbol;App 图标是白底黑色 `timelapse`
+- 弹窗第一行展示账号信息和套餐
+- 弹窗使用两行分段电量条展示额度窗口,标签根据 `windowDurationMins` 动态生成
+- 每行额度在进度条右侧展示剩余百分比和重置时间
+- 更新时间显示在额度行下方,并使用 `HH:mm:ss` 格式
+- 应用运行时每分钟自动刷新额度,即使弹窗未打开也会刷新
+- 双击账号图标可手动刷新
+- 不按 Option/Alt 点击菜单栏图标时,只展示额度内容
+- 按住 Option/Alt 点击菜单栏图标时,才展示「开机启动」开关和「退出」按钮
+
+## 运行要求
+
+- macOS 15.0 或更高版本
+- 已安装全局 Codex CLI,或已安装 Codex.app
+- 当前 macOS 用户已在 Codex 中完成登录
+
+CodexBar 会优先使用全局 Codex CLI 启动本机 app-server:
+
+```bash
+codex app-server --listen stdio://
+```
+
+如果找不到全局 `codex` 命令,会回退到 Codex.app 内置的二进制:
+
+```bash
+/Applications/Codex.app/Contents/Resources/codex app-server --listen stdio://
+```
+
+如果两个入口都不可用,弹窗中会展示「找不到 Codex CLI 或 Codex App」的错误。
+
+连接后会先发送初始化请求,再读取账号和额度:
+
+```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}
+```
+
+额度窗口来自 Codex app-server 返回的 `primary` 和 `secondary`:
+
+- `usedPercent`:已用百分比
+- `windowDurationMins`:额度窗口分钟数,用来生成 `5 小时`、`7 天`、`5h`、`7d` 等标签
+- `resetsAt`:秒级 Unix 时间戳,弹窗中显示为 `MM-dd HH:mm`
+
+剩余额度统一按 `100 - usedPercent` 计算。
+
+## 错误展示
+
+CodexBar 会在弹窗中用红色小字展示错误,例如未安装 Codex、app-server 启动失败、响应超时、当前未登录、需要重新验证身份、响应中缺少额度窗口等。应用不包含调试模拟入口,也不会在窗口里展示 Debug 明细。
+
+## 构建
+
+可以直接用 Xcode 打开 `CodexBar.xcodeproj`,也可以使用命令行构建:
+
+```bash
+xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/platform=macOS' build
+```
+
+## 分发
+
+如果不通过 App Store 分发,可以在 Xcode 中 Archive,然后使用 `Developer ID Application` 证书导出应用。
+
+分享给其他用户前,建议完成 notarization,这样 macOS Gatekeeper 可以正常校验应用来源。
+
+导出 `CodexBar.app` 到项目根目录后,可以用脚本生成拖拽安装 DMG:
+
+```bash
+Scripts/create-dmg.sh
+```
+
+脚本会自动查找当前目录下唯一的 `.app`,生成项目根目录下的 `CodexBar-v{version}.dmg`,并在 DMG 中放入:
+
+- `CodexBar.app`
+- `Applications -> /Applications` 快捷方式
+
+DMG 文件名中的版本号来自 Xcode target 的 `MARKETING_VERSION`,读取失败时才会回退到 app 的 `Info.plist`。如果项目中有多个 Xcode 工程或 scheme,可以通过环境变量指定:
+
+```bash
+XCODE_PROJECT=CodexBar.xcodeproj XCODE_SCHEME=CodexBar Scripts/create-dmg.sh
+```
+
+脚本会写入 Finder 布局:打开 DMG 后 `CodexBar.app` 在左侧,`Applications` 快捷方式在右侧。
+
+也可以显式指定输入 app 和输出路径:
+
+```bash
+Scripts/create-dmg.sh CodexBar.app CodexBar-v1.0.0.dmg
+```
+
+如果把应用移动到 `/Applications` 后再使用开机自启,建议打开应用后重新开启一次「开机启动」,让 macOS 记录最终的应用路径。
+
+## 隐私
+
+CodexBar 只会和本机 Codex app-server 进程通信,不会把账号信息或额度数据发送给任何第三方服务。
diff --git a/Scripts/create-dmg.sh b/Scripts/create-dmg.sh
new file mode 100755
index 0000000..57c35c0
--- /dev/null
+++ b/Scripts/create-dmg.sh
@@ -0,0 +1,193 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
+
+APP_PATH="${1:-}"
+OUTPUT_PATH="${2:-}"
+
+if [[ -z "${APP_PATH}" ]]; then
+ apps=()
+ while IFS= read -r app; do
+ apps+=("${app}")
+ done < <(find "${PROJECT_DIR}" -maxdepth 1 -type d -name "*.app" | sort)
+
+ if [[ "${#apps[@]}" -eq 0 ]]; then
+ echo "error: 当前目录没有找到 .app" >&2
+ echo "usage: Scripts/create-dmg.sh [App.app] [Output.dmg]" >&2
+ exit 1
+ fi
+
+ if [[ "${#apps[@]}" -gt 1 ]]; then
+ echo "error: 当前目录找到多个 .app, 请指定要打包的 app 路径: " >&2
+ printf ' %s\n' "${apps[@]}" >&2
+ exit 1
+ fi
+
+ APP_PATH="${apps[0]}"
+elif [[ "${APP_PATH}" != /* ]]; then
+ APP_PATH="${PROJECT_DIR}/${APP_PATH}"
+fi
+
+if [[ ! -d "${APP_PATH}" || "${APP_PATH}" != *.app ]]; then
+ echo "error: app 路径无效: ${APP_PATH}" >&2
+ exit 1
+fi
+
+APP_NAME="$(basename "${APP_PATH}" .app)"
+PLIST_PATH="${APP_PATH}/Contents/Info.plist"
+XCODE_PROJECT="${XCODE_PROJECT:-}"
+XCODE_SCHEME="${XCODE_SCHEME:-${APP_NAME}}"
+VERSION=""
+
+if [[ -z "${XCODE_PROJECT}" ]]; then
+ while IFS= read -r project; do
+ XCODE_PROJECT="${project}"
+ break
+ done < <(find "${PROJECT_DIR}" -maxdepth 1 -type d -name "*.xcodeproj" | sort)
+elif [[ "${XCODE_PROJECT}" != /* ]]; then
+ XCODE_PROJECT="${PROJECT_DIR}/${XCODE_PROJECT}"
+fi
+
+if [[ -n "${XCODE_PROJECT}" && -d "${XCODE_PROJECT}" ]]; then
+ VERSION="$(
+ xcodebuild \
+ -project "${XCODE_PROJECT}" \
+ -scheme "${XCODE_SCHEME}" \
+ -configuration Release \
+ -showBuildSettings 2>/dev/null \
+ | awk -F= '/MARKETING_VERSION/ {gsub(/[[:space:]]/, "", $2); print $2; exit}' \
+ || true
+ )"
+fi
+
+if [[ -z "${VERSION}" && -n "${XCODE_PROJECT}" && -d "${XCODE_PROJECT}" ]]; then
+ VERSION="$(
+ awk -F= '
+ /MARKETING_VERSION/ {
+ value = $2
+ gsub(/[[:space:];]/, "", value)
+ print value
+ exit
+ }
+ ' "${XCODE_PROJECT}/project.pbxproj" 2>/dev/null || true
+ )"
+fi
+
+if [[ -z "${VERSION}" && -f "${PLIST_PATH}" ]]; then
+ VERSION="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "${PLIST_PATH}" 2>/dev/null || true)"
+fi
+
+if [[ -z "${VERSION}" ]]; then
+ echo "error: 无法从 Xcode 或 Info.plist 读取版本号" >&2
+ exit 1
+fi
+
+if [[ -z "${OUTPUT_PATH}" ]]; then
+ OUTPUT_PATH="${PROJECT_DIR}/${APP_NAME}-v${VERSION}.dmg"
+elif [[ "${OUTPUT_PATH}" != /* ]]; then
+ OUTPUT_PATH="${PROJECT_DIR}/${OUTPUT_PATH}"
+fi
+
+DIST_DIR="$(dirname "${OUTPUT_PATH}")"
+VOLUME_NAME="${APP_NAME}"
+RW_DMG="${DIST_DIR}/${APP_NAME}-${VERSION}-layout-rw.dmg"
+TEMP_OUTPUT_PATH="${OUTPUT_PATH%.dmg}.tmp.dmg"
+STAGING_DIR="$(mktemp -d "/private/tmp/${APP_NAME}DMGStage.XXXXXX")"
+MOUNT_POINT=""
+
+cleanup() {
+ if [[ -n "${MOUNT_POINT}" ]]; then
+ hdiutil detach "${MOUNT_POINT}" >/dev/null 2>&1 || true
+ fi
+
+ rm -rf "${STAGING_DIR}"
+ rm -f "${RW_DMG}" "${TEMP_OUTPUT_PATH}"
+}
+trap cleanup EXIT
+
+require_command() {
+ if ! command -v "$1" >/dev/null 2>&1; then
+ echo "error: 缺少命令: $1" >&2
+ exit 1
+ fi
+}
+
+require_command hdiutil
+require_command osascript
+require_command ditto
+
+mkdir -p "${DIST_DIR}"
+rm -f "${RW_DMG}" "${TEMP_OUTPUT_PATH}"
+
+echo "==> Preparing DMG contents"
+ditto "${APP_PATH}" "${STAGING_DIR}/${APP_NAME}.app"
+ln -sfn /Applications "${STAGING_DIR}/Applications"
+
+echo "==> Creating writable DMG"
+hdiutil create \
+ -volname "${VOLUME_NAME}" \
+ -srcfolder "${STAGING_DIR}" \
+ -ov \
+ -format UDRW \
+ "${RW_DMG}" >/dev/null
+
+echo "==> Mounting writable DMG"
+ATTACH_OUTPUT="$(hdiutil attach -readwrite -noverify -noautoopen "${RW_DMG}")"
+MOUNT_POINT="$(printf '%s\n' "${ATTACH_OUTPUT}" | awk '/\/Volumes\// {print substr($0, index($0, "/Volumes/")); exit}')"
+
+if [[ -z "${MOUNT_POINT}" || ! -d "${MOUNT_POINT}" ]]; then
+ echo "error: 挂载 DMG 失败" >&2
+ printf '%s\n' "${ATTACH_OUTPUT}" >&2
+ exit 1
+fi
+
+echo "==> Writing Finder layout"
+osascript <<APPLESCRIPT
+set mountFolder to POSIX file "${MOUNT_POINT}" as alias
+
+tell application "Finder"
+ open mountFolder
+ delay 1
+ set targetWindow to front Finder window
+ set current view of targetWindow to icon view
+ set toolbar visible of targetWindow to false
+ set statusbar visible of targetWindow to false
+ set bounds of targetWindow to {120, 120, 640, 420}
+ set theViewOptions to icon view options of targetWindow
+ set arrangement of theViewOptions to not arranged
+ set icon size of theViewOptions to 96
+ set text size of theViewOptions to 13
+ set position of item "${APP_NAME}.app" of mountFolder to {170, 80}
+ set position of item "Applications" of mountFolder to {350, 80}
+ update mountFolder without registering applications
+ delay 2
+ try
+ close targetWindow
+ end try
+end tell
+APPLESCRIPT
+
+DS_STORE="${MOUNT_POINT}/.DS_Store"
+if [[ ! -s "${DS_STORE}" ]]; then
+ echo "warning: 没有写入 .DS_Store 窗口布局不会生效" >&2
+else
+ echo "==> Finder layout saved"
+fi
+
+sync
+hdiutil detach "${MOUNT_POINT}" >/dev/null
+MOUNT_POINT=""
+
+echo "==> Creating compressed DMG"
+hdiutil convert \
+ "${RW_DMG}" \
+ -format UDZO \
+ -imagekey zlib-level=9 \
+ -ov \
+ -o "${TEMP_OUTPUT_PATH}" >/dev/null
+
+mv -f "${TEMP_OUTPUT_PATH}" "${OUTPUT_PATH}"
+
+echo "==> Created ${OUTPUT_PATH}"