Skip to content

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

feat: 在主面板展示 Codex 服务状态

Bobe59755285f3e
diff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swift
index 6550b3a..4394eb6 100644
--- a/CodexBar/App/CodexBarAppDelegate.swift
+++ b/CodexBar/App/CodexBarAppDelegate.swift
@@ -22,6 +22,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
let globalHotKeySettings = GlobalHotKeySettings()
let menuBarQuotaSettings = MenuBarQuotaSettings()
let mainPanelSettings = MainPanelSettings()
+ let serviceStatusMonitor = CodexServiceStatusMonitor()
let taskGlowSettings = TaskGlowSettings()
let notificationSettings = NotificationSettings()
let autoResetSettings = AutoResetSettings()
@@ -48,6 +49,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
globalHotKeySettings: globalHotKeySettings,
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
+ serviceStatusMonitor: serviceStatusMonitor,
taskGlowSettings: taskGlowSettings,
notificationSettings: notificationSettings,
autoResetSettings: autoResetSettings,
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 13ce8c5..2bb4954 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -13,6 +13,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private let globalHotKeySettings: GlobalHotKeySettings
private let menuBarQuotaSettings: MenuBarQuotaSettings
private let mainPanelSettings: MainPanelSettings
+ private let serviceStatusMonitor: CodexServiceStatusMonitor
private let taskGlowSettings: TaskGlowSettings
private let notificationSettings: NotificationSettings
private let autoResetSettings: AutoResetSettings
@@ -119,6 +120,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
globalHotKeySettings: GlobalHotKeySettings,
menuBarQuotaSettings: MenuBarQuotaSettings,
mainPanelSettings: MainPanelSettings,
+ serviceStatusMonitor: CodexServiceStatusMonitor,
taskGlowSettings: TaskGlowSettings,
notificationSettings: NotificationSettings,
autoResetSettings: AutoResetSettings,
@@ -133,6 +135,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
self.globalHotKeySettings = globalHotKeySettings
self.menuBarQuotaSettings = menuBarQuotaSettings
self.mainPanelSettings = mainPanelSettings
+ self.serviceStatusMonitor = serviceStatusMonitor
self.taskGlowSettings = taskGlowSettings
self.notificationSettings = notificationSettings
self.autoResetSettings = autoResetSettings
@@ -154,6 +157,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
func uninstall() {
closeMenuSurface(animated: false)
+ serviceStatusMonitor.setActive(false, refreshInterval: .seconds(viewModel.dataUpdateInterval.duration))
auxiliaryWindowFocusRestoreTask?.cancel()
statusIconExpirationTask?.cancel()
statusIconHostingView?.removeFromSuperview()
@@ -231,6 +235,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
viewModel: viewModel,
historyViewModel: historyViewModel,
mainPanelSettings: mainPanelSettings,
+ serviceStatusMonitor: serviceStatusMonitor,
activityMonitor: activityMonitor,
syncSettings: syncSettings,
keepAliveController: keepAliveController,
@@ -267,6 +272,19 @@ final class StatusItemController: NSObject, NSMenuDelegate {
// MARK: - 订阅与全局快捷键
private func observeViewModel() {
+ Publishers.CombineLatest3(
+ menuSurfaceVisibility.$isVisible,
+ mainPanelSettings.$layout,
+ viewModel.$dataUpdateInterval
+ )
+ .sink { [weak self] isVisible, layout, interval in
+ self?.serviceStatusMonitor.setActive(
+ isVisible && layout.isVisible(.serviceStatus),
+ refreshInterval: .seconds(interval.duration)
+ )
+ }
+ .store(in: &cancellables)
+
let hasTaskCenterContent = activityMonitor.$snapshot
.map(\.hasTaskCenterContent)
.removeDuplicates()
diff --git a/CodexBar/Models/CodexServiceStatus.swift b/CodexBar/Models/CodexServiceStatus.swift
new file mode 100644
index 0000000..f09adff
--- /dev/null
+++ b/CodexBar/Models/CodexServiceStatus.swift
@@ -0,0 +1,118 @@
+import Foundation
+
+nonisolated struct CodexServiceStatus: Equatable, Sendable {
+ enum Level: String, CaseIterable, Sendable {
+ case operational
+ case degradedPerformance = "degraded_performance"
+ case partialOutage = "partial_outage"
+ case fullOutage = "full_outage"
+ case underMaintenance = "under_maintenance"
+
+ /// 维护不表示故障, 与故障同时存在时优先展示故障级别
+ fileprivate var priority: Int {
+ switch self {
+ case .operational: 0
+ case .underMaintenance: 1
+ case .degradedPerformance: 2
+ case .partialOutage: 3
+ case .fullOutage: 4
+ }
+ }
+ }
+
+ static let operational = Self(level: .operational, componentNames: [])
+ let level: Level
+ let componentNames: [String]
+
+ init(level: Level, componentNames: [String]) {
+ self.level = level
+ self.componentNames = componentNames
+ }
+
+ init(data: Data) throws {
+ let summary = try JSONDecoder().decode(Response.self, from: data).summary
+ let groups = summary.structure.items.compactMap(\.group).filter { $0.name == "Codex" && $0.hidden != true }
+ let groupIDs = Set(groups.flatMap(\.components).filter { $0.hidden != true }.map(\.componentID))
+ let componentIDs = Set(summary.components.map(\.id))
+ guard !groupIDs.isEmpty, groupIDs.isSubset(of: componentIDs) else {
+ throw ParseError.missingComponents
+ }
+
+ // Desktop 的 Codex 组件位于 ChatGPT 分组, 不能只检查 Codex 分组
+ let codexIDs = groupIDs.union(summary.components.filter { $0.name.hasPrefix("Codex ") }.map(\.id))
+ var highestLevel = Level.operational
+ var highestIDs = Set<String>()
+ for component in summary.affectedComponents where codexIDs.contains(component.componentID) {
+ guard let level = Level(rawValue: component.status) else { throw ParseError.unknownStatus }
+ if level.priority > highestLevel.priority {
+ highestLevel = level
+ highestIDs.removeAll()
+ }
+ if level == highestLevel, level != .operational {
+ highestIDs.insert(component.componentID)
+ }
+ }
+ self.init(level: highestLevel, componentNames: summary.components.compactMap { component in
+ highestIDs.contains(component.id) ? component.name : nil
+ })
+ }
+
+ enum ParseError: Error {
+ case missingComponents
+ case unknownStatus
+ }
+}
+
+private nonisolated struct Response: Decodable {
+ let summary: Summary
+}
+
+private nonisolated struct Summary: Decodable {
+ let components: [ResponseComponent]
+ let affectedComponents: [AffectedComponent]
+ let structure: Structure
+
+ enum CodingKeys: String, CodingKey {
+ case components, structure
+ case affectedComponents = "affected_components"
+ }
+}
+
+private nonisolated struct ResponseComponent: Decodable {
+ let id: String
+ let name: String
+}
+
+private nonisolated struct AffectedComponent: Decodable {
+ let componentID: String
+ let status: String
+
+ enum CodingKeys: String, CodingKey {
+ case componentID = "component_id"
+ case status
+ }
+}
+
+private nonisolated struct Structure: Decodable {
+ let items: [StructureItem]
+}
+
+private nonisolated struct StructureItem: Decodable {
+ let group: ServiceGroup?
+}
+
+private nonisolated struct ServiceGroup: Decodable {
+ let name: String
+ let hidden: Bool?
+ let components: [ComponentReference]
+}
+
+private nonisolated struct ComponentReference: Decodable {
+ let componentID: String
+ let hidden: Bool?
+
+ enum CodingKeys: String, CodingKey {
+ case componentID = "component_id"
+ case hidden
+ }
+}
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index b7e492b..4549ff4 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -4897,6 +4897,22 @@
}
}
},
+ "service-status.title" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex Service Status"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Codex 服务状态"
+ }
+ }
+ }
+ },
"settings.about.github-project" : {
"localizations" : {
"en" : {
@@ -4993,22 +5009,6 @@
}
}
},
- "settings.about.openai-status" : {
- "localizations" : {
- "en" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "OpenAI Status"
- }
- },
- "zh-Hans" : {
- "stringUnit" : {
- "state" : "translated",
- "value" : "OpenAI 服务状态"
- }
- }
- }
- },
"settings.about.version" : {
"localizations" : {
"en" : {
@@ -5308,7 +5308,7 @@
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "主面板布局"
+ "value" : "面板布局"
}
}
}
@@ -5318,13 +5318,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Account"
+ "value" : "Account Info"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "账户"
+ "value" : "账户信息"
}
}
}
@@ -5334,13 +5334,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Tasks"
+ "value" : "Task Status"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "任务"
+ "value" : "任务状态"
}
}
}
@@ -5350,13 +5350,29 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Quota"
+ "value" : "Quota Info"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "额度"
+ "value" : "额度信息"
+ }
+ }
+ }
+ },
+ "settings.main-panel.section.service-status" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Service Status"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "服务状态"
}
}
}
@@ -5366,13 +5382,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Status"
+ "value" : "Update Status"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "状态"
+ "value" : "更新状态"
}
}
}
@@ -5382,13 +5398,13 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Usage"
+ "value" : "Usage Statistics"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "用量"
+ "value" : "用量统计"
}
}
}
@@ -6531,4 +6547,4 @@
}
},
"version" : "1.0"
-}
\ No newline at end of file
+}
diff --git a/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift b/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift
new file mode 100644
index 0000000..efc60cc
--- /dev/null
+++ b/CodexBar/Services/CodexStatus/CodexServiceStatusMonitor.swift
@@ -0,0 +1,71 @@
+import Combine
+import Foundation
+
+@MainActor
+final class CodexServiceStatusMonitor: ObservableObject {
+ enum State: Equatable {
+ case checking
+ case available(CodexServiceStatus)
+ case unavailable
+ }
+
+ @Published private(set) var state: State = .checking
+ private let fetch: @Sendable () async throws -> CodexServiceStatus
+ private var refreshInterval: Duration
+ private var refreshTask: Task<Void, Never>?
+ private var lastRefresh: ContinuousClock.Instant?
+
+ private var nextRefresh: ContinuousClock.Instant? {
+ lastRefresh?.advanced(by: refreshInterval)
+ }
+
+ convenience init() {
+ let service = CodexServiceStatusService()
+ self.init(fetch: { try await service.fetch() })
+ }
+
+ init(refreshInterval: Duration = .seconds(60), fetch: @escaping @Sendable () async throws -> CodexServiceStatus) {
+ self.refreshInterval = refreshInterval
+ self.fetch = fetch
+ }
+
+ deinit {
+ refreshTask?.cancel()
+ }
+
+ func setActive(_ active: Bool, refreshInterval: Duration) {
+ let intervalChanged = self.refreshInterval != refreshInterval
+ self.refreshInterval = refreshInterval
+ if !active || intervalChanged {
+ refreshTask?.cancel()
+ refreshTask = nil
+ }
+ guard active, refreshTask == nil else { return }
+ if nextRefresh.map({ $0 <= .now }) ?? true {
+ state = .checking
+ }
+ refreshTask = Task { [weak self] in
+ while !Task.isCancelled {
+ if let deadline = self?.nextRefresh {
+ do { try await Task.sleep(until: deadline, clock: ContinuousClock()) } catch { return }
+ }
+ guard !Task.isCancelled, let self else { return }
+ await refresh()
+ }
+ }
+ }
+
+ private func refresh() async {
+ do {
+ let status = try await fetch()
+ try Task.checkCancellation()
+ lastRefresh = .now
+ state = .available(status)
+ } catch {
+ // 隐藏后取消的旧请求不能覆盖重开面板后的结果
+ guard !Task.isCancelled else { return }
+ lastRefresh = .now
+ state = .unavailable
+ }
+ }
+}
diff --git a/CodexBar/Services/CodexStatus/CodexServiceStatusService.swift b/CodexBar/Services/CodexStatus/CodexServiceStatusService.swift
new file mode 100644
index 0000000..5fde5f4
--- /dev/null
+++ b/CodexBar/Services/CodexStatus/CodexServiceStatusService.swift
@@ -0,0 +1,45 @@
+import Foundation
+
+actor CodexServiceStatusService {
+ static let statusPageURL = URL(string: "https://status.openai.com")!
+ private static let endpoint = URL(string: "https://status.openai.com/proxy/status.openai.com")!
+ private static let maximumResponseBytes = 256 * 1024
+ private let session: URLSession
+
+ init(session: URLSession? = nil) {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.httpShouldSetCookies = false
+ configuration.httpCookieStorage = nil
+ configuration.urlCredentialStorage = nil
+ configuration.urlCache = nil
+ configuration.timeoutIntervalForRequest = 10
+ configuration.timeoutIntervalForResource = 15
+ self.session = session ?? URLSession(configuration: configuration)
+ }
+
+ deinit {
+ session.invalidateAndCancel()
+ }
+
+ func fetch() async throws -> CodexServiceStatus {
+ var request = URLRequest(url: Self.endpoint, cachePolicy: .reloadIgnoringLocalCacheData)
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
+ let (bytes, response) = try await session.bytes(for: request)
+ defer { bytes.task.cancel() }
+ guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
+ throw URLError(.badServerResponse)
+ }
+ guard response.expectedContentLength <= Self.maximumResponseBytes else {
+ throw URLError(.dataLengthExceedsMaximum)
+ }
+ var data = Data()
+ for try await byte in bytes {
+ guard data.count < Self.maximumResponseBytes else {
+ throw URLError(.dataLengthExceedsMaximum)
+ }
+ data.append(byte)
+ }
+ try Task.checkCancellation()
+ return try CodexServiceStatus(data: data)
+ }
+}
diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swift
index 5ab1e72..f8f0390 100644
--- a/CodexBar/Services/Settings/MainPanelSettings.swift
+++ b/CodexBar/Services/Settings/MainPanelSettings.swift
@@ -7,6 +7,7 @@ nonisolated enum MainPanelSection: String, CaseIterable, Identifiable, Sendable
case quota
case activity
case usage
+ case serviceStatus
case status
var id: Self {
diff --git a/CodexBar/Views/Menu/CodexServiceStatusRow.swift b/CodexBar/Views/Menu/CodexServiceStatusRow.swift
new file mode 100644
index 0000000..79588b1
--- /dev/null
+++ b/CodexBar/Views/Menu/CodexServiceStatusRow.swift
@@ -0,0 +1,120 @@
+import SwiftUI
+
+struct CodexServiceStatusRow: View {
+ @ObservedObject var monitor: CodexServiceStatusMonitor
+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations
+ @Environment(\.colorScheme) private var colorScheme
+ @State private var isHovered = false
+
+ var body: some View {
+ Link(destination: CodexServiceStatusService.statusPageURL) {
+ HStack(spacing: 8) {
+ ZStack {
+ Image(systemName: statusSymbol)
+ .resizable()
+ .scaledToFit()
+ .frame(width: statusSymbolSize, height: statusSymbolSize)
+ .id(statusSymbol)
+ .transition(allowsAnimations ? .opacity : .identity)
+ }
+ .font(.system(size: MenuMetrics.accountIconSize, weight: .medium))
+ .foregroundStyle(statusColor)
+ .frame(width: MenuMetrics.accountIconSize, height: MenuMetrics.accountIconSize)
+
+ Text("service-status.title")
+ .font(.caption.weight(.semibold))
+ .foregroundStyle(Color.codexLabel)
+ .layoutPriority(1)
+
+ Spacer(minLength: 8)
+
+ if !displayedComponents.isEmpty {
+ Text(verbatim: displayedComponents.map { Self.shortComponentName($0) }.joined(separator: " • "))
+ .font(.caption2.weight(.medium))
+ .foregroundStyle(statusColor)
+ .contentTransition(allowsAnimations ? .opacity : .identity)
+ .truncationMode(.tail)
+ .layoutPriority(-1)
+ .help(Text(verbatim: displayedComponents.joined(separator: "\n")))
+ .transition(allowsAnimations ? .opacity : .identity)
+ }
+ }
+ .lineLimit(1)
+ .padding(.horizontal, MenuMetrics.panelPadding)
+ .padding(.vertical, 8)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)
+ .overlay {
+ RoundedRectangle(cornerRadius: MenuMetrics.panelCornerRadius)
+ .strokeBorder(Color.primary.opacity(isHovered ? 0.14 : 0), lineWidth: 1)
+ .allowsHitTesting(false)
+ }
+ .onHover { isHovered = $0 }
+ .animation(allowsAnimations ? .codexStatus : nil, value: isHovered)
+ .animation(allowsAnimations ? .codexStatus : nil, value: monitor.state)
+ }
+
+ private var displayedComponents: [String] {
+ guard case let .available(status) = monitor.state else { return [] }
+ return status.componentNames
+ }
+
+ private static func shortComponentName(_ name: String) -> String {
+ switch name {
+ case "Codex Web": "Web"
+ case "Codex API": "API"
+ case "VS Code extension": "VS Code"
+ case "Codex in ChatGPT Desktop": "Desktop"
+ default: name
+ }
+ }
+
+ private var statusSymbol: String {
+ switch monitor.state {
+ case .checking: "ellipsis.circle"
+ case let .available(status): status.level.symbolName
+ case .unavailable: "questionmark.circle"
+ }
+ }
+
+ private var statusSymbolSize: CGFloat {
+ switch monitor.state {
+ // 三角和斜向工具的视觉面积较小, 略放大以接近圆形符号
+ case let .available(status) where status.level == .partialOutage || status.level == .underMaintenance:
+ MenuMetrics.accountIconSize + 1
+ default:
+ MenuMetrics.accountIconSize
+ }
+ }
+
+ private var statusColor: Color {
+ switch monitor.state {
+ case let .available(status): status.level.tint(for: colorScheme)
+ case .checking, .unavailable: .secondary
+ }
+ }
+}
+
+private extension CodexServiceStatus.Level {
+ var symbolName: String {
+ switch self {
+ case .operational: "checkmark.circle.fill"
+ case .degradedPerformance: "exclamationmark.circle.fill"
+ case .partialOutage: "exclamationmark.triangle.fill"
+ case .fullOutage: "xmark.octagon.fill"
+ case .underMaintenance: "wrench.fill"
+ }
+ }
+
+ func tint(for colorScheme: ColorScheme) -> Color {
+ switch self {
+ case .operational: .green
+ case .degradedPerformance: Color(hex: colorScheme == .dark ? 0xE4C66A : 0xBE9B38)
+ case .partialOutage: .orange
+ case .fullOutage: .red
+ case .underMaintenance: .blue
+ }
+ }
+}
diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swift
index ac40cc1..269b8ba 100644
--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift
+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift
@@ -36,6 +36,7 @@ struct CodexStatusMenuView: View {
@ObservedObject var viewModel: CodexStatusViewModel
@ObservedObject var historyViewModel: HistoryViewModel
@ObservedObject var mainPanelSettings: MainPanelSettings
+ let serviceStatusMonitor: CodexServiceStatusMonitor
// 活动状态与时间变化由卡片自行观察, 避免刷新整个菜单树
let activityMonitor: ActivityMonitor
@ObservedObject var syncSettings: SyncSettings
@@ -144,6 +145,8 @@ private extension CodexStatusMenuView {
usageSection(dataPlaceholderSection: dataPlaceholderSection)
case .status:
statusSection
+ case .serviceStatus:
+ CodexServiceStatusRow(monitor: serviceStatusMonitor)
}
}
@@ -244,7 +247,7 @@ private extension CodexStatusMenuView {
case .usage:
viewModel.snapshot != nil || !historyViewModel.snapshot.activityData.isEmpty
|| !historyViewModel.snapshot.tokenUsageByDate.isEmpty
- case .account, .activity, .status:
+ case .account, .activity, .status, .serviceStatus:
false
}
}
@@ -263,6 +266,8 @@ private extension CodexStatusMenuView {
hasData(for: section) || dataPlaceholderSection == section
case .status:
viewModel.snapshot != nil
+ case .serviceStatus:
+ true
}
}
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index f45f29b..f361e76 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -205,7 +205,6 @@ private extension AppSettingsView {
static let statusAnimation = Animation.codexStatus
}
- static let openAIStatusURL = URL(string: "https://status.openai.com")!
static let githubProjectURL = URL(string: "https://github.com/bob-zebedy/CodexBar")!
// MARK: - 分页骨架
@@ -318,8 +317,6 @@ private extension AppSettingsView {
VStack(alignment: .leading, spacing: Metrics.rowSpacing) {
codexVersionSection
LiquidGlassDivider()
- openAIStatusRow
- LiquidGlassDivider()
HelperInstallationStatusRow(status: keepAliveController.helperInstallationStatus)
LiquidGlassDivider()
versionRow
@@ -957,10 +954,6 @@ private extension AppSettingsView {
)
}
- var openAIStatusRow: some View {
- externalLinkRow(title: "settings.about.openai-status", icon: "waveform.path.ecg.rectangle", destination: Self.openAIStatusURL)
- }
-
var githubProjectRow: some View {
externalLinkRow(title: "settings.about.github-project", icon: "globe", destination: Self.githubProjectURL)
}
diff --git a/CodexBar/Views/Settings/MainPanelOptionsView.swift b/CodexBar/Views/Settings/MainPanelOptionsView.swift
index ff1bb79..ffbc6ea 100644
--- a/CodexBar/Views/Settings/MainPanelOptionsView.swift
+++ b/CodexBar/Views/Settings/MainPanelOptionsView.swift
@@ -1,7 +1,7 @@
import Foundation
import SwiftUI
-/// 通用设置页中的主面板布局入口, 自己持有定位锚点
+/// 通用设置页中的面板布局入口, 自己持有定位锚点
struct MainPanelLayoutSettingsRow: View {
let onOptionsTap: (ScreenFrameProvider) -> Void
@State private var anchorProvider = ScreenFrameProvider()
@@ -26,7 +26,7 @@ struct MainPanelLayoutSettingsRow: View {
}
}
-/// 主面板布局子选项, 拖放调整区域顺序并控制显隐
+/// 面板布局子选项, 拖放调整区域顺序并控制显隐
struct MainPanelOptionsView: View {
@ObservedObject var settings: MainPanelSettings
let undoManager: UndoManager
@@ -262,6 +262,8 @@ private extension MainPanelSection {
"settings.main-panel.section.usage"
case .status:
"settings.main-panel.section.status"
+ case .serviceStatus:
+ "settings.main-panel.section.service-status"
}
}
@@ -277,6 +279,8 @@ private extension MainPanelSection {
"chart.bar.xaxis"
case .status:
"clock"
+ case .serviceStatus:
+ "waveform.path.ecg.rectangle"
}
}
}
diff --git a/CodexBarTests/CodexStatus/CodexServiceStatusTests.swift b/CodexBarTests/CodexStatus/CodexServiceStatusTests.swift
new file mode 100644
index 0000000..b5b3aae
--- /dev/null
+++ b/CodexBarTests/CodexStatus/CodexServiceStatusTests.swift
@@ -0,0 +1,272 @@
+import Foundation
+import Testing
+
+struct CodexServiceStatusTests {
+ @Test func unrelatedIncidentsDoNotChangeCodexStatus() throws {
+ let data = try Self.response(affected: [("chatgpt", "full_outage")])
+ #expect(try CodexServiceStatus(data: data) == .operational)
+ }
+
+ @Test(arguments: [
+ ("api", "Codex API"), ("cli", "CLI"), ("web", "Codex Web"),
+ ("extension", "VS Code extension"), ("desktop", "Codex in ChatGPT Desktop")
+ ])
+ func includesCodexGroupAndDesktop(_ component: String, _ name: String) throws {
+ let data = try Self.response(affected: [(component, "degraded_performance")])
+ #expect(try CodexServiceStatus(data: data) == CodexServiceStatus(level: .degradedPerformance, componentNames: [name]))
+ }
+
+ @Test(arguments: CodexServiceStatus.Level.allCases)
+ func preservesComponentLevel(_ level: CodexServiceStatus.Level) throws {
+ let status = try CodexServiceStatus(data: Self.response(affected: [("cli", level.rawValue)]))
+ #expect(status.level == level)
+ #expect(status.componentNames == (level == .operational ? [] : ["CLI"]))
+ }
+
+ @Test func reportsHighestComponentsOnceInCatalogOrder() throws {
+ let affected = [
+ ("web", "partial_outage"), ("cli", "full_outage"), ("api", "full_outage"), ("cli", "degraded_performance"),
+ ("chatgpt", "full_outage"), ("web", "operational"), ("desktop", "full_outage"), ("cli", "operational"),
+ ("api", "full_outage")
+ ]
+ let expected = CodexServiceStatus(level: .fullOutage, componentNames: ["Codex API", "Codex in ChatGPT Desktop", "CLI"])
+ #expect(try CodexServiceStatus(data: Self.response(affected: affected)) == expected)
+ #expect(try CodexServiceStatus(data: Self.response(affected: Array(affected.reversed()))) == expected)
+ }
+
+ @Test(arguments: [
+ CodexServiceStatus.Level.degradedPerformance, .partialOutage, .fullOutage, .underMaintenance
+ ])
+ func showsAllAffectedComponentsAtTheSameLevel(_ level: CodexServiceStatus.Level) throws {
+ let data = try Self.response(affected: ["web", "api", "cli", "extension", "desktop", "chatgpt"].map {
+ ($0, level.rawValue)
+ })
+ let status = try CodexServiceStatus(data: data)
+ #expect(status.level == level)
+ #expect(status.componentNames == [
+ "Codex API", "Codex Web", "VS Code extension", "Codex in ChatGPT Desktop", "CLI"
+ ])
+ }
+
+ @Test(arguments: [
+ (CodexServiceStatus.Level.fullOutage, CodexServiceStatus.Level.partialOutage),
+ (.fullOutage, .degradedPerformance), (.fullOutage, .underMaintenance),
+ (.partialOutage, .degradedPerformance), (.partialOutage, .underMaintenance),
+ (.degradedPerformance, .underMaintenance)
+ ])
+ func showsEveryComponentAtTheHighestLevel(
+ _ highest: CodexServiceStatus.Level,
+ _ lower: CodexServiceStatus.Level
+ ) throws {
+ let data = try Self.response(affected: [
+ ("web", lower.rawValue), ("api", highest.rawValue), ("cli", highest.rawValue),
+ ("desktop", lower.rawValue), ("chatgpt", "full_outage")
+ ])
+ let status = try CodexServiceStatus(data: data)
+ #expect(status.level == highest)
+ #expect(status.componentNames == ["Codex API", "CLI"])
+ }
+
+ @Test func statusEqualityTracksDisplayedComponents() throws {
+ let initial = try CodexServiceStatus(data: Self.response(affected: [
+ ("api", "full_outage"), ("web", "partial_outage")
+ ]))
+ let lowerLevelsChanged = try CodexServiceStatus(data: Self.response(affected: [
+ ("api", "full_outage"), ("web", "operational"), ("desktop", "under_maintenance"), ("cli", "degraded_performance")
+ ]))
+ let highestComponentsChanged = try CodexServiceStatus(data: Self.response(affected: [
+ ("api", "full_outage"), ("cli", "full_outage")
+ ]))
+ #expect(initial == lowerLevelsChanged)
+ #expect(initial != highestComponentsChanged)
+ }
+
+ @Test(arguments: ["api", "cli"])
+ func unknownStatusAfterFullOutageIsRejected(_ component: String) throws {
+ let data = try Self.response(affected: [("cli", "full_outage"), (component, "new-status")])
+ #expect(throws: CodexServiceStatus.ParseError.self) { try CodexServiceStatus(data: data) }
+ }
+
+ @Test func incompleteOrUnknownDataDoesNotLookHealthy() throws {
+ let unknown = try Self.response(affected: [("cli", "new-status")])
+ #expect(throws: CodexServiceStatus.ParseError.self) { try CodexServiceStatus(data: unknown) }
+ let missingGroup = try Self.response(groupName: "Other")
+ #expect(throws: CodexServiceStatus.ParseError.self) { try CodexServiceStatus(data: missingGroup) }
+ let missingComponent = try Self.response(omitsCLI: true)
+ #expect(throws: CodexServiceStatus.ParseError.self) { try CodexServiceStatus(data: missingComponent) }
+ #expect(throws: DecodingError.self) { try CodexServiceStatus(data: Data(#"{"summary":{}}"#.utf8)) }
+ }
+
+ @Test func noImpactAndExplicitRecoveryAreOperational() throws {
+ #expect(try CodexServiceStatus(data: Self.response()) == .operational)
+ #expect(try CodexServiceStatus(data: Self.response(affected: [("cli", "operational")])) == .operational)
+ #expect(CodexServiceStatus.operational.level == .operational)
+ #expect(CodexServiceStatus.operational.componentNames.isEmpty)
+ }
+
+ @Test func monitorCachesAcrossReopeningAndStopsWhileHidden() async throws {
+ let probe = ServiceStatusProbe()
+ let monitor = CodexServiceStatusMonitor(fetch: { try await probe.fetch() })
+ defer { monitor.setActive(false, refreshInterval: .seconds(60)) }
+ monitor.setActive(false, refreshInterval: .seconds(60))
+ #expect(await probe.calls == 0)
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ try await wait { monitor.state == .available(.operational) }
+ monitor.setActive(false, refreshInterval: .seconds(60))
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ try await Task.sleep(for: .milliseconds(30))
+ #expect(await probe.calls == 1)
+ monitor.setActive(false, refreshInterval: .milliseconds(10))
+ try await Task.sleep(for: .milliseconds(30))
+ #expect(await probe.calls == 1)
+ }
+
+ @Test func changingIntervalReschedulesFromLastRefresh() async throws {
+ let probe = ServiceStatusProbe()
+ let monitor = CodexServiceStatusMonitor(fetch: { try await probe.fetch() })
+ defer { monitor.setActive(false, refreshInterval: .seconds(60)) }
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ try await wait { monitor.state == .available(.operational) }
+ monitor.setActive(true, refreshInterval: .milliseconds(10))
+ try await wait { await probe.calls >= 2 }
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ let count = await probe.calls
+ try await Task.sleep(for: .milliseconds(40))
+ #expect(await probe.calls == count)
+ }
+
+ @Test func failedRefreshDoesNotKeepShowingHealthy() async throws {
+ let probe = ServiceStatusProbe()
+ let monitor = CodexServiceStatusMonitor(fetch: { try await probe.fetch() })
+ defer { monitor.setActive(false, refreshInterval: .seconds(60)) }
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ try await wait { monitor.state == .available(.operational) }
+ await probe.fail()
+ monitor.setActive(true, refreshInterval: .milliseconds(10))
+ try await wait { monitor.state == .unavailable }
+ monitor.setActive(false, refreshInterval: .seconds(60))
+ #expect(monitor.state == .unavailable)
+ }
+
+ @Test func cancelledResultCannotOverwriteReopenedPanel() async throws {
+ let probe = ServiceStatusProbe(holdsFirst: true)
+ let monitor = CodexServiceStatusMonitor(fetch: { try await probe.fetch() })
+ defer { monitor.setActive(false, refreshInterval: .seconds(60)) }
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ try await wait { await probe.calls == 1 }
+ monitor.setActive(false, refreshInterval: .seconds(60))
+ monitor.setActive(true, refreshInterval: .seconds(60))
+ let outage = CodexServiceStatus(level: .fullOutage, componentNames: ["CLI"])
+ try await wait { monitor.state == .available(outage) }
+ await probe.releaseFirst()
+ try await Task.sleep(for: .milliseconds(20))
+ #expect(monitor.state == .available(outage))
+ #expect(await probe.calls == 2)
+ }
+
+ @Test(arguments: ["valid", "http-error", "invalid-json", "oversized-header", "oversized-body"])
+ func transportValidatesResponses(_ scenario: String) async throws {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.protocolClasses = [ServiceStatusURLProtocol.self]
+ configuration.httpAdditionalHeaders = ["X-Test-Scenario": scenario]
+ let service = CodexServiceStatusService(session: URLSession(configuration: configuration))
+ if scenario == "valid" {
+ #expect(try await service.fetch() == .operational)
+ } else {
+ await #expect(throws: (any Error).self) { try await service.fetch() }
+ }
+ }
+
+ private func wait(_ condition: () async -> Bool) async throws {
+ let deadline = ContinuousClock.now.advanced(by: .seconds(3))
+ while await !condition(), ContinuousClock.now < deadline {
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ #expect(await condition())
+ }
+
+ fileprivate nonisolated static func response(
+ affected: [(id: String, status: String)] = [],
+ groupName: String = "Codex",
+ omitsCLI: Bool = false
+ ) throws -> Data {
+ var components = [
+ ["id": "api", "name": "Codex API"], ["id": "web", "name": "Codex Web"],
+ ["id": "extension", "name": "VS Code extension"], ["id": "desktop", "name": "Codex in ChatGPT Desktop"],
+ ["id": "chatgpt", "name": "Conversations"]
+ ]
+ if !omitsCLI {
+ components.append(["id": "cli", "name": "CLI"])
+ }
+ return try JSONSerialization.data(withJSONObject: ["summary": [
+ "components": components,
+ "affected_components": affected.map { ["component_id": $0.id, "status": $0.status] },
+ "structure": ["items": [["group": [
+ "name": groupName, "hidden": false,
+ "components": ["api", "cli", "web", "extension"].map { ["component_id": $0] }
+ ]]]]
+ ]])
+ }
+}
+
+private actor ServiceStatusProbe {
+ private(set) var calls = 0
+ private var fails = false
+ private let holdsFirst: Bool
+ private var first: CheckedContinuation<CodexServiceStatus, Never>?
+
+ init(holdsFirst: Bool = false) {
+ self.holdsFirst = holdsFirst
+ }
+
+ func fetch() async throws -> CodexServiceStatus {
+ calls += 1
+ if holdsFirst, calls == 1 {
+ return await withCheckedContinuation { first = $0 }
+ }
+ if fails {
+ throw URLError(.notConnectedToInternet)
+ }
+ return holdsFirst ? CodexServiceStatus(level: .fullOutage, componentNames: ["CLI"]) : .operational
+ }
+
+ func fail() {
+ fails = true
+ }
+
+ func releaseFirst() {
+ first?.resume(returning: .operational)
+ first = nil
+ }
+}
+
+private final nonisolated class ServiceStatusURLProtocol: URLProtocol, @unchecked Sendable {
+ override static func canInit(with _: URLRequest) -> Bool {
+ true
+ }
+
+ override static func canonicalRequest(for request: URLRequest) -> URLRequest {
+ request
+ }
+
+ override func startLoading() {
+ let scenario = request.value(forHTTPHeaderField: "X-Test-Scenario") ?? "valid"
+ do {
+ let data: Data = switch scenario {
+ case "invalid-json": Data("<html>Unavailable</html>".utf8)
+ case "oversized-body": Data(repeating: 32, count: 256 * 1024 + 1)
+ default: try CodexServiceStatusTests.response()
+ }
+ let headers = scenario == "oversized-header" ? ["Content-Length": "1048576"] : [:]
+ let response = HTTPURLResponse(url: request.url!, statusCode: scenario == "http-error" ? 503 : 200, httpVersion: nil, headerFields: headers)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: data)
+ client?.urlProtocolDidFinishLoading(self)
+ } catch {
+ client?.urlProtocol(self, didFailWithError: error)
+ }
+ }
+
+ override func stopLoading() {}
+}
diff --git a/CodexBarTests/Presentation/SettingsTests.swift b/CodexBarTests/Presentation/SettingsTests.swift
index db15907..fc5e03e 100644
--- a/CodexBarTests/Presentation/SettingsTests.swift
+++ b/CodexBarTests/Presentation/SettingsTests.swift
@@ -124,7 +124,7 @@ struct SettingsTests {
@Test func layoutRepairsDuplicateOrderAndAlwaysKeepsAVisibleSection() {
let layout = MainPanelLayout(orderedSections: [.usage, .usage, .activity], hiddenSections: Set(MainPanelSection.allCases))
- #expect(layout.orderedSections == [.usage, .activity, .account, .quota, .status])
+ #expect(layout.orderedSections == [.usage, .activity, .account, .quota, .serviceStatus, .status])
#expect(layout.visibleSections == [.usage])
let activityOnly = MainPanelLayout(orderedSections: [.activity], hiddenSections: Set(MainPanelSection.allCases).subtracting([.activity]))
#expect(activityOnly.visibleSections == [.activity])
@@ -151,4 +151,29 @@ struct SettingsTests {
undo.undo()
#expect(!settings.layout.isVisible(.activity))
}
+
+ @Test func serviceStatusAppendsToExistingLayoutAndPreservesPreferences() throws {
+ let preferences = try TestPreferences()
+ defer { preferences.remove() }
+ let previousOrder = ["usage", "account", "status", "quota", "activity"]
+ preferences.defaults.set(previousOrder, forKey: "MainPanel.sectionOrder")
+ preferences.defaults.set(["quota", "activity"], forKey: "MainPanel.hiddenSections")
+ let settings = MainPanelSettings(defaults: preferences.defaults)
+ #expect(settings.layout.orderedSections.map(\.rawValue) == previousOrder + ["serviceStatus"])
+ #expect(settings.layout.hiddenSections == [.quota, .activity])
+ #expect(settings.layout.isVisible(.serviceStatus))
+
+ let undo = UndoManager()
+ undo.groupsByEvent = false
+ undo.beginUndoGrouping()
+ settings.setSectionOrder([.serviceStatus] + settings.layout.orderedSections, undoManager: undo)
+ settings.setSection(.serviceStatus, isVisible: false, undoManager: undo)
+ undo.endUndoGrouping()
+ let restored = MainPanelSettings(defaults: preferences.defaults)
+ #expect(restored.layout.orderedSections.first == .serviceStatus)
+ #expect(restored.layout.hiddenSections == [.quota, .activity, .serviceStatus])
+ undo.undo()
+ #expect(settings.layout.orderedSections.last == .serviceStatus)
+ #expect(settings.layout.isVisible(.serviceStatus))
+ }
}