CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 统一主面板首次加载占位并稳定展开布局
Bobe1d96fa5e4b3
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 122ad58..2c5bf0e 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -270,14 +270,14 @@ final class StatusItemController: NSObject, NSMenuDelegate {.frame(width: CodexStatusMenuView.menuWidth).fixedSize(horizontal: false, vertical: true)- let rootView = MenuPanelLayout { menuContent }- .coordinateSpace(name: ActivityCenterPanelAnchor.coordinateSpace)- .onGeometryChange(for: CGFloat.self) { geometry in- geometry.size.height- } action: { [weak self] height in+ let rootView = MenuPanelLayout(+ onHeightChange: { [weak self] height inguard !usesPreferredContentSize else { return }self?.fallbackPanelController.resizeIfVisible(contentHeight: height)- }+ },+ content: { menuContent }+ )+ .coordinateSpace(name: ActivityCenterPanelAnchor.coordinateSpace)let hostingController = NSHostingController(rootView: AnyView(rootView))if usesPreferredContentSize {diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex f84c8fd..4bb2a0f 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -3122,6 +3122,22 @@}}},+ "common.status.loading" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Loading"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在加载"+ }+ }+ }+ },"common.status.not-set" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/Settings/MainPanelSettings.swift b/CodexBar/Services/Settings/MainPanelSettings.swiftindex 017b567..db1c16f 100644--- a/CodexBar/Services/Settings/MainPanelSettings.swift+++ b/CodexBar/Services/Settings/MainPanelSettings.swift@@ -114,7 +114,7 @@ final class MainPanelSettings: ObservableObject {}AppLog.settings.notice(- "主面板区域显隐变更: section=\(section.rawValue, privacy: .public); visible=\(isVisible ? 1 : 0)"+ "主面板区域显示变更: section=\(section.rawValue, privacy: .public); visible=\(isVisible ? 1 : 0)")applyUndoableLayout(MainPanelLayout(diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex 363cc11..968c052 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -148,6 +148,45 @@ struct StatusAccountCard: View {}}+struct LoadingDataPanel: View {+ @Environment(\.contentAnimationsEnabled) private var allowsAnimations++ var body: some View {+ VStack(alignment: .leading, spacing: 14) {+ Text("common.status.loading")+ .font(MenuMetrics.bodyFont)+ .foregroundStyle(.secondary)++ if allowsAnimations {+ skeleton.phaseAnimator([false, true]) { content, isDimmed in+ content.opacity(isDimmed ? 0.5 : 1)+ } animation: { _ in+ .easeInOut(duration: 1.2)+ }+ } else {+ skeleton+ }+ }+ .padding(.vertical, 8)+ .padding(MenuMetrics.panelPadding)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ .allowsHitTesting(false)+ }++ private var skeleton: some View {+ GeometryReader { geometry in+ VStack(alignment: .leading, spacing: 12) {+ Capsule()+ .frame(width: geometry.size.width * 0.6, height: 10)+ Capsule()+ .frame(width: geometry.size.width * 0.38, height: 10)+ }+ .foregroundStyle(Color.primary.opacity(0.08))+ }+ .frame(height: 32)+ }+}+/// 额度和用量均无数据时的统一占位面板struct EmptyDataPanel: View {var body: some View {diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 7462934..3f3b2ff 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -49,6 +49,8 @@ struct CodexStatusMenuView: View {let onActivityCenterTap: (ActivityCenterPanelAnchor) -> Void@EnvironmentObject private var appUpdater: AppUpdater@State private var activitySectionVisibility: Bool?+ @State private var contentHeight: CGFloat = -1+ @State private var animatesContentHeight = falseprivate var showsActivitySection: Bool {// 订阅建立前直接读取当前状态, 避免首次打开时先显示空卡片再收回@@ -57,6 +59,7 @@ struct CodexStatusMenuView: View {}var body: some View {+ let loadState = viewModel.loadStateMenuSectionLayout(spacing: Metrics.verticalSpacing) {content}@@ -64,13 +67,25 @@ struct CodexStatusMenuView: View {\.mainPanelEntranceAnimationsEnabled,mainPanelSettings.areAnimationsEnabled)- .padding(Metrics.padding)- .liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true)- .animation(Metrics.statusAnimation, value: viewModel.loadState)+ .animation(Metrics.statusAnimation, value: loadState).animation(Metrics.statusAnimation, value: mainPanelSettings.layout).animation(Metrics.statusAnimation, value: syncSettings.isEnabled).animation(Metrics.statusAnimation, value: syncSettings.isSyncing).animation(Metrics.statusAnimation, value: syncSettings.hasSyncFailure)+ .fixedSize(horizontal: false, vertical: true)+ .onGeometryChange(for: ContentGeometry.self) { geometry in+ ContentGeometry(height: geometry.size.height, loadState: loadState)+ } action: { oldValue, newValue in+ // 活动区域自行逐帧改变高度, 这里只对账户加载状态切换插值, 避免叠加动画+ animatesContentHeight = contentHeight >= 0 && oldValue.loadState != newValue.loadState+ contentHeight = newValue.height+ }+ .modifier(MenuContentHeight(height: contentHeight))+ .animation(animatesContentHeight ? Metrics.statusAnimation : nil, value: contentHeight)+ .padding(Metrics.padding)+ .clipped()+ // 外层表面直接跟随当前高度, 不参与内容事务中的独立尺寸和位置插值+ .liquidGlassSurface(cornerRadius: Metrics.surfaceCornerRadius, isOuterSurface: true).onReceive(activityMonitor.$snapshot.combineLatest(activityMonitor.$isActivitySourceHealthy)@@ -82,6 +97,11 @@ struct CodexStatusMenuView: View {}private extension CodexStatusMenuView {+ nonisolated struct ContentGeometry: Equatable {+ let height: CGFloat+ let loadState: CodexLoadState+ }+enum Metrics {static let padding: CGFloat = 12static let surfaceCornerRadius: CGFloat = 14@@ -91,6 +111,17 @@ private extension CodexStatusMenuView {@ViewBuildervar content: some View {+ if viewModel.loadState == .loading, viewModel.snapshot == nil {+ // 本地历史可能先于账户快照就绪, 首次加载仍统一占位, 避免展开不完整的数据区域+ accountSection+ LoadingDataPanel()+ } else {+ configuredContent+ }+ }++ @ViewBuilder+ var configuredContent: some View {let visibleSections = mainPanelSettings.layout.visibleSections.filter { section insection != .activity || showsActivitySection}diff --git a/CodexBar/Views/Menu/MenuPanelLayout.swift b/CodexBar/Views/Menu/MenuPanelLayout.swiftindex 594f9c8..944e03c 100644--- a/CodexBar/Views/Menu/MenuPanelLayout.swift+++ b/CodexBar/Views/Menu/MenuPanelLayout.swift@@ -4,6 +4,20 @@ nonisolated struct MenuSectionVisibilityKey: LayoutValueKey {static let defaultValue: CGFloat = 1}+/// 将插值高度反馈给宿主尺寸测量, 内容始终从顶部布局+struct MenuContentHeight: Animatable, ViewModifier {+ var height: CGFloat++ var animatableData: CGFloat {+ get { height }+ set { height = newValue }+ }++ func body(content: Content) -> some View {+ content.frame(height: height < 0 ? nil : height, alignment: .topLeading)+ }+}+/// 区域高度和相邻间距使用同一展开进度, 移除零高度区域时总高度保持不变struct MenuSectionLayout: Layout {var spacing: CGFloat@@ -35,8 +49,25 @@ struct MenuSectionLayout: Layout {}}-/// 宿主窗口和内容共用整点高度, 保持顶部位置稳定-struct MenuPanelLayout: Layout {+/// 菜单宿主统一测量内容高度, 并在窗口尺寸尚未收敛时保持顶部对齐+struct MenuPanelLayout<Content: View>: View {+ var onHeightChange: (CGFloat) -> Void = { _ in }+ @ViewBuilder let content: () -> Content++ var body: some View {+ MenuPanelSizingLayout { content() }+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.size.height+ } action: { height in+ onHeightChange(height)+ }+ // 测量发生在填满宿主之前, 避免将旧窗口高度当成内容高度而无法收起+ .frame(maxHeight: .infinity, alignment: .top)+ }+}++/// 宿主窗口和内容共用整点高度, 取整留下的空间放在底部+private struct MenuPanelSizingLayout: Layout {func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {guard let subview = subviews.first else { return .zero }let size = subview.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil))diff --git a/Config/BuildNumber.xcconfig b/Config/BuildNumber.xcconfigindex 38f6adf..b60e852 100644--- a/Config/BuildNumber.xcconfig+++ b/Config/BuildNumber.xcconfig@@ -1,3 +1,3 @@// 请勿手动修改// Do not modify manually-CURRENT_PROJECT_VERSION = 294\ No newline at end of file+CURRENT_PROJECT_VERSION = 313\ No newline at end of filediff --git a/Tests/App/Presentation/MenuLoadingTests.swift b/Tests/App/Presentation/MenuLoadingTests.swiftnew file mode 100644index 0000000..006967e--- /dev/null+++ b/Tests/App/Presentation/MenuLoadingTests.swift@@ -0,0 +1,198 @@+import AppKit+import SwiftUI+import Testing++@MainActor+struct MenuLoadingTests {+ @Test func sharedHostKeepsContentAtTopWhenWindowHeightLags() {+ var measuredHeight: CGFloat = 0+ var contentTop: CGFloat = -1+ let view = MenuPanelLayout(+ onHeightChange: { measuredHeight = $0 },+ content: {+ Color.blue+ .frame(width: 200, height: 80.5)+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.frame(in: .global).minY+ } action: { contentTop = $0 }+ }+ )+ let host = NSHostingView(rootView: view)+ // 模拟内容已经收起, 宿主仍保留上一帧高度+ host.frame = CGRect(x: 0, y: 0, width: 200, height: 240)+ host.layoutSubtreeIfNeeded()++ #expect(host.fittingSize.height == 81)+ #expect(measuredHeight == 81)+ #expect(contentTop == 0)+ }++ @Test func initialLoadingKeepsOneAccountAndPlaceholderAcrossLayouts() throws {+ let fixture = try Fixture()+ defer { fixture.cleanUp() }+ let initialSize = fixture.size()+ #expect(initialSize.width == CodexStatusMenuView.menuWidth)+ #expect(initialSize.height > 100 && initialSize.height < 180)++ for visible in [[MainPanelSection.account], [.usage], [.activity, .serviceStatus], MainPanelSection.allCases] {+ fixture.preferences.defaults.set(+ MainPanelSection.allCases.filter { !visible.contains($0) }.map(\.rawValue),+ forKey: "MainPanel.hiddenSections"+ )+ fixture.preferences.defaults.set(MainPanelSection.allCases.reversed().map(\.rawValue), forKey: "MainPanel.sectionOrder")+ fixture.settings.refresh()+ #expect(fixture.size() == initialSize)+ #expect(fixture.settings.layout.visibleSections == MainPanelSection.allCases.reversed().filter { visible.contains($0) })+ }+ }++ @Test(.tags(.integration)) func cachedHistoryDoesNotExpandTheInitialPlaceholder() async throws {+ let fixture = try Fixture()+ defer { fixture.cleanUp() }+ let initialSize = fixture.size()+ try fixture.directory.seedTokenUsageAggregates([+ TestFixtures.tokenUsageAggregate(at: Date(), tokenUsage: TestFixtures.tokenUsage(100))+ ])+ fixture.history.refresh()+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) {+ !fixture.history.snapshot.tokenUsageByDate.isEmpty+ })+ #expect(fixture.model.loadState == .loading)+ #expect(fixture.size() == initialSize)+ }++ @Test(.tags(.integration), arguments: [true, false])+ func firstResponseRestoresConfiguredLayoutAndStopsLoading(signedIn: Bool) async throws {+ let server = try makeServer(signedIn: signedIn)+ defer { server.close() }+ let fixture = try Fixture(socketURL: server.url)+ defer { fixture.cleanUp() }+ fixture.preferences.defaults.set(+ MainPanelSection.allCases.filter { $0 != .account }.map(\.rawValue),+ forKey: "MainPanel.hiddenSections"+ )+ fixture.settings.refresh()+ let initialHeight = fixture.size().height+ fixture.model.refresh(trigger: .manual)+ try #require(try await waitForCondition(timeout: .seconds(3), pollInterval: .milliseconds(10)) {+ !fixture.model.isRefreshing && fixture.model.loadState != .loading+ })+ #expect(fixture.model.loadState == (signedIn ? .loaded : .notLoggedIn))+ #expect(fixture.settings.layout.visibleSections == [.account])+ #expect(fixture.size().height < initialHeight - 60)+ try server.finish()+ }++ @Test(.tags(.integration), arguments: [true, false])+ func firstResponseKeepsSurfaceAnchoredWhileResizing(signedIn: Bool) async throws {+ let server = try makeServer(signedIn: signedIn)+ defer { server.close() }+ let fixture = try Fixture(socketURL: server.url)+ defer { fixture.cleanUp() }+ if !signedIn {+ fixture.preferences.defaults.set(+ MainPanelSection.allCases.filter { $0 != .account }.map(\.rawValue),+ forKey: "MainPanel.hiddenSections"+ )+ fixture.settings.refresh()+ }+ fixture.animationState.allowsAnimations = true+ let host = fixture.host()+ var heights: [CGFloat] = []++ for frame in 0 ..< 50 {+ if frame == 3 {+ fixture.model.refresh(trigger: .manual)+ }+ host.frame = CGRect(origin: .zero, size: host.fittingSize)+ host.layoutSubtreeIfNeeded()+ let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: bitmap)+ let top = try #require(bitmap.colorAt(x: bitmap.pixelsWide / 2, y: 4))+ // 取顶部中央避开圆角, 外层玻璃居中插值时这里会出现透明缺口+ #expect(top.alphaComponent > 0.5)+ #expect(host.frame.width == CodexStatusMenuView.menuWidth)+ heights.append(host.frame.height)+ try await Task.sleep(for: .milliseconds(10))+ }++ #expect(fixture.model.loadState == (signedIn ? .loaded : .notLoggedIn))+ let first = try #require(heights.first)+ let last = try #require(heights.last)+ #expect(abs(first - last) > 10)+ #expect(heights.contains { $0 > min(first, last) + 1 && $0 < max(first, last) - 1 })+ #expect(heights.allSatisfy { $0 >= min(first, last) - 1 && $0 <= max(first, last) + 1 })+ try server.finish()+ }++ private func makeServer(signedIn: Bool) throws -> SharedServerFixture {+ try SharedServerFixture { peer in+ let initialize = try peer.readMessage()+ try peer.reply(to: initialize, result: ["userAgent": "codex/0.162.0"])+ _ = try peer.readMessage()+ let account = try peer.readMessage()+ if signedIn {+ try peer.reply(to: account, result: ["account": ["type": "chatgpt", "email": "[email protected]", "planType": "pro"]])+ let limits = try peer.readMessage()+ try peer.reply(to: limits, result: ["rateLimits": [:]])+ let usage = try peer.readMessage()+ try peer.reply(to: usage, result: ["summary": ["lifetimeTokens": 100]])+ } else {+ try peer.reply(to: account, result: ["account": NSNull()])+ }+ }+ }++ private final class Fixture {+ let directory: TestDirectory+ let preferences: TestPreferences+ let model: CodexStatusViewModel+ let history: HistoryViewModel+ let settings: MainPanelSettings+ let menu: CodexStatusMenuView+ let updater = AppUpdater(bundle: Bundle(for: NSView.self))+ let animationState = MenuSurfaceAnimationState()++ init(socketURL: URL? = nil) throws {+ directory = try TestDirectory()+ preferences = try TestPreferences()+ settings = MainPanelSettings(defaults: preferences.defaults)+ model = CodexStatusViewModel(+ service: CodexStatusService(socketURL: socketURL ?? directory.url.appendingPathComponent("unused.sock"), logStorage: nil),+ defaults: preferences.defaults+ )+ history = HistoryViewModel(service: HistoryService(directoryURL: directory.url))+ let activity = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url), activityDataDirectoryURL: directory.url+ )+ menu = CodexStatusMenuView(+ viewModel: model, historyViewModel: history, mainPanelSettings: settings,+ serviceStatusMonitor: CodexServiceStatusMonitor(fetch: { .operational }), activityMonitor: activity,+ syncSettings: SyncSettings(defaults: preferences.defaults, queryAvailability: { .available }, loadLastUpload: { nil }),+ keepAliveController: KeepAliveController(activityMonitor: activity, defaults: preferences.defaults),+ menuSurfaceVisibility: MenuSurfaceVisibilityState(), animationState: animationState,+ activityCenterPresentationState: ActivityCenterPresentationState(),+ activityCardPresentationState: ActivityCardPresentationState(activityMonitor: activity),+ onUsageHeatmapHoverChange: { _ in }, onResetCreditsTap: { _ in }, onActivityCenterTap: { _ in }+ )+ }++ func size() -> CGSize {+ host().fittingSize+ }++ func host() -> NSHostingView<AnyView> {+ let view = menu.environmentObject(updater)+ .frame(width: CodexStatusMenuView.menuWidth)+ .fixedSize(horizontal: false, vertical: true)+ .preferredColorScheme(.light)+ return NSHostingView(rootView: AnyView(MenuPanelLayout { view }))+ }++ func cleanUp() {+ preferences.remove()+ try? directory.remove()+ }+ }+}