CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 增加 Codex 版本信息展示
Bobf61474c3e9e6
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex c5c453a..944ac2c 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -275,7 +275,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 6;+ CURRENT_PROJECT_VERSION = 7;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -290,7 +290,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.3.3;+ MARKETING_VERSION = 1.3.4;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -312,7 +312,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 6;+ CURRENT_PROJECT_VERSION = 7;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;ENABLE_APP_SANDBOX = NO;@@ -327,7 +327,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 1.3.3;+ MARKETING_VERSION = 1.3.4;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/AppSettingsView.swift b/CodexBar/AppSettingsView.swiftindex 80fe0d0..4667b1b 100644--- a/CodexBar/AppSettingsView.swift+++ b/CodexBar/AppSettingsView.swift@@ -9,9 +9,12 @@ import AppKitimport SwiftUIstruct AppSettingsView: View {+ @EnvironmentObject private var rateLimitsViewModel: RateLimitsViewModel@EnvironmentObject private var appUpdater: AppUpdater@StateObject private var loginItemSettings = LoginItemSettings()-+ @StateObject private var codexVersions = CodexCLIVersionViewModel()+ @State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]+var body: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {@@ -20,10 +23,12 @@ struct AppSettingsView: View {automaticUpdateCheckRowLiquidGlassDivider()versionRow+ LiquidGlassDivider()+ codexVersionSection}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)-+HStack(alignment: .center, spacing: 12) {quitButtonstatusText@@ -48,6 +53,13 @@ struct AppSettingsView: View {.onAppear {loginItemSettings.refresh()appUpdater.refreshAutomaticCheckSetting()+ refreshCodexVersionSection()+ }+ .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in+ refreshCodexVersionSection()+ }+ .onDisappear {+ copiedPathResetTasks.values.forEach { $0.cancel() }}}}@@ -55,15 +67,17 @@ struct AppSettingsView: View {private extension AppSettingsView {enum Metrics {static let padding: CGFloat = 20- static let windowWidth: CGFloat = 380+ static let windowWidth: CGFloat = 430static let sectionSpacing: CGFloat = 18static let rowSpacing: CGFloat = 14static let panelPadding: CGFloat = 12static let surfaceCornerRadius: CGFloat = 16static let panelCornerRadius: CGFloat = 10static let iconWidth: CGFloat = 18+ static let codexChildIndent: CGFloat = 28+ static let codexVersionColumnWidth: CGFloat = 270}-+var launchAtLoginRow: some View {settingsToggleRow(icon: "power",@@ -74,7 +88,7 @@ private extension AppSettingsView {))}-+var automaticUpdateCheckRow: some View {settingsToggleRow(icon: "arrow.triangle.2.circlepath",@@ -86,7 +100,7 @@ private extension AppSettingsView {isEnabled: appUpdater.canConfigureAutomaticChecks)}-+func settingsToggleRow(icon: String,title: String,@@ -97,11 +111,11 @@ private extension AppSettingsView {Image(systemName: icon).frame(width: Metrics.iconWidth).foregroundStyle(.tint)-+Text(title)-+Spacer()-+Toggle(title, isOn: isOn).labelsHidden().toggleStyle(.switch)@@ -109,22 +123,22 @@ private extension AppSettingsView {.disabled(!isEnabled)}}-+var versionRow: some View {HStack(spacing: 10) {Image(systemName: "info.circle").frame(width: Metrics.iconWidth).foregroundStyle(.secondary)-- Text("当前 APP 版本")-++ Text("CodexBar 版本")+Spacer()-+Text(versionStatus.text).font(versionStatus.isVersionLabel ? .body.monospacedDigit() : .body).foregroundStyle(.secondary).lineLimit(1)-+if appUpdater.availableUpdateMessage != nil {Button {appUpdater.startUpdate()@@ -136,19 +150,115 @@ private extension AppSettingsView {.buttonStyle(.plain).foregroundStyle(.tint).help("立即更新")- .accessibilityLabel("立即更新")}}}-- /// 版本行文案;无任何动态消息时回退到版本号(此时用等宽数字)++ /// 版本行文案;无任何动态消息时回退到版本号 (此时用等宽数字)var versionStatus: (text: String, isVersionLabel: Bool) {if let message = appUpdater.settingsStatusMessage ?? appUpdater.availableUpdateMessage {return (message, false)}return (Bundle.main.displayVersionLabel, true)}-++ var codexVersionSection: some View {+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ HStack(spacing: 10) {+ Image(systemName: "number.circle")+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.secondary)++ Text("Codex 版本")++ Spacer()+ }++ LiquidGlassDivider()+ .padding(.leading, Metrics.iconWidth + 10)++ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ codexVersionRow(icon: "terminal", item: codexVersions.snapshot.global)++ codexVersionRow(icon: "app.badge", item: codexVersions.snapshot.bundled)+ }+ .padding(.leading, Metrics.codexChildIndent)+ }+ }++ func refreshCodexVersionSection() {+ // 版本探测是慢路径且自带并发合并; 连接信息只是一次缓存读取, 顺带刷新+ codexVersions.refresh()+ rateLimitsViewModel.refreshCodexConnectionInfo()+ }++ func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {+ let row = CodexCLIVersionDisplay(item: item, connection: rateLimitsViewModel.codexConnectionInfo)+ let isPathCopied = copiedPathResetTasks[item.source] != nil++ return HStack(alignment: .top, spacing: 10) {+ Image(systemName: icon)+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tertiary)++ Text(item.source.displayName)+ .foregroundStyle(.secondary)++ Spacer(minLength: 28)++ VStack(alignment: .trailing, spacing: 3) {+ HStack(spacing: 12) {+ if row.isCurrent {+ Text("当前使用")+ .font(.caption2.weight(.medium))+ .foregroundStyle(.green)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .liquidGlassCapsule(tint: .green)+ }++ Text(row.displayVersion)+ .font(row.hasVersion ? .body.monospacedDigit() : .body)+ .foregroundStyle(row.hasVersion ? .secondary : .tertiary)+ .lineLimit(1)+ }++ if let newerInstalledVersion = row.newerInstalledVersion {+ Text("已更新至 \(newerInstalledVersion)")+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.orange)+ .lineLimit(1)+ }++ if let path = row.path {+ Text(isPathCopied ? "已复制" : path)+ .font(.caption2)+ .foregroundStyle(isPathCopied ? .green : .secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ .help(isPathCopied ? "已复制" : "点击复制")+ .onTapGesture {+ copyPathToPasteboard(path, source: item.source)+ }+ }+ }+ .frame(maxWidth: Metrics.codexVersionColumnWidth, alignment: .trailing)+ }+ }++ func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(path, forType: .string)++ copiedPathResetTasks[source]?.cancel()+ copiedPathResetTasks[source] = Task { @MainActor in+ try? await Task.sleep(for: .milliseconds(1500))+ guard !Task.isCancelled else { return }++ copiedPathResetTasks[source] = nil+ }+ }+@ViewBuildervar statusText: some View {if let message = loginItemSettings.errorMessage {@@ -158,7 +268,7 @@ private extension AppSettingsView {.fixedSize(horizontal: false, vertical: true)}}-+var checkUpdateButton: some View {Button {appUpdater.checkForUpdates()@@ -166,7 +276,7 @@ private extension AppSettingsView {Label("检查更新", systemImage: "arrow.down.circle")}}-+var quitButton: some View {Button(role: .destructive) {NSApplication.shared.terminate(nil)diff --git a/CodexBar/AppUpdater.swift b/CodexBar/AppUpdater.swiftindex 4a18550..cfd9070 100644--- a/CodexBar/AppUpdater.swift+++ b/CodexBar/AppUpdater.swift@@ -16,20 +16,20 @@ final class AppUpdater: NSObject, ObservableObject {@Published private(set) var panelUpdateMessage: String?@Published private(set) var availableUpdateMessage: String?@Published private(set) var automaticallyChecksForUpdates = false-+var canConfigureAutomaticChecks: Bool { updaterController != nil }-+private var updaterController: SPUStandardUpdaterController?private var clearSettingsStatusMessageTask: Task<Void, Never>?private var isManualCheckInProgress = false-+init(bundle: Bundle = .main) {super.init()-+guard Self.hasUsableSparkleConfiguration(in: bundle) else {return}-+updaterController = SPUStandardUpdaterController(startingUpdater: true,updaterDelegate: self,@@ -37,61 +37,61 @@ final class AppUpdater: NSObject, ObservableObject {)refreshAutomaticCheckSetting()}-+func checkForUpdates() {guard let updaterController else {showSettingsStatusMessage("未配置更新资源")return}-+if let availableUpdateMessage {showSettingsStatusMessage(availableUpdateMessage, autoDismissDelay: nil)return}-+isManualCheckInProgress = trueshowSettingsStatusMessage("正在检查更新")updaterController.updater.checkForUpdateInformation()}-+func startUpdate() {guard let updaterController else {showSettingsStatusMessage("未配置更新资源")return}-+NSApplication.shared.activate()updaterController.checkForUpdates(nil)}-+func setAutomaticallyChecksForUpdates(_ isEnabled: Bool) {guard let updaterController else {automaticallyChecksForUpdates = falseshowSettingsStatusMessage("未配置更新资源")return}-+updaterController.updater.automaticallyChecksForUpdates = isEnabledrefreshAutomaticCheckSetting()}-+func refreshAutomaticCheckSetting() {automaticallyChecksForUpdates = updaterController?.updater.automaticallyChecksForUpdates ?? false}-+private func showSettingsStatusMessage(_ message: String, autoDismissDelay: Duration? = .seconds(3)) {clearSettingsStatusMessageTask?.cancel()settingsStatusMessage = message-+guard let autoDismissDelay else { return }-+clearSettingsStatusMessageTask = Task { [weak self] intry? await Task.sleep(for: autoDismissDelay)guard !Task.isCancelled else { return }self?.settingsStatusMessage = nil}}-+private static func hasUsableSparkleConfiguration(in bundle: Bundle) -> Bool {guardlet feedURLString = bundle.object(forInfoDictionaryKey: "SUFeedURL") as? String,@@ -101,7 +101,7 @@ final class AppUpdater: NSObject, ObservableObject {else {return false}-+return !publicKey.isEmpty}}@@ -110,32 +110,32 @@ extension AppUpdater: SPUUpdaterDelegate {func updater(_ updater: SPUUpdater, didFindValidUpdate item: SUAppcastItem) {let message = "发现新版本: v\(item.displayVersionString)"availableUpdateMessage = message-+if isManualCheckInProgress {showSettingsStatusMessage(message, autoDismissDelay: nil)} else {panelUpdateMessage = message}-+isManualCheckInProgress = false}-+func updaterDidNotFindUpdate(_ updater: SPUUpdater, error: Error) {availableUpdateMessage = nilpanelUpdateMessage = nil-+if isManualCheckInProgress {- showSettingsStatusMessage("没有可用更新", autoDismissDelay: .milliseconds(1500))+ showSettingsStatusMessage("没有可用更新", autoDismissDelay: .milliseconds(1000))}-+isManualCheckInProgress = false}-+func updater(_ updater: SPUUpdater, didAbortWithError error: Error) {guard isManualCheckInProgress else {return}-+showSettingsStatusMessage("检查更新失败")isManualCheckInProgress = false}diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/CodexBarApp.swiftindex 30aeb3e..cb2fb68 100644--- a/CodexBar/CodexBarApp.swift+++ b/CodexBar/CodexBarApp.swift@@ -11,7 +11,7 @@ import SwiftUI@mainstruct CodexBarApp: App {@NSApplicationDelegateAdaptor(CodexBarAppDelegate.self) private var appDelegate-+var body: some Scene {// 实际 UI 由 CodexBarAppDelegate 的 StatusItemController 驱动// App 仅需声明一个占位 Scene 设置窗口走右键菜单的 makeSettingsWindow@@ -25,7 +25,7 @@ nonisolated extension Bundle {var shortVersionString: String? {object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String}-+/// `v1.2.3` 形式的版本文案,缺失时回退 `--`(不带 v 前缀)var displayVersionLabel: String {guard let version = shortVersionString else { return "--" }diff --git a/CodexBar/CodexCLIResolver.swift b/CodexBar/CodexCLIResolver.swiftnew file mode 100644index 0000000..2b748ce--- /dev/null+++ b/CodexBar/CodexCLIResolver.swift@@ -0,0 +1,169 @@+//+// CodexCLIResolver.swift+// CodexBar+//+// Created by Bob on 2026-06-15.+//++import Darwin+import Foundation++nonisolated enum CodexCLIExecutableSource: String, Sendable, Equatable {+ case global+ case bundled++ var displayName: String {+ switch self {+ case .global: return "Codex CLI"+ case .bundled: return "Codex APP"+ }+ }+}++nonisolated struct AppServerCommand: Sendable, Equatable {+ let source: CodexCLIExecutableSource+ let executablePath: String+ let arguments = ["app-server", "--listen", "stdio://"]+}++nonisolated struct CodexCLIConnectionInfo: Sendable, Equatable {+ let source: CodexCLIExecutableSource+ let executablePath: String+ // initialize 握手里 app-server 自报的运行版本, 反映当前进程真实在跑的二进制+ let version: String?+ let openedAt: Date+}++nonisolated struct CodexCLIInstallations: Sendable, Equatable {+ let globalPath: String?+ let bundledPath: String?++ /// 当前会被启动的来源, 与 resolveAppServerCommand 优先级一致: 全局优先, 回退内置+ var activeSource: CodexCLIExecutableSource? {+ if globalPath != nil { return .global }+ if bundledPath != nil { return .bundled }+ return nil+ }++ func path(for source: CodexCLIExecutableSource) -> String? {+ switch source {+ case .global: return globalPath+ case .bundled: return bundledPath+ }+ }+}++nonisolated enum CodexCLIResolver {+ static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"+ static let environment = appServerEnvironment()++ static func resolveAppServerCommand(environment: [String: String] = environment) throws -> AppServerCommand {+ try command(from: resolveInstallations(environment: environment))+ }++ /// 从一份已解析的安装信息派生启动命令, 避免重复扫描 PATH+ static func command(from installations: CodexCLIInstallations) throws -> AppServerCommand {+ guard let source = installations.activeSource,+ let path = installations.path(for: source) else {+ throw CodexRateLimitError.executableNotFound+ }++ return AppServerCommand(source: source, executablePath: path)+ }++ static func resolveInstallations(environment: [String: String] = environment) -> CodexCLIInstallations {+ let cliPath = findExecutable(named: "codex", environment: environment)+ let cliIsBundled = cliPath.map { pathsAreEquivalent($0, bundledExecutablePath) } ?? false++ let bundledPath: String?+ if FileManager.default.isExecutableFile(atPath: bundledExecutablePath) {+ bundledPath = bundledExecutablePath+ } else {+ bundledPath = cliIsBundled ? cliPath : nil+ }++ return CodexCLIInstallations(+ globalPath: cliIsBundled ? nil : cliPath,+ bundledPath: bundledPath+ )+ }++ private 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 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 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 static func pathsAreEquivalent(_ lhs: String, _ rhs: String) -> Bool {+ canonicalPath(lhs) == canonicalPath(rhs)+ }++ private static func canonicalPath(_ path: String) -> String {+ URL(fileURLWithPath: path)+ .resolvingSymlinksInPath()+ .standardizedFileURL+ .path+ }++ private static func realUserHomeDirectory() -> String {+ guard let passwd = getpwuid(getuid()),+ let home = passwd.pointee.pw_dir else {+ return NSHomeDirectory()+ }++ return String(cString: home)+ }+}diff --git a/CodexBar/CodexCLIVersionService.swift b/CodexBar/CodexCLIVersionService.swiftnew file mode 100644index 0000000..b15a7c3--- /dev/null+++ b/CodexBar/CodexCLIVersionService.swift@@ -0,0 +1,269 @@+//+// CodexCLIVersionService.swift+// CodexBar+//+// Created by Bob on 2026-06-15.+//++import Combine+import Foundation++nonisolated struct CodexCLIVersionSnapshot: Equatable, Sendable {+ let global: CodexCLIVersionItem+ let bundled: CodexCLIVersionItem+ let refreshedAt: Date++ // distantPast 让首个 refresh 一定通过新鲜度门槛+ static let empty = CodexCLIVersionSnapshot(+ global: CodexCLIVersionItem(source: .global),+ bundled: CodexCLIVersionItem(source: .bundled),+ refreshedAt: .distantPast+ )+}++nonisolated struct CodexCLIVersionItem: Equatable, Identifiable, Sendable {+ let source: CodexCLIExecutableSource+ let path: String?+ let version: String?+ let errorMessage: String?++ var id: CodexCLIExecutableSource { source }++ init(+ source: CodexCLIExecutableSource,+ path: String? = nil,+ version: String? = nil,+ errorMessage: String? = nil+ ) {+ self.source = source+ self.path = path+ self.version = version+ self.errorMessage = errorMessage+ }++ var displayVersion: String {+ if path == nil {+ return "未找到 \(source.displayName)"+ }++ return version ?? errorMessage ?? "未知版本"+ }+}++/// 把磁盘探测(item)与连接握手(connection)两路版本信息合成为一行可直接渲染的展示数据+nonisolated struct CodexCLIVersionDisplay: Equatable {+ let source: CodexCLIExecutableSource+ let isCurrent: Bool+ let displayVersion: String+ let hasVersion: Bool+ let path: String?+ /// 运行版本落后于磁盘已安装版本时(后台升级尚未重连)的新版本号, 否则 nil+ let newerInstalledVersion: String?++ init(item: CodexCLIVersionItem, connection: CodexCLIConnectionInfo?) {+ let isCurrent = connection?.source == item.source+ // 当前来源优先用正在运行的版本(连接握手自报), 其余用磁盘安装版本+ let runningVersion = isCurrent ? connection?.version : nil+ let version = runningVersion ?? item.version++ self.source = item.source+ self.isCurrent = isCurrent+ self.hasVersion = version != nil+ self.displayVersion = version ?? item.displayVersion+ self.path = (isCurrent ? connection?.executablePath : nil) ?? item.path++ if let runningVersion, let installed = item.version, installed != runningVersion {+ self.newerInstalledVersion = installed+ } else {+ self.newerInstalledVersion = nil+ }+ }+}++nonisolated final class CodexCLIVersionService: @unchecked Sendable {+ private let queue = DispatchQueue(label: "CodexBar.codex-version", qos: .utility)+ private let timeout: TimeInterval++ init(timeout: TimeInterval = 5) {+ self.timeout = timeout+ }++ func fetchSnapshot() async -> CodexCLIVersionSnapshot {+ await withCheckedContinuation { continuation in+ queue.async {+ continuation.resume(returning: Self.fetchSnapshotOnQueue(timeout: self.timeout))+ }+ }+ }++ private static func fetchSnapshotOnQueue(timeout: TimeInterval) -> CodexCLIVersionSnapshot {+ let environment = CodexCLIResolver.environment+ let installations = CodexCLIResolver.resolveInstallations(environment: environment)++ // 两个探测互不依赖, 先并发启动子进程, 再分别收集, 避免串行叠加超时+ let globalProbe = startProbe(+ source: .global,+ path: installations.globalPath,+ environment: environment,+ timeout: timeout+ )+ let bundledProbe = startProbe(+ source: .bundled,+ path: installations.bundledPath,+ environment: environment,+ timeout: timeout+ )++ return CodexCLIVersionSnapshot(+ global: finishProbe(globalProbe),+ bundled: finishProbe(bundledProbe),+ refreshedAt: Date()+ )+ }++ /// 一个已启动、等待收集的版本探测子进程+ private struct RunningProbe {+ let source: CodexCLIExecutableSource+ let path: String+ let process: Process+ let standardOutput: Pipe+ let standardError: Pipe+ let finished: DispatchSemaphore+ let deadline: DispatchTime+ }++ private enum ProbeOutcome {+ case resolved(CodexCLIVersionItem)+ case running(RunningProbe)+ }++ private static func startProbe(+ source: CodexCLIExecutableSource,+ path: String?,+ environment: [String: String],+ timeout: TimeInterval+ ) -> ProbeOutcome {+ guard let path else {+ return .resolved(CodexCLIVersionItem(source: source))+ }++ let process = Process()+ process.executableURL = URL(fileURLWithPath: path)+ process.arguments = ["--version"]+ process.environment = environment++ let standardOutput = Pipe()+ let standardError = Pipe()+ let finished = DispatchSemaphore(value: 0)++ process.standardOutput = standardOutput+ process.standardError = standardError+ process.terminationHandler = { _ in finished.signal() }++ do {+ try process.run()+ } catch {+ return .resolved(CodexCLIVersionItem(source: source, path: path, errorMessage: "启动失败"))+ }++ return .running(RunningProbe(+ source: source,+ path: path,+ process: process,+ standardOutput: standardOutput,+ standardError: standardError,+ finished: finished,+ deadline: .now() + timeout+ ))+ }++ private static func finishProbe(_ outcome: ProbeOutcome) -> CodexCLIVersionItem {+ switch outcome {+ case .resolved(let item):+ return item+ case .running(let probe):+ guard probe.finished.wait(timeout: probe.deadline) == .success else {+ probe.process.terminate()+ return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取超时")+ }++ let output = String(+ data: probe.standardOutput.fileHandleForReading.readDataToEndOfFile(),+ encoding: .utf8+ ) ?? ""+ let errorOutput = String(+ data: probe.standardError.fileHandleForReading.readDataToEndOfFile(),+ encoding: .utf8+ ) ?? ""++ guard probe.process.terminationStatus == 0 else {+ return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "读取失败")+ }++ guard let version = firstLine(in: output) ?? firstLine(in: errorOutput) else {+ return CodexCLIVersionItem(source: probe.source, path: probe.path, errorMessage: "版本未知")+ }++ return CodexCLIVersionItem(+ source: probe.source,+ path: probe.path,+ version: CodexCLIVersionReader.displayVersion(from: version)+ )+ }+ }++ private static func firstLine(in text: String) -> String? {+ text+ .split(whereSeparator: \.isNewline)+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+ .first { !$0.isEmpty }+ }++}++nonisolated enum CodexCLIVersionReader {+ static func displayVersion(from output: String) -> String {+ output+ .split(whereSeparator: \.isWhitespace)+ .first { $0.first?.isNumber == true }+ .map(String.init) ?? output+ }+}++@MainActor+final class CodexCLIVersionViewModel: ObservableObject {+ @Published private(set) var snapshot = CodexCLIVersionSnapshot.empty+ @Published private(set) var isRefreshing = false++ // 版本几乎不变, 短时间内重复触发(didBecomeActive 频繁到达)直接复用上次结果+ private static let refreshThrottle: TimeInterval = 60++ private let service: CodexCLIVersionService+ private var refreshTask: Task<Void, Never>?++ init(service: CodexCLIVersionService = CodexCLIVersionService()) {+ self.service = service+ }++ deinit {+ refreshTask?.cancel()+ }++ func refresh() {+ // 合并并发触发与短时重复触发(onAppear 与 didBecomeActive 常同时/频繁到达), 避免重复启动子进程+ guard !isRefreshing,+ Date().timeIntervalSince(snapshot.refreshedAt) > Self.refreshThrottle else {+ return+ }+ isRefreshing = true++ refreshTask = Task {+ let snapshot = await service.fetchSnapshot()++ guard !Task.isCancelled else { return }++ self.snapshot = snapshot+ self.isRefreshing = false+ }+ }+}diff --git a/CodexBar/CodexRateLimitService.swift b/CodexBar/CodexRateLimitService.swiftindex 221605a..9942524 100644--- a/CodexBar/CodexRateLimitService.swift+++ b/CodexBar/CodexRateLimitService.swift@@ -5,29 +5,27 @@// Created by Bob on 2026-06-10.//-import Darwinimport Foundation/// 与 codex app-server 维持一条常驻连接: 首次拉取时启动进程并完成握手/// 之后所有额度读取复用同一会话; 进程退出或请求失败时自动重建连接nonisolated final class CodexRateLimitService: @unchecked Sendable {- private nonisolated static let bundledExecutablePath = "/Applications/Codex.app/Contents/Resources/codex"private static let requestTimeout: TimeInterval = 20// 连接定期回收: 覆盖 codex 全局升级后换用新二进制private static let connectionMaxAge: TimeInterval = 1 * 60 * 60// 进程环境在应用启动后不会变化, 只构建一次- private static let environment = appServerEnvironment()-+ private static let environment = CodexCLIResolver.environment+// 连接状态只在 queue 上读写private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)private var connection: AppServerConnection?-+init() {}-+deinit {connection?.session.close()}-+func fetchRateLimits() async throws -> CodexQuotaSnapshot {try await withCheckedThrowingContinuation { continuation inqueue.async {@@ -35,7 +33,15 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {}}}-++ func currentConnectionInfo() async -> CodexCLIConnectionInfo? {+ await withCheckedContinuation { continuation in+ queue.async {+ continuation.resume(returning: self.currentConnectionInfoOnQueue())+ }+ }+ }+private func fetchRateLimitsOnQueue() throws -> CodexQuotaSnapshot {do {let (connection, reused) = try ensureConnection()@@ -53,32 +59,40 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {throw error}}-+private func ensureConnection() throws -> (connection: AppServerConnection, reused: Bool) {if let connection, connection.session.process.isRunning,Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {return (connection, reused: true)}-+teardownConnection()-- let command = try Self.resolveAppServerCommand(environment: Self.environment)++ let command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)let newConnection = try Self.openConnection(command: command,environment: Self.environment,clientVersion: Self.clientVersion(),timeout: Self.requestTimeout)-+connection = newConnectionreturn (newConnection, reused: false)}-+private func teardownConnection() {connection?.session.close()connection = nil}-++ private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {+ guard let connection, connection.session.process.isRunning else {+ return nil+ }++ return connection.commandInfo+ }+private static func fetchSnapshot(using connection: AppServerConnection) throws -> CodexQuotaSnapshot {func readRateLimits() throws -> AccountRateLimitsResponse {try connection.session.request(@@ -86,7 +100,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {as: AccountRateLimitsResponse.self)}-+let rateLimitsResponse: AccountRateLimitsResponsedo {rateLimitsResponse = try readRateLimits()@@ -96,28 +110,28 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {params: ["refreshToken": true],as: AccountReadResponse.self)-+do {rateLimitsResponse = try readRateLimits()} catch let retryError as CodexRateLimitError where retryError.isAuthenticationRequired {throw CodexRateLimitError.authenticationRequired}}-+let usageResponse = readUsageIfAvailable(using: connection)-+return try CodexQuotaSnapshot(accountResponse: connection.accountResponse,rateLimitsResponse: rateLimitsResponse,usageResponse: usageResponse)}-+private static func readUsageIfAvailable(using connection: AppServerConnection) -> AccountUsageResponse? {guard connection.isUsageReadAvailable else {return nil}-+do {return try connection.session.request("account/usage/read",@@ -130,7 +144,7 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {return nil}}-+/// 启动 app-server 进程并完成 initialize、account/read 握手, 返回可复用的连接private static func openConnection(command: AppServerCommand,@@ -142,23 +156,24 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {process.executableURL = URL(fileURLWithPath: command.executablePath)process.arguments = command.argumentsprocess.environment = environment-+let standardInput = Pipe()let standardOutput = Pipe()let standardError = Pipe()let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)let errorReader = PipeDrain(fileHandle: standardError.fileHandleForReading)-+process.standardInput = standardInputprocess.standardOutput = standardOutputprocess.standardError = standardError-+do {try process.run()} catch {throw CodexRateLimitError.serverStartFailed(error.localizedDescription)}-+ let openedAt = Date()+let session = AppServerSession(process: process,input: standardInput,@@ -166,9 +181,9 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {errorReader: errorReader,timeout: timeout)-+do {- _ = try session.request(+ let initializeResult = try session.request("initialize",params: ["clientInfo": [@@ -177,147 +192,83 @@ nonisolated final class CodexRateLimitService: @unchecked Sendable {"version": clientVersion]],- as: EmptyResponse.self+ as: InitializeResult.self)-+try session.notify("initialized")-+let accountResponse = try session.request("account/read",params: ["refreshToken": false],as: AccountReadResponse.self)-++ let commandInfo = CodexCLIConnectionInfo(+ source: command.source,+ executablePath: command.executablePath,+ version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),+ openedAt: openedAt+ )+return AppServerConnection(session: session,- accountResponse: accountResponse+ accountResponse: accountResponse,+ commandInfo: commandInfo)} catch {session.close()throw error}}-- 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.shortVersionString, !version.isEmpty else {return "1.0.0"}-+return version}-- private nonisolated static func realUserHomeDirectory() -> String {- guard let passwd = getpwuid(getuid()),- let home = passwd.pointee.pw_dir else {- return NSHomeDirectory()++ /// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号+ private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {+ guard let firstToken = userAgent?.split(separator: " ").first,+ let slashIndex = firstToken.firstIndex(of: "/") else {+ return nil}-- return String(cString: home)++ let version = firstToken[firstToken.index(after: slashIndex)...]+ return version.isEmpty ? nil : String(version)}}private nonisolated final class AppServerConnection {let session: AppServerSession- let openedAt = Date()+ let commandInfo: CodexCLIConnectionInfovar accountResponse: AccountReadResponsevar isUsageReadAvailable = true-- init(session: AppServerSession, accountResponse: AccountReadResponse) {++ var openedAt: Date { commandInfo.openedAt }++ init(+ session: AppServerSession,+ accountResponse: AccountReadResponse,+ commandInfo: CodexCLIConnectionInfo+ ) {self.session = sessionself.accountResponse = accountResponse+ self.commandInfo = commandInfo}}private nonisolated final class AppServerSession {let process: Process-+private let input: Pipeprivate let lineReader: JSONLineReaderprivate let errorReader: PipeDrainprivate let timeout: TimeIntervalprivate var nextId = 1-+init(process: Process,input: Pipe,@@ -331,21 +282,21 @@ private nonisolated final class AppServerSession {self.errorReader = errorReaderself.timeout = timeout}-+func close() {lineReader.stop()errorReader.stop()try? input.fileHandleForWriting.close()-+if process.isRunning {process.terminate()}}-+func notify(_ method: String, params: [String: Any]? = nil) throws {try write(message(method: method, id: nil, params: params), step: method)}-+func request<Response: Decodable>(_ method: String,params: [String: Any]? = nil,@@ -356,7 +307,7 @@ private nonisolated final class AppServerSession {try write(message(method: method, id: id, params: params), step: method)return try waitForResponse(id: id, step: method, decode: type)}-+private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {var object: [String: Any] = ["method": method]if let id {@@ -367,18 +318,18 @@ private nonisolated final class AppServerSession {}return object}-+private func write(_ object: [String: Any], step: String) throws {var data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])data.append(0x0A)-+do {try input.fileHandleForWriting.write(contentsOf: data)} catch {throw CodexRateLimitError.serverConnectionClosed(step)}}-+private func waitForResponse<Response: Decodable>(id: Int,step: String,@@ -386,49 +337,46 @@ private nonisolated final class AppServerSession {) throws -> Response {let deadline = Date().addingTimeInterval(timeout)let decoder = JSONDecoder()-+while Date() < deadline {guard let line = lineReader.nextLine(timeout: deadline.timeIntervalSinceNow) else {if lineReader.isClosed {throw CodexRateLimitError.serverConnectionClosed(step)}-+continue}-+guard let data = line.data(using: .utf8) else {continue}-+guard let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),idEnvelope.id == id else {continue}-+if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: data),let error = errorEnvelope.error {throw CodexRateLimitError.serverError(error.message)}-+guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: data),let result = envelope.result else {throw CodexRateLimitError.invalidServerResponse(step)}-+return result}-+throw CodexRateLimitError.serverTimeout(step)}}-private nonisolated struct AppServerCommand: Sendable {- let executablePath: String- let arguments = ["app-server", "--listen", "stdio://"]+private nonisolated struct InitializeResult: Decodable {+ let userAgent: String?}-private nonisolated struct EmptyResponse: Decodable {}-private nonisolated struct RPCIDEnvelope: Decodable {let id: Int?}@@ -454,58 +402,58 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {private var buffer = Data()private var lines: [String] = []private var closed = false-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { [weak self] handle inself?.append(handle.availableData)}}-+func nextLine(timeout: TimeInterval) -> String? {if let line = popLine() {return line}-+if isClosed {return nil}-+let result = semaphore.wait(timeout: .now() + timeout)guard result == .success else {return nil}-+return popLine()}-+func stop() {fileHandle.readabilityHandler = nilmarkClosed()}-+var isClosed: Bool {lock.lock()defer { lock.unlock() }-+return closed && lines.isEmpty}-+private func append(_ data: Data) {guard !data.isEmpty else {markClosed()return}-+lock.lock()defer { lock.unlock() }-+buffer.append(data)-+while let newlineRange = buffer.firstRange(of: Data([0x0A])) {let lineData = buffer[..<newlineRange.lowerBound]buffer.removeSubrange(...newlineRange.lowerBound)-+if let line = String(data: lineData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),!line.isEmpty {@@ -514,14 +462,14 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {}}}-+private func markClosed() {lock.lock()defer {lock.unlock()semaphore.signal()}-+if !buffer.isEmpty {if let line = String(data: buffer, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines),@@ -530,30 +478,30 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {}buffer.removeAll()}-+closed = true}-+private func popLine() -> String? {lock.lock()defer { lock.unlock() }-+guard !lines.isEmpty else {return nil}-+return lines.removeFirst()}}private nonisolated final class PipeDrain: @unchecked Sendable {private let fileHandle: FileHandle-+init(fileHandle: FileHandle) {self.fileHandle = fileHandlefileHandle.readabilityHandler = { _ = $0.availableData }}-+func stop() {fileHandle.readabilityHandler = nil}diff --git a/CodexBar/QuotaRow.swift b/CodexBar/QuotaRow.swiftindex 950d11f..29a1db9 100644--- a/CodexBar/QuotaRow.swift+++ b/CodexBar/QuotaRow.swift@@ -9,22 +9,22 @@ import SwiftUIstruct QuotaRow: View {let window: QuotaWindow-+var body: some View {HStack(alignment: .center, spacing: Metrics.spacing) {Text(window.label).font(.caption.weight(.semibold)).lineLimit(1).frame(width: Metrics.labelWidth, alignment: .leading)-+SegmentedQuotaBar(percent: window.hasData ? window.remainingPercent : nil).frame(height: Metrics.barHeight)-+Text(percentText).font(.caption.monospacedDigit().weight(.semibold)).lineLimit(1).frame(width: Metrics.percentWidth, alignment: .leading)-+Text(resetText).font(.caption2.monospacedDigit()).foregroundStyle(.secondary)@@ -42,27 +42,27 @@ private extension QuotaRow {static let percentWidth: CGFloat = 32static let resetWidth: CGFloat = 76}-+var resetText: String {guard window.hasData else {return "暂无数据"}-+guard let resetsAt = window.resetsAt else {return "--"}-+return Self.resetFormatter.string(from: resetsAt)}-+var percentText: String {guard window.hasData else {return "--"}-+return "\(window.remainingPercent)%"}-+static let resetFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")@@ -73,12 +73,12 @@ private extension QuotaRow {private struct SegmentedQuotaBar: View {let percent: Int?-+var body: some View {GeometryReader { proxy inlet segmentCount = segmentCount(for: proxy.size.width)let filledSegments = filledSegments(for: segmentCount)-+HStack(spacing: Metrics.spacing) {ForEach(0..<segmentCount, id: \.self) { index inCapsule(style: .continuous)@@ -87,7 +87,6 @@ private struct SegmentedQuotaBar: View {}}}- .accessibilityLabel(accessibilityLabel)}}@@ -96,32 +95,32 @@ private extension SegmentedQuotaBar {static let spacing: CGFloat = 2static let idealSegmentWidth: CGFloat = 6}-+func segmentCount(for width: CGFloat) -> Int {max(1, Int((width + Metrics.spacing) / (Metrics.idealSegmentWidth + Metrics.spacing)))}-+func filledSegments(for segmentCount: Int) -> Int {guard let percent else {return 0}-+return Int((Double(percent) / 100.0 * Double(segmentCount)).rounded())}-+func fillStyle(for index: Int, filledSegments: Int) -> Color {guard percent != nil else {return placeholderStyle}-+return index < filledSegments ? filledStyle : emptyStyle}-+var filledStyle: Color {guard let percent else {return placeholderStyle}-+switch percent {case 50...:return .green@@ -131,20 +130,12 @@ private extension SegmentedQuotaBar {return .red}}-+var emptyStyle: Color {Color.secondary.opacity(0.18)}-+var placeholderStyle: Color {Color.secondary.opacity(0.12)}-- var accessibilityLabel: String {- guard let percent else {- return "暂无额度数据"- }-- return "剩余 \(percent)%"- }}diff --git a/CodexBar/RateLimitModels.swift b/CodexBar/RateLimitModels.swiftindex 3131352..3d5a428 100644--- a/CodexBar/RateLimitModels.swift+++ b/CodexBar/RateLimitModels.swift@@ -13,11 +13,11 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let generatedAt: Datelet limits: [CodexQuotaLimitSnapshot]let usage: CodexUsageSnapshot?-+var accountLabel: String {account.displayName}-+var planLabel: String? {account.planType ?? planType}@@ -27,14 +27,14 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {let limitId: Stringlet limitName: String?let windows: [QuotaWindow]-+var id: String { limitId }-+var title: String {if let limitName, !limitName.isEmpty {return limitName.capitalizingFirstLetter()}-+return limitId.capitalizingFirstLetter()}}@@ -44,7 +44,7 @@ nonisolated private extension String {guard let first else {return self}-+return first.uppercased() + dropFirst()}}@@ -53,16 +53,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {let type: Stringlet email: String?let planType: String?-+var hasEmail: Bool {email?.isEmpty == false}-+var displayName: String {if let email, hasEmail {return email}-+switch type {case "apiKey":return "API Key"@@ -85,36 +85,36 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {let windowDurationMins: Int?let usedPercent: Int?let resetsAt: Date?-+var label: String {Self.windowLabel(for: windowDurationMins)}-+var remainingPercent: Int {guard let usedPercent else {return 0}-+return max(0, min(100, 100 - usedPercent))}-+var hasData: Bool {usedPercent != nil}-+private static func windowLabel(for minutes: Int?) -> String {guard let minutes, minutes > 0 else {return "额度"}-+if minutes.isMultiple(of: 1_440) {return "\(minutes / 1_440) 天"}-+if minutes.isMultiple(of: 60) {return "\(minutes / 60) 小时"}-+return "\(minutes) 分钟"}}@@ -136,7 +136,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))@@ -156,31 +156,31 @@ nonisolated struct UsageSummary: Decodable, Equatable {nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {let startDate: Stringlet tokens: Int-+var id: String { startDate }}nonisolated struct CodexUsageSnapshot: Equatable {let summary: UsageSummarylet dailyBuckets: [DailyUsageBucket]-+func recentDays(count: Int, endingDaysAgo: Int) -> [DailyUsageBucket] {let calendar = Calendar.currentlet today = calendar.startOfDay(for: Date())let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket inresult[bucket.startDate, default: 0] += bucket.tokens}-+return (0..<count).reversed().compactMap { offset inguard let date = calendar.date(byAdding: .day, value: -(offset + endingDaysAgo), to: today) else {return nil}-+let startDate = Self.dayFormatter.string(from: date)return DailyUsageBucket(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)}}-+private nonisolated static let dayFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "en_US_POSIX")@@ -199,15 +199,15 @@ nonisolated extension CodexQuotaSnapshot {guard let account = accountResponse.account else {throw CodexRateLimitError.notLoggedIn}-+let limits = Self.orderedSnapshots(from: rateLimitsResponse).compactMap { entry inCodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)}-+guard !limits.isEmpty else {throw CodexRateLimitError.missingRateLimitWindow}-+self.init(account: account,planType: rateLimitsResponse.rateLimits.planType,@@ -218,31 +218,31 @@ nonisolated extension CodexQuotaSnapshot {})}-+/// 展示顺序: 顶层 rateLimits 指向的主 limit 置顶, 其余按名称排序private static func orderedSnapshots(from response: AccountRateLimitsResponse) -> [(limitId: String, snapshot: RateLimitSnapshot)] {let primaryLimitId = response.rateLimits.limitId ?? "codex"-+guard let byLimitId = response.rateLimitsByLimitId, !byLimitId.isEmpty else {return [(primaryLimitId, response.rateLimits)]}-+return byLimitId.map { (limitId: $0.key, snapshot: $0.value) }.sorted { lhs, rhs inif (lhs.limitId == primaryLimitId) != (rhs.limitId == primaryLimitId) {return lhs.limitId == primaryLimitId}-+let lhsName = lhs.snapshot.limitName ?? lhs.limitIdlet rhsName = rhs.snapshot.limitName ?? rhs.limitIdlet nameOrder = lhsName.localizedStandardCompare(rhsName)if nameOrder != .orderedSame {return nameOrder == .orderedAscending}-+return lhs.limitId.localizedStandardCompare(rhs.limitId) == .orderedAscending}}@@ -254,11 +254,11 @@ nonisolated extension CodexQuotaLimitSnapshot {.compactMap { id, window inwindow.map { QuotaWindow(id: id, window: $0) }}-+guard !windows.isEmpty else {return nil}-+self.init(limitId: limitId,limitName: snapshot.limitName,@@ -288,7 +288,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {case missingRateLimitWindowcase notLoggedIncase authenticationRequired-+var errorDescription: String? {switch self {case .executableNotFound:@@ -311,7 +311,7 @@ nonisolated enum CodexRateLimitError: LocalizedError {return "Codex 需要身份验证"}}-+var isAuthenticationRequired: Bool {switch self {case .serverError(let message):@@ -322,19 +322,19 @@ nonisolated enum CodexRateLimitError: LocalizedError {return false}}-+var isUnsupportedUsageMethod: Bool {guard case .serverError(let message) = self else {return false}-+let normalizedMessage = message.lowercased()return normalizedMessage.contains("method not found")|| normalizedMessage.contains("unknown method")|| normalizedMessage.contains("unsupported")|| normalizedMessage.contains("not supported")}-+/// 凭证已失效或未登录, 需要用户在 Codex 中重新登录才能恢复var requiresLogin: Bool {switch self {diff --git a/CodexBar/RateLimitsMenuView.swift b/CodexBar/RateLimitsMenuView.swiftindex df0c867..c823703 100644--- a/CodexBar/RateLimitsMenuView.swift+++ b/CodexBar/RateLimitsMenuView.swift@@ -9,11 +9,11 @@ import SwiftUIstruct RateLimitsMenuView: View {static let menuWidth: CGFloat = Metrics.padding * 2 + Metrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth-+@ObservedObject var viewModel: RateLimitsViewModel@EnvironmentObject private var appUpdater: AppUpdater@State private var isEmailBlurred = false-+var body: some View {VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {content@@ -38,13 +38,13 @@ private extension RateLimitsMenuView {static let accountIconSize: CGFloat = 14static let loadingVerticalPadding: CGFloat = 16}-+@ViewBuildervar content: some View {if viewModel.requiresLogin {loginRequiredNotice}-+if let snapshot = viewModel.snapshot {Group {accountCard(@@ -52,13 +52,13 @@ private extension RateLimitsMenuView {isEmail: snapshot.account.hasEmail,plan: snapshot.planLabel)-+quotaLimitsView(snapshot.limits)-+if let usage = snapshot.usage {UsageSummaryView(usage: usage)}-+updatedAtRow(for: snapshot).padding(.horizontal, Metrics.panelPadding).padding(.vertical, 7)@@ -73,42 +73,42 @@ private extension RateLimitsMenuView {.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)}}-+var loginRequiredNotice: some View {HStack(spacing: 8) {Image(systemName: "person.crop.circle.badge.exclamationmark").foregroundStyle(.orange)-+Text("Codex 未登录").font(.caption).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)-+Spacer()}}-+var emptyView: some View {Text("暂无数据").foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .center).padding(.vertical, Metrics.loadingVerticalPadding)}-+func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot]) -> some View {VStack(alignment: .leading, spacing: 8) {ForEach(limits) { limit inif limit.id != limits.first?.id {LiquidGlassDivider()}-+quotaLimitSection(limit)}}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .green)}-+func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {VStack(alignment: .leading, spacing: 6) {Text(limit.title)@@ -116,7 +116,7 @@ private extension RateLimitsMenuView {.foregroundStyle(.primary).lineLimit(1).truncationMode(.middle)-+VStack(spacing: 8) {ForEach(limit.windows) { window inQuotaRow(window: window)@@ -124,14 +124,14 @@ private extension RateLimitsMenuView {}}}-+func accountCard(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {accountRow(title: title, isEmail: isEmail, plan: plan).padding(.horizontal, Metrics.panelPadding).padding(.vertical, 8).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)}-+func accountRow(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {HStack(spacing: 8) {Image(systemName: "person.fill")@@ -140,7 +140,7 @@ private extension RateLimitsMenuView {.onTapGesture(count: 2) {viewModel.refresh()}-+Text(title).font(.caption.weight(.semibold)).lineLimit(1)@@ -151,18 +151,18 @@ private extension RateLimitsMenuView {guard isEmail else { return }isEmailBlurred.toggle()}-+if viewModel.isRefreshing {ProgressView().controlSize(.mini).padding(.leading, 2)}-+Spacer()-+if let plan {let tint = planBadgeTint(for: plan)-+Text(plan.uppercased()).font(.caption2).foregroundStyle(tint)@@ -173,15 +173,15 @@ private extension RateLimitsMenuView {}}}-+func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {HStack {Text("数据更新时间 \(snapshot.generatedAt, formatter: Self.timeFormatter)").font(.caption2).foregroundStyle(.secondary)-+Spacer()-+if let message = appUpdater.panelUpdateMessage {Text(message).font(.caption2.monospacedDigit())@@ -193,7 +193,7 @@ private extension RateLimitsMenuView {}}}-+@ViewBuilderfunc errorView(_ message: String?) -> some View {if let message {@@ -204,37 +204,37 @@ private extension RateLimitsMenuView {.frame(maxWidth: .infinity, alignment: .leading)}}-+func planBadgeTint(for plan: String) -> Color {let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()-+if normalizedPlan.contains("enterprise") {return .green}-+if normalizedPlan.contains("team") || normalizedPlan.contains("business") {return .orange}-+if normalizedPlan.contains("pro") {return .purple}-+if normalizedPlan.contains("plus") {return .blue}-+if normalizedPlan.contains("edu") {return .teal}-+if normalizedPlan.contains("free") {return .secondary}-+return .cyan}-+static let timeFormatter: DateFormatter = {let formatter = DateFormatter()formatter.locale = Locale(identifier: "zh_CN")diff --git a/CodexBar/RateLimitsViewModel.swift b/CodexBar/RateLimitsViewModel.swiftindex b67ad39..38bffdb 100644--- a/CodexBar/RateLimitsViewModel.swift+++ b/CodexBar/RateLimitsViewModel.swift@@ -13,68 +13,75 @@ final class RateLimitsViewModel: ObservableObject {@Published private(set) var snapshot: CodexQuotaSnapshot?@Published private(set) var isRefreshing = false@Published private(set) var lastError: CodexRateLimitError?-+ @Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?+// UI 状态统一从 lastError 派生, 保证单一真相来源var errorMessage: String? { lastError?.errorDescription }var requiresLogin: Bool { lastError?.requiresLogin ?? false }var hasError: Bool { lastError != nil }-+private static let refreshInterval: TimeInterval = 60-+private let service: CodexRateLimitServiceprivate var autoRefreshTask: Task<Void, Never>?-+init(service: CodexRateLimitService = CodexRateLimitService()) {self.service = service}-+deinit {autoRefreshTask?.cancel()}-+func refreshIfNeeded() {guard Date().timeIntervalSince(snapshot?.generatedAt ?? .distantPast) > Self.refreshInterval else {return}-+refresh()}-+func startAutoRefresh() {guard autoRefreshTask == nil else {return}-+autoRefreshTask = Task { [weak self] inself?.refreshIfNeeded()-+while !Task.isCancelled {if (try? await Task.sleep(nanoseconds: UInt64(Self.refreshInterval * 1_000_000_000))) == nil {break}-+self?.refresh()}}}-+func refresh() {guard !isRefreshing else {return}-+isRefreshing = true-+Task {do {- let snapshot = try await service.fetchRateLimits()- self.snapshot = snapshot+ self.snapshot = try await service.fetchRateLimits()self.lastError = nil} catch {self.lastError = (error as? CodexRateLimitError) ?? .serverError(error.localizedDescription)}-++ self.codexConnectionInfo = await service.currentConnectionInfo()self.isRefreshing = false}}++ func refreshCodexConnectionInfo() {+ Task {+ self.codexConnectionInfo = await service.currentConnectionInfo()+ }+ }}diff --git a/CodexBar/SettingsWindowController.swift b/CodexBar/SettingsWindowController.swiftindex e5cd89a..d9a4935 100644--- a/CodexBar/SettingsWindowController.swift+++ b/CodexBar/SettingsWindowController.swift@@ -10,36 +10,55 @@ import SwiftUI@MainActorfinal class SettingsWindowController {+ private let viewModel: RateLimitsViewModelprivate let appUpdater: AppUpdaterprivate let screenProvider: () -> NSScreen?private var window: NSWindow?-- init(appUpdater: AppUpdater, screenProvider: @escaping () -> NSScreen?) {++ init(+ viewModel: RateLimitsViewModel,+ appUpdater: AppUpdater,+ screenProvider: @escaping () -> NSScreen?+ ) {+ self.viewModel = viewModelself.appUpdater = appUpdaterself.screenProvider = screenProvider}-+func open() {if window == nil {window = makeWindow()}-+guard let window else {return}-++ if !window.isVisible {+ prepareForDisplay(window)+ }++ bringToFront(window)+ }++ private func bringToFront(_ window: NSWindow) {+ if window.isMiniaturized {+ window.deminiaturize(nil)+ }+NSApplication.shared.activate()- prepareForDisplay(window)window.makeKeyAndOrderFront(nil)+ window.orderFrontRegardless()}-+private func makeWindow() -> NSWindow {let hostingController = NSHostingController(rootView: AppSettingsView()+ .environmentObject(viewModel).environmentObject(appUpdater))hostingController.sizingOptions = [.preferredContentSize]-+let window = NSWindow(contentViewController: hostingController)window.title = "CodexBar 设置"window.styleMask = [.titled, .closable, .miniaturizable]@@ -47,10 +66,10 @@ final class SettingsWindowController {window.contentMinSize = Metrics.minimumContentSizereturn window}-+private func prepareForDisplay(_ window: NSWindow) {window.contentViewController?.view.layoutSubtreeIfNeeded()-+if let fittingSize = window.contentViewController?.view.fittingSize,fittingSize.width > 0,fittingSize.height > 0 {@@ -61,26 +80,26 @@ final class SettingsWindowController {))}-+center(window)}-+private func center(_ window: NSWindow) {guard let screen = screenProvider() ?? window.screen ?? NSScreen.main else {window.center()return}-+let visibleFrame = screen.visibleFramelet windowFrame = window.framelet origin = NSPoint(x: visibleFrame.midX - windowFrame.width / 2,y: visibleFrame.midY - windowFrame.height / 2)-+window.setFrameOrigin(origin)}-+private enum Metrics {static let minimumContentSize = NSSize(width: 420, height: 240)}diff --git a/CodexBar/StatusItemController.swift b/CodexBar/StatusItemController.swiftindex 788bcd9..ae012ca 100644--- a/CodexBar/StatusItemController.swift+++ b/CodexBar/StatusItemController.swift@@ -13,15 +13,15 @@ import SwiftUIfinal class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let viewModel = RateLimitsViewModel()let appUpdater = AppUpdater()-+private var statusItemController: StatusItemController?-+func applicationDidFinishLaunching(_ notification: Notification) {let controller = StatusItemController(viewModel: viewModel, appUpdater: appUpdater)controller.install()statusItemController = controller}-+func applicationWillTerminate(_ notification: Notification) {statusItemController?.uninstall()}@@ -33,8 +33,11 @@ private final class StatusItemController: NSObject {private let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()-- private lazy var settingsWindowController = SettingsWindowController(appUpdater: appUpdater) { [weak self] in++ private lazy var settingsWindowController = SettingsWindowController(+ viewModel: viewModel,+ appUpdater: appUpdater+ ) { [weak self] inself?.statusItem.button?.window?.screen}private var deferredRefreshTask: Task<Void, Never>?@@ -46,16 +49,16 @@ private final class StatusItemController: NSObject {private var globalMouseEventMonitor: Any?private var cancellables = Set<AnyCancellable>()private var lastHasError: Bool?-+private static let normalImage = NSImage(systemSymbolName: "person.fill.checkmark", accessibilityDescription: nil)private static let errorImage = NSImage(systemSymbolName: "person.fill.xmark", accessibilityDescription: nil)-+init(viewModel: RateLimitsViewModel, appUpdater: AppUpdater) {self.viewModel = viewModelself.appUpdater = appUpdatersuper.init()}-+func install() {configureStatusButton()configurePopover()@@ -63,38 +66,38 @@ private final class StatusItemController: NSObject {updateStatusImage()viewModel.startAutoRefresh()}-+func uninstall() {closePopover(animated: false)cancellables.removeAll()NSStatusBar.system.removeStatusItem(statusItem)}-+private func configureStatusButton() {guard let button = statusItem.button else {return}-+button.target = selfbutton.action = #selector(statusItemClicked(_:))button.imagePosition = .imageOnlybutton.toolTip = "CodexBar"button.sendAction(on: [.leftMouseUp, .rightMouseUp])}-+private func configurePopover() {let rootView = RateLimitsMenuView(viewModel: viewModel).environmentObject(appUpdater).frame(width: RateLimitsMenuView.menuWidth)-+let hostingController = NSHostingController(rootView: rootView)hostingController.sizingOptions = [.preferredContentSize]-+popover.behavior = .applicationDefinedpopover.animates = falsepopover.contentViewController = hostingController}-+private func observeViewModel() {viewModel.objectWillChange.sink { [weak self] _ in@@ -104,30 +107,30 @@ private final class StatusItemController: NSObject {}.store(in: &cancellables)}-+private func updateStatusImage() {let hasError = viewModel.hasErrorguard hasError != lastHasError else {return}-+lastHasError = hasErrorstatusItem.button?.image = hasError ? Self.errorImage : Self.normalImage}-+@objc private func statusItemClicked(_ sender: NSStatusBarButton) {guard let event = NSApplication.shared.currentEvent else {togglePopover(relativeTo: sender)return}-+if event.type == .rightMouseUp || event.modifierFlags.contains(.control) {showContextMenu(relativeTo: sender)} else {togglePopover(relativeTo: sender)}}-+private func togglePopover(relativeTo button: NSStatusBarButton) {switch popoverState {case .hidden:@@ -139,7 +142,7 @@ private final class StatusItemController: NSObject {openPopover(relativeTo: button)}}-+private func cancelPopoverTasks() {deferredRefreshTask?.cancel()deferredRefreshTask = nil@@ -148,39 +151,39 @@ private final class StatusItemController: NSObject {popoverCloseTask?.cancel()popoverCloseTask = nil}-+private func openPopover(relativeTo button: NSStatusBarButton) {cancelPopoverTasks()-+popoverAnimationGeneration += 1let generation = popoverAnimationGenerationpopoverState = .opening-+preparePopoverForFadeIn()popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)stabilizePopoverChromeAppearance()installPopoverDismissMonitors()fadePopover(to: 1, duration: Metrics.fadeInDuration)-+popoverOpenTask = Task { @MainActor [weak self] intry? await Task.sleep(for: .milliseconds(Int(Metrics.fadeInDuration * 1000)))guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {return}-+self.resetPopoverAlpha()self.popoverState = .shownself.popoverOpenTask = nil}-+scheduleDeferredRefresh()}-+private func showContextMenu(relativeTo button: NSStatusBarButton) {closePopover(animated: false)-+let menu = NSMenu()-+let settingsItem = NSMenuItem(title: "设置",action: #selector(openSettings),@@ -189,9 +192,9 @@ private final class StatusItemController: NSObject {settingsItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)settingsItem.target = selfmenu.addItem(settingsItem)-+menu.addItem(.separator())-+let quitItem = NSMenuItem(title: "退出",action: #selector(quit),@@ -200,45 +203,45 @@ private final class StatusItemController: NSObject {quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil)quitItem.target = selfmenu.addItem(quitItem)-+menu.popUp(positioning: nil,at: NSPoint(x: 0, y: button.bounds.minY - 4),in: button)}-+@objc private func openSettings() {settingsWindowController.open()}-+@objc private func quit() {NSApplication.shared.terminate(nil)}-+private func closePopover(animated: Bool = true) {if popoverState == .closing && animated {return}-+cancelPopoverTasks()removePopoverDismissMonitors()-+guard popover.isShown else {resetPopoverAlpha()popoverState = .hiddenreturn}-+guard animated, let contentView = popover.contentViewController?.view else {finishPopoverClose()return}-+popoverAnimationGeneration += 1let generation = popoverAnimationGenerationpopoverState = .closing-+let popoverWindow = contentView.windowfadePopover(to: 0, duration: Metrics.fadeOutDuration)popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in@@ -246,7 +249,7 @@ private final class StatusItemController: NSObject {guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {return}-+self.popover.performClose(nil)contentView?.alphaValue = 1popoverWindow?.alphaValue = 1@@ -254,131 +257,131 @@ private final class StatusItemController: NSObject {self.popoverCloseTask = nil}}-+private func finishPopoverClose() {cancelPopoverTasks()popoverAnimationGeneration += 1removePopoverDismissMonitors()-+if popover.isShown {popover.performClose(nil)}-+resetPopoverAlpha()popoverState = .hidden}-+private func installPopoverDismissMonitors() {removePopoverDismissMonitors()-+localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event inself?.closePopoverIfNeeded(for: event)self?.restabilizePopoverChromeAfterEvent()return event}-+globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] _ inself?.closePopover()}}-+private func removePopoverDismissMonitors() {if let localMouseEventMonitor {NSEvent.removeMonitor(localMouseEventMonitor)self.localMouseEventMonitor = nil}-+if let globalMouseEventMonitor {NSEvent.removeMonitor(globalMouseEventMonitor)self.globalMouseEventMonitor = nil}}-+private func restabilizePopoverChromeAfterEvent() {Task { @MainActor [weak self] inawait Task.yield()guard let self, self.popover.isShown else {return}-+self.stabilizePopoverChromeAppearance()}}-+private func stabilizePopoverChromeAppearance() {guard let rootView = popover.contentViewController?.view.window?.contentView else {return}-+stabilizeVisualEffectViews(in: rootView)}-+private func stabilizeVisualEffectViews(in view: NSView) {if let visualEffectView = view as? NSVisualEffectView {visualEffectView.state = .inactivevisualEffectView.isEmphasized = false}-+for subview in view.subviews {stabilizeVisualEffectViews(in: subview)}}-+private func closePopoverIfNeeded(for event: NSEvent) {guard popover.isShown else {return}-+if isEventInsidePopover(event) || isEventInsideStatusButton(event) {return}-+closePopover()}-+private func isEventInsidePopover(_ event: NSEvent) -> Bool {guard let contentView = popover.contentViewController?.view,event.window == contentView.window else {return false}-+let point = contentView.convert(event.locationInWindow, from: nil)return contentView.bounds.contains(point)}-+private func isEventInsideStatusButton(_ event: NSEvent) -> Bool {guard let button = statusItem.button,let buttonWindow = button.window else {return false}-+let eventScreenPoint = event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocationlet buttonRectInWindow = button.convert(button.bounds, to: nil)let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)return buttonScreenRect.contains(eventScreenPoint)}-+private func preparePopoverForFadeIn() {popover.contentViewController?.view.alphaValue = 0popover.contentViewController?.view.window?.alphaValue = 0}-+private func resetPopoverAlpha() {popover.contentViewController?.view.alphaValue = 1popover.contentViewController?.view.window?.alphaValue = 1}-+private func fadePopover(to alpha: CGFloat, duration: TimeInterval) {guard let contentView = popover.contentViewController?.view else {return}-+let popoverWindow = contentView.window// 淡入前窗口可能刚由 popover.show 懒创建,先把窗口 alpha 归零再动画if alpha == 1 {popoverWindow?.alphaValue = 0}-+NSAnimationContext.runAnimationGroup { context incontext.duration = durationcontext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)@@ -386,7 +389,7 @@ private final class StatusItemController: NSObject {contentView.animator().alphaValue = alpha}}-+private func scheduleDeferredRefresh() {deferredRefreshTask?.cancel()deferredRefreshTask = Task { @MainActor [weak self] in@@ -394,11 +397,11 @@ private final class StatusItemController: NSObject {guard let self, !Task.isCancelled, self.popover.isShown else {return}-+self.viewModel.refreshIfNeeded()}}-+private enum Metrics {static let dismissEventMask: NSEvent.EventTypeMask = [.leftMouseDown,@@ -408,7 +411,7 @@ private final class StatusItemController: NSObject {static let fadeInDuration: TimeInterval = 0.24static let fadeOutDuration: TimeInterval = 0.18}-+private enum PopoverState {case hiddencase openingdiff --git a/CodexBar/TokenCountText.swift b/CodexBar/TokenCountText.swiftindex 5bfb73d..ee412a2 100644--- a/CodexBar/TokenCountText.swift+++ b/CodexBar/TokenCountText.swift@@ -9,7 +9,7 @@ import SwiftUIstruct TokenCountText: View {let tokens: Int-+var body: some View {Text(TokenCountFormatter.string(from: tokens)).font(.caption.monospacedDigit().weight(.semibold))@@ -25,16 +25,18 @@ private enum TokenCountFormatter {return decimal(Double(tokens) / 1_000_000_000) + "B"case 1_000_000...:return decimal(Double(tokens) / 1_000_000) + "M"- default:+ case 1_000...:return decimal(Double(tokens) / 1_000) + "K"+ default:+ return String(tokens)}}-+private static func decimal(_ value: Double) -> String {let rounded = value >= 0.1 ? (value * 10).rounded() / 10 : (value * 100).rounded() / 100return formatter.string(from: NSNumber(value: rounded)) ?? String(format: "%.1f", rounded)}-+private static let formatter: NumberFormatter = {let formatter = NumberFormatter()formatter.numberStyle = .decimaldiff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/UsageHeatmap.swiftindex e8b4ec7..1981f96 100644--- a/CodexBar/UsageHeatmap.swift+++ b/CodexBar/UsageHeatmap.swift@@ -11,12 +11,12 @@ struct UsageSummaryView: View {let usage: CodexUsageSnapshotprivate let days: [DailyUsageBucket]@State private var hoveredDay: DailyUsageBucket?-+init(usage: CodexUsageSnapshot) {self.usage = usageself.days = usage.recentDays(count: UsageHeatmap.Metrics.dayCount, endingDaysAgo: 1)}-+var body: some View {VStack(alignment: .leading, spacing: 8) {HStack(alignment: .firstTextBaseline) {@@ -24,7 +24,7 @@ struct UsageSummaryView: View {Spacer()metric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .trailing)}-+UsageHeatmap(days: days, hoveredDay: $hoveredDay)}.padding(10)@@ -33,14 +33,14 @@ struct UsageSummaryView: View {hoveredDay = nil}}-+private func metric(label: String, value: Int, alignment: Alignment) -> some View {VStack(alignment: .leading, spacing: 2) {Text(label).font(.caption2).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: alignment)-+TokenCountText(tokens: value).frame(maxWidth: .infinity, alignment: alignment)}@@ -54,17 +54,17 @@ struct UsageHeatmap: View {@State private var hoveredSquareFrame: CGRect = .zero// hover 期间 body 频繁重算, 峰值只在构建时求一次private let peakTokens: Int-+init(days: [DailyUsageBucket], hoveredDay: Binding<DailyUsageBucket?>) {self.days = daysself._hoveredDay = hoveredDayself.peakTokens = max(days.lazy.map(\.tokens).max() ?? 0, 1)}-+var body: some View {ZStack(alignment: .topLeading) {heatmapGrid-+if let hoveredDay {UsageHeatmapTooltip(day: hoveredDay).id(hoveredDay.id)@@ -77,16 +77,16 @@ struct UsageHeatmap: View {.frame(height: Metrics.height).coordinateSpace(name: Metrics.coordinateSpaceName)}-+private var heatmapGrid: some View {VStack(alignment: .leading, spacing: 6) {HStack(alignment: .firstTextBaseline) {Text("近 \(days.count) 天").font(.caption2.weight(.medium)).foregroundStyle(.secondary)-+Spacer()-+if let firstDate = days.first?.startDate, let lastDate = days.last?.startDate {Text("\(firstDate) ~ \(lastDate)").font(.caption2.monospacedDigit())@@ -94,13 +94,13 @@ struct UsageHeatmap: View {.lineLimit(1)}}-+HStack(alignment: .top, spacing: Metrics.squareSpacing) {ForEach(0..<Metrics.columnCount, id: \.self) { column inVStack(spacing: Metrics.squareSpacing) {ForEach(0..<Metrics.rowCount, id: \.self) { row inlet index = column * Metrics.rowCount + row-+if days.indices.contains(index) {let day = days[index]UsageHeatmapSquare(@@ -134,30 +134,30 @@ struct UsageHeatmap: View {}.frame(maxWidth: .infinity, alignment: .leading)}-+private var tooltipOffset: CGSize {let aboveY = hoveredSquareFrame.minY - Metrics.tooltipSquareSpacing - Metrics.tooltipHeightlet tooltipY = aboveY >= 0 ? aboveY : hoveredSquareFrame.maxY + Metrics.tooltipSquareSpacing-+return CGSize(width: tooltipX(for: hoveredSquareFrame),height: min(max(tooltipY, 0), max(0, Metrics.height - Metrics.tooltipHeight)))}-+private func tooltipX(for squareFrame: CGRect) -> CGFloat {let trailingX = squareFrame.maxX + Metrics.tooltipSquareSpacinglet leadingX = squareFrame.minX - Metrics.tooltipSquareSpacing - Metrics.tooltipWidthlet maxX = max(0, Metrics.totalWidth - Metrics.tooltipWidth)-+if leadingX >= 0 {return leadingX}-+if trailingX + Metrics.tooltipWidth <= Metrics.totalWidth {return trailingX}-+return min(max(leadingX, 0), maxX)}}@@ -174,9 +174,9 @@ extension UsageHeatmap {static let tooltipHeight: CGFloat = 38static let tooltipSquareSpacing: CGFloat = 2static let tooltipFadeDuration: TimeInterval = 0.15-+static var dayCount: Int { columnCount * rowCount }-+static var totalWidth: CGFloat {CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing}@@ -189,7 +189,7 @@ private struct UsageHeatmapSquare: View {let isHovered: Boollet onActive: (CGRect) -> Voidlet onEnded: () -> Void-+var body: some View {GeometryReader { proxy inRoundedRectangle(cornerRadius: 4, style: .continuous)@@ -213,39 +213,39 @@ private struct UsageHeatmapSquare: View {.contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous)).animation(.snappy(duration: 0.14), value: isHovered)}-+private var clampedPercent: Double {min(max(percent, 0), 1)}-+private var fillColor: Color {guard day.tokens > 0 else {return Color.blue.opacity(isHovered ? 0.16 : 0.08)}-+let intensity = pow(clampedPercent, 0.62)let opacity = 0.18 + intensity * 0.68return Color.blue.opacity(isHovered ? min(opacity + 0.10, 1.0) : opacity)}-+private var borderColor: Color {if isHovered {return Color.blue.opacity(0.78)}-+return Color.blue.opacity(day.tokens > 0 ? 0.18 : 0.10)}}private struct UsageHeatmapTooltip: View {let day: DailyUsageBucket-+var body: some View {VStack(alignment: .leading, spacing: 2) {Text(day.startDate).font(.caption2.monospacedDigit()).foregroundStyle(Color(nsColor: .secondaryLabelColor))-+TokenCountText(tokens: day.tokens).foregroundStyle(Color(nsColor: .labelColor))}diff --git a/Updates/appcast.xml b/Updates/appcast.xmlindex 549bd6b..cc9a761 100644--- a/Updates/appcast.xml+++ b/Updates/appcast.xml@@ -7,6 +7,15 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 1.3.4</title>+ <sparkle:version>7</sparkle:version>+ <sparkle:shortVersionString>1.3.4</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes/1.3.4.html</sparkle:releaseNotesLink>+ <pubDate>Mon, 15 Jun 2026 13:59:04 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v1.3.4.dmg" sparkle:edSignature="1Eozkv41L4r7ecCVr6wpAeOR2ZPLcnKOfGEtsFv6EZZuNaFSpMw5EUvc1KESoReaxVZU7PkpVGhZrCw4FexPAA==" length="1461243" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 1.3.3</title><sparkle:version>6</sparkle:version>