CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
refactor: 重组源码目录结构
Bob91700996da3f
diff --git a/AGENTS.md b/AGENTS.mdindex b725a69..3519a2d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -67,6 +67,7 @@ git status --short- 当前 build settings: `MACOSX_DEPLOYMENT_TARGET = 15.0`, `MARKETING_VERSION = 2.0.0`, `CURRENT_PROJECT_VERSION = 10`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`。- App Sandbox 必须保持关闭(`ENABLE_APP_SANDBOX = NO`), 因为应用要启动本机 Codex CLI/APP 内置 CLI, 并读取真实 macOS 用户的 Codex 登录状态。- 工程使用 `PBXFileSystemSynchronizedRootGroup`; 新增或删除 `CodexBar/` 下 Swift 文件通常无需改 `project.pbxproj`。只有依赖、target/build settings 或资源归属变更才改 Xcode 工程文件。+- Swift 源码按目录组织: `App/`、`Controllers/`、`Models/`、`Services/`、`Views/`。不要把新 Swift 文件直接放回 `CodexBar/` 根层。- 不要为 macOS 15 以下添加 SF Symbols 或 SwiftUI API fallback。## 架构地图@@ -82,24 +83,36 @@ CodexStatusService(JSON-RPC app-server)关键文件职责:-- `CodexBarApp.swift`: `@main` 入口、空 `Settings` scene、`Bundle.displayVersionLabel`。-- `StatusItemController.swift`: `NSStatusItem`、`NSPopover`、右键菜单、设置/日志窗口入口、外部点击监控、淡入淡出状态机、自动刷新启动。-- `HostingWindowController.swift`: 设置和日志窗口的懒创建、居中、置顶和跨桌面打开行为。-- `SettingsWindowController.swift`: 独立设置窗口。-- `LogWindowController.swift`: 独立日志窗口。-- `CodexStatusViewModel.swift`: `@MainActor ObservableObject`, 发布 `snapshot`、`isRefreshing`、`loadState`、`codexConnectionInfo`、`autoRefreshCountdownStartedAt`。-- `CodexStatusService.swift`: app-server 进程、JSON-RPC、连接复用、认证刷新、usage 降级、连接信息。-- `RequestLog.swift`: 常驻交互日志存储, 记录请求、响应、错误和无响应请求。-- `LogView.swift`: 日志窗口 UI, 状态标签为「进行」「完成」「错误」「请求」。-- `CodexCLIResolver.swift`: 解析全局 `codex` 与 `/Applications/Codex.app/Contents/Resources/codex`, 并构造真实用户环境。-- `CodexCLIVersionService.swift`: 并发探测全局 CLI 与 Codex APP 内置 CLI 的磁盘版本, 合成当前运行版本和「已更新至」提示。-- `CodexQuotaModels.swift`: wire DTO、业务快照、limit/usage 转换、错误分类。-- `CodexStatusMenuView.swift`: popover 主 UI, 包含账号卡片、状态卡片、额度、usage、更新时间倒计时和更新提示。-- `QuotaRow.swift`: 单个 quota window 行和分段额度条。-- `UsageHeatmap.swift` / `TokenCountText.swift`: token 汇总、近 30 周热力图、hover tooltip 和 K/M/B 紧凑数字格式。-- `AppSettingsView.swift` / `LoginItemSettings.swift`: 设置窗口、开机自启、CodexBar 版本、Codex CLI/Codex APP 版本与路径复制。-- `AppUpdater.swift`: Sparkle 封装, 更新状态按设置窗、popover 和可用更新拆分。-- `LiquidGlassStyle.swift`: 自绘 Liquid Glass 视觉入口。+- `App/CodexBarApp.swift`: `@main` 入口、空 `Settings` scene、`Bundle.displayVersionLabel`。+- `Controllers/StatusItemController.swift`: `NSStatusItem`、`NSPopover` 状态切换、右键菜单、设置/日志窗口入口、自动刷新启动。+- `Controllers/PopoverDismissMonitor.swift`: popover 外部点击关闭监控, 并稳定 `NSVisualEffectView` inactive 外观。+- `Controllers/PopoverFadeCoordinator.swift`: popover 淡入淡出、alpha 重置和动画任务取消。+- `Controllers/HostingWindowController.swift`: 设置和日志窗口的懒创建、居中、置顶和跨桌面打开行为。+- `Controllers/SettingsWindowController.swift`: 独立设置窗口。+- `Controllers/LogWindowController.swift`: 独立日志窗口。+- `Services/CodexStatus/CodexStatusViewModel.swift`: `@MainActor ObservableObject`, 发布 `snapshot`、`isRefreshing`、`loadState`、`codexConnectionInfo`、`autoRefreshCountdownStartedAt`。+- `Services/CodexStatus/CodexStatusService.swift`: app-server 连接生命周期、连接复用、认证刷新、rate limits/usage 降级和连接信息。+- `Services/CodexStatus/AppServerSession.swift`: JSON-RPC 请求/通知、请求日志回填、业务错误重试、unsupported method 记录。+- `Services/CodexStatus/AppServerPipeReaders.swift`: stdout 按行读取和 stderr drain, 不把子进程 stderr 展示给用户。+- `Services/CodexStatus/RequestLog.swift`: 常驻交互日志存储, 记录请求、响应、错误和无响应请求。+- `Services/CodexCLI/CodexCLIResolver.swift`: 解析全局 `codex` 与 `/Applications/Codex.app/Contents/Resources/codex`, 并构造真实用户环境。+- `Services/CodexCLI/CodexCLIVersionService.swift`: 并发探测全局 CLI 与 Codex APP 内置 CLI 的磁盘版本, 合成当前运行版本和「已更新至」提示。+- `Services/Settings/LoginItemSettings.swift`: 开机自启状态读取和注册/注销。+- `Services/Updates/AppUpdater.swift`: Sparkle 封装, 更新状态按设置窗、popover 和可用更新拆分。+- `Models/CodexAccountModels.swift`: account/read 响应和账号展示名。+- `Models/CodexQuotaModels.swift`: rate limits DTO、quota 业务快照、limit/window 转换和排序。+- `Models/CodexUsageModels.swift`: usage DTO、token summary、daily bucket 和近 30 周日期网格。+- `Models/CodexStatusError.swift`: app-server、传输、认证和 unsupported method 错误分类。+- `Views/Menu/CodexStatusMenuView.swift`: popover 主 UI 装配。+- `Views/Menu/CodexStatusMenuSections.swift`: 账号卡片、状态卡片、额度区、空数据和更新时间行。+- `Views/Menu/AutoRefreshCountdownView.swift`: 更新时间倒计时圆环和 popover 可见时的 `TimelineView` tick。+- `Views/Menu/QuotaRow.swift`: 单个 quota window 行和分段额度条。+- `Views/Menu/UsageHeatmap.swift` / `Views/Menu/TokenCountText.swift`: token 汇总、近 30 周热力图、hover tooltip 和 K/M/B 紧凑数字格式。+- `Views/Settings/AppSettingsView.swift`: 设置窗口主布局、开机自启、CodexBar 版本和更新操作入口。+- `Views/Settings/CodexVersionSection.swift`: Codex CLI/Codex APP 版本、当前使用标记、路径复制和「已更新至」提示。+- `Views/Settings/SettingsToggleRow.swift`: 设置页通用开关行。+- `Views/Log/LogView.swift`: 日志窗口 UI, 状态标签为「进行」「完成」「错误」「请求」。+- `Views/Shared/LiquidGlassStyle.swift`: 自绘 Liquid Glass 视觉入口。## app-server 合约diff --git a/CodexBar/CodexBarApp.swift b/CodexBar/App/CodexBarApp.swiftsimilarity index 100%rename from CodexBar/CodexBarApp.swiftrename to CodexBar/App/CodexBarApp.swiftdiff --git a/CodexBar/CodexStatusMenuView.swift b/CodexBar/CodexStatusMenuView.swiftdeleted file mode 100644index 431f015..0000000--- a/CodexBar/CodexStatusMenuView.swift+++ /dev/null@@ -1,338 +0,0 @@-import Combine-import SwiftUI--@MainActor-final class PopoverVisibilityState: ObservableObject {- @Published var isVisible = false-}--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- }- .padding(Metrics.padding)- .liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true)- .animation(Metrics.statusAnimation, value: viewModel.loadState)- .onChange(of: viewModel.snapshot?.account.email) { _, _ in- isEmailBlurred = false- }- }-}--private extension CodexStatusMenuView {- enum Metrics {- static let padding: CGFloat = 12- static let panelPadding: CGFloat = 10- static let surfaceCornerRadius: CGFloat = 14- static let panelCornerRadius: CGFloat = 8- static let verticalSpacing: CGFloat = 10- static let accountIconSize: CGFloat = 14- static let loadingVerticalPadding: CGFloat = 16- static let statusAnimation = Animation.codexStatus- }-- @ViewBuilder- var content: some View {- if let snapshot = viewModel.snapshot {- accountCard(- title: snapshot.accountLabel,- isEmail: snapshot.account.hasEmail,- plan: snapshot.planLabel- )-- dataSection(snapshot)- } else {- // 仅展示未登录 / 初始化失败两种特殊状态, 其余错误只进日志- statusAccountCard- emptyPanel- }- }-- @ViewBuilder- func dataSection(_ snapshot: CodexQuotaSnapshot) -> some View {- if snapshot.limits.isEmpty, snapshot.usage == nil {- emptyPanel- } else {- if !snapshot.limits.isEmpty {- quotaLimitsView(snapshot.limits, isStale: snapshot.isRateLimitsStale)- }-- if let usage = snapshot.usage {- UsageSummaryView(usage: usage, isStale: snapshot.isUsageStale)- }- }-- updatedAtRow(for: snapshot)- .padding(.horizontal, Metrics.panelPadding)- .padding(.vertical, 7)- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)- }-- var statusAccountCard: some View {- HStack(spacing: 8) {- Image(systemName: "person.fill")- .font(.system(size: Metrics.accountIconSize, weight: .medium))- .foregroundStyle(statusDisplay.color)- .onTapGesture(count: 2) {- viewModel.refresh()- }-- if let text = statusDisplay.text {- Text(text)- .font(.caption.weight(.semibold))- .foregroundStyle(statusDisplay.color)- .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)- }-- var statusDisplay: (text: String?, color: Color) {- switch viewModel.loadState {- case .notLoggedIn:- return ("未登录", .orange)- case .initializationFailed:- return ("初始化失败", .red)- case .loading, .loaded:- 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)- }-- func quotaLimitsView(_ limits: [CodexQuotaLimitSnapshot], isStale: Bool) -> some View {- VStack(alignment: .leading, spacing: 8) {- ForEach(limits) { limit in- if limit.id != limits.first?.id {- LiquidGlassDivider()- }-- quotaLimitSection(limit)- }- }- .markStale(isStale)- .padding(Metrics.panelPadding)- .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)- }-- func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {- VStack(alignment: .leading, spacing: 6) {- Text(limit.title)- .font(.caption.weight(.semibold))- .foregroundStyle(.primary)- .lineLimit(1)- .truncationMode(.middle)-- VStack(spacing: 8) {- ForEach(limit.windows) { window in- QuotaRow(window: window)- }- }- }- }-- 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)- }-- func accountRow(title: String, isEmail: Bool = false, plan: String? = nil) -> some View {- HStack(spacing: 8) {- Image(systemName: "person.fill")- .font(.system(size: Metrics.accountIconSize, weight: .medium))- .foregroundStyle(.tint)- .onTapGesture(count: 2) {- viewModel.refresh()- }-- Text(title)- .font(.caption.weight(.semibold))- .lineLimit(1)- .truncationMode(.middle)- .blur(radius: isEmail && isEmailBlurred ? 3 : 0)- .animation(.snappy(duration: 0.20), value: isEmailBlurred)- .onTapGesture(count: 2) {- 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)- .lineLimit(1)- }- }- }-- func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {- HStack {- HStack(spacing: 5) {- AutoRefreshCountdownTimeline(- startedAt: viewModel.autoRefreshCountdownStartedAt ?? snapshot.generatedAt,- interval: viewModel.autoRefreshInterval,- isActive: popoverVisibility.isVisible,- color: .blue- )-- Text("数据更新时间")- .foregroundStyle(Self.secondaryTextColor)-- Text(Self.timeFormatter.string(from: snapshot.generatedAt))- .monospacedDigit()- .contentTransition(.numericText())- .foregroundStyle(Self.secondaryTextColor)- }- .font(.caption2)- .animation(Metrics.statusAnimation, value: snapshot.generatedAt)-- Spacer()-- if let message = appUpdater.panelUpdateMessage {- Text(message)- .font(.caption2.monospacedDigit())- .foregroundStyle(.secondary)- .lineLimit(1)- .contentTransition(.opacity)- .transition(.opacity)- .onTapGesture(count: 2) {- appUpdater.startUpdate()- }- }- }- .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"], Color(hex: 0x15803D)),- (["team", "business"], Color(hex: 0xD97706)),- (["pro"], Color(hex: 0xC026D3)),- (["plus"], Color(hex: 0x2563EB)),- (["edu"], Color(hex: 0x0891B2)),- (["free"], Color(hex: 0x64748B))- ]-- 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-}--private struct AutoRefreshCountdownTimeline: View {- let startedAt: Date- let interval: TimeInterval- let isActive: Bool- let color: Color-- var body: some View {- if isActive {- TimelineView(.periodic(from: .now, by: 1)) { timeline in- circle(now: timeline.date)- }- } else {- circle(now: Date())- }- }-- private func circle(now: Date) -> AutoRefreshCountdownCircle {- AutoRefreshCountdownCircle(- startedAt: startedAt,- interval: interval,- now: now,- isActive: isActive,- color: color- )- }-}--private struct AutoRefreshCountdownCircle: View {- let startedAt: Date- let interval: TimeInterval- 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(- color,- style: StrokeStyle(lineWidth: 1.4, lineCap: .round)- )- .rotationEffect(.degrees(-90))- }- .frame(width: 8, height: 8)- // 只让刷新起点变化触发动画, 避免每秒 tick 被补间- .animation(isActive ? .linear(duration: Metrics.resetAnimationDuration) : nil, value: startedAt)- }-- private enum Metrics {- static let resetAnimationDuration: TimeInterval = 0.50- }-}diff --git a/CodexBar/HostingWindowController.swift b/CodexBar/Controllers/HostingWindowController.swiftsimilarity index 100%rename from CodexBar/HostingWindowController.swiftrename to CodexBar/Controllers/HostingWindowController.swiftdiff --git a/CodexBar/LogWindowController.swift b/CodexBar/Controllers/LogWindowController.swiftsimilarity index 100%rename from CodexBar/LogWindowController.swiftrename to CodexBar/Controllers/LogWindowController.swiftdiff --git a/CodexBar/Controllers/PopoverDismissMonitor.swift b/CodexBar/Controllers/PopoverDismissMonitor.swiftnew file mode 100644index 0000000..5292be7--- /dev/null+++ b/CodexBar/Controllers/PopoverDismissMonitor.swift@@ -0,0 +1,116 @@+import AppKit++@MainActor+final class PopoverDismissMonitor {+ private let popover: NSPopover+ private let statusButtonProvider: () -> NSStatusBarButton?+ private var localMouseEventMonitor: Any?+ private var globalMouseEventMonitor: Any?++ init(+ popover: NSPopover,+ statusButtonProvider: @escaping () -> NSStatusBarButton?+ ) {+ self.popover = popover+ self.statusButtonProvider = statusButtonProvider+ }++ func install(onDismiss: @escaping () -> Void) {+ remove()++ localMouseEventMonitor = NSEvent.addLocalMonitorForEvents(matching: Metrics.dismissEventMask) { [weak self] event in+ self?.dismissIfNeeded(for: event, onDismiss: onDismiss)+ self?.restabilizePopoverChromeAfterEvent()+ return event+ }++ globalMouseEventMonitor = NSEvent.addGlobalMonitorForEvents(matching: Metrics.dismissEventMask) { _ in+ onDismiss()+ }+ }++ func remove() {+ if let localMouseEventMonitor {+ NSEvent.removeMonitor(localMouseEventMonitor)+ self.localMouseEventMonitor = nil+ }++ if let globalMouseEventMonitor {+ NSEvent.removeMonitor(globalMouseEventMonitor)+ self.globalMouseEventMonitor = nil+ }+ }++ private func dismissIfNeeded(for event: NSEvent, onDismiss: () -> Void) {+ guard popover.isShown else {+ return+ }++ if isEventInsidePopover(event) || isEventInsideStatusButton(event) {+ return+ }++ onDismiss()+ }++ 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 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 = statusButtonProvider(),+ 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 enum Metrics {+ static let dismissEventMask: NSEvent.EventTypeMask = [+ .leftMouseDown,+ .rightMouseDown,+ .otherMouseDown+ ]+ }+}diff --git a/CodexBar/Controllers/PopoverFadeCoordinator.swift b/CodexBar/Controllers/PopoverFadeCoordinator.swiftnew file mode 100644index 0000000..c4ea85f--- /dev/null+++ b/CodexBar/Controllers/PopoverFadeCoordinator.swift@@ -0,0 +1,98 @@+import AppKit++@MainActor+final class PopoverFadeCoordinator {+ private let popover: NSPopover+ private var openTask: Task<Void, Never>?+ private var closeTask: Task<Void, Never>?+ private var generation = 0++ init(popover: NSPopover) {+ self.popover = popover+ }++ func cancel() {+ openTask?.cancel()+ openTask = nil+ closeTask?.cancel()+ closeTask = nil+ }++ func prepareForFadeIn() {+ contentView?.alphaValue = 0+ contentView?.window?.alphaValue = 0+ }++ func resetAlpha() {+ contentView?.alphaValue = 1+ contentView?.window?.alphaValue = 1+ }++ func fadeIn(duration: TimeInterval, completion: @escaping () -> Void) {+ let operationGeneration = nextGeneration()+ fade(to: 1, duration: duration)++ openTask = Task { @MainActor [weak self] in+ try? await Task.sleep(for: .milliseconds(Int(duration * 1000)))+ guard let self, !Task.isCancelled, self.generation == operationGeneration else {+ return+ }++ self.resetAlpha()+ self.openTask = nil+ completion()+ }+ }++ func fadeOut(duration: TimeInterval, completion: @escaping () -> Void) -> Bool {+ guard let contentView else {+ return false+ }++ let operationGeneration = nextGeneration()+ let popoverWindow = contentView.window+ fade(to: 0, duration: duration)++ closeTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in+ try? await Task.sleep(for: .milliseconds(Int(duration * 1000)))+ guard let self, !Task.isCancelled, self.generation == operationGeneration else {+ return+ }++ self.popover.performClose(nil)+ contentView?.alphaValue = 1+ popoverWindow?.alphaValue = 1+ self.closeTask = nil+ completion()+ }++ return true+ }++ private var contentView: NSView? {+ popover.contentViewController?.view+ }++ private func nextGeneration() -> Int {+ generation += 1+ return generation+ }++ private func fade(to alpha: CGFloat, duration: TimeInterval) {+ guard let contentView else {+ return+ }++ let popoverWindow = contentView.window+ if alpha == 1 {+ popoverWindow?.alphaValue = 0+ }++ NSAnimationContext.runAnimationGroup { context in+ context.duration = duration+ context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)+ popoverWindow?.animator().alphaValue = alpha+ contentView.animator().alphaValue = alpha+ }+ }+}diff --git a/CodexBar/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftsimilarity index 100%rename from CodexBar/SettingsWindowController.swiftrename to CodexBar/Controllers/SettingsWindowController.swiftdiff --git a/CodexBar/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftsimilarity index 57%rename from CodexBar/StatusItemController.swiftrename to CodexBar/Controllers/StatusItemController.swiftindex 2645da4..dab8ae1 100644--- a/CodexBar/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -37,13 +37,12 @@ private final class StatusItemController: NSObject {private lazy var logWindowController = LogWindowController { [weak self] inself?.statusItem.button?.window?.screen}+ private lazy var popoverFadeCoordinator = PopoverFadeCoordinator(popover: popover)+ private lazy var popoverDismissMonitor = PopoverDismissMonitor(popover: popover) { [weak self] in+ self?.statusItem.button+ }private var deferredRefreshTask: Task<Void, Never>?- private var popoverOpenTask: Task<Void, Never>?- private var popoverCloseTask: Task<Void, Never>?private var popoverState = PopoverState.hidden- private var popoverAnimationGeneration = 0- private var localMouseEventMonitor: Any?- private var globalMouseEventMonitor: Any?private var cancellables = Set<AnyCancellable>()private var lastHasError: Bool?@@ -161,35 +160,23 @@ private final class StatusItemController: NSObject {private func cancelPopoverTasks() {deferredRefreshTask?.cancel()deferredRefreshTask = nil- popoverOpenTask?.cancel()- popoverOpenTask = nil- popoverCloseTask?.cancel()- popoverCloseTask = nil+ popoverFadeCoordinator.cancel()}private func openPopover(relativeTo button: NSStatusBarButton) {cancelPopoverTasks()- popoverAnimationGeneration += 1- let generation = popoverAnimationGenerationpopoverState = .opening- preparePopoverForFadeIn()+ popoverFadeCoordinator.prepareForFadeIn()popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)popoverVisibility.isVisible = true- stabilizePopoverChromeAppearance()- installPopoverDismissMonitors()- fadePopover(to: 1, duration: Metrics.fadeInDuration)+ popoverDismissMonitor.install { [weak self] in+ self?.closePopover()+ }- 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+ popoverFadeCoordinator.fadeIn(duration: Metrics.fadeInDuration) { [weak self] in+ self?.popoverState = .shown}scheduleDeferredRefresh()@@ -254,173 +241,43 @@ private final class StatusItemController: NSObject {}cancelPopoverTasks()- removePopoverDismissMonitors()+ popoverDismissMonitor.remove()popoverVisibility.isVisible = falseguard popover.isShown else {- resetPopoverAlpha()+ popoverFadeCoordinator.resetAlpha()popoverState = .hiddenreturn}- guard animated, let contentView = popover.contentViewController?.view else {+ guard animated else {finishPopoverClose()return}- popoverAnimationGeneration += 1- let generation = popoverAnimationGenerationpopoverState = .closing+ let didStartFadeOut = popoverFadeCoordinator.fadeOut(duration: Metrics.fadeOutDuration) { [weak self] in+ self?.popoverState = .hidden+ }- let popoverWindow = contentView.window- fadePopover(to: 0, duration: Metrics.fadeOutDuration)- popoverCloseTask = Task { @MainActor [weak self, weak contentView, weak popoverWindow] in- try? await Task.sleep(for: .milliseconds(Int(Metrics.fadeOutDuration * 1000)))- guard let self, !Task.isCancelled, self.popoverAnimationGeneration == generation else {- return- }-- self.popover.performClose(nil)- contentView?.alphaValue = 1- popoverWindow?.alphaValue = 1- self.popoverState = .hidden- self.popoverCloseTask = nil+ if !didStartFadeOut {+ finishPopoverClose()}}private func finishPopoverClose() {cancelPopoverTasks()- popoverAnimationGeneration += 1- removePopoverDismissMonitors()+ popoverDismissMonitor.remove()if popover.isShown {popover.performClose(nil)}popoverVisibility.isVisible = false- resetPopoverAlpha()+ popoverFadeCoordinator.resetAlpha()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)- popoverWindow?.animator().alphaValue = alpha- contentView.animator().alphaValue = alpha- }- }-private func scheduleDeferredRefresh() {deferredRefreshTask?.cancel()deferredRefreshTask = Task { @MainActor [weak self] in@@ -434,11 +291,6 @@ private final class StatusItemController: NSObject {}private enum Metrics {- static let dismissEventMask: NSEvent.EventTypeMask = [- .leftMouseDown,- .rightMouseDown,- .otherMouseDown- ]static let fadeInDuration: TimeInterval = 0.24static let fadeOutDuration: TimeInterval = 0.18}diff --git a/CodexBar/Models/CodexAccountModels.swift b/CodexBar/Models/CodexAccountModels.swiftnew file mode 100644index 0000000..42c5019--- /dev/null+++ b/CodexBar/Models/CodexAccountModels.swift@@ -0,0 +1,32 @@+import Foundation++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"+ case "chatgpt":+ return "ChatGPT"+ case "amazonBedrock":+ return "Amazon Bedrock"+ default:+ return type+ }+ }+}++nonisolated struct AccountReadResponse: Decodable {+ let account: CodexAccount?+}diff --git a/CodexBar/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftsimilarity index 52%rename from CodexBar/CodexQuotaModels.swiftrename to CodexBar/Models/CodexQuotaModels.swiftindex ec89211..33c17fc 100644--- a/CodexBar/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -44,37 +44,6 @@ nonisolated private extension String {}}-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"- case "chatgpt":- return "ChatGPT"- case "amazonBedrock":- return "Amazon Bedrock"- default:- return type- }- }-}--nonisolated struct AccountReadResponse: Decodable {- let account: CodexAccount?-}-nonisolated struct QuotaWindow: Equatable, Identifiable {let id: Stringlet windowDurationMins: Int?@@ -138,90 +107,6 @@ nonisolated struct RateLimitWindow: Decodable {}}-nonisolated struct AccountUsageResponse: Decodable {- let summary: UsageSummary- let dailyUsageBuckets: [DailyUsageBucket]-}--nonisolated struct UsageSummary: Decodable, Equatable {- let currentStreakDays: Int?- let lifetimeTokens: Int- let longestRunningTurnSec: Int?- let longestStreakDays: Int?- let peakDailyTokens: Int-}--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(- byAdding: .day,- value: -max(endingDaysAgo, 0),- to: todayStart- ) ?? todayStart- let currentWeekStart = Self.sundayStartOfWeek(containing: lastVisibleDate, calendar: calendar)- guard let firstWeekStart = calendar.date(- byAdding: .weekOfYear,- value: -(columnCount - 1),- to: currentWeekStart- ) 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")- formatter.dateFormat = "yyyy-MM-dd"- return formatter- }()-}-nonisolated extension CodexQuotaSnapshot {init(accountResponse: AccountReadResponse,@@ -315,63 +200,3 @@ nonisolated extension QuotaWindow {)}}--nonisolated enum CodexStatusError: LocalizedError {- case executableNotFound- case serverTimeout- case serverConnectionClosed- case invalidServerResponse- case serverError(String)- case unsupportedMethod- case notLoggedIn-- var errorDescription: String? {- switch self {- case .executableNotFound:- return "找不到 Codex CLI 或 Codex APP"- default:- return nil- }- }-- // codex app-server 未登录- var isAuthenticationRequired: Bool {- serverErrorMessageContains("codex account authentication required")- }-- // codex app-server 不支持的方法- var isUnsupportedMethod: Bool {- switch self {- case .unsupportedMethod:- return true- default:- return serverErrorMessageContains("Invalid request: unknown variant")- }- }-- var isRetriableServerError: Bool {- guard case .serverError = self else {- return false- }-- return !isAuthenticationRequired && !isUnsupportedMethod- }-- // 连接断开、超时、无法解析都需要重建 app-server 会话- var isTransportFailure: Bool {- switch self {- case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:- return true- default:- 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/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swiftnew file mode 100644index 0000000..e820b3b--- /dev/null+++ b/CodexBar/Models/CodexStatusError.swift@@ -0,0 +1,61 @@+import Foundation++nonisolated enum CodexStatusError: LocalizedError {+ case executableNotFound+ case serverTimeout+ case serverConnectionClosed+ case invalidServerResponse+ case serverError(String)+ case unsupportedMethod+ case notLoggedIn++ var errorDescription: String? {+ switch self {+ case .executableNotFound:+ return "找不到 Codex CLI 或 Codex APP"+ default:+ return nil+ }+ }++ // codex app-server 未登录+ var isAuthenticationRequired: Bool {+ serverErrorMessageContains("codex account authentication required")+ }++ // codex app-server 不支持的方法+ var isUnsupportedMethod: Bool {+ switch self {+ case .unsupportedMethod:+ return true+ default:+ return serverErrorMessageContains("Invalid request: unknown variant")+ }+ }++ var isRetriableServerError: Bool {+ guard case .serverError = self else {+ return false+ }++ return !isAuthenticationRequired && !isUnsupportedMethod+ }++ // 连接断开、超时、无法解析都需要重建 app-server 会话+ var isTransportFailure: Bool {+ switch self {+ case .serverConnectionClosed, .serverTimeout, .invalidServerResponse:+ return true+ default:+ 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/Models/CodexUsageModels.swift b/CodexBar/Models/CodexUsageModels.swiftnew file mode 100644index 0000000..e7b3653--- /dev/null+++ b/CodexBar/Models/CodexUsageModels.swift@@ -0,0 +1,85 @@+import Foundation++nonisolated struct AccountUsageResponse: Decodable {+ let summary: UsageSummary+ let dailyUsageBuckets: [DailyUsageBucket]+}++nonisolated struct UsageSummary: Decodable, Equatable {+ let currentStreakDays: Int?+ let lifetimeTokens: Int+ let longestRunningTurnSec: Int?+ let longestStreakDays: Int?+ let peakDailyTokens: Int+}++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(+ byAdding: .day,+ value: -max(endingDaysAgo, 0),+ to: todayStart+ ) ?? todayStart+ let currentWeekStart = Self.sundayStartOfWeek(containing: lastVisibleDate, calendar: calendar)+ guard let firstWeekStart = calendar.date(+ byAdding: .weekOfYear,+ value: -(columnCount - 1),+ to: currentWeekStart+ ) 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")+ formatter.dateFormat = "yyyy-MM-dd"+ return formatter+ }()+}diff --git a/CodexBar/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swiftsimilarity index 100%rename from CodexBar/CodexCLIResolver.swiftrename to CodexBar/Services/CodexCLI/CodexCLIResolver.swiftdiff --git a/CodexBar/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftsimilarity index 100%rename from CodexBar/CodexCLIVersionService.swiftrename to CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftdiff --git a/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swiftnew file mode 100644index 0000000..d1db7e1--- /dev/null+++ b/CodexBar/Services/CodexStatus/AppServerPipeReaders.swift@@ -0,0 +1,119 @@+import Foundation++nonisolated final class JSONLineReader: @unchecked Sendable {+ private let lock = NSLock()+ private let semaphore = DispatchSemaphore(value: 0)+ private let fileHandle: FileHandle+ private var buffer = Data()+ private var lines: [String] = []+ private var closed = false++ init(fileHandle: FileHandle) {+ self.fileHandle = fileHandle+ fileHandle.readabilityHandler = { [weak self] handle in+ let data = handle.availableData+ guard !data.isEmpty else {+ handle.readabilityHandler = nil+ self?.markClosed()+ return+ }+ 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 {+ lines.append(line)+ semaphore.signal()+ }+ }+ }++ private func markClosed() {+ lock.lock()+ defer {+ lock.unlock()+ semaphore.signal()+ }++ if !buffer.isEmpty {+ if let line = String(data: buffer, encoding: .utf8)?+ .trimmingCharacters(in: .whitespacesAndNewlines),+ !line.isEmpty {+ lines.append(line)+ }+ buffer.removeAll()+ }++ closed = true+ }++ private func popLine() -> String? {+ lock.lock()+ defer { lock.unlock() }++ guard !lines.isEmpty else {+ return nil+ }++ return lines.removeFirst()+ }+}++nonisolated final class PipeDrain: @unchecked Sendable {+ private let fileHandle: FileHandle++ init(fileHandle: FileHandle) {+ self.fileHandle = fileHandle+ fileHandle.readabilityHandler = { handle in+ guard !handle.availableData.isEmpty else {+ handle.readabilityHandler = nil+ return+ }+ }+ }++ func stop() {+ fileHandle.readabilityHandler = nil+ }+}diff --git a/CodexBar/Services/CodexStatus/AppServerSession.swift b/CodexBar/Services/CodexStatus/AppServerSession.swiftnew file mode 100644index 0000000..eaaae79--- /dev/null+++ b/CodexBar/Services/CodexStatus/AppServerSession.swift@@ -0,0 +1,226 @@+import Foundation++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+ private var unsupportedMethods: Set<String> = []++ init(+ process: Process,+ input: Pipe,+ lineReader: JSONLineReader,+ errorReader: PipeDrain,+ timeout: TimeInterval+ ) {+ self.process = process+ self.input = input+ self.lineReader = lineReader+ 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,+ as type: Response.Type+ ) throws -> Response {+ guard !unsupportedMethods.contains(method) else {+ throw CodexStatusError.unsupportedMethod+ }++ do {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ } catch let error as CodexStatusError where error.isRetriableServerError {+ return try performRequestRememberingUnsupported(method, params: params, as: type)+ }+ }++ private func performRequestRememberingUnsupported<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ do {+ return try performRequest(method, params: params, as: type)+ } catch let error as CodexStatusError {+ if error.isUnsupportedMethod {+ unsupportedMethods.insert(method)+ }+ throw error+ }+ }++ private func performRequest<Response: Decodable>(+ _ method: String,+ params: [String: Any]? = nil,+ as type: Response.Type+ ) throws -> Response {+ let id = nextId+ 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 {+ object["id"] = id+ }+ if let params {+ object["params"] = params+ }+ 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)+ } catch {+ onFailure()+ 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,+ decode type: Response.Type+ ) throws -> Response {+ let deadline = Date().addingTimeInterval(timeout)+ let decoder = JSONDecoder()++ while Date() < deadline {+ guard let line = try nextResponseLine(+ matching: id,+ before: deadline,+ token: token,+ decoder: decoder+ ) 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,+ token: UUID,+ decoder: JSONDecoder+ ) throws -> ResponseLine? {+ guard let text = lineReader.nextLine(timeout: max(0, deadline.timeIntervalSinceNow)) else {+ 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,+ token: UUID,+ decoder: JSONDecoder+ ) throws -> Response {+ if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: line.data),+ 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+ }+}++private nonisolated struct RPCIDEnvelope: Decodable {+ let id: Int?+}++private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {+ let id: Int?+ let result: Response?+}++private nonisolated struct RPCErrorEnvelope: Decodable {+ let id: Int?+ let error: RPCError?+}++private nonisolated struct RPCError: Decodable {+ let message: String+}diff --git a/CodexBar/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftsimilarity index 59%rename from CodexBar/CodexStatusService.swiftrename to CodexBar/Services/CodexStatus/CodexStatusService.swiftindex b5e4061..d276362 100644--- a/CodexBar/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -446,349 +446,6 @@ 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- private var unsupportedMethods: Set<String> = []-- init(- process: Process,- input: Pipe,- lineReader: JSONLineReader,- errorReader: PipeDrain,- timeout: TimeInterval- ) {- self.process = process- self.input = input- self.lineReader = lineReader- 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,- as type: Response.Type- ) throws -> Response {- guard !unsupportedMethods.contains(method) else {- throw CodexStatusError.unsupportedMethod- }-- do {- return try performRequestRememberingUnsupported(method, params: params, as: type)- } catch let error as CodexStatusError where error.isRetriableServerError {- return try performRequestRememberingUnsupported(method, params: params, as: type)- }- }-- private func performRequestRememberingUnsupported<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- do {- return try performRequest(method, params: params, as: type)- } catch let error as CodexStatusError {- if error.isUnsupportedMethod {- unsupportedMethods.insert(method)- }- throw error- }- }-- private func performRequest<Response: Decodable>(- _ method: String,- params: [String: Any]? = nil,- as type: Response.Type- ) throws -> Response {- let id = nextId- 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 {- object["id"] = id- }- if let params {- object["params"] = params- }- 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)- } catch {- onFailure()- 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,- decode type: Response.Type- ) throws -> Response {- let deadline = Date().addingTimeInterval(timeout)- let decoder = JSONDecoder()-- while Date() < deadline {- guard let line = try nextResponseLine(- matching: id,- before: deadline,- token: token,- decoder: decoder- ) 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,- token: UUID,- decoder: JSONDecoder- ) throws -> ResponseLine? {- guard let text = lineReader.nextLine(timeout: max(0, deadline.timeIntervalSinceNow)) else {- 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,- token: UUID,- decoder: JSONDecoder- ) throws -> Response {- if let errorEnvelope = try? decoder.decode(RPCErrorEnvelope.self, from: line.data),- 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- }-}-private nonisolated struct InitializeResult: Decodable {let userAgent: String?}--private nonisolated struct RPCIDEnvelope: Decodable {- let id: Int?-}--private nonisolated struct RPCResponseEnvelope<Response: Decodable>: Decodable {- let id: Int?- let result: Response?-}--private nonisolated struct RPCErrorEnvelope: Decodable {- let id: Int?- let error: RPCError?-}--private nonisolated struct RPCError: Decodable {- let message: String-}--private nonisolated final class JSONLineReader: @unchecked Sendable {- private let lock = NSLock()- private let semaphore = DispatchSemaphore(value: 0)- private let fileHandle: FileHandle- private var buffer = Data()- private var lines: [String] = []- private var closed = false-- init(fileHandle: FileHandle) {- self.fileHandle = fileHandle- fileHandle.readabilityHandler = { [weak self] handle in- let data = handle.availableData- guard !data.isEmpty else {- handle.readabilityHandler = nil- self?.markClosed()- return- }- 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 {- lines.append(line)- semaphore.signal()- }- }- }-- private func markClosed() {- lock.lock()- defer {- lock.unlock()- semaphore.signal()- }-- if !buffer.isEmpty {- if let line = String(data: buffer, encoding: .utf8)?- .trimmingCharacters(in: .whitespacesAndNewlines),- !line.isEmpty {- lines.append(line)- }- 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- guard !handle.availableData.isEmpty else {- handle.readabilityHandler = nil- return- }- }- }-- func stop() {- fileHandle.readabilityHandler = nil- }-}diff --git a/CodexBar/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftsimilarity index 100%rename from CodexBar/CodexStatusViewModel.swiftrename to CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftdiff --git a/CodexBar/RequestLog.swift b/CodexBar/Services/CodexStatus/RequestLog.swiftsimilarity index 100%rename from CodexBar/RequestLog.swiftrename to CodexBar/Services/CodexStatus/RequestLog.swiftdiff --git a/CodexBar/LoginItemSettings.swift b/CodexBar/Services/Settings/LoginItemSettings.swiftsimilarity index 100%rename from CodexBar/LoginItemSettings.swiftrename to CodexBar/Services/Settings/LoginItemSettings.swiftdiff --git a/CodexBar/AppUpdater.swift b/CodexBar/Services/Updates/AppUpdater.swiftsimilarity index 100%rename from CodexBar/AppUpdater.swiftrename to CodexBar/Services/Updates/AppUpdater.swiftdiff --git a/CodexBar/LogView.swift b/CodexBar/Views/Log/LogView.swiftsimilarity index 100%rename from CodexBar/LogView.swiftrename to CodexBar/Views/Log/LogView.swiftdiff --git a/CodexBar/Views/Menu/AutoRefreshCountdownView.swift b/CodexBar/Views/Menu/AutoRefreshCountdownView.swiftnew file mode 100644index 0000000..94a78c9--- /dev/null+++ b/CodexBar/Views/Menu/AutoRefreshCountdownView.swift@@ -0,0 +1,67 @@+import SwiftUI++struct AutoRefreshCountdownTimeline: View {+ let startedAt: Date+ let interval: TimeInterval+ let isActive: Bool+ let color: Color++ var body: some View {+ if isActive {+ TimelineView(.periodic(from: .now, by: 1)) { timeline in+ circle(now: timeline.date)+ }+ } else {+ circle(now: Date())+ }+ }++ private func circle(now: Date) -> AutoRefreshCountdownCircle {+ AutoRefreshCountdownCircle(+ startedAt: startedAt,+ interval: interval,+ now: now,+ isActive: isActive,+ color: color+ )+ }+}++private struct AutoRefreshCountdownCircle: View {+ let startedAt: Date+ let interval: TimeInterval+ 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(+ color,+ style: StrokeStyle(lineWidth: 1.4, lineCap: .round)+ )+ .rotationEffect(.degrees(-90))+ }+ .frame(width: 8, height: 8)+ // 只让刷新起点变化触发动画, 避免每秒 tick 被补间+ .animation(isActive ? .linear(duration: Metrics.resetAnimationDuration) : nil, value: startedAt)+ }++ private enum Metrics {+ static let resetAnimationDuration: TimeInterval = 0.50+ }+}diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftnew file mode 100644index 0000000..db3821e--- /dev/null+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -0,0 +1,224 @@+import SwiftUI++enum MenuMetrics {+ static let panelPadding: CGFloat = 10+ static let panelCornerRadius: CGFloat = 8+ static let accountIconSize: CGFloat = 14+ static let loadingVerticalPadding: CGFloat = 16+}++struct AccountCard: View {+ let title: String+ let isEmail: Bool+ let plan: String?+ let isRefreshing: Bool+ let onRefresh: () -> Void+ @State private var isEmailBlurred = false++ var body: some View {+ HStack(spacing: 8) {+ Image(systemName: "person.fill")+ .font(.system(size: MenuMetrics.accountIconSize, weight: .medium))+ .foregroundStyle(.tint)+ .onTapGesture(count: 2, perform: onRefresh)++ Text(title)+ .font(.caption.weight(.semibold))+ .lineLimit(1)+ .truncationMode(.middle)+ .blur(radius: isEmail && isEmailBlurred ? 3 : 0)+ .animation(.snappy(duration: 0.20), value: isEmailBlurred)+ .onTapGesture(count: 2) {+ guard isEmail else { return }+ isEmailBlurred.toggle()+ }++ if isRefreshing {+ ProgressView()+ .controlSize(.mini)+ .padding(.leading, 2)+ }++ Spacer()++ if let plan {+ Text(plan.uppercased())+ .font(.caption2.weight(.bold))+ .foregroundStyle(Self.planBadgeTint(for: plan))+ .lineLimit(1)+ }+ }+ .padding(.horizontal, MenuMetrics.panelPadding)+ .padding(.vertical, 8)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ .onChange(of: title) { _, _ in+ isEmailBlurred = false+ }+ }++ private static func planBadgeTint(for plan: String) -> Color {+ let normalizedPlan = plan.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ return planTintRules.first { rule in+ rule.keywords.contains { normalizedPlan.contains($0) }+ }?.tint ?? .cyan+ }++ private static let planTintRules: [(keywords: [String], tint: Color)] = [+ (["enterprise"], Color(hex: 0x15803D)),+ (["team", "business"], Color(hex: 0xD97706)),+ (["pro"], Color(hex: 0xC026D3)),+ (["plus"], Color(hex: 0x2563EB)),+ (["edu"], Color(hex: 0x0891B2)),+ (["free"], Color(hex: 0x64748B))+ ]+}++struct StatusAccountCard: View {+ let loadState: CodexLoadState+ let isRefreshing: Bool+ let onRefresh: () -> Void++ var body: some View {+ HStack(spacing: 8) {+ Image(systemName: "person.fill")+ .font(.system(size: MenuMetrics.accountIconSize, weight: .medium))+ .foregroundStyle(statusDisplay.color)+ .onTapGesture(count: 2, perform: onRefresh)++ if let text = statusDisplay.text {+ Text(text)+ .font(.caption.weight(.semibold))+ .foregroundStyle(statusDisplay.color)+ .lineLimit(1)+ .truncationMode(.middle)+ }++ if isRefreshing {+ ProgressView()+ .controlSize(.mini)+ .padding(.leading, 2)+ }++ Spacer()+ }+ .padding(.horizontal, MenuMetrics.panelPadding)+ .padding(.vertical, 8)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ }++ private var statusDisplay: (text: String?, color: Color) {+ switch loadState {+ case .notLoggedIn:+ return ("未登录", .orange)+ case .initializationFailed:+ return ("初始化失败", .red)+ case .loading, .loaded:+ return (nil, .accentColor)+ }+ }+}++struct EmptyDataPanel: View {+ var body: some View {+ Text("暂无数据")+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity, alignment: .center)+ .padding(.vertical, MenuMetrics.loadingVerticalPadding)+ .padding(MenuMetrics.panelPadding)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ }+}++struct QuotaLimitsSection: View {+ let limits: [CodexQuotaLimitSnapshot]+ let isStale: Bool++ var body: some View {+ VStack(alignment: .leading, spacing: 8) {+ ForEach(limits) { limit in+ if limit.id != limits.first?.id {+ LiquidGlassDivider()+ }++ quotaLimitSection(limit)+ }+ }+ .markStale(isStale)+ .padding(MenuMetrics.panelPadding)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ }++ private func quotaLimitSection(_ limit: CodexQuotaLimitSnapshot) -> some View {+ VStack(alignment: .leading, spacing: 6) {+ Text(limit.title)+ .font(.caption.weight(.semibold))+ .foregroundStyle(.primary)+ .lineLimit(1)+ .truncationMode(.middle)++ VStack(spacing: 8) {+ ForEach(limit.windows) { window in+ QuotaRow(window: window)+ }+ }+ }+ }+}++struct UpdatedAtRow: View {+ let snapshot: CodexQuotaSnapshot+ let countdownStartedAt: Date+ let countdownInterval: TimeInterval+ let isCountdownActive: Bool+ let updateMessage: String?+ let startUpdate: () -> Void++ var body: some View {+ HStack {+ HStack(spacing: 5) {+ AutoRefreshCountdownTimeline(+ startedAt: countdownStartedAt,+ interval: countdownInterval,+ isActive: isCountdownActive,+ color: .blue+ )++ Text("数据更新时间")+ .foregroundStyle(Self.secondaryTextColor)++ Text(Self.timeFormatter.string(from: snapshot.generatedAt))+ .monospacedDigit()+ .contentTransition(.numericText())+ .foregroundStyle(Self.secondaryTextColor)+ }+ .font(.caption2)+ .animation(Metrics.statusAnimation, value: snapshot.generatedAt)++ Spacer()++ if let updateMessage {+ Text(updateMessage)+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .contentTransition(.opacity)+ .transition(.opacity)+ .onTapGesture(count: 2, perform: startUpdate)+ }+ }+ .animation(Metrics.statusAnimation, value: updateMessage)+ }++ private static let timeFormatter: DateFormatter = {+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "zh_CN")+ formatter.dateFormat = "HH:mm:ss"+ return formatter+ }()++ private static let secondaryTextColor = Color.codexSecondaryLabel++ private enum Metrics {+ static let statusAnimation = Animation.codexStatus+ }+}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftnew file mode 100644index 0000000..9321655--- /dev/null+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -0,0 +1,89 @@+import Combine+import SwiftUI++@MainActor+final class PopoverVisibilityState: ObservableObject {+ @Published var isVisible = false+}++struct CodexStatusMenuView: View {+ static let menuWidth: CGFloat = Metrics.padding * 2 + MenuMetrics.panelPadding * 2 + UsageHeatmap.Metrics.totalWidth++ @ObservedObject var viewModel: CodexStatusViewModel+ @ObservedObject var popoverVisibility: PopoverVisibilityState+ @EnvironmentObject private var appUpdater: AppUpdater++ var body: some View {+ VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {+ content+ }+ .padding(Metrics.padding)+ .liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true)+ .animation(Metrics.statusAnimation, value: viewModel.loadState)+ }+}++private extension CodexStatusMenuView {+ enum Metrics {+ static let padding: CGFloat = 12+ static let panelPadding: CGFloat = 10+ static let surfaceCornerRadius: CGFloat = 14+ static let panelCornerRadius: CGFloat = 8+ static let verticalSpacing: CGFloat = 10+ static let statusAnimation = Animation.codexStatus+ }++ @ViewBuilder+ var content: some View {+ if let snapshot = viewModel.snapshot {+ AccountCard(+ title: snapshot.accountLabel,+ isEmail: snapshot.account.hasEmail,+ plan: snapshot.planLabel,+ isRefreshing: viewModel.isRefreshing,+ onRefresh: viewModel.refresh+ )++ dataSection(snapshot)+ } else {+ // 仅展示未登录 / 初始化失败两种特殊状态, 其余错误只进日志+ StatusAccountCard(+ loadState: viewModel.loadState,+ isRefreshing: viewModel.isRefreshing,+ onRefresh: viewModel.refresh+ )+ EmptyDataPanel()+ }+ }++ @ViewBuilder+ func dataSection(_ snapshot: CodexQuotaSnapshot) -> some View {+ if snapshot.limits.isEmpty, snapshot.usage == nil {+ EmptyDataPanel()+ } else {+ if !snapshot.limits.isEmpty {+ QuotaLimitsSection(limits: snapshot.limits, isStale: snapshot.isRateLimitsStale)+ }++ if let usage = snapshot.usage {+ UsageSummaryView(usage: usage, isStale: snapshot.isUsageStale)+ }+ }++ updatedAtRow(for: snapshot)+ .padding(.horizontal, Metrics.panelPadding)+ .padding(.vertical, 7)+ .liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)+ }++ func updatedAtRow(for snapshot: CodexQuotaSnapshot) -> some View {+ UpdatedAtRow(+ snapshot: snapshot,+ countdownStartedAt: viewModel.autoRefreshCountdownStartedAt ?? snapshot.generatedAt,+ countdownInterval: viewModel.autoRefreshInterval,+ isCountdownActive: popoverVisibility.isVisible,+ updateMessage: appUpdater.panelUpdateMessage,+ startUpdate: appUpdater.startUpdate+ )+ }+}diff --git a/CodexBar/QuotaRow.swift b/CodexBar/Views/Menu/QuotaRow.swiftsimilarity index 100%rename from CodexBar/QuotaRow.swiftrename to CodexBar/Views/Menu/QuotaRow.swiftdiff --git a/CodexBar/TokenCountText.swift b/CodexBar/Views/Menu/TokenCountText.swiftsimilarity index 100%rename from CodexBar/TokenCountText.swiftrename to CodexBar/Views/Menu/TokenCountText.swiftdiff --git a/CodexBar/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftsimilarity index 100%rename from CodexBar/UsageHeatmap.swiftrename to CodexBar/Views/Menu/UsageHeatmap.swiftdiff --git a/CodexBar/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftsimilarity index 51%rename from CodexBar/AppSettingsView.swiftrename to CodexBar/Views/Settings/AppSettingsView.swiftindex 3137df0..73bbc48 100644--- a/CodexBar/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -6,7 +6,6 @@ struct AppSettingsView: View {@EnvironmentObject private var appUpdater: AppUpdater@StateObject private var loginItemSettings = LoginItemSettings()@StateObject private var codexVersions = CodexCLIVersionViewModel()- @State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]var body: some View {VStack(alignment: .leading, spacing: Metrics.sectionSpacing) {@@ -51,9 +50,6 @@ struct AppSettingsView: View {.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ inrefreshCodexVersionSection()}- .onDisappear {- copiedPathResetTasks.values.forEach { $0.cancel() }- }}}@@ -67,13 +63,11 @@ private extension AppSettingsView {static let surfaceCornerRadius: CGFloat = 16static let panelCornerRadius: CGFloat = 10static let iconWidth: CGFloat = 18- static let codexChildIndent: CGFloat = 28- static let codexVersionColumnWidth: CGFloat = 270static let statusAnimation = Animation.codexStatus}var launchAtLoginRow: some View {- settingsToggleRow(+ SettingsToggleRow(icon: "power",title: "开机自动启动",isOn: Binding(@@ -84,7 +78,7 @@ private extension AppSettingsView {}var automaticUpdateCheckRow: some View {- settingsToggleRow(+ SettingsToggleRow(icon: "arrow.triangle.2.circlepath",title: "自动检查更新",isOn: Binding(@@ -95,29 +89,6 @@ private extension AppSettingsView {)}- func settingsToggleRow(- icon: String,- title: String,- isOn: Binding<Bool>,- isEnabled: Bool = true- ) -> some View {- HStack(spacing: 10) {- Image(systemName: icon)- .frame(width: Metrics.iconWidth)- .foregroundStyle(.tint)-- Text(title)-- Spacer()-- Toggle(title, isOn: isOn)- .labelsHidden()- .toggleStyle(.switch)- .controlSize(.small)- .disabled(!isEnabled)- }- }-var versionRow: some View {let status = versionStatus@@ -163,27 +134,10 @@ private extension AppSettingsView {}var codexVersionSection: some View {- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {- HStack(spacing: 10) {- Image(systemName: "number.circle")- .frame(width: Metrics.iconWidth)- .foregroundStyle(.secondary)-- Text("Codex 版本")-- Spacer()- }-- LiquidGlassDivider()- .padding(.leading, Metrics.iconWidth + 10)-- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {- codexVersionRow(icon: "terminal", item: codexVersions.snapshot.global)-- codexVersionRow(icon: "app.badge", item: codexVersions.snapshot.bundled)- }- .padding(.leading, Metrics.codexChildIndent)- }+ CodexVersionSection(+ snapshot: codexVersions.snapshot,+ connectionInfo: statusViewModel.codexConnectionInfo+ )}func refreshCodexVersionSection() {@@ -192,96 +146,6 @@ private extension AppSettingsView {statusViewModel.refreshCodexConnectionInfo()}- func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {- let row = CodexCLIVersionDisplay(item: item, connection: statusViewModel.codexConnectionInfo)- let isPathCopied = copiedPathResetTasks[item.source] != nil-- return HStack(alignment: .top, spacing: 10) {- Image(systemName: icon)- .frame(width: Metrics.iconWidth)- .foregroundStyle(.tertiary)-- Text(item.source.displayName)- .foregroundStyle(.secondary)-- Spacer(minLength: 28)-- VStack(alignment: .trailing, spacing: 3) {- HStack(spacing: 12) {- if row.isCurrent {- Text("当前使用")- .font(.caption2.weight(.medium))- .foregroundStyle(.green)- .padding(.horizontal, 6)- .padding(.vertical, 2)- .liquidGlassCapsule(tint: .green)- .transition(.opacity)- }-- Text(row.displayVersion)- .font(row.hasVersion ? .body.monospacedDigit() : .body)- .foregroundStyle(row.hasVersion ? .secondary : .tertiary)- .lineLimit(1)- .contentTransition(.opacity)- .animation(Metrics.statusAnimation, value: row.displayVersion)- }- .animation(Metrics.statusAnimation, value: row.isCurrent)-- if let newerInstalledVersion = row.newerInstalledVersion {- Text("已更新至 \(newerInstalledVersion)")- .font(.caption2.monospacedDigit())- .foregroundStyle(.orange)- .lineLimit(1)- .transition(.opacity)- }-- if let path = row.path {- copiedPathText(path: path, isCopied: isPathCopied)- .animation(Metrics.statusAnimation, value: isPathCopied)- .help(isPathCopied ? "已复制" : "点击复制")- .onTapGesture {- copyPathToPasteboard(path, source: item.source)- }- .transition(.opacity)- }- }- .frame(maxWidth: Metrics.codexVersionColumnWidth, alignment: .trailing)- .animation(Metrics.statusAnimation, value: row.newerInstalledVersion)- .animation(Metrics.statusAnimation, value: row.path)- }- }-- func copiedPathText(path: String, isCopied: Bool) -> some View {- ZStack(alignment: .trailing) {- Text(path)- .font(.caption2)- .foregroundStyle(.secondary)- .lineLimit(1)- .truncationMode(.middle)- .opacity(isCopied ? 0 : 1)-- Text("已复制")- .font(.caption2)- .foregroundStyle(.green)- .lineLimit(1)- .opacity(isCopied ? 1 : 0)- }- .frame(maxWidth: .infinity, alignment: .trailing)- }-- func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(path, forType: .string)-- copiedPathResetTasks[source]?.cancel()- copiedPathResetTasks[source] = Task { @MainActor in- try? await Task.sleep(for: .milliseconds(1500))- guard !Task.isCancelled else { return }-- copiedPathResetTasks[source] = nil- }- }-@ViewBuildervar statusText: some View {if let message = loginItemSettings.errorMessage {diff --git a/CodexBar/Views/Settings/CodexVersionSection.swift b/CodexBar/Views/Settings/CodexVersionSection.swiftnew file mode 100644index 0000000..d7ba481--- /dev/null+++ b/CodexBar/Views/Settings/CodexVersionSection.swift@@ -0,0 +1,138 @@+import AppKit+import SwiftUI++struct CodexVersionSection: View {+ let snapshot: CodexCLIVersionSnapshot+ let connectionInfo: CodexCLIConnectionInfo?+ @State private var copiedPathResetTasks: [CodexCLIExecutableSource: Task<Void, Never>] = [:]++ var body: some View {+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ HStack(spacing: 10) {+ Image(systemName: "number.circle")+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.secondary)++ Text("Codex 版本")++ Spacer()+ }++ LiquidGlassDivider()+ .padding(.leading, Metrics.iconWidth + 10)++ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ codexVersionRow(icon: "terminal", item: snapshot.global)++ codexVersionRow(icon: "app.badge", item: snapshot.bundled)+ }+ .padding(.leading, Metrics.childIndent)+ }+ .onDisappear {+ copiedPathResetTasks.values.forEach { $0.cancel() }+ }+ }++ private func codexVersionRow(icon: String, item: CodexCLIVersionItem) -> some View {+ let row = CodexCLIVersionDisplay(item: item, connection: connectionInfo)+ let isPathCopied = copiedPathResetTasks[item.source] != nil++ return HStack(alignment: .top, spacing: 10) {+ Image(systemName: icon)+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tertiary)++ Text(item.source.displayName)+ .foregroundStyle(.secondary)++ Spacer(minLength: 28)++ VStack(alignment: .trailing, spacing: 3) {+ HStack(spacing: 12) {+ if row.isCurrent {+ Text("当前使用")+ .font(.caption2.weight(.medium))+ .foregroundStyle(.green)+ .padding(.horizontal, 6)+ .padding(.vertical, 2)+ .liquidGlassCapsule(tint: .green)+ .transition(.opacity)+ }++ Text(row.displayVersion)+ .font(row.hasVersion ? .body.monospacedDigit() : .body)+ .foregroundStyle(row.hasVersion ? .secondary : .tertiary)+ .lineLimit(1)+ .contentTransition(.opacity)+ .animation(Metrics.statusAnimation, value: row.displayVersion)+ }+ .animation(Metrics.statusAnimation, value: row.isCurrent)++ if let newerInstalledVersion = row.newerInstalledVersion {+ Text("已更新至 \(newerInstalledVersion)")+ .font(.caption2.monospacedDigit())+ .foregroundStyle(.orange)+ .lineLimit(1)+ .transition(.opacity)+ }++ if let path = row.path {+ CopyablePathText(path: path, isCopied: isPathCopied)+ .animation(Metrics.statusAnimation, value: isPathCopied)+ .help(isPathCopied ? "已复制" : "点击复制")+ .onTapGesture {+ copyPathToPasteboard(path, source: item.source)+ }+ .transition(.opacity)+ }+ }+ .frame(maxWidth: Metrics.versionColumnWidth, alignment: .trailing)+ .animation(Metrics.statusAnimation, value: row.newerInstalledVersion)+ .animation(Metrics.statusAnimation, value: row.path)+ }+ }++ private func copyPathToPasteboard(_ path: String, source: CodexCLIExecutableSource) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(path, forType: .string)++ copiedPathResetTasks[source]?.cancel()+ copiedPathResetTasks[source] = Task { @MainActor in+ try? await Task.sleep(for: .milliseconds(1500))+ guard !Task.isCancelled else { return }++ copiedPathResetTasks[source] = nil+ }+ }++ private enum Metrics {+ static let rowSpacing: CGFloat = 14+ static let iconWidth: CGFloat = 18+ static let childIndent: CGFloat = 28+ static let versionColumnWidth: CGFloat = 270+ static let statusAnimation = Animation.codexStatus+ }+}++private struct CopyablePathText: View {+ let path: String+ let isCopied: Bool++ var body: some View {+ ZStack(alignment: .trailing) {+ Text(path)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .truncationMode(.middle)+ .opacity(isCopied ? 0 : 1)++ Text("已复制")+ .font(.caption2)+ .foregroundStyle(.green)+ .lineLimit(1)+ .opacity(isCopied ? 1 : 0)+ }+ .frame(maxWidth: .infinity, alignment: .trailing)+ }+}diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftnew file mode 100644index 0000000..c1c301c--- /dev/null+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -0,0 +1,30 @@+import SwiftUI++struct SettingsToggleRow: View {+ let icon: String+ let title: String+ let isOn: Binding<Bool>+ var isEnabled = true++ var body: some View {+ HStack(spacing: 10) {+ Image(systemName: icon)+ .frame(width: Metrics.iconWidth)+ .foregroundStyle(.tint)++ Text(title)++ Spacer()++ Toggle(title, isOn: isOn)+ .labelsHidden()+ .toggleStyle(.switch)+ .controlSize(.small)+ .disabled(!isEnabled)+ }+ }++ private enum Metrics {+ static let iconWidth: CGFloat = 18+ }+}diff --git a/CodexBar/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swiftsimilarity index 100%rename from CodexBar/LiquidGlassStyle.swiftrename to CodexBar/Views/Shared/LiquidGlassStyle.swiftdiff --git a/Images/screenshot.png b/Images/screenshot.pngindex 67d08fc..bff5f35 100644Binary files a/Images/screenshot.png and b/Images/screenshot.png differdiff --git a/README.md b/README.mdindex f285853..7a8fd0e 100644--- a/README.md+++ b/README.md@@ -42,6 +42,16 @@ xcodebuild -project CodexBar.xcodeproj -scheme CodexBar -destination 'generic/pl也可以直接用 Xcode 打开 `CodexBar.xcodeproj` 运行。项目使用 SwiftUI + MVVM 依赖 Sparkle (SwiftPM)+## 源码结构++Swift 源码按职责放在 `CodexBar/` 下的子目录中:++- `App/`: 应用入口+- `Controllers/`: 菜单栏、popover 和独立窗口控制器+- `Models/`: account、quota、usage 和错误分类模型+- `Services/`: app-server 会话、Codex CLI 解析、版本探测、开机自启和 Sparkle 更新+- `Views/`: 菜单栏弹窗、设置窗口、日志窗口和共享 Liquid Glass 样式+## 隐私CodexBar 只与本机 Codex app-server 进程通信。账号信息和额度数据不会被收集或发送给任何个人或服务。