CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 改善主面板刷新反馈并缩短请求等待
Bob1786bf63a1d0
diff --git a/CodexBar/Services/AppServer/AccountSession.swift b/CodexBar/Services/AppServer/AccountSession.swiftindex 4322ab6..9a315e7 100644--- a/CodexBar/Services/AppServer/AccountSession.swift+++ b/CodexBar/Services/AppServer/AccountSession.swift@@ -55,36 +55,26 @@ final nonisolated class AccountSession {}func perform<Response>(_ request: AppServerRequest<Response>) throws -> Response {- try self.request(request.method, params: request.params, as: Response.self)- }-- func request<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- guard !unsupportedMethods.contains(method) else {+ guard !unsupportedMethods.contains(request.method) else {throw CodexStatusError.unsupportedMethod}// app-server 偶发业务错误可重试一次; 传输错误由上层重建连接do {- return try performRequestRememberingUnsupported(method, params: params, as: type)- } catch let error as CodexStatusError where error.isRetriableServerError && AppServerRPC.permitsRetry(method) {- return try performRequestRememberingUnsupported(method, params: params, as: type)+ return try performRequestRememberingUnsupported(request)+ } catch let error as CodexStatusError where error.isRetriableServerError && AppServerRPC.permitsRetry(request.method) {+ return try performRequestRememberingUnsupported(request)}}- private func performRequestRememberingUnsupported<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as _: Response.Type+ private func performRequestRememberingUnsupported<Response>(+ _ request: AppServerRequest<Response>) throws -> Response {do {- return try transport.request(method, params: params, timeout: timeout)+ return try transport.request(request.method, params: request.params, timeout: request.timeout ?? timeout)} catch let error as CodexStatusError {if error.isUnsupportedMethod {- unsupportedMethods.insert(method)+ unsupportedMethods.insert(request.method)}throw error}diff --git a/CodexBar/Services/AppServer/AppServerRequests.swift b/CodexBar/Services/AppServer/AppServerRequests.swiftindex fb9d662..987d069 100644--- a/CodexBar/Services/AppServer/AppServerRequests.swift+++ b/CodexBar/Services/AppServer/AppServerRequests.swift@@ -4,19 +4,20 @@ import Foundationnonisolated struct AppServerRequest<Response: Decodable> {let method: Stringvar params: [String: Any]?+ var timeout: TimeInterval?}nonisolated enum AccountRequests {static func account(refreshToken: Bool) -> AppServerRequest<AccountReadResponse> {- AppServerRequest(method: "account/read", params: ["refreshToken": refreshToken])+ AppServerRequest(method: "account/read", params: ["refreshToken": refreshToken], timeout: refreshToken ? nil : 10)}static var rateLimits: AppServerRequest<AccountRateLimitsResponse> {- AppServerRequest(method: "account/rateLimits/read")+ AppServerRequest(method: "account/rateLimits/read", timeout: 10)}static var usage: AppServerRequest<AccountUsageResponse> {- AppServerRequest(method: "account/usage/read")+ AppServerRequest(method: "account/usage/read", timeout: 10)}static var configuration: AppServerRequest<ConfigReadResponse> {diff --git a/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift b/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swiftindex 2287fe3..11cbbb1 100644--- a/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift+++ b/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift@@ -38,6 +38,7 @@ final class CodexServiceStatusMonitor: ObservableObject {func refresh() async {guard isEnabled, !Task.isCancelled else { return }if refreshTask == nil {+ state = .checkingrefreshTask = Task { [weak self, fetch] inlet result: Statedo {diff --git a/CodexBar/Views/Menu/CodexServiceStatusRow.swift b/CodexBar/Views/Menu/CodexServiceStatusRow.swiftindex 4ceddd5..f9a88ba 100644--- a/CodexBar/Views/Menu/CodexServiceStatusRow.swift+++ b/CodexBar/Views/Menu/CodexServiceStatusRow.swift@@ -14,17 +14,17 @@ struct CodexServiceStatusRow: View {.resizable().scaledToFit().frame(width: MenuMetrics.statusIconSize, height: MenuMetrics.statusIconSize)+ .foregroundStyle(statusColor).id(statusSymbol).transition(allowsAnimations ? .opacity : .identity)}.font(.system(size: MenuMetrics.statusIconSize, weight: .medium))- .foregroundStyle(statusColor).frame(width: MenuMetrics.statusIconSize, height: MenuMetrics.statusIconSize)Text(statusTitle).font(.caption).foregroundStyle(Color.codexLabel)- .contentTransition(allowsAnimations ? .opacity : .identity)+ .numericTransition(value: monitor.state, enabled: allowsAnimations).layoutPriority(1)Spacer(minLength: 8)@@ -33,7 +33,7 @@ struct CodexServiceStatusRow: View {Text(verbatim: displayedComponents.map { Self.shortComponentName($0) }.joined(separator: " • ")).font(.caption2.weight(.medium)).foregroundStyle(statusColor)- .contentTransition(allowsAnimations ? .opacity : .identity)+ .numericTransition(value: displayedComponents, enabled: allowsAnimations).truncationMode(.tail).layoutPriority(-1).transition(allowsAnimations ? .opacity : .identity)diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex b07f3d6..0cdb281 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 5.0.2-CURRENT_PROJECT_VERSION = 202+MARKETING_VERSION = 5.0.3+CURRENT_PROJECT_VERSION = 203diff --git a/Tests/App/AppServer/AppServerRequestBudgetTests.swift b/Tests/App/AppServer/AppServerRequestBudgetTests.swiftindex 9169e1d..f7b9c24 100644--- a/Tests/App/AppServer/AppServerRequestBudgetTests.swift+++ b/Tests/App/AppServer/AppServerRequestBudgetTests.swift@@ -17,7 +17,7 @@ struct AppServerRequestBudgetTests {let budget = AppServerRequestBudget(deadline: Date().addingTimeInterval(-1))#expect(throws: CodexStatusError.self) {try AppServerRequestBudget.$current.withValue(budget) {- let _: [String: String] = try session.request("account/read", as: [String: String].self)+ let _: [String: String] = try session.perform(AppServerRequest(method: "account/read"))}}}.value@@ -42,7 +42,7 @@ struct AppServerRequestBudgetTests {let budget = AppServerRequestBudget(deadline: Date().addingTimeInterval(0.1))#expect(throws: CodexStatusError.self) {try AppServerRequestBudget.$current.withValue(budget) {- let _: [String: String] = try session.request("account/read", as: [String: String].self)+ let _: [String: String] = try session.perform(AppServerRequest(method: "account/read"))}}#expect(started.duration(to: .now) < .seconds(1))diff --git a/Tests/App/AppServer/AppServerSessionTests.swift b/Tests/App/AppServer/AppServerSessionTests.swiftindex 1b05c2d..aa8fbce 100644--- a/Tests/App/AppServer/AppServerSessionTests.swift+++ b/Tests/App/AppServer/AppServerSessionTests.swift@@ -119,16 +119,49 @@ struct AppServerSessionTests {defer { server.close() }let session = try AccountSession(socketURL: server.url, logStorage: nil)defer { session.close() }- let first = try session.request("account/read", as: Value.self)+ let first = try session.perform(AppServerRequest<Value>(method: "account/read"))#expect(first.value == 7)for _ in 0 ..< 2 {- #expect(throws: CodexStatusError.self) { _ = try session.request("missing", as: Value.self) }+ #expect(throws: CodexStatusError.self) { _ = try session.perform(AppServerRequest<Value>(method: "missing")) }}- let next = try session.request("probe", as: Value.self)+ let next = try session.perform(AppServerRequest<Value>(method: "probe"))#expect(next.value == 8)try server.finish()}+ @Test(arguments: [false, true])+ func accountRequestTimeoutAppliesToInitialAttemptAndRetry(_ retries: Bool) async throws {+ let server = try SharedServerFixture { peer in+ let first = try peer.readMessage()+ if retries {+ try peer.send(["id": #require(first["id"]), "error": ["code": -32000, "message": "temporary failure"]])+ _ = try peer.readMessage()+ }+ var byte: UInt8 = 0+ #expect(Darwin.read(peer.descriptor, &byte, 1) == 0)+ }+ defer { server.close() }+ let socketURL = server.url+ try await Task.detached {+ let session = try AccountSession(socketURL: socketURL, timeout: 2, logStorage: nil)+ defer { session.close() }+ let request = AppServerRequest<Value>(method: "account/read", timeout: 0.1)+ let started = ContinuousClock.now+ do {+ _ = try session.perform(request)+ Issue.record("Expected request timeout")+ } catch let error as CodexStatusError {+ guard case .serverTimeout = error else {+ Issue.record("Wrong error: \(error)")+ return+ }+ }+ #expect(started.duration(to: .now) < .seconds(1))+ #expect(!session.isOpen)+ }.value+ try server.finish()+ }+@Test(arguments: [true, false])func activityReaderValidatesVersionAndReusesConnection(_ supported: Bool) async throws {let directory = try TestDirectory()@@ -389,7 +422,7 @@ struct AppServerSessionTests {let session = try AccountSession(socketURL: server.url, logStorage: nil)defer { session.close() }do {- _ = try session.request("probe", as: Value.self)+ _ = try session.perform(AppServerRequest<Value>(method: "probe"))Issue.record("Expected a payload error")} catch let error as CodexStatusError {#expect(!error.isTransportFailure)@@ -398,7 +431,7 @@ struct AppServerSessionTests {}}#expect(session.isOpen)- let value = try session.request("probe", as: Value.self)+ let value = try session.perform(AppServerRequest<Value>(method: "probe"))#expect(value.value == 42)try server.finish()}@@ -440,7 +473,7 @@ struct AppServerSessionTests {defer { server.close() }let session = try AccountSession(socketURL: server.url, logStorage: nil)#expect(throws: CodexStatusError.self) {- _ = try session.request("probe", as: Value.self)+ _ = try session.perform(AppServerRequest<Value>(method: "probe"))}#expect(!session.isOpen)try server.finish()diff --git a/Tests/App/CodexStatus/AccountNotificationTests.swift b/Tests/App/CodexStatus/AccountNotificationTests.swiftindex 243f865..ca1fdcd 100644--- a/Tests/App/CodexStatus/AccountNotificationTests.swift+++ b/Tests/App/CodexStatus/AccountNotificationTests.swift@@ -56,11 +56,11 @@ struct AccountNotificationTests {defer { server.close() }let session = try AccountSession(socketURL: server.url, logStorage: nil)defer { session.close() }- let first = try session.request("probe", as: Value.self)+ let first = try session.perform(AppServerRequest<Value>(method: "probe"))#expect(first.value == 1)#expect(try session.pollChanges() == .account)#expect(try session.pollChanges() == nil)- let second = try session.request("probe", as: Value.self)+ let second = try session.perform(AppServerRequest<Value>(method: "probe"))#expect(second.value == 2)#expect(try session.pollChanges() == .rateLimits)#expect(try session.pollChanges() == nil)diff --git a/Tests/App/CodexStatus/CodexServiceStatusTests.swift b/Tests/App/CodexStatus/CodexServiceStatusTests.swiftindex 42ee5c0..8b381c1 100644--- a/Tests/App/CodexStatus/CodexServiceStatusTests.swift+++ b/Tests/App/CodexStatus/CodexServiceStatusTests.swift@@ -1,3 +1,4 @@+import Combineimport Foundationimport Testing@@ -109,6 +110,7 @@ struct CodexServiceStatusTests {await monitor.refresh()try await Task.sleep(for: .milliseconds(30))#expect(await probe.calls == 1)+ #expect(monitor.state == .available(.operational))}@Test func eachRefreshFetchesWithoutAnIndependentTimer() async throws {@@ -144,12 +146,16 @@ struct CodexServiceStatusTests {monitor.setEnabled(true)await monitor.refresh()#expect(monitor.state == .available(.operational))+ var states: [CodexServiceStatusMonitor.State] = []+ let observation = monitor.$state.sink { states.append($0) }+ defer { observation.cancel() }await probe.fail()await monitor.refresh()#expect(monitor.state == .unavailable)await probe.recover()await monitor.refresh()#expect(monitor.state == .available(.operational))+ #expect(states == [.available(.operational), .checking, .unavailable, .checking, .available(.operational)])}@Test func cancelledResultCannotOverwriteReenabledMonitor() async throws {@@ -193,6 +199,15 @@ struct CodexServiceStatusTests {#expect(monitor.state == .available(.operational))#expect(model.autoRefreshCountdownStartedAt != nil)#expect(await probe.calls == 1)++ var states: [CodexServiceStatusMonitor.State] = []+ let observation = monitor.$state.sink { states.append($0) }+ defer { observation.cancel() }+ model.refresh(trigger: trigger)+ try await wait { !model.isRefreshing }+ let outage = CodexServiceStatus(level: .fullOutage, componentNames: ["CLI"])+ #expect(states == [.available(.operational), .checking, .available(outage)])+ #expect(await probe.calls == 2)}@Test func notificationsPreserveSharedTimeAndManualRefreshIncludesServiceFailure() async throws {diff --git a/appcast.xml b/appcast.xmlindex 67b0664..3d996e5 100644--- a/appcast.xml+++ b/appcast.xml@@ -5,6 +5,20 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 5.0.3</title>+ <sparkle:version>203</sparkle:version>+ <sparkle:shortVersionString>5.0.3</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:minimumAutoupdateVersion>200</sparkle:minimumAutoupdateVersion>+ <sparkle:informationalUpdate><sparkle:belowVersion>200</sparkle:belowVersion></sparkle:informationalUpdate>+ <link xml:lang="en">https://codexbar.zabrian.app/notes?lang=en#5.0.0-Guide</link>+ <link xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.0-Guide</link>+ <sparkle:releaseNotesLink xml:lang="en">https://codexbar.zabrian.app/notes?lang=en#5.0.3</sparkle:releaseNotesLink>+ <sparkle:releaseNotesLink xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.3</sparkle:releaseNotesLink>+ <pubDate>Thu, 22 Oct 2026 10:03:58 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v5.0.3.dmg" sparkle:edSignature="BAZqS3TEuLIRnmbE2KzZn6KEgj6m0R1tOLHN0ThAOp18Yuosek2jRY4nM+620ZBnCUyZZ7l+dy25c0C/VsfYCA==" length="10174464" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 5.0.2</title><sparkle:version>202</sparkle:version>