Skip to content

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

chore: 提交当前工作区内容

Bob24eb7aa1104c
diff --git a/AGENTS.md b/AGENTS.md
index cf828b5..a1fed17 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -272,9 +272,9 @@ Popover:
## 发布脚本
-- `Scripts/create-dmg.sh [App.app] [Output.dmg]` 创建带 `/Applications` 链接的 DMG, 会尝试写 Finder 布局。
-- `Scripts/update-appcast.sh [CodexBar-vX.Y.Z.dmg]` 更新 `Updates/appcast.xml`, 需要 Sparkle `sign_update`。
-- 改发布脚本后至少运行 `bash -n Scripts/create-dmg.sh` 和 `bash -n Scripts/update-appcast.sh`。
+- `Scripts/dmg.sh [App.app] [Output.dmg]` 创建带 `/Applications` 链接的 DMG, 会尝试写 Finder 布局。
+- `Scripts/appcast.sh [CodexBar-vX.Y.Z.dmg]` 更新 `appcast.xml`, 需要 Sparkle `sign_update`。
+- 改发布脚本后至少运行 `bash -n Scripts/dmg.sh` 和 `bash -n Scripts/appcast.sh`。
- 更新 appcast、tag、push、上传 DMG 都必须先得到用户明确同意。
## Git 规则
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index 1bb0d34..36b46bf 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 = 10;
+ CURRENT_PROJECT_VERSION = 11;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -290,7 +290,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 2.0.0;
+ MARKETING_VERSION = 2.1.0;
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 = 10;
+ CURRENT_PROJECT_VERSION = 11;
DEVELOPMENT_TEAM = 4KJ362VJW5;
ENABLE_APP_INTENTS_METADATA_GENERATION = NO;
ENABLE_APP_SANDBOX = NO;
@@ -327,7 +327,7 @@
"$(inherited)",
"@executable_path/../Frameworks",
);
- MARKETING_VERSION = 2.0.0;
+ MARKETING_VERSION = 2.1.0;
PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/CodexBar/CodexQuotaModels.swift b/CodexBar/CodexQuotaModels.swift
index 3cf7136..5012938 100644
--- a/CodexBar/CodexQuotaModels.swift
+++ b/CodexBar/CodexQuotaModels.swift
@@ -6,11 +6,11 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
let generatedAt: Date
let limits: [CodexQuotaLimitSnapshot]
let usage: CodexUsageSnapshot?
-
+
var accountLabel: String {
account.displayName
}
-
+
var planLabel: String? {
account.planType ?? planType
}
@@ -20,14 +20,14 @@ nonisolated struct CodexQuotaLimitSnapshot: Equatable, Identifiable {
let limitId: String
let limitName: String?
let windows: [QuotaWindow]
-
+
var id: String { limitId }
-
+
var title: String {
if let limitName, !limitName.isEmpty {
return limitName.capitalizingFirstLetter()
}
-
+
return limitId.capitalizingFirstLetter()
}
}
@@ -37,7 +37,7 @@ nonisolated private extension String {
guard let first else {
return self
}
-
+
return first.uppercased() + dropFirst()
}
}
@@ -46,16 +46,16 @@ nonisolated struct CodexAccount: Decodable, Equatable {
let type: String
let email: String?
let planType: String?
-
+
var hasEmail: Bool {
email?.isEmpty == false
}
-
+
var displayName: String {
if let email, hasEmail {
return email
}
-
+
switch type {
case "apiKey":
return "API Key"
@@ -78,36 +78,36 @@ nonisolated struct QuotaWindow: Equatable, Identifiable {
let windowDurationMins: Int?
let usedPercent: Int?
let resetsAt: Date?
-
+
var label: String {
Self.windowLabel(for: windowDurationMins)
}
-
+
var remainingPercent: Int {
guard let usedPercent else {
return 0
}
-
+
return max(0, min(100, 100 - usedPercent))
}
-
+
var hasData: Bool {
usedPercent != nil
}
-
+
private static func windowLabel(for minutes: Int?) -> String {
guard let minutes, minutes > 0 else {
return "额度"
}
-
+
if minutes.isMultiple(of: 1_440) {
return "\(minutes / 1_440) 天"
}
-
+
if minutes.isMultiple(of: 60) {
return "\(minutes / 60) 小时"
}
-
+
return "\(minutes) 分钟"
}
}
@@ -129,7 +129,7 @@ nonisolated struct RateLimitWindow: Decodable {
let usedPercent: Int?
let resetsAt: Int?
let windowDurationMins: Int?
-
+
var resetDate: Date? {
guard let resetsAt else { return nil }
return Date(timeIntervalSince1970: TimeInterval(resetsAt))
@@ -152,20 +152,20 @@ nonisolated struct UsageSummary: Decodable, Equatable {
nonisolated struct DailyUsageBucket: Decodable, Equatable, Identifiable {
let startDate: String
let tokens: Int
-
+
var id: String { startDate }
}
nonisolated struct CodexUsageSnapshot: Equatable {
let summary: UsageSummary
let dailyBuckets: [DailyUsageBucket]
-
+
/// 给热力图生成按周排列的最近日期网格, 每列从周日开始
func recentWeekGrid(columnCount: Int, endingDaysAgo: Int = 0, today: Date = Date()) -> [DailyUsageBucket?] {
guard columnCount > 0 else {
return []
}
-
+
let calendar = Calendar.current
let todayStart = calendar.startOfDay(for: today)
let lastVisibleDate = calendar.date(
@@ -181,37 +181,37 @@ nonisolated struct CodexUsageSnapshot: Equatable {
) else {
return []
}
-
+
let tokensByDate = dailyBuckets.reduce(into: [String: Int]()) { result, bucket in
result[bucket.startDate, default: 0] += bucket.tokens
}
-
+
return (0..<columnCount).flatMap { column -> [DailyUsageBucket?] in
guard let weekStart = calendar.date(byAdding: .weekOfYear, value: column, to: firstWeekStart) else {
return Array(repeating: nil, count: 7)
}
-
+
return (0..<7).map { weekdayOffset -> DailyUsageBucket? in
guard let date = calendar.date(byAdding: .day, value: weekdayOffset, to: weekStart) else {
return nil
}
-
+
guard date <= lastVisibleDate else {
return nil
}
-
+
let startDate = Self.dayFormatter.string(from: date)
return DailyUsageBucket(startDate: startDate, tokens: tokensByDate[startDate] ?? 0)
}
}
}
-
+
private static func sundayStartOfWeek(containing date: Date, calendar: Calendar) -> Date {
let weekday = calendar.component(.weekday, from: date)
let daysSinceSunday = weekday - 1
return calendar.date(byAdding: .day, value: -daysSinceSunday, to: date) ?? date
}
-
+
private nonisolated static let dayFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
@@ -230,17 +230,17 @@ nonisolated extension CodexQuotaSnapshot {
guard let account = accountResponse.account else {
throw CodexStatusError.notLoggedIn
}
-
+
let limits = rateLimitsResponse.map { response in
Self.orderedSnapshots(from: response).compactMap { entry in
CodexQuotaLimitSnapshot(limitId: entry.limitId, snapshot: entry.snapshot)
}
} ?? []
-
+
let usage = usageResponse.map {
CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)
}
-
+
// rateLimits/usage 可同时为空, 账户有效时仍生成快照给 UI 展示"暂无数据"
self.init(
account: account,
@@ -250,31 +250,31 @@ nonisolated extension CodexQuotaSnapshot {
usage: usage
)
}
-
+
/// 展示顺序: 顶层 rateLimits 指向的主 limit 置顶, 其余按名称排序
private static func orderedSnapshots(
from response: AccountRateLimitsResponse
) -> [(limitId: String, snapshot: RateLimitSnapshot)] {
let primaryLimitId = response.rateLimits.limitId ?? "codex"
-
+
guard let byLimitId = response.rateLimitsByLimitId, !byLimitId.isEmpty else {
return [(primaryLimitId, response.rateLimits)]
}
-
+
return byLimitId
.map { (limitId: $0.key, snapshot: $0.value) }
.sorted { lhs, rhs in
if (lhs.limitId == primaryLimitId) != (rhs.limitId == primaryLimitId) {
return lhs.limitId == primaryLimitId
}
-
+
let lhsName = lhs.snapshot.limitName ?? lhs.limitId
let rhsName = rhs.snapshot.limitName ?? rhs.limitId
let nameOrder = lhsName.localizedStandardCompare(rhsName)
if nameOrder != .orderedSame {
return nameOrder == .orderedAscending
}
-
+
return lhs.limitId.localizedStandardCompare(rhs.limitId) == .orderedAscending
}
}
@@ -286,11 +286,11 @@ nonisolated extension CodexQuotaLimitSnapshot {
.compactMap { id, window in
window.map { QuotaWindow(id: id, window: $0) }
}
-
+
guard !windows.isEmpty else {
return nil
}
-
+
self.init(
limitId: limitId,
limitName: snapshot.limitName,
@@ -317,7 +317,7 @@ nonisolated enum CodexStatusError: LocalizedError {
case invalidServerResponse
case serverError(String)
case notLoggedIn
-
+
var errorDescription: String? {
switch self {
case .executableNotFound:
@@ -326,12 +326,12 @@ nonisolated enum CodexStatusError: LocalizedError {
return nil
}
}
-
+
/// codex app-server 目前通过 serverError 文案表示认证失败
var isAuthenticationRequired: Bool {
serverErrorMessageContains("authentication required")
}
-
+
var isUnsupportedUsageMethod: Bool {
serverErrorMessageContains("unknown variant")
|| serverErrorMessageContains("method not found")
@@ -339,7 +339,7 @@ nonisolated enum CodexStatusError: LocalizedError {
|| serverErrorMessageContains("unsupported")
|| serverErrorMessageContains("not supported")
}
-
+
/// 连接断开、超时、无法解析都需要重建 app-server 会话
var isTransportFailure: Bool {
switch self {
@@ -349,12 +349,12 @@ nonisolated enum CodexStatusError: LocalizedError {
return false
}
}
-
+
private func serverErrorMessageContains(_ keyword: String) -> Bool {
guard case .serverError(let message) = self else {
return false
}
-
+
return message.range(of: keyword, options: .caseInsensitive) != nil
}
}
diff --git a/CodexBar/CodexStatusMenuView.swift b/CodexBar/CodexStatusMenuView.swift
index 4dcdc82..c9c14f3 100644
--- a/CodexBar/CodexStatusMenuView.swift
+++ b/CodexBar/CodexStatusMenuView.swift
@@ -8,12 +8,12 @@ final class PopoverVisibilityState: ObservableObject {
struct CodexStatusMenuView: View {
static let menuWidth: CGFloat = Metrics.padding * 2 + Metrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth
-
+
@ObservedObject var viewModel: CodexStatusViewModel
@ObservedObject var popoverVisibility: PopoverVisibilityState
@EnvironmentObject private var appUpdater: AppUpdater
@State private var isEmailBlurred = false
-
+
var body: some View {
VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {
content
@@ -38,7 +38,7 @@ private extension CodexStatusMenuView {
static let loadingVerticalPadding: CGFloat = 16
static let statusAnimation = Animation.codexStatus
}
-
+
@ViewBuilder
var content: some View {
if let snapshot = viewModel.snapshot {
@@ -47,39 +47,35 @@ private extension CodexStatusMenuView {
isEmail: snapshot.account.hasEmail,
plan: snapshot.planLabel
)
-
+
dataSection(snapshot)
} else {
// 仅展示未登录 / 初始化失败两种特殊状态, 其余错误只进日志
statusAccountCard
- emptyView
- .padding(Metrics.panelPadding)
- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+ emptyPanel
}
}
-
+
@ViewBuilder
func dataSection(_ snapshot: CodexQuotaSnapshot) -> some View {
if snapshot.limits.isEmpty, snapshot.usage == nil {
- emptyView
- .padding(Metrics.panelPadding)
- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+ emptyPanel
} else {
if !snapshot.limits.isEmpty {
quotaLimitsView(snapshot.limits)
}
-
+
if let usage = snapshot.usage {
UsageSummaryView(usage: usage)
}
}
-
+
updatedAtRow(for: snapshot)
.padding(.horizontal, Metrics.panelPadding)
.padding(.vertical, 7)
.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .mint)
}
-
+
var statusAccountCard: some View {
HStack(spacing: 8) {
Image(systemName: "person.fill")
@@ -88,7 +84,7 @@ private extension CodexStatusMenuView {
.onTapGesture(count: 2) {
viewModel.refresh()
}
-
+
if let text = statusDisplay.text {
Text(text)
.font(.caption.weight(.semibold))
@@ -96,20 +92,20 @@ private extension CodexStatusMenuView {
.lineLimit(1)
.truncationMode(.middle)
}
-
+
if viewModel.isRefreshing {
ProgressView()
.controlSize(.mini)
.padding(.leading, 2)
}
-
+
Spacer()
}
.padding(.horizontal, Metrics.panelPadding)
.padding(.vertical, 8)
.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
}
-
+
var statusDisplay: (text: String?, color: Color) {
switch viewModel.loadState {
case .notLoggedIn:
@@ -120,28 +116,34 @@ private extension CodexStatusMenuView {
return (nil, .accentColor)
}
}
-
+
var emptyView: some View {
Text("暂无数据")
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .center)
.padding(.vertical, Metrics.loadingVerticalPadding)
}
-
+
+ var emptyPanel: some View {
+ emptyView
+ .padding(Metrics.panelPadding)
+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .cyan)
+ }
+
func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot]) -> some View {
VStack(alignment: .leading, spacing: 8) {
ForEach(limits) { limit in
if limit.id != limits.first?.id {
LiquidGlassDivider()
}
-
+
quotaLimitSection(limit)
}
}
.padding(Metrics.panelPadding)
.liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius, tint: .green)
}
-
+
func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {
VStack(alignment: .leading, spacing: 6) {
Text(limit.title)
@@ -149,7 +151,7 @@ private extension CodexStatusMenuView {
.foregroundStyle(.primary)
.lineLimit(1)
.truncationMode(.middle)
-
+
VStack(spacing: 8) {
ForEach(limit.windows) { window in
QuotaRow(window: window)
@@ -157,14 +159,14 @@ private extension CodexStatusMenuView {
}
}
}
-
+
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")
@@ -173,7 +175,7 @@ private extension CodexStatusMenuView {
.onTapGesture(count: 2) {
viewModel.refresh()
}
-
+
Text(title)
.font(.caption.weight(.semibold))
.lineLimit(1)
@@ -184,18 +186,18 @@ private extension CodexStatusMenuView {
guard isEmail else { return }
isEmailBlurred.toggle()
}
-
+
if viewModel.isRefreshing {
ProgressView()
.controlSize(.mini)
.padding(.leading, 2)
}
-
+
Spacer()
-
+
if let plan {
let tint = planBadgeTint(for: plan)
-
+
Text(plan.uppercased())
.font(.caption2.weight(.bold))
.foregroundStyle(tint)
@@ -203,7 +205,7 @@ private extension CodexStatusMenuView {
}
}
}
-
+
func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {
HStack {
HStack(spacing: 5) {
@@ -213,10 +215,10 @@ private extension CodexStatusMenuView {
isActive: popoverVisibility.isVisible,
color: .blue
)
-
+
Text("数据更新时间")
.foregroundStyle(Self.secondaryTextColor)
-
+
Text(Self.timeFormatter.string(from: snapshot.generatedAt))
.monospacedDigit()
.contentTransition(.numericText())
@@ -224,9 +226,9 @@ private extension CodexStatusMenuView {
}
.font(.caption2)
.animation(Metrics.statusAnimation, value: snapshot.generatedAt)
-
+
Spacer()
-
+
if let message = appUpdater.panelUpdateMessage {
Text(message)
.font(.caption2.monospacedDigit())
@@ -241,14 +243,14 @@ private extension CodexStatusMenuView {
}
.animation(Metrics.statusAnimation, value: appUpdater.panelUpdateMessage)
}
-
+
func planBadgeTint(for plan: String) -> Color {
let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return Self.planTintRules.first { rule in
rule.keywords.contains { normalizedPlan.contains($0) }
}?.tint ?? .cyan
}
-
+
static let planTintRules: [(keywords: [String], tint: Color)] = [
(["enterprise"], .green),
(["team", "business"], .orange),
@@ -257,14 +259,14 @@ private extension CodexStatusMenuView {
(["edu"], .teal),
(["free"], .secondary)
]
-
+
static let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh_CN")
formatter.dateFormat = "HH:mm:ss"
return formatter
}()
-
+
static let secondaryTextColor = Color.codexSecondaryLabel
}
@@ -273,7 +275,7 @@ private struct AutoRefreshCountdownTimeline: View {
let interval: TimeInterval
let isActive: Bool
let color: Color
-
+
var body: some View {
if isActive {
TimelineView(.periodic(from: .now, by: 1)) { timeline in
@@ -283,7 +285,7 @@ private struct AutoRefreshCountdownTimeline: View {
circle(now: Date())
}
}
-
+
private func circle(now: Date) -> AutoRefreshCountdownCircle {
AutoRefreshCountdownCircle(
startedAt: startedAt,
@@ -301,21 +303,21 @@ private struct AutoRefreshCountdownCircle: View {
let now: Date
let isActive: Bool
let color: Color
-
+
private var progress: Double {
guard interval > 0 else {
return 0
}
-
+
let elapsed = max(0, now.timeIntervalSince(startedAt))
return max(0, 1 - elapsed / interval)
}
-
+
var body: some View {
ZStack {
Circle()
.stroke(color.opacity(0.15), lineWidth: 1.4)
-
+
Circle()
.trim(from: 1 - progress, to: 1)
.stroke(
@@ -328,7 +330,7 @@ private struct AutoRefreshCountdownCircle: View {
// 只让刷新起点变化触发动画, 避免每秒 tick 被补间
.animation(isActive ? .linear(duration: Metrics.resetAnimationDuration) : nil, value: startedAt)
}
-
+
private enum Metrics {
static let resetAnimationDuration: TimeInterval = 0.50
}
diff --git a/CodexBar/CodexStatusService.swift b/CodexBar/CodexStatusService.swift
index 71db524..b303bac 100644
--- a/CodexBar/CodexStatusService.swift
+++ b/CodexBar/CodexStatusService.swift
@@ -33,7 +33,7 @@ nonisolated private extension ReadResult {
}
return false
}
-
+
func valueAfterAuthAttempt() throws -> Value? {
switch self {
case .value(let value):
@@ -54,24 +54,24 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
// 定期回收连接, 让后台升级后的 codex 二进制有机会生效
private static let connectionMaxAge: TimeInterval = 1 * 60 * 60
private static let environment = CodexCLIResolver.environment
-
+
// connection 只在这个队列上访问
private let queue = DispatchQueue(label: "CodexBar.app-server", qos: .utility)
private var connection: AppServerConnection?
-
+
// app-server 退出后继续写管道会触发 SIGPIPE; 忽略信号, 让 write 抛错后走重建
private static let ignoreBrokenPipeSignal: Void = {
signal(SIGPIPE, SIG_IGN)
}()
-
+
init() {
_ = Self.ignoreBrokenPipeSignal
}
-
+
deinit {
connection?.session.close()
}
-
+
func fetchOutcome() async -> CodexFetchOutcome {
await withCheckedContinuation { continuation in
queue.async {
@@ -79,7 +79,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
}
-
+
func currentConnectionInfo() async -> CodexCLIConnectionInfo? {
await withCheckedContinuation { continuation in
queue.async {
@@ -87,7 +87,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
}
-
+
/// 复用连接出现传输故障时只重建重试一次, 避免故障状态下反复拉起进程
private func resolveOutcomeOnQueue(allowRebuild: Bool) -> CodexFetchOutcome {
switch ensureConnection() {
@@ -114,15 +114,15 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
}
}
-
+
private func ensureConnection() -> ConnectionResolution {
if let connection, connection.session.process.isRunning,
Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {
return .ready(connection: connection, reused: true)
}
-
+
teardownConnection()
-
+
let command: AppServerCommand
do {
command = try CodexCLIResolver.resolveAppServerCommand(environment: Self.environment)
@@ -130,7 +130,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
RequestLogStore.shared.recordFailure(message: error.localizedDescription)
return .initializationFailed
}
-
+
let resolution = Self.openConnection(
command: command,
environment: Self.environment,
@@ -142,40 +142,40 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
}
return resolution
}
-
+
private func teardownConnection() {
connection?.session.close()
connection = nil
}
-
+
private func currentConnectionInfoOnQueue() -> CodexCLIConnectionInfo? {
guard let connection, connection.session.process.isRunning else {
return nil
}
-
+
return connection.commandInfo
}
-
+
/// 额度与用量独立读取; 认证失败全程只刷新一次 token, 传输故障交给外层重建连接
private static func fetchData(using connection: AppServerConnection, refreshAccountInfo: Bool) throws -> CodexQuotaSnapshot {
var didRefresh = false
-
+
func refreshTokenIfNeeded() throws {
guard !didRefresh else { throw FetchFailure.notLoggedIn }
didRefresh = true
try refreshAccount(using: connection)
}
-
+
func readWithAuthRefresh<Value>(_ read: () -> ReadResult<Value>) throws -> Value? {
let firstAttempt = read()
guard firstAttempt.isAuthenticationRequired else {
return try firstAttempt.valueAfterAuthAttempt()
}
-
+
try refreshTokenIfNeeded()
return try read().valueAfterAuthAttempt()
}
-
+
// 新建连接已读过 account; 复用连接才刷新账户状态
if refreshAccountInfo {
if let response: AccountReadResponse = try readWithAuthRefresh({
@@ -185,15 +185,15 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
connection.accountResponse = response
}
}
-
+
let rateLimits: AccountRateLimitsResponse? = try readWithAuthRefresh({
read("account/rateLimits/read", using: connection, as: AccountRateLimitsResponse.self)
})
-
+
let usage: AccountUsageResponse? = try readWithAuthRefresh {
readUsage(using: connection)
}
-
+
// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"
guard let snapshot = try? CodexQuotaSnapshot(
accountResponse: connection.accountResponse,
@@ -202,10 +202,10 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
) else {
throw FetchFailure.notLoggedIn
}
-
+
return snapshot
}
-
+
private static func read<Value: Decodable>(
_ method: String,
params: [String: Any]? = nil,
@@ -220,12 +220,12 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return .broken
}
}
-
+
private static func readUsage(using connection: AppServerConnection) -> ReadResult<AccountUsageResponse> {
guard connection.isUsageReadAvailable else {
return .skipped
}
-
+
do {
return .value(try connection.session.request("account/usage/read", as: AccountUsageResponse.self))
} catch let error as CodexStatusError where error.isUnsupportedUsageMethod {
@@ -238,7 +238,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return .broken
}
}
-
+
private static func classify<Value>(_ error: CodexStatusError) -> ReadResult<Value> {
if error.isAuthenticationRequired {
return .authRequired
@@ -246,7 +246,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
// 非认证的业务错误不阻断整轮刷新, 详情只保留在日志中
return error.isTransportFailure ? .broken : .skipped
}
-
+
private static func refreshAccount(using connection: AppServerConnection) throws {
let response: AccountReadResponse
do {
@@ -260,13 +260,13 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
} catch {
throw FetchFailure.needsRebuild
}
-
+
connection.accountResponse = response
if response.account == nil {
throw FetchFailure.notLoggedIn
}
}
-
+
/// 初始化失败与未登录在这里分流; 两者都不复用本次新建的进程
private static func openConnection(
command: AppServerCommand,
@@ -278,17 +278,17 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
process.executableURL = URL(fileURLWithPath: command.executablePath)
process.arguments = command.arguments
process.environment = environment
-
+
let standardInput = Pipe()
let standardOutput = Pipe()
let standardError = Pipe()
let lineReader = JSONLineReader(fileHandle: standardOutput.fileHandleForReading)
let errorReader = PipeDrain(fileHandle: standardError.fileHandleForReading)
-
+
process.standardInput = standardInput
process.standardOutput = standardOutput
process.standardError = standardError
-
+
do {
try process.run()
} catch {
@@ -296,7 +296,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return .initializationFailed
}
let openedAt = Date()
-
+
let session = AppServerSession(
process: process,
input: standardInput,
@@ -304,7 +304,7 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
errorReader: errorReader,
timeout: timeout
)
-
+
do {
let initializeResult = try session.request(
"initialize",
@@ -317,27 +317,27 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
],
as: InitializeResult.self
)
-
+
try session.notify("initialized")
-
+
let accountResponse = try session.request(
"account/read",
params: ["refreshToken": false],
as: AccountReadResponse.self
)
-
+
guard accountResponse.account != nil else {
session.close()
return .notLoggedIn
}
-
+
let commandInfo = CodexCLIConnectionInfo(
source: command.source,
executablePath: command.executablePath,
version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),
openedAt: openedAt
)
-
+
return .ready(
connection: AppServerConnection(
session: session,
@@ -351,22 +351,22 @@ nonisolated final class CodexStatusService: @unchecked Sendable {
return .initializationFailed
}
}
-
+
private nonisolated static func clientVersion() -> String {
guard let version = Bundle.main.shortVersionString, !version.isEmpty else {
return "1.0.0"
}
-
+
return version
}
-
+
/// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号
private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {
guard let firstToken = userAgent?.split(separator: " ").first,
let slashIndex = firstToken.firstIndex(of: "/") else {
return nil
}
-
+
let version = firstToken[firstToken.index(after: slashIndex)...]
return version.isEmpty ? nil : String(version)
}
@@ -377,9 +377,9 @@ private nonisolated final class AppServerConnection {
let commandInfo: CodexCLIConnectionInfo
var accountResponse: AccountReadResponse
var isUsageReadAvailable = true
-
+
var openedAt: Date { commandInfo.openedAt }
-
+
init(
session: AppServerSession,
accountResponse: AccountReadResponse,
@@ -393,20 +393,20 @@ private nonisolated final class AppServerConnection {
private nonisolated final class AppServerSession {
let process: Process
-
+
private typealias EncodedMessage = (data: Data, text: String)
private typealias ResponseLine = (text: String, data: Data)
-
+
private static let writeFailureMessage = "连接断开, 无法写入请求"
private static let responseConnectionClosedMessage = "连接断开, 等待响应失败"
private static let responseTimeoutMessage = "响应超时"
-
+
private let input: Pipe
private let lineReader: JSONLineReader
private let errorReader: PipeDrain
private let timeout: TimeInterval
private var nextId = 1
-
+
init(
process: Process,
input: Pipe,
@@ -420,26 +420,26 @@ private nonisolated final class AppServerSession {
self.errorReader = errorReader
self.timeout = timeout
}
-
+
func close() {
lineReader.stop()
errorReader.stop()
try? input.fileHandleForWriting.close()
-
+
if process.isRunning {
process.terminate()
}
}
-
+
func notify(_ method: String, params: [String: Any]? = nil) throws {
let encoded = try encodeMessage(method: method, id: nil, params: params)
-
+
try writeEncoded(encoded) {
RequestLogStore.shared.recordFailure(method: method, message: Self.writeFailureMessage)
}
RequestLogStore.shared.recordRequestWithEmptyResponse(method: method, payload: encoded.text)
}
-
+
func request<Response: Decodable>(
_ method: String,
params: [String: Any]? = nil,
@@ -449,18 +449,18 @@ private nonisolated final class AppServerSession {
nextId += 1
let encoded = try encodeMessage(method: method, id: id, params: params)
let token = RequestLogStore.shared.beginRequest(method: method, payload: encoded.text)
-
+
try writeEncoded(encoded) {
RequestLogStore.shared.failRequest(token, message: Self.writeFailureMessage)
}
-
+
return try waitForResponse(id: id, token: token, decode: type)
}
-
+
private func encodeMessage(method: String, id: Int?, params: [String: Any]?) throws -> EncodedMessage {
try encode(message(method: method, id: id, params: params))
}
-
+
private func message(method: String, id: Int?, params: [String: Any]?) -> [String: Any] {
var object: [String: Any] = ["method": method]
if let id {
@@ -471,12 +471,12 @@ private nonisolated final class AppServerSession {
}
return object
}
-
+
private func encode(_ object: [String: Any]) throws -> EncodedMessage {
let data = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])
return (data, String(decoding: data, as: UTF8.self))
}
-
+
private func writeEncoded(_ encoded: EncodedMessage, onFailure: () -> Void) throws {
do {
try writeData(encoded.data)
@@ -485,13 +485,13 @@ private nonisolated final class AppServerSession {
throw CodexStatusError.serverConnectionClosed
}
}
-
+
private func writeData(_ data: Data) throws {
var payload = data
payload.append(0x0A)
try input.fileHandleForWriting.write(contentsOf: payload)
}
-
+
private func waitForResponse<Response: Decodable>(
id: Int,
token: UUID,
@@ -499,7 +499,7 @@ private nonisolated final class AppServerSession {
) throws -> Response {
let deadline = Date().addingTimeInterval(timeout)
let decoder = JSONDecoder()
-
+
while Date() < deadline {
guard let line = try nextResponseLine(
matching: id,
@@ -509,15 +509,15 @@ private nonisolated final class AppServerSession {
) else {
continue
}
-
+
let result = try decodeResponse(line, as: type, token: token, decoder: decoder)
RequestLogStore.shared.finishRequest(token, response: line.text)
return result
}
-
+
try failRequest(token, message: Self.responseTimeoutMessage, error: .serverTimeout)
}
-
+
private func nextResponseLine(
matching id: Int,
before deadline: Date,
@@ -528,19 +528,19 @@ private nonisolated final class AppServerSession {
if lineReader.isClosed {
try failRequest(token, message: Self.responseConnectionClosedMessage, error: .serverConnectionClosed)
}
-
+
return nil
}
-
+
guard let data = text.data(using: .utf8),
let idEnvelope = try? decoder.decode(RPCIDEnvelope.self, from: data),
idEnvelope.id == id else {
return nil
}
-
+
return (text, data)
}
-
+
private func decodeResponse<Response: Decodable>(
_ line: ResponseLine,
as type: Response.Type,
@@ -551,15 +551,15 @@ private nonisolated final class AppServerSession {
let error = errorEnvelope.error {
try failRequest(token, message: line.text, error: .serverError(error.message))
}
-
+
guard let envelope = try? decoder.decode(RPCResponseEnvelope<Response>.self, from: line.data),
let result = envelope.result else {
try failRequest(token, message: line.text, error: .invalidServerResponse)
}
-
+
return result
}
-
+
private func failRequest(_ token: UUID, message: String, error: CodexStatusError) throws -> Never {
RequestLogStore.shared.failRequest(token, message: message)
throw error
@@ -595,7 +595,7 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {
private var buffer = Data()
private var lines: [String] = []
private var closed = false
-
+
init(fileHandle: FileHandle) {
self.fileHandle = fileHandle
fileHandle.readabilityHandler = { [weak self] handle in
@@ -608,46 +608,46 @@ private nonisolated final class JSONLineReader: @unchecked Sendable {
self?.append(data)
}
}
-
+
func nextLine(timeout: TimeInterval) -> String? {
if let line = popLine() {
return line
}
-
+
if isClosed {
return nil
}
-
+
let result = semaphore.wait(timeout: .now() + timeout)
guard result == .success else {
return nil
}
-
+
return popLine()
}
-
+
func stop() {
fileHandle.readabilityHandler = nil
markClosed()
}
-
+
var isClosed: Bool {
lock.lock()
defer { lock.unlock() }
-
+
return closed && lines.isEmpty
}
-
+
private func append(_ data: Data) {
lock.lock()
defer { lock.unlock() }
-
+
buffer.append(data)
-
+
while let newlineRange = buffer.firstRange(of: Data([0x0A])) {
let lineData = buffer[..<newlineRange.lowerBound]
buffer.removeSubrange(...newlineRange.lowerBound)
-
+
if let line = String(data: lineData, encoding: .utf8)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!line.isEmpty {
@@ -656,14 +656,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),
@@ -672,25 +672,25 @@ 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 = fileHandle
fileHandle.readabilityHandler = { handle in
@@ -700,7 +700,7 @@ private nonisolated final class PipeDrain: @unchecked Sendable {
}
}
}
-
+
func stop() {
fileHandle.readabilityHandler = nil
}
diff --git a/CodexBar/CodexStatusViewModel.swift b/CodexBar/CodexStatusViewModel.swift
index 626bfc1..e0892e0 100644
--- a/CodexBar/CodexStatusViewModel.swift
+++ b/CodexBar/CodexStatusViewModel.swift
@@ -7,8 +7,13 @@ nonisolated enum CodexLoadState: Equatable {
case loaded
case notLoggedIn
case initializationFailed
-
- var isError: Bool { self == .notLoggedIn || self == .initializationFailed }
+
+ var isError: Bool {
+ switch self {
+ case .notLoggedIn, .initializationFailed: true
+ case .loading, .loaded: false
+ }
+ }
}
@MainActor
@@ -18,57 +23,57 @@ final class CodexStatusViewModel: ObservableObject {
@Published private(set) var loadState: CodexLoadState = .loading
@Published private(set) var codexConnectionInfo: CodexCLIConnectionInfo?
@Published private(set) var autoRefreshCountdownStartedAt: Date?
-
+
var hasError: Bool { loadState.isError }
var autoRefreshInterval: TimeInterval { Self.refreshInterval }
-
+
private static let refreshInterval: TimeInterval = 60
-
+
private let service: CodexStatusService
private var autoRefreshTask: Task<Void, Never>?
-
+
init(service: CodexStatusService = CodexStatusService()) {
self.service = service
}
-
+
deinit {
autoRefreshTask?.cancel()
}
-
+
func refreshIfNeeded() {
guard Date().timeIntervalSince(autoRefreshCountdownStartedAt ?? .distantPast) > Self.refreshInterval else {
return
}
-
+
refresh()
}
-
+
func startAutoRefresh() {
guard autoRefreshTask == nil else {
return
}
-
+
autoRefreshTask = Task { [weak self] in
self?.refreshIfNeeded()
-
+
while !Task.isCancelled {
let delay = self?.autoRefreshDelay ?? Self.refreshInterval
if (try? await Task.sleep(for: .seconds(delay))) == nil {
break
}
-
+
self?.refreshIfNeeded()
}
}
}
-
+
func refresh() {
guard !isRefreshing else {
return
}
-
+
isRefreshing = true
-
+
Task {
switch await service.fetchOutcome() {
case .data(let snapshot):
@@ -81,24 +86,24 @@ final class CodexStatusViewModel: ObservableObject {
self.snapshot = nil
self.loadState = .initializationFailed
}
-
+
self.codexConnectionInfo = await service.currentConnectionInfo()
self.autoRefreshCountdownStartedAt = Date()
self.isRefreshing = false
}
}
-
+
func refreshCodexConnectionInfo() {
Task {
self.codexConnectionInfo = await service.currentConnectionInfo()
}
}
-
+
private var autoRefreshDelay: TimeInterval {
guard let autoRefreshCountdownStartedAt else {
return Self.refreshInterval
}
-
+
let remaining = Self.refreshInterval - Date().timeIntervalSince(autoRefreshCountdownStartedAt)
return max(1, remaining)
}
diff --git a/CodexBar/LogView.swift b/CodexBar/LogView.swift
index 35d8386..9d39c34 100644
--- a/CodexBar/LogView.swift
+++ b/CodexBar/LogView.swift
@@ -4,20 +4,22 @@ struct LogView: View {
@ObservedObject var store: RequestLogStore
var body: some View {
+ // 整表是锁内拷贝, 每轮渲染只取一次复用
+ let entries = store.entries
VStack(spacing: 0) {
- header
+ header(entries: entries)
Divider()
- if store.entries.isEmpty {
+ if entries.isEmpty {
emptyState
} else {
- logList
+ logList(entries: entries)
}
}
.frame(minWidth: 640, minHeight: 480)
}
- private var header: some View {
+ private func header(entries: [RequestLogEntry]) -> some View {
HStack(spacing: 10) {
Image(systemName: "doc.text.magnifyingglass")
.foregroundStyle(.tint)
@@ -25,7 +27,7 @@ struct LogView: View {
Text("Codex 日志")
.font(.headline)
- Text("\(store.entries.count)")
+ Text("\(entries.count)")
.font(.caption.monospacedDigit())
.foregroundStyle(.secondary)
.padding(.horizontal, 7)
@@ -40,7 +42,7 @@ struct LogView: View {
Label("清空", systemImage: "trash")
}
.controlSize(.small)
- .disabled(store.entries.isEmpty)
+ .disabled(entries.isEmpty)
}
.padding(.horizontal, 16)
.padding(.vertical, 10)
@@ -58,10 +60,10 @@ struct LogView: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
- private var logList: some View {
+ private func logList(entries: [RequestLogEntry]) -> some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
- ForEach(store.entries) { entry in
+ ForEach(entries) { entry in
LogRow(entry: entry)
Divider()
}
@@ -89,7 +91,7 @@ private struct LogRow: View {
if isExpanded {
VStack(alignment: .leading, spacing: 8) {
if let request = entry.request {
- payloadBlock(caption: requestCaption, time: entry.requestedAt, text: request, color: .primary)
+ payloadBlock(caption: "请求", time: entry.requestedAt, text: request, color: .primary)
}
if let detail = entry.detail {
@@ -177,10 +179,6 @@ private struct LogRow: View {
}
}
- private var requestCaption: String {
- "请求"
- }
-
private var detailCaption: String {
switch entry.kind {
case .response, .emptyResponse:
diff --git a/CodexBar/StatusItemController.swift b/CodexBar/StatusItemController.swift
index cce5932..877a05f 100644
--- a/CodexBar/StatusItemController.swift
+++ b/CodexBar/StatusItemController.swift
@@ -6,15 +6,15 @@ import SwiftUI
final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
let viewModel = CodexStatusViewModel()
let appUpdater = AppUpdater()
-
+
private var statusItemController: StatusItemController?
-
+
func applicationDidFinishLaunching(_ notification: Notification) {
let controller = StatusItemController(viewModel: viewModel, appUpdater: appUpdater)
controller.install()
statusItemController = controller
}
-
+
func applicationWillTerminate(_ notification: Notification) {
statusItemController?.uninstall()
}
@@ -27,7 +27,7 @@ private final class StatusItemController: NSObject {
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let popover = NSPopover()
private let popoverVisibility = PopoverVisibilityState()
-
+
private lazy var settingsWindowController = SettingsWindowController(
viewModel: viewModel,
appUpdater: appUpdater
@@ -46,16 +46,16 @@ private final class StatusItemController: NSObject {
private var globalMouseEventMonitor: Any?
private var cancellables = Set<AnyCancellable>()
private var lastHasError: Bool?
-
+
private static let normalImage = NSImage(systemSymbolName: "person.fill.checkmark", accessibilityDescription: nil)
private static let errorImage = NSImage(systemSymbolName: "person.fill.xmark", accessibilityDescription: nil)
-
+
init(viewModel: CodexStatusViewModel, appUpdater: AppUpdater) {
self.viewModel = viewModel
self.appUpdater = appUpdater
super.init()
}
-
+
func install() {
configureStatusButton()
configurePopover()
@@ -63,25 +63,25 @@ private final class StatusItemController: NSObject {
updateStatusImage()
viewModel.startAutoRefresh()
}
-
+
func uninstall() {
closePopover(animated: false)
cancellables.removeAll()
NSStatusBar.system.removeStatusItem(statusItem)
}
-
+
private func configureStatusButton() {
guard let button = statusItem.button else {
return
}
-
+
button.target = self
button.action = #selector(statusItemClicked(_:))
button.imagePosition = .imageOnly
button.toolTip = "CodexBar"
button.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
-
+
private func configurePopover() {
let rootView = CodexStatusMenuView(
viewModel: viewModel,
@@ -89,15 +89,15 @@ private final class StatusItemController: NSObject {
)
.environmentObject(appUpdater)
.frame(width: CodexStatusMenuView.menuWidth)
-
+
let hostingController = NSHostingController(rootView: rootView)
hostingController.sizingOptions = [.preferredContentSize]
-
+
popover.behavior = .applicationDefined
popover.animates = false
popover.contentViewController = hostingController
}
-
+
private func observeViewModel() {
viewModel.$loadState
.map(\.isError)
@@ -107,33 +107,33 @@ private final class StatusItemController: NSObject {
}
.store(in: &cancellables)
}
-
+
private func updateStatusImage() {
updateStatusImage(hasError: viewModel.hasError)
}
-
+
private func updateStatusImage(hasError: Bool) {
guard hasError != lastHasError else {
return
}
-
+
lastHasError = hasError
statusItem.button?.image = hasError ? Self.errorImage : Self.normalImage
}
-
+
@objc private func statusItemClicked(_ sender: NSStatusBarButton) {
guard let event = NSApplication.shared.currentEvent else {
togglePopover(relativeTo: sender)
return
}
-
+
if event.type == .rightMouseUp || event.modifierFlags.contains(.control) {
showContextMenu(relativeTo: sender)
} else {
togglePopover(relativeTo: sender)
}
}
-
+
private func togglePopover(relativeTo button: NSStatusBarButton) {
switch popoverState {
case .hidden:
@@ -145,7 +145,7 @@ private final class StatusItemController: NSObject {
openPopover(relativeTo: button)
}
}
-
+
private func cancelPopoverTasks() {
deferredRefreshTask?.cancel()
deferredRefreshTask = nil
@@ -154,40 +154,40 @@ private final class StatusItemController: NSObject {
popoverCloseTask?.cancel()
popoverCloseTask = nil
}
-
+
private func openPopover(relativeTo button: NSStatusBarButton) {
cancelPopoverTasks()
-
+
popoverAnimationGeneration += 1
let generation = popoverAnimationGeneration
popoverState = .opening
-
+
preparePopoverForFadeIn()
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
popoverVisibility.isVisible = true
stabilizePopoverChromeAppearance()
installPopoverDismissMonitors()
fadePopover(to: 1, duration: Metrics.fadeInDuration)
-
+
popoverOpenTask = Task { @MainActor [weak self] in
try? await Task.sleep(for: .milliseconds(Int(Metrics.fadeInDuration * 1000)))
guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
return
}
-
+
self.resetPopoverAlpha()
self.popoverState = .shown
self.popoverOpenTask = nil
}
-
+
scheduleDeferredRefresh()
}
-
+
private func showContextMenu(relativeTo button: NSStatusBarButton) {
closePopover(animated: false)
-
+
let menu = NSMenu()
-
+
let settingsItem = NSMenuItem(
title: "设置",
action: #selector(openSettings),
@@ -196,7 +196,7 @@ private final class StatusItemController: NSObject {
settingsItem.image = NSImage(systemSymbolName: "gearshape", accessibilityDescription: nil)
settingsItem.target = self
menu.addItem(settingsItem)
-
+
let logItem = NSMenuItem(
title: "日志",
action: #selector(openLog),
@@ -205,9 +205,9 @@ private final class StatusItemController: NSObject {
logItem.image = NSImage(systemSymbolName: "doc.text.magnifyingglass", accessibilityDescription: nil)
logItem.target = self
menu.addItem(logItem)
-
+
menu.addItem(.separator())
-
+
let quitItem = NSMenuItem(
title: "退出",
action: #selector(quit),
@@ -216,50 +216,50 @@ private final class StatusItemController: NSObject {
quitItem.image = NSImage(systemSymbolName: "power", accessibilityDescription: nil)
quitItem.target = self
menu.addItem(quitItem)
-
+
menu.popUp(
positioning: nil,
at: NSPoint(x: 0, y: button.bounds.minY - 4),
in: button
)
}
-
+
@objc private func openSettings() {
settingsWindowController.open()
}
-
+
@objc private func openLog() {
logWindowController.open()
}
-
+
@objc private func quit() {
NSApplication.shared.terminate(nil)
}
-
+
private func closePopover(animated: Bool = true) {
if popoverState == .closing && animated {
return
}
-
+
cancelPopoverTasks()
removePopoverDismissMonitors()
popoverVisibility.isVisible = false
-
+
guard popover.isShown else {
resetPopoverAlpha()
popoverState = .hidden
return
}
-
+
guard animated, let contentView = popover.contentViewController?.view else {
finishPopoverClose()
return
}
-
+
popoverAnimationGeneration += 1
let generation = popoverAnimationGeneration
popoverState = .closing
-
+
let popoverWindow = contentView.window
fadePopover(to: 0, duration: Metrics.fadeOutDuration)
popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in
@@ -267,7 +267,7 @@ private final class StatusItemController: NSObject {
guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {
return
}
-
+
self.popover.performClose(nil)
contentView?.alphaValue = 1
popoverWindow?.alphaValue = 1
@@ -275,132 +275,132 @@ private final class StatusItemController: NSObject {
self.popoverCloseTask = nil
}
}
-
+
private func finishPopoverClose() {
cancelPopoverTasks()
popoverAnimationGeneration += 1
removePopoverDismissMonitors()
-
+
if popover.isShown {
popover.performClose(nil)
}
-
+
popoverVisibility.isVisible = false
resetPopoverAlpha()
popoverState = .hidden
}
-
+
private func installPopoverDismissMonitors() {
removePopoverDismissMonitors()
-
+
localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event in
self?.closePopoverIfNeeded(for: event)
self?.restabilizePopoverChromeAfterEvent()
return event
}
-
+
globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] _ in
self?.closePopover()
}
}
-
+
private func removePopoverDismissMonitors() {
if let localMouseEventMonitor {
NSEvent.removeMonitor(localMouseEventMonitor)
self.localMouseEventMonitor = nil
}
-
+
if let globalMouseEventMonitor {
NSEvent.removeMonitor(globalMouseEventMonitor)
self.globalMouseEventMonitor = nil
}
}
-
+
private func restabilizePopoverChromeAfterEvent() {
Task { @MainActor [weak self] in
await Task.yield()
guard let self, self.popover.isShown else {
return
}
-
+
self.stabilizePopoverChromeAppearance()
}
}
-
+
private func stabilizePopoverChromeAppearance() {
guard let rootView = popover.contentViewController?.view.window?.contentView else {
return
}
-
+
// NSPopover 会在点击后重新强调 NSVisualEffectView, 这里固定为 inactive 避免背景明暗跳变
stabilizeVisualEffectViews(in: rootView)
}
-
+
private func stabilizeVisualEffectViews(in view: NSView) {
if let visualEffectView = view as? NSVisualEffectView {
visualEffectView.state = .inactive
visualEffectView.isEmphasized = false
}
-
+
for subview in view.subviews {
stabilizeVisualEffectViews(in: subview)
}
}
-
+
private func closePopoverIfNeeded(for event: NSEvent) {
guard popover.isShown else {
return
}
-
+
if isEventInsidePopover(event) || isEventInsideStatusButton(event) {
return
}
-
+
closePopover()
}
-
+
private func isEventInsidePopover(_ event: NSEvent) -> Bool {
guard let contentView = popover.contentViewController?.view,
event.window == contentView.window else {
return false
}
-
+
let point = contentView.convert(event.locationInWindow, from: nil)
return contentView.bounds.contains(point)
}
-
+
private func isEventInsideStatusButton(_ event: NSEvent) -> Bool {
guard let button = statusItem.button,
let buttonWindow = button.window else {
return false
}
-
+
let eventScreenPoint = event.window?.convertPoint(toScreen: event.locationInWindow) ?? NSEvent.mouseLocation
let buttonRectInWindow = button.convert(button.bounds, to: nil)
let buttonScreenRect = buttonWindow.convertToScreen(buttonRectInWindow)
return buttonScreenRect.contains(eventScreenPoint)
}
-
+
private func preparePopoverForFadeIn() {
popover.contentViewController?.view.alphaValue = 0
popover.contentViewController?.view.window?.alphaValue = 0
}
-
+
private func resetPopoverAlpha() {
popover.contentViewController?.view.alphaValue = 1
popover.contentViewController?.view.window?.alphaValue = 1
}
-
+
private func fadePopover(to alpha: CGFloat, duration: TimeInterval) {
guard let contentView = popover.contentViewController?.view else {
return
}
-
+
let popoverWindow = contentView.window
if alpha == 1 {
popoverWindow?.alphaValue = 0
}
-
+
NSAnimationContext.runAnimationGroup { context in
context.duration = duration
context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
@@ -408,7 +408,7 @@ private final class StatusItemController: NSObject {
contentView.animator().alphaValue = alpha
}
}
-
+
private func scheduleDeferredRefresh() {
deferredRefreshTask?.cancel()
deferredRefreshTask = Task { @MainActor [weak self] in
@@ -416,11 +416,11 @@ private final class StatusItemController: NSObject {
guard let self, !Task.isCancelled, self.popover.isShown else {
return
}
-
+
self.viewModel.refreshIfNeeded()
}
}
-
+
private enum Metrics {
static let dismissEventMask: NSEvent.EventTypeMask = [
.leftMouseDown,
@@ -430,7 +430,7 @@ private final class StatusItemController: NSObject {
static let fadeInDuration: TimeInterval = 0.24
static let fadeOutDuration: TimeInterval = 0.18
}
-
+
private enum PopoverState {
case hidden
case opening
diff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/UsageHeatmap.swift
index dd5b7c3..3deae3c 100644
--- a/CodexBar/UsageHeatmap.swift
+++ b/CodexBar/UsageHeatmap.swift
@@ -4,16 +4,16 @@ struct UsageSummaryView: View {
let usage: CodexUsageSnapshot
private let days: [DailyUsageBucket?]
@State private var hoveredDay: DailyUsageBucket?
-
+
init(usage: CodexUsageSnapshot) {
self.usage = usage
self.days = usage.recentWeekGrid(columnCount: UsageHeatmap.Metrics.columnCount, endingDaysAgo: 1)
}
-
+
var body: some View {
VStack(alignment: .leading, spacing: 8) {
metricsGrid
-
+
UsageHeatmap(days: days, hoveredDay: $hoveredDay)
}
.padding(10)
@@ -22,7 +22,7 @@ struct UsageSummaryView: View {
hoveredDay = nil
}
}
-
+
private var metricsGrid: some View {
HStack(alignment: .firstTextBaseline, spacing: Metrics.metricSpacing) {
tokenMetric(label: "全时累计", value: usage.summary.lifetimeTokens, alignment: .center)
@@ -32,13 +32,13 @@ struct UsageSummaryView: View {
textMetric(label: "最长任务", value: Self.durationText(seconds: usage.summary.longestRunningTurnSec))
}
}
-
+
private func tokenMetric(label: String, value: Int, alignment: Alignment) -> some View {
metric(label: label, alignment: alignment) {
TokenCountText(tokens: value)
}
}
-
+
private func textMetric(label: String, value: String) -> some View {
metric(label: label, alignment: .center) {
Text(value)
@@ -47,7 +47,7 @@ struct UsageSummaryView: View {
.minimumScaleFactor(0.8)
}
}
-
+
private func metric<Content: View>(
label: String,
alignment: Alignment,
@@ -58,47 +58,47 @@ struct UsageSummaryView: View {
.font(.caption2)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: alignment)
-
+
value()
.frame(maxWidth: .infinity, alignment: alignment)
}
.frame(maxWidth: .infinity)
}
-
+
private static func dayText(_ days: Int?) -> String {
guard let days else {
return "--"
}
-
+
return "\(max(days, 0))天"
}
-
+
private static func durationText(seconds: Int?) -> String {
guard let seconds else {
return "--"
}
-
+
let duration = max(seconds, 0)
let days = duration / 86_400
let hours = duration % 86_400 / 3_600
let minutes = duration % 3_600 / 60
let remainingSeconds = duration % 60
-
+
if days > 0 {
return "\(days) 天 \(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"
}
-
+
if hours > 0 {
return "\(hours) 时 \(minutes) 分 \(remainingSeconds) 秒"
}
-
+
if minutes > 0 {
return "\(minutes) 分 \(remainingSeconds) 秒"
}
-
+
return "\(remainingSeconds) 秒"
}
-
+
private enum Metrics {
static let metricSpacing: CGFloat = 8
}
@@ -110,17 +110,17 @@ struct UsageHeatmap: View {
@State private var hoveredSquareFrame: CGRect = .zero
// hover 期间 body 频繁重算, 峰值只在构建时求一次
private let peakTokens: Int
-
+
init(days: [DailyUsageBucket?], hoveredDay: Binding<DailyUsageBucket?>) {
self.days = days
self._hoveredDay = hoveredDay
self.peakTokens = max(days.lazy.compactMap { $0?.tokens }.max() ?? 0, 1)
}
-
+
var body: some View {
ZStack(alignment: .topLeading) {
heatmapGrid
-
+
if let hoveredDay {
UsageHeatmapTooltip(day: hoveredDay)
.id(hoveredDay.id)
@@ -133,16 +133,16 @@ struct UsageHeatmap: View {
.frame(height: Metrics.height)
.coordinateSpace(name: Metrics.coordinateSpaceName)
}
-
+
private var heatmapGrid: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(alignment: .firstTextBaseline) {
Text("近 \(Metrics.columnCount) 周")
.font(.caption2.weight(.medium))
.foregroundStyle(.secondary)
-
+
Spacer()
-
+
if let firstDate = visibleDays.first?.startDate, let lastDate = visibleDays.last?.startDate {
Text("\(firstDate) ~ \(lastDate)")
.font(.caption2.monospacedDigit())
@@ -150,13 +150,13 @@ struct UsageHeatmap: View {
.lineLimit(1)
}
}
-
+
HStack(alignment: .top, spacing: Metrics.squareSpacing) {
ForEach(0..<Metrics.columnCount, id: \.self) { column in
VStack(spacing: Metrics.squareSpacing) {
ForEach(0..<Metrics.rowCount, id: \.self) { row in
let index = column * Metrics.rowCount + row
-
+
if days.indices.contains(index), let day = days[index] {
UsageHeatmapSquare(
day: day,
@@ -189,34 +189,34 @@ struct UsageHeatmap: View {
}
.frame(maxWidth: .infinity, alignment: .leading)
}
-
+
private var visibleDays: [DailyUsageBucket] {
days.compactMap { $0 }
}
-
+
private var tooltipOffset: CGSize {
let aboveY = hoveredSquareFrame.minY - Metrics.tooltipSquareSpacing - Metrics.tooltipHeight
let tooltipY = aboveY >= 0 ? aboveY : hoveredSquareFrame.maxY + Metrics.tooltipSquareSpacing
-
+
return CGSize(
width: tooltipX(for: hoveredSquareFrame),
height: min(max(tooltipY, 0), max(0, Metrics.height - Metrics.tooltipHeight))
)
}
-
+
private func tooltipX(for squareFrame: CGRect) -> CGFloat {
let trailingX = squareFrame.maxX + Metrics.tooltipSquareSpacing
let leadingX = squareFrame.minX - Metrics.tooltipSquareSpacing - Metrics.tooltipWidth
let maxX = max(0, Metrics.totalWidth - Metrics.tooltipWidth)
-
+
if leadingX >= 0 {
return leadingX
}
-
+
if trailingX + Metrics.tooltipWidth <= Metrics.totalWidth {
return trailingX
}
-
+
return min(max(leadingX, 0), maxX)
}
}
@@ -233,7 +233,7 @@ extension UsageHeatmap {
static let tooltipHeight: CGFloat = 38
static let tooltipSquareSpacing: CGFloat = 2
static let tooltipFadeDuration: TimeInterval = 0.15
-
+
static var totalWidth: CGFloat {
CGFloat(columnCount) * squareSize + CGFloat(columnCount - 1) * squareSpacing
}
@@ -246,7 +246,7 @@ private struct UsageHeatmapSquare: View {
let isHovered: Bool
let onActive: (CGRect) -> Void
let onEnded: () -> Void
-
+
var body: some View {
GeometryReader { proxy in
RoundedRectangle(cornerRadius: 4, style: .continuous)
@@ -270,39 +270,39 @@ private struct UsageHeatmapSquare: View {
.contentShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
.animation(.snappy(duration: 0.14), value: isHovered)
}
-
+
private var clampedPercent: Double {
min(max(percent, 0), 1)
}
-
+
private var fillColor: Color {
guard day.tokens > 0 else {
return Color.blue.opacity(isHovered ? 0.16 : 0.08)
}
-
+
let intensity = pow(clampedPercent, 0.62)
let opacity = 0.18 + intensity * 0.68
return Color.blue.opacity(isHovered ? min(opacity + 0.10, 1.0) : opacity)
}
-
+
private var borderColor: Color {
if isHovered {
return Color.blue.opacity(0.78)
}
-
+
return Color.blue.opacity(day.tokens > 0 ? 0.18 : 0.10)
}
}
private struct UsageHeatmapTooltip: View {
let day: DailyUsageBucket
-
+
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Text(day.startDate)
.font(.caption2.monospacedDigit())
.foregroundStyle(Color.codexSecondaryLabel)
-
+
TokenCountText(tokens: day.tokens)
.foregroundStyle(Color.codexLabel)
}
diff --git a/Scripts/update-appcast.sh b/Scripts/appcast.sh
similarity index 97%
rename from Scripts/update-appcast.sh
rename to Scripts/appcast.sh
index 4a35203..32cc976 100755
--- a/Scripts/update-appcast.sh
+++ b/Scripts/appcast.sh
@@ -5,7 +5,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
DMG_PATH="${1:-}"
-APPCAST_PATH="${APPCAST_PATH:-${PROJECT_DIR}/Updates/appcast.xml}"
+APPCAST_PATH="${APPCAST_PATH:-${PROJECT_DIR}/appcast.xml}"
DOWNLOAD_BASE_URL="${DOWNLOAD_BASE_URL:-https://codexbar.zabrian.app/download}"
RELEASE_NOTES_BASE_URL="${RELEASE_NOTES_BASE_URL:-https://codexbar.zabrian.app/notes}"
MINIMUM_SYSTEM_VERSION="${MINIMUM_SYSTEM_VERSION:-15.0}"
@@ -16,10 +16,10 @@ XCODE_SCHEME="${XCODE_SCHEME:-CodexBar}"
usage() {
cat >&2 <<USAGE
-usage: Scripts/update-appcast.sh [CodexBar-vX.Y.Z.dmg]
+usage: Scripts/appcast.sh [CodexBar-vX.Y.Z.dmg]
Environment:
- APPCAST_PATH Path to appcast.xml. Defaults to Updates/appcast.xml.
+ APPCAST_PATH Path to appcast.xml. Defaults to appcast.xml.
DOWNLOAD_BASE_URL Base URL for DMG downloads.
Defaults to https://codexbar.zabrian.app/download.
RELEASE_NOTES_BASE_URL Base URL for release notes.
diff --git a/Scripts/create-dmg.sh b/Scripts/dmg.sh
similarity index 97%
rename from Scripts/create-dmg.sh
rename to Scripts/dmg.sh
index 76d4c19..fcb1da2 100755
--- a/Scripts/create-dmg.sh
+++ b/Scripts/dmg.sh
@@ -15,7 +15,7 @@ if [[ -z "${APP_PATH}" ]]; then
if [[ "${#apps[@]}" -eq 0 ]]; then
echo "error: 当前目录没有找到 .app" >&2
- echo "usage: Scripts/create-dmg.sh [App.app] [Output.dmg]" >&2
+ echo "usage: Scripts/dmg.sh [App.app] [Output.dmg]" >&2
exit 1
fi
@@ -191,4 +191,4 @@ hdiutil convert \
mv -f "${TEMP_OUTPUT_PATH}" "${OUTPUT_PATH}"
echo "==> Created ${OUTPUT_PATH}"
-echo "==> Update appcast with: Scripts/update-appcast.sh \"${OUTPUT_PATH}\""
+echo "==> Update appcast with: Scripts/appcast.sh \"${OUTPUT_PATH}\""
diff --git a/Updates/appcast.xml b/appcast.xml
similarity index 91%
rename from Updates/appcast.xml
rename to appcast.xml
index 6836f0b..c013191 100644
--- a/Updates/appcast.xml
+++ b/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 2.1.0</title>
+ <sparkle:version>11</sparkle:version>
+ <sparkle:shortVersionString>2.1.0</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes/2.1.0.html</sparkle:releaseNotesLink>
+ <pubDate>Thu, 18 Jun 2026 16:05:00 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v2.1.0.dmg" sparkle:edSignature="2FBNtL8I4tLW1hfkA6kDgLaShjnGw55q3qQbaUwW2238ulf8IzJeLemzGju0b9LRdrSVQoavheydTljCHJyMDQ==" length="1564567" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 2.0.0</title>
<sparkle:version>10</sparkle:version>