CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 完善菜单栏指标与任务事件展示并修复面板交互
Boba91fb6df7811
diff --git a/CodexBar/App/CodexBarAppDelegate.swift b/CodexBar/App/CodexBarAppDelegate.swiftindex dafe34f..08af70d 100644--- a/CodexBar/App/CodexBarAppDelegate.swift+++ b/CodexBar/App/CodexBarAppDelegate.swift@@ -21,7 +21,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {)let syncSettings = SyncSettings()let globalHotKeySettings = GlobalHotKeySettings()- let menuBarQuotaSettings = MenuBarQuotaSettings()+ let menuBarIndicatorSettings = MenuBarIndicatorSettings()let appearanceSettings = AppearanceSettings()let mainPanelSettings = MainPanelSettings()let serviceStatusMonitor = CodexServiceStatusMonitor()@@ -52,7 +52,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {activityMonitor: activityMonitor,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,- menuBarQuotaSettings: menuBarQuotaSettings,+ menuBarIndicatorSettings: menuBarIndicatorSettings,appearanceSettings: appearanceSettings,mainPanelSettings: mainPanelSettings,serviceStatusMonitor: serviceStatusMonitor,@@ -219,7 +219,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {"notification=\(notificationSettings.isEnabled ? 1 : 0)","autoReset=\(autoResetSettings.isEnabled ? 1 : 0)","autoResetLeadTimeSeconds=\(autoResetSettings.leadTime.rawValue)",- "menuBarQuota=\(menuBarQuotaSettings.selection.rawValue)",+ "menuBarIndicators=\(menuBarIndicatorSettings.configuration.visibleMetrics(in: viewModel.snapshot?.codexLimit?.windows ?? []).map(\.rawValue).joined(separator: ","))","mainPanel=\(mainPanelSettings.layout.visibleSections.map(\.rawValue).joined(separator: ","))","usageHeatmapMode=\(mainPanelSettings.usageHeatmapMode.rawValue)","hotKey=\(globalHotKeySettings.shortcut == nil ? 0 : 1)"diff --git a/CodexBar/Controllers/OptionsPanelController.swift b/CodexBar/Controllers/OptionsPanelController.swiftindex d11d032..f4d66f7 100644--- a/CodexBar/Controllers/OptionsPanelController.swift+++ b/CodexBar/Controllers/OptionsPanelController.swift@@ -5,6 +5,7 @@ import SwiftUI/// 设置窗口右侧的子选项面板, 同一时刻只展开一个enum SettingsOptionsPanel: CaseIterable, Hashable {case mainPanel+ case menuBarIndicatorcase taskGlowcase notificationcase autoReset@@ -48,16 +49,19 @@ private struct SidePanelEntryRebuildHost<Content: View>: View {@MainActorfinal class OptionsPanelController {private let animationKey: String- private let initialPanelSize: CGSize+ private let resizeDuration: TimeInterval+ private let resizesWithContent: Bool+ private let mainPanelSettings: MainPanelSettings/// 展开前的准备动作, 例如刷新仅在此面板显示的设置项private let willShow: (() -> Void)?private let willHide: (() -> Void)?- private let contentControllerProvider: (SidePanelEntryCue) -> NSViewController+ private let contentControllerProvider: (SidePanelEntryCue, @escaping @MainActor (CGSize) -> Void) -> NSViewControllerprivate let entryCue = SidePanelEntryCue()private var panel: NSPanel?private var hostingController: NSViewController?- private var cancellables = Set<AnyCancellable>()+ private weak var anchorContentView: NSView?+ private var expansionSide = UsageHeatmapDetailSide.right/// 展开时保留主设置窗口的键盘焦点, 用户点击输入框后再由面板接管private lazy var presenter = SidePanelDrawerPresenter(animationKey: animationKey,@@ -68,39 +72,34 @@ final class OptionsPanelController {)private var panelResizeTask: Task<Void, Never>?private var isEntryAnimationRunning = false+ private var acceptsContentResize = falseinit(mainPanelSettings: MainPanelSettings,animationKey: String,- initialPanelSize: CGSize,+ resizeDuration: TimeInterval = SettingsOptionsPanelMetrics.resizeDuration,+ resizesWithContent: Bool = false,willShow: (() -> Void)? = nil,willHide: (() -> Void)? = nil,- contentProvider: @escaping () -> some View,- contentChanges: AnyPublisher<Void, Never>? = nil+ contentProvider: @escaping () -> some View) {self.animationKey = animationKey- self.initialPanelSize = initialPanelSize+ self.resizeDuration = resizeDuration+ self.resizesWithContent = resizesWithContent+ self.mainPanelSettings = mainPanelSettingsself.willShow = willShowself.willHide = willHide// 内容闭包在首次构造面板时才执行, 保留 SwiftUI 状态的创建时机- contentControllerProvider = { cue in+ contentControllerProvider = { cue, onSizeChanged inlet controller = NSHostingController(rootView: SidePanelEntryRebuildHost(cue: cue, content: contentProvider()).contentAnimations(settings: mainPanelSettings)+ .environment(\.settingsOptionsPanelSizeObserver, SettingsOptionsPanelSizeObserver(onChange: onSizeChanged)))- // 高度重算依赖 preferredContentSize 提交的 fitting size- controller.sizingOptions = [.preferredContentSize]+ // 保留 fittingSize 所需的固有尺寸报告, 窗口动画仍由控制器统一提交+ controller.sizingOptions = [.intrinsicContentSize]return controller}- // 只有内容行数会动态增删的面板才传变化源- // 面板收着时由 scheduleResize 的守卫过滤变化- if let contentChanges {- contentChanges- .sink { [weak self] in- self?.scheduleResize()- }- .store(in: &cancellables)- }}var isVisible: Bool {@@ -131,6 +130,7 @@ final class OptionsPanelController {panelResizeTask?.cancel()panelResizeTask = nilisEntryAnimationRunning = false+ acceptsContentResize = false// 原生输入框的焦点环不跟随内容层平移, 收起前结束编辑也避免下次展开恢复旧焦点panel?.makeFirstResponder(panel)presenter.hide(immediate: immediate)@@ -138,13 +138,13 @@ final class OptionsPanelController {private func scheduleResize() {// 同步检查 isVisible, 隐藏时跳过 Task 创建及两轮 runloop 等待- guard panel?.isVisible == true, !isEntryAnimationRunning else {+ guard !resizesWithContent, panel?.isVisible == true, !isEntryAnimationRunning else {return}panelResizeTask?.cancel()panelResizeTask = Task { @MainActor [weak self] in- // @Published 先于 SwiftUI 布局发出变更, 等待视图提交新的 fitting size+ // 等待入场重建后的 SwiftUI 布局提交, 再读取 fitting sizeawait Task.yield()await Task.yield()guard let self,@@ -172,9 +172,12 @@ final class OptionsPanelController {willShow?()// 仅首次构造后需要重建, 后续复用常驻 hosting controller 和已创建的 portallet needsEntryRebuild = panel == nil- let panel = ensurePanel()+ guard let panel = ensurePanel(),+ let panelSize = hostingController?.view.validFittingSize else {+ return+ }(panel as? KeyableBorderlessPanel)?.sharedUndoManager = window.undoManager- // measuredPanelSize 会通过 validFittingSize 调用 layoutSubtreeIfNeeded, 无需提前布局+ // validFittingSize 已完成布局, 无需再次测量// 此前的操作只影响设置窗口, 不会使面板布局失效let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.framelet screen = window.screen ?? NSScreen.main@@ -183,7 +186,6 @@ final class OptionsPanelController {anchorProvider.currentScreenFrame(in: window),menuSurfaceFrame: windowSurfaceFrame)- let panelSize = measuredPanelSize()// clampsToSurfaceBottom 设为 false, 保持顶边对齐主开关行, 允许底边超出设置窗口let position = SidePanelSupport.anchoredPosition(panelSize: panelSize,@@ -194,17 +196,25 @@ final class OptionsPanelController {preferredSide: .right,clampsToSurfaceBottom: false)+ anchorContentView = contentView+ expansionSide = position.sidepanel.level = window.levelpanelResizeTask?.cancel()isEntryAnimationRunning = true+ acceptsContentResize = falsepresenter.present(panel, at: position, relativeTo: window) { [weak self] inguard let self else {return}isEntryAnimationRunning = false- scheduleResize()+ acceptsContentResize = true+ if resizesWithContent, let size = hostingController?.view.validFittingSize {+ resizeFromContent(size)+ } else {+ scheduleResize()+ }}// present 已将内容移出可视区, 此时重建不会出现在画面中if needsEntryRebuild {@@ -212,17 +222,22 @@ final class OptionsPanelController {}}- private func ensurePanel() -> NSPanel {+ private func ensurePanel() -> NSPanel? {if let panel {return panel}+ let hostingController = contentControllerProvider(entryCue) { [weak self] size in+ self?.resizeFromContent(size)+ }+ guard let size = hostingController.view.validFittingSize else {+ return nil+ }let panel = SidePanelSupport.makePanel(- initialSize: initialPanelSize,+ initialSize: size,ignoresMouseEvents: false,keyable: true)- let hostingController = contentControllerProvider(entryCue)panel.contentViewController = hostingControllerSidePanelSupport.configureLayers(hostingView: hostingController.view,@@ -234,11 +249,20 @@ final class OptionsPanelController {return panel}- private func measuredPanelSize() -> CGSize {- hostingController?.view.validFittingSize ?? initialPanelSize+ private func resizeFromContent(_ size: CGSize) {+ guard resizesWithContent,+ acceptsContentResize,+ let panel,+ panel.isVisible,+ !isEntryAnimationRunning,+ size.width.isFinite, size.width > 0,+ size.height.isFinite, size.height > 0 else {+ return+ }+ resizePanel(panel, to: size, animated: false)}- private func resizePanel(_ panel: NSPanel, to size: CGSize) {+ private func resizePanel(_ panel: NSPanel, to size: CGSize, animated: Bool = true) {guard size != panel.frame.size else {return}@@ -250,18 +274,33 @@ final class OptionsPanelController {targetFrame.size = sizetargetFrame.origin.y = topEdge - targetFrame.heightif let visibleFrame = panel.screen?.visibleFrame {- // 复用初次展开的夹紧规则, 保持重算位置与 position 的结果一致- targetFrame = SidePanelSupport.clampedVertically(targetFrame, in: visibleFrame)+ if size.width != panel.frame.width, let parent = panel.parent {+ let surfaceFrame = SidePanelSupport.contentScreenFrame(for: anchorContentView, in: parent) ?? parent.frame+ let position = SidePanelSupport.position(+ panelSize: size,+ menuSurfaceFrame: surfaceFrame,+ visibleFrame: visibleFrame,+ preferredSide: expansionSide,+ proposedY: targetFrame.minY,+ clampsToSurfaceBottom: false+ )+ targetFrame = position.frame+ expansionSide = position.side+ presenter.updateSide(position.side)+ } else {+ targetFrame = SidePanelSupport.clampedVertically(targetFrame, in: visibleFrame)+ }+ }++ guard animated, mainPanelSettings.areAnimationsEnabled else {+ panel.setFrame(targetFrame, display: false)+ return}NSAnimationContext.runAnimationGroup { context in- context.duration = Metrics.resizeDuration+ context.duration = resizeDurationcontext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)panel.animator().setFrame(targetFrame, display: true)}}-- private enum Metrics {- static let resizeDuration: TimeInterval = 0.16- }}diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 5efe5d9..90a6333 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -10,7 +10,7 @@ final class SettingsWindowController: HostingWindowController {private let tuiNotificationSettings: TUINotificationSettingsprivate let syncSettings: SyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettings- private let menuBarQuotaSettings: MenuBarQuotaSettings+ private let menuBarIndicatorSettings: MenuBarIndicatorSettingsprivate let appearanceSettings: AppearanceSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let taskGlowSettings: TaskGlowSettings@@ -38,7 +38,7 @@ final class SettingsWindowController: HostingWindowController {tuiNotificationSettings: TUINotificationSettings,syncSettings: SyncSettings,globalHotKeySettings: GlobalHotKeySettings,- menuBarQuotaSettings: MenuBarQuotaSettings,+ menuBarIndicatorSettings: MenuBarIndicatorSettings,appearanceSettings: AppearanceSettings,mainPanelSettings: MainPanelSettings,taskGlowSettings: TaskGlowSettings,@@ -55,7 +55,7 @@ final class SettingsWindowController: HostingWindowController {self.tuiNotificationSettings = tuiNotificationSettingsself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettings- self.menuBarQuotaSettings = menuBarQuotaSettings+ self.menuBarIndicatorSettings = menuBarIndicatorSettingsself.appearanceSettings = appearanceSettingsself.mainPanelSettings = mainPanelSettingsself.taskGlowSettings = taskGlowSettings@@ -83,7 +83,7 @@ final class SettingsWindowController: HostingWindowController {rootView: AppSettingsView(syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,- menuBarQuotaSettings: menuBarQuotaSettings,+ menuBarIndicatorSettings: menuBarIndicatorSettings,appearanceSettings: appearanceSettings,mainPanelSettings: mainPanelSettings,taskGlowSettings: taskGlowSettings,@@ -155,7 +155,7 @@ final class SettingsWindowController: HostingWindowController {notificationSettings.refreshAuthorizationStatus()tuiNotificationSettings.refresh()syncSettings.refresh()- menuBarQuotaSettings.refresh()+ menuBarIndicatorSettings.refresh()appearanceSettings.refresh()mainPanelSettings.refresh()taskGlowSettings.refresh()@@ -189,11 +189,12 @@ final class SettingsWindowController: HostingWindowController {switch panel {case .mainPanel:makeMainPanelOptionsPanelController()+ case .menuBarIndicator:+ makeMenuBarIndicatorOptionsPanelController()case .taskGlow:OptionsPanelController(mainPanelSettings: mainPanelSettings,animationKey: "CodexBar.taskGlowOptionsDrawerTransform",- initialPanelSize: TaskGlowOptionsView.initialPanelSize,willHide: { [taskGlowSettings] in taskGlowSettings.endColorPreview() },contentProvider: { [taskGlowSettings] inTaskGlowOptionsView(settings: taskGlowSettings)@@ -203,7 +204,7 @@ final class SettingsWindowController: HostingWindowController {OptionsPanelController(mainPanelSettings: mainPanelSettings,animationKey: "CodexBar.notificationOptionsDrawerTransform",- initialPanelSize: NotificationOptionsView.initialPanelSize,+ resizesWithContent: true,willShow: { [tuiNotificationSettings] intuiNotificationSettings.refresh()},@@ -214,27 +215,12 @@ final class SettingsWindowController: HostingWindowController {autoResetSettings: autoResetSettings,keepAliveController: keepAliveController)- },- // 通知选项的可用性会影响音效子行显隐, 需要订阅各项依赖的派生状态- // 防睡眠只订阅相关派生值, 避免每次任务起停都触发面板高度重算- contentChanges: Publishers.MergeMany([- notificationSettings.objectWillChange.eraseToAnyPublisher(),- autoResetSettings.$isEnabled- .map { _ in () }- .eraseToAnyPublisher(),- keepAliveController.$isLowBatteryProtectionEnabled- .map { _ in () }- .eraseToAnyPublisher(),- keepAliveController.$isMaximumDurationEnabled- .map { _ in () }- .eraseToAnyPublisher()- ]).eraseToAnyPublisher()+ })case .autoReset:OptionsPanelController(mainPanelSettings: mainPanelSettings,animationKey: "CodexBar.autoResetOptionsDrawerTransform",- initialPanelSize: AutoResetOptionsView.initialPanelSize,contentProvider: { [autoResetSettings] inAutoResetOptionsView(settings: autoResetSettings)}@@ -243,26 +229,32 @@ final class SettingsWindowController: HostingWindowController {OptionsPanelController(mainPanelSettings: mainPanelSettings,animationKey: "CodexBar.keepAliveOptionsDrawerTransform",- initialPanelSize: KeepAliveOptionsView.initialPanelSize,+ resizesWithContent: true,contentProvider: { [keepAliveController, protectionSettings] inKeepAliveOptionsView(keepAliveController: keepAliveController,protectionSettings: protectionSettings)- },- // 面板里只有 hasBattery 会增删行, 其余各行的取值不改高度- contentChanges: keepAliveController.$hasBattery- .map { _ in () }- .eraseToAnyPublisher()+ })}}+ private func makeMenuBarIndicatorOptionsPanelController() -> OptionsPanelController {+ OptionsPanelController(+ mainPanelSettings: mainPanelSettings,+ animationKey: "CodexBar.menuBarIndicatorOptionsDrawerTransform",+ resizesWithContent: true,+ contentProvider: { [menuBarIndicatorSettings, viewModel] in+ MenuBarIndicatorOptionsView(settings: menuBarIndicatorSettings, statusViewModel: viewModel)+ }+ )+ }+private func makeMainPanelOptionsPanelController() -> OptionsPanelController {OptionsPanelController(mainPanelSettings: mainPanelSettings,animationKey: "CodexBar.mainPanelOptionsDrawerTransform",- initialPanelSize: MainPanelOptionsView.initialPanelSize,willShow: { [mainPanelSettings] inmainPanelSettings.refresh()},diff --git a/CodexBar/Controllers/SidePanelPresenter.swift b/CodexBar/Controllers/SidePanelPresenter.swiftindex c18e179..ed6f0b9 100644--- a/CodexBar/Controllers/SidePanelPresenter.swift+++ b/CodexBar/Controllers/SidePanelPresenter.swift@@ -191,6 +191,10 @@ final class SidePanelDrawerPresenter {)}+ func updateSide(_ side: UsageHeatmapDetailSide) {+ currentSide = side+ }+func hide(immediate: Bool = false) {guard let panel else {returndiff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 2c5bf0e..4de9379 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -11,7 +11,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private let activityMonitor: ActivityMonitorprivate let syncSettings: SyncSettingsprivate let globalHotKeySettings: GlobalHotKeySettings- private let menuBarQuotaSettings: MenuBarQuotaSettings+ private let menuBarIndicatorSettings: MenuBarIndicatorSettingsprivate let appearanceSettings: AppearanceSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let serviceStatusMonitor: CodexServiceStatusMonitor@@ -49,7 +49,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {tuiNotificationSettings: tuiNotificationSettings,syncSettings: syncSettings,globalHotKeySettings: globalHotKeySettings,- menuBarQuotaSettings: menuBarQuotaSettings,+ menuBarIndicatorSettings: menuBarIndicatorSettings,appearanceSettings: appearanceSettings,mainPanelSettings: mainPanelSettings,taskGlowSettings: taskGlowSettings,@@ -108,7 +108,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {private var statusIconState: StatusIconState?private let statusIconPresentation = StatusItemIconPresentation()private var statusIconHostingView: StatusItemIconHostingView?- private var statusIconExpirationTask: Task<Void, Never>?+ private var statusIconRefreshTask: Task<Void, Never>?private var registeredHotKeyShortcut: GlobalHotKeyShortcut?private var auxiliaryWindowFocusRestoreTask: Task<Void, Never>?private var activeStatusItemMenu: NSMenu?@@ -121,7 +121,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {activityMonitor: ActivityMonitor,syncSettings: SyncSettings,globalHotKeySettings: GlobalHotKeySettings,- menuBarQuotaSettings: MenuBarQuotaSettings,+ menuBarIndicatorSettings: MenuBarIndicatorSettings,appearanceSettings: AppearanceSettings,mainPanelSettings: MainPanelSettings,serviceStatusMonitor: CodexServiceStatusMonitor,@@ -137,7 +137,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {self.activityMonitor = activityMonitorself.syncSettings = syncSettingsself.globalHotKeySettings = globalHotKeySettings- self.menuBarQuotaSettings = menuBarQuotaSettings+ self.menuBarIndicatorSettings = menuBarIndicatorSettingsself.appearanceSettings = appearanceSettingsself.mainPanelSettings = mainPanelSettingsself.serviceStatusMonitor = serviceStatusMonitor@@ -164,7 +164,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {closeMenuSurface(animated: false)serviceStatusMonitor.setEnabled(false)auxiliaryWindowFocusRestoreTask?.cancel()- statusIconExpirationTask?.cancel()+ statusIconRefreshTask?.cancel()statusIconHostingView?.removeFromSuperview()statusIconHostingView = nilsyncScheduler.cancel()@@ -218,7 +218,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {.receive(on: DispatchQueue.main).sink { [weak self] _ inself?.refreshStatusIconPresentation(animated: false)- self?.scheduleStatusIconExpiration()+ self?.scheduleStatusIconRefresh()}.store(in: &cancellables)}@@ -324,19 +324,13 @@ final class StatusItemController: NSObject, NSMenuDelegate {}.store(in: &cancellables)- Publishers.CombineLatest4(+ Publishers.CombineLatest3(viewModel.$loadState,viewModel.$snapshot,- menuBarQuotaSettings.$selection,- activityMonitor.$snapshot+ menuBarIndicatorSettings.$configuration)- .map { loadState, snapshot, selection, activity in- StatusIconState(- usesErrorImage: loadState.isError || snapshot?.hasTrustedData == false,- ordinaryUsageAllowed: snapshot?.ordinaryUsageAllowed,- progress: StatusIconProgress(snapshot: snapshot, selection: selection),- activity: activity- )+ .map { loadState, snapshot, configuration in+ StatusIconState(loadState: loadState, snapshot: snapshot, configuration: configuration)}.removeDuplicates().sink { [weak self] state in@@ -423,29 +417,34 @@ final class StatusItemController: NSObject, NSMenuDelegate {guard previousState != state else { return }statusIconState = staterefreshStatusIconPresentation(animated: previousState != nil)- scheduleStatusIconExpiration()+ scheduleStatusIconRefresh()}private func refreshStatusIconPresentation(animated: Bool = true) {guard let state = statusIconState else { return }let now = Date()+ statusItem.button?.toolTip = state.toolTip(at: now)statusIconPresentation.update(- symbolName: state.symbolName(at: now),+ isUnavailable: state.isUnavailable,ordinaryUsageAllowed: state.ordinaryUsageAllowed,- percent: state.progress?.percent,- isStale: state.progress?.isStale ?? false,+ indicators: state.progress.map { progress in+ progress.map {+ StatusItemIconPresentation.Indicator(percent: $0.percent(at: now), isStale: $0.isStale)+ }+ },animated: animated)}- /// 终态提示按墙上时间到期, 即使没有后续活动事件也会恢复普通图标- private func scheduleStatusIconExpiration() {- statusIconExpirationTask?.cancel()- statusIconExpirationTask = nil- guard let expiration = statusIconState?.activity.statusItemActivityExpiration else { return }- let delay = expiration.timeIntervalSinceNow+ /// 重置进度按墙上时间计算下一次刷新+ private func scheduleStatusIconRefresh() {+ statusIconRefreshTask?.cancel()+ statusIconRefreshTask = nil+ let now = Date()+ guard let expiration = statusIconState?.nextRefreshDate(after: now) else { return }+ let delay = expiration.timeIntervalSince(now)guard delay > 0 else { return }- statusIconExpirationTask = Task { @MainActor [weak self] in+ statusIconRefreshTask = Task { @MainActor [weak self] indo {try await Task.sleep(for: .seconds(delay))} catch {@@ -453,7 +452,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {}guard let self, !Task.isCancelled else { return }refreshStatusIconPresentation()- scheduleStatusIconExpiration()+ scheduleStatusIconRefresh()}}diff --git a/CodexBar/Models/ActivityCardSelection.swift b/CodexBar/Models/ActivityCardSelection.swiftindex 8d4c1ca..b84150e 100644--- a/CodexBar/Models/ActivityCardSelection.swift+++ b/CodexBar/Models/ActivityCardSelection.swift@@ -81,7 +81,11 @@ nonisolated struct ActivityCardSelection: Equatable {if snapshot.hasActiveTasks {automaticID = incomingIDs.first} else {- automaticID = snapshot.primaryActivity.cardSelectionID+ automaticID = switch snapshot.latestTerminalEvent {+ case let .completed(completion): completion.threadID+ case let .terminated(termination): termination.threadID+ case nil: nil+ }}if let gestureActivities,!Set(gestureActivities.compactMap(\.cardSelectionID)).isSubset(of: Set(incomingIDs)) {diff --git a/CodexBar/Models/ActivityModels.swift b/CodexBar/Models/ActivityModels.swiftindex d1b557b..3e2e7f0 100644--- a/CodexBar/Models/ActivityModels.swift+++ b/CodexBar/Models/ActivityModels.swift@@ -119,14 +119,6 @@ nonisolated struct ActivitySnapshot: Equatable {return (Set(runningTasks.map(\.id)).subtracting(waiting), waiting)}- var primaryWaitingTask: ActivityTaskSnapshot? {- waitingTasks.first- }-- var primaryRunningTask: ActivityTaskSnapshot? {- runningTasks.first- }-var mostRecentCompletion: ActivityCompletion? {recentCompletions.first}@@ -162,43 +154,6 @@ nonisolated struct ActivitySnapshot: Equatable {var hasTaskCenterContent: Bool {hasActiveTasks || !recentCompletions.isEmpty || !recentTerminations.isEmpty}-- /// 主活动优先展示等待回应和运行中任务, 空闲时保留最近完成或终止记录- var primaryActivity: CodexPrimaryActivity {- if let task = primaryWaitingTask {- return .waiting(task)- }- if let task = primaryRunningTask {- return .running(task)- }- switch latestTerminalEvent {- case let .terminated(termination):- return .terminated(termination)- case let .completed(completion):- return .completed(completion)- case nil:- return .idle- }- }-- /// 菜单栏只短暂显示最新终态, 不改变活动卡片的历史展示规则- func statusItemActivity(at now: Date) -> CodexPrimaryActivity {- let activity = primaryActivity- switch activity {- case .completed, .terminated:- guard let expiration = statusItemActivityExpiration, now < expiration else {- return .idle- }- return activity- case .waiting, .running, .idle:- return activity- }- }-- var statusItemActivityExpiration: Date? {- guard !hasActiveTasks else { return nil }- return latestTerminalEvent?.endedAt.addingTimeInterval(10)- }}/// 快照归一后的主活动状态diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex 712a146..c5f1df9 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -86,7 +86,7 @@ private nonisolated extension String {}}-/// 模型层定义的 primary/secondary 窗口标识, 用于转换菜单栏额度偏好 (MenuBarQuotaSelection) 和查找窗口+/// 模型层定义的 primary/secondary 窗口标识, 用于选择指示器数据源和查找窗口nonisolated enum QuotaWindowKind: String, Equatable {case primarycase secondarydiff --git a/CodexBar/Models/StatusIconState.swift b/CodexBar/Models/StatusIconState.swiftindex 0a0d379..af33b3f 100644--- a/CodexBar/Models/StatusIconState.swift+++ b/CodexBar/Models/StatusIconState.swift@@ -1,35 +1,92 @@import Foundationstruct StatusIconState: Equatable {- let usesErrorImage: Bool+ let isUnavailable: Boollet ordinaryUsageAllowed: Bool?- let progress: StatusIconProgress?- let activity: ActivitySnapshot-- func symbolName(at now: Date) -> String {- switch activity.statusItemActivity(at: now) {- case .waiting: "person.badge.key.fill"- case .running: "person.badge.clock.fill"- case .completed: "person.badge.shield.checkmark.fill"- case .terminated: "person.badge.shield.exclamationmark.fill"- case .idle: usesErrorImage ? "person.slash.fill" : "person.fill"+ let progress: [StatusIconProgress?]+ private let metrics: [MenuBarIndicatorMetric]++ init(loadState: CodexLoadState, snapshot: CodexQuotaSnapshot?, configuration: MenuBarIndicatorConfiguration) {+ isUnavailable = loadState.isError || snapshot?.hasTrustedData == false+ ordinaryUsageAllowed = snapshot?.ordinaryUsageAllowed+ metrics = configuration.visibleMetrics(in: snapshot?.codexLimit?.windows ?? [])+ progress = metrics.map { StatusIconProgress(snapshot: snapshot, metric: $0) }+ }++ func toolTip(at now: Date) -> String? {+ guard !metrics.isEmpty else { return nil }+ return zip(metrics, progress).map { metric, progress in+ let value = progress?.toolTipValue(at: now) ?? "--"+ return metric.isResetTime+ ? String(localized: "menu-bar-indicator.tooltip.reset", defaultValue: "\(value)")+ : String(localized: "menu-bar-indicator.tooltip.quota", defaultValue: "\(value)")}+ .joined(separator: " | ")+ }++ func nextRefreshDate(after now: Date) -> Date? {+ progress.compactMap { $0?.nextRefreshDate(after: now) }.min()}}struct StatusIconProgress: Equatable {- let percent: Int+ enum Value: Equatable {+ case quota(Int)+ case reset(duration: TimeInterval, date: Date)+ }++ let value: Valuelet isStale: Bool- init?(snapshot: CodexQuotaSnapshot?, selection: MenuBarQuotaSelection) {- guard let targetKind = selection.windowKind,- let snapshot,- let window = snapshot.codexLimit?.window(ofKind: targetKind),- window.hasData else {- return nil+ init?(snapshot: CodexQuotaSnapshot?, metric: MenuBarIndicatorMetric) {+ guard let snapshot,+ let window = snapshot.codexLimit?.window(ofKind: metric.windowKind) else { return nil }+ if metric.isResetTime {+ guard let minutes = window.windowDurationMins, minutes > 0,+ let date = window.resetsAt, date.timeIntervalSinceReferenceDate.isFinite else { return nil }+ value = .reset(duration: Double(minutes) * 60, date: date)+ } else {+ guard window.hasData else { return nil }+ value = .quota(window.remainingPercent)}-- percent = window.remainingPercentisStale = snapshot.isRateLimitsStale}++ func percent(at now: Date) -> Double {+ switch value {+ case let .quota(percent):+ Double(percent)+ case let .reset(duration, date):+ min(100, max(0, (1 - date.timeIntervalSince(now) / duration) * 100))+ }+ }++ func nextRefreshDate(after now: Date) -> Date? {+ guard case let .reset(_, date) = value, date > now else { return nil }+ // 在剩余分钟数变化时同步刷新进度和悬停说明, 到重置时刻补齐至满值+ let remainder = date.timeIntervalSince(now).truncatingRemainder(dividingBy: 60)+ return now.addingTimeInterval(remainder > 0 ? remainder : 60)+ }++ func toolTipValue(at now: Date) -> String {+ switch value {+ case let .quota(percent):+ return CodexPercentageFormat.string(from: percent)+ case let .reset(_, date):+ guard let minutes = Int(exactly: (max(0, date.timeIntervalSince(now)) / 60).rounded(.up)) else { return "--" }+ let days = minutes / (24 * 60)+ let hours = minutes / 60 % 24+ let remainingMinutes = minutes % 60+ if days > 0 {+ return String(localized: "menu-bar-indicator.tooltip.duration", defaultValue: "\(days) \(hours) \(remainingMinutes)")+ }+ if hours > 0 {+ return String(localized: "menu-bar-indicator.tooltip.duration-hours", defaultValue: "\(hours) \(remainingMinutes)")+ }+ if remainingMinutes > 0 {+ return String(localized: "menu-bar-indicator.tooltip.duration-minutes", defaultValue: "\(remainingMinutes)")+ }+ return String(localized: "menu-bar-indicator.tooltip.reset-now")+ }+ }}diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 0b3d273..140ad3c 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -1137,23 +1137,6 @@}}},- "activity.live.current-event" : {- "extractionState" : "manual",- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Current event"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "当前事件"- }- }- }- },"activity.live.diff-updated" : {"localizations" : {"en" : {@@ -1319,13 +1302,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Finding in page"+ "value" : "Searching within page"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在网页查找内容"+ "value" : "正在检索网页"}}}@@ -1458,6 +1441,22 @@}}},+ "activity.live.image-view" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Image viewing"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "图片查看"+ }+ }+ }+ },"activity.live.interrupted" : {"localizations" : {"en" : {@@ -1682,22 +1681,6 @@}}},- "activity.live.recent-event" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Latest event"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "最近事件"- }- }- }- },"activity.live.reconnecting" : {"localizations" : {"en" : {@@ -1869,7 +1852,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "正在等待计时结束"+ "value" : "正在等待计时"}}}@@ -1906,6 +1889,54 @@}}},+ "activity.live.timer-completed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Timer ended"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "计时结束"+ }+ }+ }+ },+ "activity.live.timer-declined" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Timer declined"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "计时被拒绝"+ }+ }+ }+ },+ "activity.live.timer-failed" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Timer failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "计时失败"+ }+ }+ }+ },"activity.live.tool-completed" : {"localizations" : {"en" : {@@ -2178,6 +2209,70 @@}}},+ "activity.live.web-browse" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Web browsing"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "网页浏览"+ }+ }+ }+ },+ "activity.live.web-find" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "In-page search"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "网页检索"+ }+ }+ }+ },+ "activity.live.web-open" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Page opening"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "网页打开"+ }+ }+ }+ },+ "activity.live.web-search" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Web search"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "网页搜索"+ }+ }+ }+ },"activity.relative.completed-minutes-ago" : {"localizations" : {"en" : {@@ -4402,50 +4497,242 @@}}},- "menu-bar-quota.selection.off" : {+ "menu-bar-indicator.layout.dual" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Off"+ "value" : "Dual"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "关闭"+ "value" : "双侧"+ }+ }+ }+ },+ "menu-bar-indicator.layout.single" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Single"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "单侧"+ }+ }+ }+ },+ "menu-bar-indicator.layout.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Indicator Layout"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指示器布局"+ }+ }+ }+ },+ "menu-bar-indicator.left" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Left Content"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "左侧内容"+ }+ }+ }+ },+ "menu-bar-indicator.metric.quota" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Quota Data"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "额度数据"+ }+ }+ }+ },+ "menu-bar-indicator.metric.time" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Time Data"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重置时间"+ }+ }+ }+ },+ "menu-bar-indicator.metric.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Metric"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指标"+ }+ }+ }+ },+ "menu-bar-indicator.right" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Right Content"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "右侧内容"+ }+ }+ }+ },+ "menu-bar-indicator.single" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Indicator"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指示器"}}}},- "menu-bar-quota.selection.primary" : {+ "menu-bar-indicator.tooltip.duration" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Primary"+ "value" : "%1$lldd %2$lldh %3$lldm"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "主额度"+ "value" : "%1$lld天%2$lld小时%3$lld分钟"}}}},- "menu-bar-quota.selection.secondary" : {+ "menu-bar-indicator.tooltip.duration-hours" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Secondary"+ "value" : "%1$lldh %2$lldm"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "次额度"+ "value" : "%1$lld小时%2$lld分钟"+ }+ }+ }+ },+ "menu-bar-indicator.tooltip.duration-minutes" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lldm"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld分钟"+ }+ }+ }+ },+ "menu-bar-indicator.tooltip.quota" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Quota remaining: %@"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "额度剩余: %@"+ }+ }+ }+ },+ "menu-bar-indicator.tooltip.reset" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Time remaining: %@"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重置剩余: %@"+ }+ }+ }+ },+ "menu-bar-indicator.tooltip.reset-now" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Now"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "现在"}}}@@ -5543,7 +5830,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable automatic use of banked resets that are about to expire"+ "value" : "Enable/Disable automatic use of banked resets that are about to expire"}},"zh-Hans" : {@@ -5687,7 +5974,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Automatically Check for Updates"+ "value" : "Auto Update Checks"}},"zh-Hans" : {@@ -5703,7 +5990,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable automatic checks for new versions of CodexBar. You can still check for updates manually from the About page when this is disabled"+ "value" : "Enable/Disable automatic checks for new versions of CodexBar. You can still check for updates manually from the About page when this is disabled"}},"zh-Hans" : {@@ -5767,7 +6054,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable launching CodexBar automatically when you log in to macOS"+ "value" : "Enable/Disable launching CodexBar automatically when you log in to macOS"}},"zh-Hans" : {@@ -5863,7 +6150,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable sleep prevention while Codex tasks are running"+ "value" : "Enable/Disable sleep prevention while Codex tasks are running"}},"zh-Hans" : {@@ -5895,13 +6182,13 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable animations in the app"+ "value" : "Enable/Disable animations in the app"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "启用/禁用 App 内展示动画效果"+ "value" : "启用/禁用 App 内动画效果"}}}@@ -6034,50 +6321,34 @@}}},- "settings.menu-bar-quota.title" : {+ "settings.menu-bar-indicator.title" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Menu Bar Quota Indicator"+ "value" : "Menu Bar Indicators"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "菜单栏额度指示"+ "value" : "菜单栏指示器"}}}},- "settings.menu-bar-quota.title.help" : {+ "settings.menu-bar-indicator.title.help" : {"localizations" : {"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable quota display in the menu bar icon"+ "value" : "Enable/Disable menu bar indicators"}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "启用/禁用 菜单栏图标显示额度信息"- }- }- }- },- "settings.menu-bar-quota.window" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Quota Window"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "额度窗口"+ "value" : "启用/禁用 菜单栏指示器"}}}@@ -6354,6 +6625,22 @@}}},+ "settings.notifications.system.permission-unavailable" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Unable to verify notification permission"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法确认系统通知权限"+ }+ }+ }+ },"settings.notifications.system.title" : {"localizations" : {"en" : {@@ -6375,7 +6662,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable CodexBar notifications. The first time you turn this on, you'll need to grant notification permission in macOS"+ "value" : "Enable/Disable CodexBar notifications. The first time you turn this on, you'll need to grant notification permission in macOS"}},"zh-Hans" : {@@ -6519,7 +6806,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable data syncing across devices using your iCloud account"+ "value" : "Enable/Disable data syncing across devices using your iCloud account"}},"zh-Hans" : {@@ -6599,7 +6886,7 @@"en" : {"stringUnit" : {"state" : "translated",- "value" : "Enable or disable the glow at the top of the screen that shows Codex task status"+ "value" : "Enable/Disable the glow at the top of the screen that shows Codex task status"}},"zh-Hans" : {diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swiftindex 69242af..0c86260 100644--- a/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Localization.swift@@ -162,6 +162,8 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.image-declined")case "image-failed":String(localized: "activity.live.image-failed")+ case "image-view":+ String(localized: "activity.live.image-view")case "interrupted", "action-interrupted":String(localized: "activity.live.interrupted")case "model-changed":@@ -176,8 +178,6 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.plan-updated")case "processing":String(localized: "activity.live.processing")- case "recent-event":- String(localized: "activity.live.recent-event")case "reconnecting":String(localized: "activity.live.reconnecting")case "recovering-auth":@@ -202,6 +202,12 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.sleeping")case "thinking":String(localized: "activity.live.thinking")+ case "timer-completed":+ String(localized: "activity.live.timer-completed")+ case "timer-declined":+ String(localized: "activity.live.timer-declined")+ case "timer-failed":+ String(localized: "activity.live.timer-failed")case "tool-completed", "action-completed":String(localized: "activity.live.tool-completed")case "tool-declined", "action-declined":@@ -228,6 +234,14 @@ nonisolated extension ActivityLiveLabel {String(localized: "activity.live.waiting-input")case "waiting-service":String(localized: "activity.live.waiting-service")+ case "web-search":+ String(localized: "activity.live.web-search")+ case "web-open":+ String(localized: "activity.live.web-open")+ case "web-find":+ String(localized: "activity.live.web-find")+ case "web-browse":+ String(localized: "activity.live.web-browse")default:String(localized: "activity.live.processing")}diff --git a/CodexBar/Services/Activity/ActivityLiveLabel+Symbols.swift b/CodexBar/Services/Activity/ActivityLiveLabel+Symbols.swiftnew file mode 100644index 0000000..a487222--- /dev/null+++ b/CodexBar/Services/Activity/ActivityLiveLabel+Symbols.swift@@ -0,0 +1,60 @@+nonisolated extension ActivityLiveLabel {+ static func symbolName(for key: String) -> String {+ switch key {+ case "thinking":+ "brain"+ case "answering", "replying", "commentary":+ "text.bubble"+ case "command-read":+ "book"+ case "command-listfiles":+ "folder"+ case "command-search":+ "magnifyingglass"+ case "command-read-listfiles", "command-read-search", "command-listfiles-search", "command-read-listfiles-search":+ "doc.text.magnifyingglass"+ case "command", "executing-tool", "executing-tools", "command-completed", "command-failed", "command-declined",+ "tools-completed", "tools-failed", "tools-declined":+ "terminal"+ case "editing", "file-completed", "file-failed", "file-declined":+ "square.and.pencil"+ case "searching-web", "opening-web", "finding-web", "using-web":+ "globe"+ case "viewing-image":+ "photo"+ case "generating-image", "image-completed", "image-failed", "image-declined":+ "wand.and.stars"+ case "calling-tool", "tool-completed", "tool-failed", "tool-declined", "action-completed", "action-failed", "action-declined", "action-interrupted":+ "wrench.and.screwdriver"+ case "agent-starting", "agent-assigning", "agent-contacting", "agent-resuming", "agent-waiting", "agent-interrupting",+ "agent-closing", "agent-querying", "agent-coordinating", "agent-started", "agent-completed", "agent-failed", "agent-interrupted":+ "person.2"+ case "compacting", "compaction-completed":+ "arrow.up.right.and.arrow.down.left.rectangle"+ case "waiting-approval":+ "hand.raised"+ case "waiting-input", "waiting-form", "waiting-external", "waiting-service", "waiting-default", "request-ended":+ "bubble.left.and.bubble.right"+ case "sleeping", "timer-completed", "timer-failed", "timer-declined":+ "hourglass"+ case "running-hook", "hook-completed", "hook-failed", "hook-blocked", "hook-stopped":+ "link"+ case "retrying":+ "arrow.clockwise"+ case "recovering-auth", "auth-recovery-ended":+ "key"+ case "buffering":+ "ellipsis.bubble"+ case "plan-updated", "plan-step-completed":+ "list.bullet"+ case "diff-updated":+ "doc.text"+ case "model-changed":+ "arrow.triangle.2.circlepath"+ case "verification-needed":+ "checkmark.shield"+ default:+ "ellipsis"+ }+ }+}diff --git a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swiftindex ea5458a..c419325 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation+Items.swift@@ -9,7 +9,7 @@ nonisolated extension ActivityItem {case .contextCompaction: ActivityLiveLabel("compacting")case .commandExecution: commandLabelcase .fileChange: ActivityLiveLabel("editing")- case .webSearch: ActivityLiveLabel(webLabel)+ case .webSearch: ActivityLiveLabel(webLabels.current)case .imageView: ActivityLiveLabel("viewing-image")case .imageGeneration: ActivityLiveLabel("generating-image")case .sleep: ActivityLiveLabel("sleeping")@@ -50,16 +50,23 @@ nonisolated extension ActivityItem {commandSummary?.toolNames.joined(separator: ", ")}- private var webLabel: String {+ private var webLabels: (current: String, action: String) {switch action?.type {- case "search": "searching-web"- case "openPage": "opening-web"- case "findInPage": "finding-web"- default: "using-web"+ case "search": ("searching-web", "web-search")+ case "openPage": ("opening-web", "web-open")+ case "findInPage": ("finding-web", "web-find")+ default: ("using-web", "web-browse")}}var liveCompletionLabel: ActivityLiveLabel? {+ guard var label = completionLabel else { return nil }+ // 通用完成文案不包含操作类型, 在这里保留原操作的图标+ label.symbolName = liveLabel?.symbolName ?? label.symbolName+ return label+ }++ private var completionLabel: ActivityLiveLabel? {if type == .subAgentActivity {return ["started": "agent-started", "completed": "agent-completed", "interrupted": "agent-interrupted"][kind ?? ""].map { ActivityLiveLabel($0) }@@ -75,7 +82,12 @@ nonisolated extension ActivityItem {return ActivityLiveLabel("agent-failed")}guard isToolCall else { return nil }- let prefix = type == .fileChange ? "file" : type == .imageGeneration ? "image" : "tool"+ let prefix = switch type {+ case .fileChange: "file"+ case .imageGeneration: "image"+ case .sleep: "timer"+ default: "tool"+ }let outcome: Stringif status == "declined" {outcome = "declined"@@ -92,10 +104,12 @@ nonisolated extension ActivityItem {}let detail = switch type {case .commandExecution: commandActionDetail+ case .webSearch: ActivityLiveLabel(webLabels.action).text+ case .imageView: ActivityLiveLabel("image-view").textcase .collabAgentToolCall: String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)default: toolDisplayName}- if detail != nil, type == .commandExecution || type == .collabAgentToolCall {+ if detail != nil, [.commandExecution, .collabAgentToolCall, .webSearch, .imageView].contains(type) {return ActivityLiveLabel("action-" + outcome, detail: detail)}return ActivityLiveLabel(prefix + "-" + outcome, detail: prefix == "tool" ? detail : nil)@@ -184,12 +198,4 @@ nonisolated extension ActivityDisplayFormat {}return [running] + (extra.map { [$0] } ?? [])}-- static func liveStatus(for task: ActivityTaskSnapshot, waiting: Bool) -> String {- task.presentation?.current.text ?? ActivityLiveLabel(waiting ? "waiting-approval" : "processing").text- }-- static func recentEvent(for task: ActivityTaskSnapshot) -> String? {- task.presentation?.recent.map { ActivityLiveLabel("recent-event").text + ": " + $0.label.text }- }}diff --git a/CodexBar/Services/Activity/ActivityLivePresentation.swift b/CodexBar/Services/Activity/ActivityLivePresentation.swiftindex 8b7a742..da7c685 100644--- a/CodexBar/Services/Activity/ActivityLivePresentation.swift+++ b/CodexBar/Services/Activity/ActivityLivePresentation.swift@@ -3,10 +3,12 @@ import Foundationnonisolated struct ActivityLiveLabel: Equatable {let key: Stringvar detail: String?+ var symbolName: String- init(_ key: String, detail: String? = nil) {+ init(_ key: String, detail: String? = nil, symbolName: String? = nil) {self.key = keyself.detail = detail.map { String($0.prefix(160)) }+ self.symbolName = symbolName ?? Self.symbolName(for: key)}}@@ -143,8 +145,8 @@ nonisolated struct ActivityLivePresentation {.inputRequested, .userInputRequested:consumeRequest(notification, at: date)case .requestResolved:- if let id = params.requestId, requests.removeValue(forKey: id) != nil {- record("request-ended", at: date)+ if let id = params.requestId, let request = requests.removeValue(forKey: id) {+ record("request-ended", symbolName: request.label.symbolName, at: date)}default:consumeSupplement(notification, at: date)@@ -191,7 +193,9 @@ nonisolated struct ActivityLivePresentation {phase = Entry(label: ActivityLiveLabel("processing"), at: items.isEmpty ? date : .distantPast)phaseItemID = nil}- if let label = item.liveCompletionLabel {+ if var label = item.liveCompletionLabel {+ // 完成消息可能省略命令动作, 沿用同一个 item 已确认的操作图标+ label.symbolName = removed?.label.symbolName ?? label.symbolNamerecent = ActivityLiveEvent(label: label, at: date)}}@@ -273,8 +277,8 @@ nonisolated struct ActivityLivePresentation {}}- private mutating func record(_ key: String, detail: String? = nil, at date: Date) {- recent = ActivityLiveEvent(label: ActivityLiveLabel(key, detail: detail), at: date)+ private mutating func record(_ key: String, detail: String? = nil, symbolName: String? = nil, at date: Date) {+ recent = ActivityLiveEvent(label: ActivityLiveLabel(key, detail: detail, symbolName: symbolName), at: date)}private mutating func boundStorage() {diff --git a/CodexBar/Services/Settings/MenuBarIndicatorSettings.swift b/CodexBar/Services/Settings/MenuBarIndicatorSettings.swiftnew file mode 100644index 0000000..c06a8fb--- /dev/null+++ b/CodexBar/Services/Settings/MenuBarIndicatorSettings.swift@@ -0,0 +1,154 @@+import Combine+import Foundation+import os++nonisolated enum MenuBarIndicatorCount: Int, CaseIterable {+ case one = 1+ case two = 2++ var title: String {+ switch self {+ case .one: String(localized: "menu-bar-indicator.layout.single")+ case .two: String(localized: "menu-bar-indicator.layout.dual")+ }+ }+}++nonisolated enum MenuBarIndicatorMetric: String {+ case primaryQuota+ case secondaryQuota+ case primaryReset+ case secondaryReset++ var windowKind: QuotaWindowKind {+ switch self {+ case .primaryQuota, .primaryReset: .primary+ case .secondaryQuota, .secondaryReset: .secondary+ }+ }++ var isResetTime: Bool {+ self == .primaryReset || self == .secondaryReset+ }++ init(windowKind: QuotaWindowKind, isResetTime: Bool) {+ switch (windowKind, isResetTime) {+ case (.primary, false): self = .primaryQuota+ case (.secondary, false): self = .secondaryQuota+ case (.primary, true): self = .primaryReset+ case (.secondary, true): self = .secondaryReset+ }+ }+}++nonisolated struct MenuBarIndicatorConfiguration: Equatable {+ var isEnabled = false+ var count = MenuBarIndicatorCount.one+ var firstMetric: MenuBarIndicatorMetric?+ var secondMetric: MenuBarIndicatorMetric?++ func metrics(in windows: [QuotaWindow]) -> [MenuBarIndicatorMetric] {+ // Weekly 可能位于 primary 或 secondary, 未手动选择时按实际周期解析默认值+ let defaultWindow = windows.first { $0.windowDurationMins == 7 * 24 * 60 }?.kind+ ?? windows.first?.kind ?? .secondary+ return [+ firstMetric ?? MenuBarIndicatorMetric(windowKind: defaultWindow, isResetTime: false),+ secondMetric ?? MenuBarIndicatorMetric(windowKind: defaultWindow, isResetTime: true)+ ]+ }++ func visibleMetrics(in windows: [QuotaWindow]) -> [MenuBarIndicatorMetric] {+ isEnabled ? Array(metrics(in: windows).prefix(count.rawValue)) : []+ }+}++@MainActor+final class MenuBarIndicatorSettings: ObservableObject {+ @Published private(set) var configuration: MenuBarIndicatorConfiguration+ private let defaults: UserDefaults+ private var pendingConfiguration: MenuBarIndicatorConfiguration?+ private var publishTask: Task<Void, Never>?++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ configuration = Self.load(from: defaults)+ }++ deinit {+ publishTask?.cancel()+ }++ func refresh() {+ publish(Self.load(from: defaults))+ }++ func setCount(_ count: MenuBarIndicatorCount) {+ var next = pendingConfiguration ?? configuration+ next.count = count+ save(next)+ }++ func setEnabled(_ enabled: Bool) {+ var next = pendingConfiguration ?? configuration+ next.isEnabled = enabled+ save(next)+ }++ func setMetric(isResetTime: Bool? = nil, windowKind: QuotaWindowKind? = nil, at index: Int, windows: [QuotaWindow]) {+ guard (0 ... 1).contains(index) else { return }+ var next = pendingConfiguration ?? configuration+ let current = next.metrics(in: windows)[index]+ let metric = MenuBarIndicatorMetric(+ windowKind: windowKind ?? current.windowKind,+ isResetTime: isResetTime ?? current.isResetTime+ )+ if index == 0 {+ next.firstMetric = metric+ } else {+ next.secondMetric = metric+ }+ save(next)+ }++ private func save(_ next: MenuBarIndicatorConfiguration) {+ guard next != pendingConfiguration ?? configuration else { return }+ defaults.set(next.isEnabled, forKey: Self.enabledKey)+ defaults.set(next.count.rawValue, forKey: Self.countKey)+ defaults.set(next.firstMetric?.rawValue, forKey: Self.firstMetricKey)+ defaults.set(next.secondMetric?.rawValue, forKey: Self.secondMetricKey)+ AppLog.settings.notice(+ "菜单栏指示器变更: enabled=\(next.isEnabled), count=\(next.count.rawValue), first=\(next.firstMetric?.rawValue ?? "default", privacy: .public), second=\(next.secondMetric?.rawValue ?? "default", privacy: .public)"+ )+ publish(next)+ }++ private func publish(_ next: MenuBarIndicatorConfiguration) {+ publishTask?.cancel()+ publishTask = nil+ pendingConfiguration = nil+ guard next != configuration else { return }+ pendingConfiguration = next+ // Picker 的回调可能仍在 SwiftUI 更新中, 合并同一轮修改后再发布+ publishTask = Task { @MainActor [weak self] in+ await Task.yield()+ guard let self, !Task.isCancelled else { return }+ configuration = next+ pendingConfiguration = nil+ publishTask = nil+ }+ }++ private static func load(from defaults: UserDefaults) -> MenuBarIndicatorConfiguration {+ MenuBarIndicatorConfiguration(+ isEnabled: defaults.object(forKey: enabledKey) as? Bool ?? false,+ count: (defaults.object(forKey: countKey) as? Int).flatMap(MenuBarIndicatorCount.init(rawValue:)) ?? .one,+ firstMetric: defaults.string(forKey: firstMetricKey).flatMap(MenuBarIndicatorMetric.init(rawValue:)),+ secondMetric: defaults.string(forKey: secondMetricKey).flatMap(MenuBarIndicatorMetric.init(rawValue:))+ )+ }++ private static let enabledKey = "MenuBarIndicator.isEnabled"+ private static let countKey = "MenuBarIndicator.count"+ private static let firstMetricKey = "MenuBarIndicator.firstMetric"+ private static let secondMetricKey = "MenuBarIndicator.secondMetric"+}diff --git a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift b/CodexBar/Services/Settings/MenuBarQuotaSettings.swiftdeleted file mode 100644index 6b24383..0000000--- a/CodexBar/Services/Settings/MenuBarQuotaSettings.swift+++ /dev/null@@ -1,152 +0,0 @@-import Combine-import Foundation-import os--/// 菜单栏额度指示偏好-@MainActor-final class MenuBarQuotaSettings: ObservableObject {- @Published private(set) var selection: MenuBarQuotaSelection-- /// 关闭指示前最后一次选中的窗口, 重新开启时恢复; 随偏好持久化- private var lastWindowSelection: MenuBarQuotaSelection- private let defaults: UserDefaults- private var pendingSelection: MenuBarQuotaSelection?- private var publishSelectionTask: Task<Void, Never>?-- init(defaults: UserDefaults = .standard) {- self.defaults = defaults- let selection = Self.loadSelection(from: defaults)- self.selection = selection- lastWindowSelection = Self.loadLastWindowSelection(from: defaults, current: selection)- }-- deinit {- publishSelectionTask?.cancel()- }-- func refresh() {- let selection = Self.loadSelection(from: defaults)- rememberLastWindowSelection(selection)- publishSelection(selection)- }-- func setSelection(_ selection: MenuBarQuotaSelection) {- rememberLastWindowSelection(selection)- guard selection != effectiveSelection else {- return- }-- AppLog.settings.notice(- "菜单栏额度指示变更: selection=\(selection.rawValue, privacy: .public)"- )- saveSelection(selection)- publishSelection(selection)- }-- func setEnabled(_ enabled: Bool) {- setSelection(enabled ? lastWindowSelection : .off)- }-- /// 供设置页 Picker 展示的窗口选择: 关闭时回退到最后一次的非 off 选择- var activeWindowSelection: MenuBarQuotaSelection {- selection == .off ? lastWindowSelection : selection- }-- private func rememberLastWindowSelection(_ selection: MenuBarQuotaSelection) {- guard selection != .off, selection != lastWindowSelection else {- return- }-- lastWindowSelection = selection- defaults.set(selection.rawValue, forKey: Self.lastWindowSelectionKey)- }-- private var effectiveSelection: MenuBarQuotaSelection {- pendingSelection ?? selection- }-- private func saveSelection(_ selection: MenuBarQuotaSelection) {- defaults.set(selection.rawValue, forKey: Self.selectionKey)- }-- private func publishSelection(_ selection: MenuBarQuotaSelection) {- publishSelectionTask?.cancel()- publishSelectionTask = nil- pendingSelection = nil-- guard selection != self.selection else {- return- }-- pendingSelection = selection- publishSelectionTask = Task { @MainActor [weak self] in- await Task.yield()- guard let self, !Task.isCancelled else {- return- }-- self.selection = selection- pendingSelection = nil- publishSelectionTask = nil- }- }-- private static func loadSelection(from defaults: UserDefaults) -> MenuBarQuotaSelection {- guard let rawValue = defaults.string(forKey: selectionKey),- let selection = MenuBarQuotaSelection(rawValue: rawValue) else {- return .primary- }-- return selection- }-- private static func loadLastWindowSelection(- from defaults: UserDefaults,- current: MenuBarQuotaSelection- ) -> MenuBarQuotaSelection {- if let rawValue = defaults.string(forKey: lastWindowSelectionKey),- let selection = MenuBarQuotaSelection(rawValue: rawValue),- selection != .off {- return selection- }-- return current == .off ? .primary : current- }-- private static let selectionKey = "MenuBarQuota.selection"- private static let lastWindowSelectionKey = "MenuBarQuota.lastWindowSelection"-}--nonisolated enum MenuBarQuotaSelection: String, Identifiable {- case off- case primary- case secondary-- var id: String {- rawValue- }-- init(windowKind: QuotaWindowKind) {- switch windowKind {- case .primary:- self = .primary- case .secondary:- self = .secondary- }- }-- var fallbackTitle: String {- switch self {- case .off:- String(localized: "menu-bar-quota.selection.off")- case .primary:- String(localized: "menu-bar-quota.selection.primary")- case .secondary:- String(localized: "menu-bar-quota.selection.secondary")- }- }-- var windowKind: QuotaWindowKind? {- QuotaWindowKind(rawValue: rawValue)- }-}diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 3a528da..0df0f02 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -8,6 +8,14 @@ import UserNotifications/// 具体的通知发送与触觉反馈由 NotificationService 处理@MainActorfinal class NotificationSettings: ObservableObject {+ enum AuthorizationState: Equatable {+ case unknown+ case notDetermined+ case denied+ case authorized+ case unavailable+ }+@Published private(set) var isEnabled: Bool@Published private(set) var isLowQuotaEnabled: Bool@Published private(set) var isQuotaResetEnabled: Bool@@ -28,35 +36,35 @@ final class NotificationSettings: ObservableObject {@Published private(set) var autoResetSound: NotificationSoundOption@Published private(set) var lowBatterySound: NotificationSoundOption@Published private(set) var keepAliveLimitSound: NotificationSoundOption- @Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined+ @Published private(set) var authorizationState: AuthorizationState = .unknown- /// 系统创建通知条目后仍可能等待用户回应, 申请中也需要显示未授权引导+ /// 查询异常不代表用户关闭了权限, 只有明确未授权时才显示系统设置引导var needsAuthorization: Bool {- isEnabled && !canDeliver+ isEnabled && (authorizationState == .notDetermined || authorizationState == .denied)}- /// 总开关开启且系统已明确允许时才发送, 未决定或未知状态都按不可发送处理- var canDeliver: Bool {- guard isEnabled else {- return false- }-- switch authorizationStatus {- case .authorized, .provisional, .ephemeral:- return true+ var authorizationMessage: String? {+ guard isEnabled else { return nil }+ switch authorizationState {case .notDetermined, .denied:- return false- @unknown default:- return false+ return String(localized: "settings.notifications.system.permission-disabled")+ case .unavailable:+ return String(localized: "settings.notifications.system.permission-unavailable")+ case .unknown, .authorized:+ return nil}}+ /// 总开关开启且系统已明确允许时才发送, 未决定或未知状态都按不可发送处理+ var canDeliver: Bool {+ isEnabled && authorizationState == .authorized+ }+/// 触觉反馈不依赖系统通知授权, 但服从 App 内通知总开关var canPerformTaskHapticFeedback: Bool {isEnabled && isTaskHapticEnabled}- /// 子选项面板仅在总开关开启且授权已明确通过时可展示var canShowOptions: Bool {canDeliver}@@ -66,18 +74,29 @@ final class NotificationSettings: ObservableObject {private let defaults: UserDefaultsprivate let readAuthorizationStatus: () async -> UNAuthorizationStatus- private var authorizationTask: Task<Void, Never>?- private var isRequestingAuthorization = false+ private let requestSystemAuthorization: () async throws -> Bool+ private let sleep: (Duration) async throws -> Void+ private var authorizationRefreshTask: Task<Void, Never>?+ private var authorizationRequestTask: Task<Void, Never>?+ private var requestsAuthorizationIfNeeded = falseprivate var appActivationObserver: AnyCancellable?init(defaults: UserDefaults = .standard,readAuthorizationStatus: @escaping () async -> UNAuthorizationStatus = {await UNUserNotificationCenter.current().notificationSettings().authorizationStatus+ },+ requestSystemAuthorization: @escaping () async throws -> Bool = {+ try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])+ },+ sleep: @escaping (Duration) async throws -> Void = {+ try await Task.sleep(for: $0)}) {self.defaults = defaultsself.readAuthorizationStatus = readAuthorizationStatus+ self.requestSystemAuthorization = requestSystemAuthorization+ self.sleep = sleepisEnabled = defaults.bool(forKey: Self.enabledKey)isLowQuotaEnabled = Self.bool(from: defaults, key: Self.lowQuotaEnabledKey, defaultValue: true)isQuotaResetEnabled = Self.bool(from: defaults, key: Self.quotaResetEnabledKey, defaultValue: true)@@ -122,7 +141,8 @@ final class NotificationSettings: ObservableObject {}deinit {- authorizationTask?.cancel()+ authorizationRefreshTask?.cancel()+ authorizationRequestTask?.cancel()}// MARK: - 偏好设置@@ -135,8 +155,12 @@ final class NotificationSettings: ObservableObject {AppLog.notification.notice("通知总开关变更: enabled=\(enabled ? 1 : 0)")isEnabled = enableddefaults.set(enabled, forKey: Self.enabledKey)+ requestsAuthorizationIfNeeded = enabledif enabled {- requestAuthorization()+ refreshAuthorizationStatus()+ } else {+ authorizationRefreshTask?.cancel()+ authorizationRefreshTask = nil}}@@ -233,32 +257,68 @@ final class NotificationSettings: ObservableObject {/// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取func refreshAuthorizationStatus() {// 系统授权弹窗也会改变 App 与窗口焦点, 查询不能取消正在等待用户回应的请求- guard !isRequestingAuthorization else {+ guard authorizationRequestTask == nil else {return}- authorizationTask?.cancel()- authorizationTask = Task { @MainActor [weak self, readAuthorizationStatus] in- let status = await readAuthorizationStatus()- guard let self, !Task.isCancelled else {- return+ authorizationRefreshTask?.cancel()+ authorizationRefreshTask = Task { @MainActor [weak self, readAuthorizationStatus, sleep] in+ for delay: Duration in [.zero, .seconds(1), .seconds(3), .seconds(10)] {+ do {+ if delay > .zero {+ try await sleep(delay)+ }+ } catch {+ return+ }+ guard !Task.isCancelled else { return }+ let status = await readAuthorizationStatus()+ guard let self, !Task.isCancelled else { return }++ acceptAuthorizationStatus(status)+ let shouldRequest = requestsAuthorizationIfNeeded+ requestsAuthorizationIfNeeded = false+ if shouldRequest, isEnabled, authorizationState == .notDetermined {+ requestAuthorization()+ return+ }+ guard isEnabled, case .unavailable = authorizationState else {+ authorizationRefreshTask = nil+ return+ }}+ self?.authorizationRefreshTask = nil+ }+ }- let previousStatus = authorizationStatus- if status != previousStatus {- let details = LogFields.joined(- "from=\(String(describing: previousStatus))",- "to=\(String(describing: status))"- )- AppLog.notification.notice("通知授权变化: \(details, privacy: .public)")- }- authorizationStatus = status- // 仅依据本轮系统查询判断重设, 初始化时的 notDetermined 占位不能清掉用户开关- if status == .notDetermined {- setEnabled(false)+ private func acceptAuthorizationStatus(_ status: UNAuthorizationStatus) {+ switch status {+ case .authorized, .provisional, .ephemeral:+ updateAuthorizationState(.authorized)+ case .denied:+ updateAuthorizationState(.denied)+ case .notDetermined:+ switch authorizationState {+ case .unknown, .notDetermined:+ updateAuthorizationState(.notDetermined)+ case .authorized, .denied, .unavailable:+ // 系统服务重启后可能把已决定的权限读成未决定, 不能据此再次申请+ updateAuthorizationState(.unavailable)}+ @unknown default:+ updateAuthorizationState(.unavailable)}}+ private func updateAuthorizationState(_ state: AuthorizationState) {+ guard state != authorizationState else { return }+ let details = LogFields.joined(+ "from=\(String(describing: authorizationState))",+ "to=\(String(describing: state))"+ )+ AppLog.notification.notice("通知授权变化: \(details, privacy: .public)")+ authorizationState = state+ }+/// 引导用户到系统设置的 CodexBar 通知面板func openSystemNotificationSettings() {let candidates = [@@ -273,29 +333,27 @@ final class NotificationSettings: ObservableObject {}private func requestAuthorization() {- guard isEnabled, !isRequestingAuthorization else {+ guard isEnabled, authorizationRequestTask == nil else {return}- authorizationTask?.cancel()- isRequestingAuthorization = true- authorizationTask = Task { @MainActor [weak self] in+ authorizationRefreshTask?.cancel()+ authorizationRefreshTask = nil+ authorizationRequestTask = Task { @MainActor [weak self, requestSystemAuthorization] indo {- _ = try await UNUserNotificationCenter.current()- .requestAuthorization(options: [.alert, .sound])+ let granted = try await requestSystemAuthorization()+ guard let self, !Task.isCancelled else { return }+ acceptAuthorizationStatus(granted ? .authorized : .denied)} catch {- guard !Task.isCancelled else {- return- }+ guard let self, !Task.isCancelled else { return }let error = error as NSErrorAppLog.notification.error("通知授权请求失败: domain=\(error.domain, privacy: .public); code=\(error.code)")+ updateAuthorizationState(.unavailable)}guard let self, !Task.isCancelled else {return}- // 授权等待结束后恢复普通查询, 后续焦点刷新才能替换尚未返回的旧查询- isRequestingAuthorization = false- authorizationTask = nil+ authorizationRequestTask = nilrefreshAuthorizationStatus()}}diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex 361005e..2460e88 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -14,7 +14,9 @@ struct ActivityCard: View {@State private var wrappedHeaderKeys: Set<HeaderWrappingKey> = []@State private var retainedContent: ActivityCardContent?@State private var outgoingContent: ActivityCardContent?- @State private var cardSize = CGSize.zero+ @State private var cardWidth: CGFloat = 0+ // 高度仅用于开始手势前的校验, 不让逐帧高度变化使读取宽度的卡片重算+ @State private var cardHeight: CGFloat = 0@State private var swipe = ActivityCardSwipe()@State private var swipeContent: ActivityCardSwipeContent?@State private var gestureOwner = UUID()@@ -28,10 +30,6 @@ struct ActivityCard: View {cardPresentation.selection}- private var cardWidth: CGFloat {- cardSize.width- }-private var snapshot: ActivitySnapshot {activityMonitor.snapshot}@@ -158,7 +156,7 @@ struct ActivityCard: View {}private func beginSwipe() {- guard selection.isVisible, selection.carouselActivities.count > 1, cardWidth > 0, cardSize.height > 0 else { return }+ guard selection.isVisible, selection.carouselActivities.count > 1, cardWidth > 0, cardHeight > 0 else { return }cardPresentation.setGestureActive(true, owner: gestureOwner)let previous = swipeContentlet step = swipe.begin(width: cardWidth, now: Date())@@ -288,7 +286,8 @@ struct ActivityCard: View {if cardWidth != size.width {cancelSwipe()}- cardSize = size+ cardWidth = size.width+ cardHeight = size.height}// 外层可以收起整个区域, 内部文字始终按自然高度排版.frame(minHeight: 0, maxHeight: .infinity, alignment: .topLeading)@@ -373,36 +372,38 @@ struct ActivityCard: View {statusHeader(content)if let detail = content.detail {- HStack(alignment: .firstTextBaseline, spacing: 0) {- if content.showsCurrentEvent {- Text(verbatim: String(localized: "activity.live.current-event") + ": ")- .foregroundStyle(Color.codexSecondaryLabel)- .fixedSize()+ if let symbolName = content.detailSymbolName {+ ActivityEventRow(symbolName: symbolName) {+ eventDetail(detail, content: content)}- ActivityStatusText(- text: detail, tint: content.tint, effect: allowsAnimations ? content.statusTextEffect : .none,- lineLimit: nil, supplement: content.detailSupplement- )- .numericTransition(value: [detail, content.detailSupplement])- .fixedSize(horizontal: false, vertical: true)+ } else {+ eventDetail(detail, content: content)+ .font(MenuMetrics.bodyFont)+ .clipped()}- .font(MenuMetrics.bodyFont)- .fixedSize(horizontal: false, vertical: true)- .clipped()}if let recent = content.recent {- Text(recent)- .font(MenuMetrics.bodyFont)- .foregroundStyle(Color.codexSecondaryLabel)- .numericTransition(value: recent)- .fixedSize(horizontal: false, vertical: true)- .clipped()+ ActivityEventRow(symbolName: recent.symbolName) {+ Text(recent.text)+ .foregroundStyle(Color.codexSecondaryLabel)+ .numericTransition(value: recent.text)+ .fixedSize(horizontal: false, vertical: true)+ }}}.frame(maxWidth: .infinity, alignment: .leading)}}+ private func eventDetail(_ detail: String, content: ActivityCardContent) -> some View {+ ActivityStatusText(+ text: detail, tint: content.tint, effect: allowsAnimations ? content.statusTextEffect : .none,+ lineLimit: nil, supplement: content.detailSupplement+ )+ .numericTransition(value: [detail, content.detailSupplement])+ .fixedSize(horizontal: false, vertical: true)+ }+private func statusHeader(_ content: ActivityCardContent) -> some View {ActivityCardHeader(components: content.headerLines,@@ -556,20 +557,21 @@ struct ActivityCard: View {waiting: Bool) -> ActivityCardContent {let summary = ActivityDisplayFormat.liveSummaryComponents(for: task, now: timelineDate, waiting: waiting)+ let current = task.presentation?.current ?? ActivityLiveLabel(waiting ? "waiting-approval" : "processing")return ActivityCardContent(taskID: task.id,projectName: task.projectName,symbolName: symbolName,tint: tint,- detail: ActivityDisplayFormat.liveStatus(for: task, waiting: waiting),+ detail: current.text,tokenUsage: task.tokenUsage,header: [task.projectName ?? String(localized: "common.codex"),ActivityDisplayFormat.modelMetadata(modelName: task.modelName, effort: task.effort)].compactMap(\.self) + summary.prefix(1),- recent: ActivityDisplayFormat.recentEvent(for: task),+ recent: task.presentation?.recent?.label,detailSupplement: summary.dropFirst().first,- showsCurrentEvent: true,+ detailSymbolName: current.symbolName,statusTextEffect: allowsAnimations ? (waiting ? .ionizing(taskID: task.id) : .shimmer) : .none)}@@ -624,9 +626,9 @@ private struct ActivityCardContent: Equatable {let detail: String?var tokenUsage: TokenUsage?let header: [String]- var recent: String?+ var recent: ActivityLiveLabel?var detailSupplement: String?- var showsCurrentEvent = false+ var detailSymbolName: String?var showsKeepAliveBadge = falsevar positionText: String?var hasPin = falsediff --git a/CodexBar/Views/Menu/ActivityCardSwipe.swift b/CodexBar/Views/Menu/ActivityCardSwipe.swiftindex 7e0dc1b..7b5660d 100644--- a/CodexBar/Views/Menu/ActivityCardSwipe.swift+++ b/CodexBar/Views/Menu/ActivityCardSwipe.swift@@ -1,7 +1,11 @@+import Observationimport SwiftUI/// 拖动和收尾共用位移, 新手势可以在收尾途中接管当前画面-nonisolated struct ActivityCardSwipe: Equatable {+/// 位移由分页容器单独观察, 不让每次拖动都重新生成整张卡片的内容+@MainActor+@Observable+final class ActivityCardSwipe {private(set) var isDragging = falseprivate(set) var settlement: Settlement?private var dragOffset: CGFloat = 0@@ -18,7 +22,7 @@ nonisolated struct ActivityCardSwipe: Equatable {}/// 已确认的翻页在下一次拖动开始时换基准, 两侧内容的屏幕位置保持不变- mutating func begin(width: CGFloat, now: Date) -> Int {+ func begin(width: CGFloat, now: Date) -> Int {let step = settlement?.step ?? 0dragOffset = offset(at: now) + CGFloat(step) * widthsettlement = nil@@ -26,12 +30,12 @@ nonisolated struct ActivityCardSwipe: Equatable {return step}- mutating func move(by delta: CGFloat, width: CGFloat) {+ func move(by delta: CGFloat, width: CGFloat) {guard isDragging, delta.isFinite, width.isFinite, width > 0 else { return }dragOffset = min(width, max(-width, dragOffset + delta))}- mutating func end(velocity: CGFloat, width: CGFloat, cancelled: Bool, now: Date) {+ func end(velocity: CGFloat, width: CGFloat, cancelled: Bool, now: Date) {guard isDragging, width.isFinite, width > 0 else { return }let velocity = velocity.isFinite ? min(width * 5, max(-width * 5, velocity)) : 0let projected = dragOffset + velocity * 0.15@@ -46,7 +50,7 @@ nonisolated struct ActivityCardSwipe: Equatable {isDragging = false}- struct Settlement: Hashable {+ nonisolated struct Settlement: Hashable {let origin: CGFloatlet target: CGFloatlet step: Intdiff --git a/CodexBar/Views/Menu/ActivityEventRow.swift b/CodexBar/Views/Menu/ActivityEventRow.swiftnew file mode 100644index 0000000..145e280--- /dev/null+++ b/CodexBar/Views/Menu/ActivityEventRow.swift@@ -0,0 +1,45 @@+import SwiftUI++struct ActivityEventRow<Content: View>: View {+ @Environment(\.contentAnimationsEnabled) private var allowsAnimations++ let symbolName: String+ private let content: Content++ init(symbolName: String, @ViewBuilder content: () -> Content) {+ self.symbolName = symbolName+ self.content = content()+ }++ var body: some View {+ HStack(alignment: .firstTextBaseline, spacing: 4) {+ Group {+ if #available(macOS 26.0, *) {+ // 保留符号身份和原生字形尺寸, 避免替换时插值图片宽高比+ Image(systemName: symbolName)+ .contentTransition(allowsAnimations ? .symbolEffect(.replace.magic(fallback: .replace.downUp.wholeSymbol)) : .identity)+ } else {+ ZStack {+ Image(systemName: symbolName)+ .resizable()+ .scaledToFit()+ .frame(width: 10, height: 10)+ .id(symbolName)+ .transition(allowsAnimations ? .opacity : .identity)+ }+ }+ }+ .symbolRenderingMode(.monochrome)+ .symbolVariant(.none)+ .font(.system(size: 10, weight: .regular))+ .frame(width: 10, height: 10)+ .alignmentGuide(.firstTextBaseline) { $0[.bottom] - 1 }+ .foregroundStyle(Color.codexSecondaryLabel)+ .animation(allowsAnimations ? .codexStatus : nil, value: symbolName)+ content+ .clipped()+ }+ .font(MenuMetrics.bodyFont)+ .fixedSize(horizontal: false, vertical: true)+ }+}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 3f3b2ff..7ac83cd 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -49,8 +49,6 @@ 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 {// 订阅建立前直接读取当前状态, 避免首次打开时先显示空卡片再收回@@ -73,15 +71,7 @@ struct CodexStatusMenuView: View {.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)+ .modifier(MenuContentSizing(loadState: loadState)).padding(Metrics.padding).clipped()// 外层表面直接跟随当前高度, 不参与内容事务中的独立尺寸和位置插值@@ -97,11 +87,6 @@ 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 = 14diff --git a/CodexBar/Views/Menu/MenuPanelLayout.swift b/CodexBar/Views/Menu/MenuPanelLayout.swiftindex 944e03c..591c07a 100644--- a/CodexBar/Views/Menu/MenuPanelLayout.swift+++ b/CodexBar/Views/Menu/MenuPanelLayout.swift@@ -5,7 +5,7 @@ nonisolated struct MenuSectionVisibilityKey: LayoutValueKey {}/// 将插值高度反馈给宿主尺寸测量, 内容始终从顶部布局-struct MenuContentHeight: Animatable, ViewModifier {+private struct MenuContentHeight: Animatable, ViewModifier {var height: CGFloatvar animatableData: CGFloat {@@ -18,6 +18,31 @@ struct MenuContentHeight: Animatable, ViewModifier {}}+/// 高度反馈限制在尺寸修饰器内, 避免活动卡片逐帧伸缩时重算整个菜单+struct MenuContentSizing: ViewModifier {+ let loadState: CodexLoadState+ @State private var contentHeight: CGFloat = -1+ @State private var animatesContentHeight = false++ func body(content: Content) -> some View {+ content+ .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 ? .codexStatus : nil, value: contentHeight)+ }++ private nonisolated struct ContentGeometry: Equatable {+ let height: CGFloat+ let loadState: CodexLoadState+ }+}+/// 区域高度和相邻间距使用同一展开进度, 移除零高度区域时总高度保持不变struct MenuSectionLayout: Layout {var spacing: CGFloatdiff --git a/CodexBar/Views/Menu/StatusItemIconView.swift b/CodexBar/Views/Menu/StatusItemIconView.swiftindex dc3680b..3f0da9a 100644--- a/CodexBar/Views/Menu/StatusItemIconView.swift+++ b/CodexBar/Views/Menu/StatusItemIconView.swift@@ -3,24 +3,44 @@ import Combineimport SwiftUIfinal class StatusItemIconPresentation: ObservableObject {+ struct Indicator: Equatable {+ let percent: Double+ let isStale: Bool+ var isVisible = true+ }+struct State: Equatable {- var symbolName = "person.fill"+ var isUnavailable = falsevar isOrdinaryUsageRestricted = false- var remainingPercent = 0- var showsQuota = false- var isStale = false+ var indicators = Array(repeating: Indicator(percent: 0, isStale: false, isVisible: false), count: 2)+ var usesSplitRingStyle = false++ var showsIndicators: Bool {+ indicators.contains(where: \.isVisible)+ }++ var isStale: Bool {+ showsIndicators && indicators.filter(\.isVisible).allSatisfy(\.isStale)+ }}@Published private(set) var state = State()- func update(symbolName: String, ordinaryUsageAllowed: Bool?, percent: Int?, isStale: Bool, animated: Bool) {- let next = State(- symbolName: symbolName,- isOrdinaryUsageRestricted: ordinaryUsageAllowed == false,- remainingPercent: percent.map { min(max($0, 0), 100) } ?? state.remainingPercent,- showsQuota: percent != nil,- isStale: percent == nil ? state.isStale : isStale- )+ func update(isUnavailable: Bool, ordinaryUsageAllowed: Bool?, indicators: [Indicator?], animated: Bool) {+ var next = state+ next.isUnavailable = isUnavailable+ next.isOrdinaryUsageRestricted = ordinaryUsageAllowed == false+ // 隐藏时保留颜色和几何, 让原来的弧线连续收回至零+ if !indicators.isEmpty {+ next.usesSplitRingStyle = indicators.count > 1+ }+ for index in next.indicators.indices {+ if indicators.indices.contains(index), let indicator = indicators[index] {+ next.indicators[index] = indicator+ } else {+ next.indicators[index].isVisible = false+ }+ }guard next != state else { return }var transaction = Transaction()transaction.disablesAnimations = !animated@@ -51,48 +71,66 @@ struct StatusItemIconView: View {var body: some View {let state = presentation.state+ let symbolName = state.isUnavailable ? "person" : "person.fill"ZStack {- ZStack {- StatusItemQuotaArc()- .stroke(- Color(nsColor: .tertiaryLabelColor).opacity(0.34),- style: StrokeStyle(lineWidth: 2, lineCap: .round)- )- .opacity(state.showsQuota ? 1 : 0)- StatusItemQuotaArc(percent: state.showsQuota ? CGFloat(state.remainingPercent) : 0)- .stroke(- QuotaPalette.color(for: state.remainingPercent),- style: StrokeStyle(lineWidth: 2, lineCap: .round)- )+ ForEach(state.indicators.indices, id: \.self) { index in+ indicatorArc(state.indicators[index], index: index)}- .opacity(state.isStale ? 0.55 : 1)- .animation(.easeInOut(duration: 0.3), value: state.showsQuota)ZStack {- symbolImage(named: state.symbolName)- .id(state.symbolName)- .transition(.opacity.combined(with: .scale(- scale: 0.75,- anchor: UnitPoint(x: 0.5, y: 18.0 / 22.0)- )))+ symbolImage(named: symbolName)+ .id(symbolName)+ .transition(.opacity)}.foregroundStyle(symbolColor)- .animation(.easeInOut(duration: 0.2), value: state.symbolName)+ .animation(.easeInOut(duration: 0.2), value: state.isUnavailable)+ .animation(.easeInOut(duration: 0.2), value: state.isOrdinaryUsageRestricted).scaleEffect(- state.showsQuota ? 1 : 16.0 / 14.0,+ state.showsIndicators ? 1 : 16.0 / 14.0,anchor: UnitPoint(x: 0.5, y: 18.0 / 22.0))- .offset(y: state.showsQuota ? 0 : -1)- .opacity(state.showsQuota && state.isStale ? 0.75 : 1)+ .offset(y: state.showsIndicators ? 0 : -1)+ .opacity(state.isStale ? 0.75 : 1)+ .animation(.easeInOut(duration: 0.2), value: state.showsIndicators)}- .animation(.easeInOut(duration: 0.2), value: state.showsQuota)// 菜单栏跨桌面切换时使用图标快照, 先合成圆弧和人物以保持绘制一致.drawingGroup().frame(width: Self.size.width, height: Self.size.height).allowsHitTesting(false)}+ private func indicatorArc(_ indicator: StatusItemIconPresentation.Indicator, index: Int) -> some View {+ let usesSplitRingStyle = index > 0 || presentation.state.usesSplitRingStyle+ let isRightSide = index > 0+ let radius = usesSplitRingStyle ? Metrics.splitRadius : Metrics.singleRadius+ let fullSweepAngle = usesSplitRingStyle ? Metrics.splitSweepAngle : Metrics.singleSweepAngle+ let startAngle = -90 + (isRightSide ? 1 : -1) * fullSweepAngle / 2+ let sweepAngle = usesSplitRingStyle+ ? (isRightSide ? -1 : 1) * (fullSweepAngle / 2 - Metrics.halfGapAngle)+ : fullSweepAngle+ let style = StrokeStyle(lineWidth: Metrics.lineWidth, lineCap: .round)+ return ZStack {+ StatusItemIndicatorArc(radius: radius, startAngle: startAngle, sweepAngle: sweepAngle)+ .stroke(Color(nsColor: .tertiaryLabelColor).opacity(0.34), style: style)+ .opacity(indicator.isVisible ? 1 : 0)+ StatusItemIndicatorArc(+ radius: radius,+ startAngle: startAngle,+ sweepAngle: sweepAngle,+ percent: indicator.isVisible ? indicator.percent : 0+ )+ .stroke(QuotaPalette.color(for: Int(indicator.percent)), style: style)+ }+ .opacity(indicator.isStale ? 0.55 : 1)+ .animation(.easeInOut(duration: 0.3), value: indicator.isVisible)+ .animation(.easeInOut(duration: 0.3), value: indicator.percent)+ .animation(.easeInOut(duration: 0.3), value: usesSplitRingStyle)+ }+private var symbolColor: Color {+ if presentation.state.isUnavailable {+ return .primary+ }guard presentation.state.isOrdinaryUsageRestricted else { return .primary }return Color(hex: colorScheme == .dark ? 0xE8B27C : 0xD99858)}@@ -113,7 +151,7 @@ struct StatusItemIconView: View {return image}- // 只在符号或屏幕倍率首次出现时栅格化, 缩放过程复用普通图片+ // 只在图形或屏幕倍率首次出现时栅格化, 缩放过程复用普通图片let renderer = ImageRenderer(content: symbolContent(named: name).foregroundStyle(.white).environment(\.displayScale, displayScale))@@ -126,7 +164,7 @@ struct StatusItemIconView: View {}private static func symbolContent(named name: String) -> some View {- // 基线固定人物主体, 徽章的下伸部分不参与居中计算+ // 固定基线作为缩放锚点, 保持指示器切换时人物主体的位置稳定Color.clear.frame(width: size.width, height: size.height).alignmentGuide(.firstTextBaseline) { _ in 18 }@@ -136,29 +174,44 @@ struct StatusItemIconView: View {.symbolRenderingMode(.monochrome)}}-}-private nonisolated struct StatusItemQuotaArc: Shape {- var percent: CGFloat = 100+ private enum Metrics {+ static let singleRadius: CGFloat = 11+ static let splitRadius: CGFloat = 11.5+ static let lineWidth: CGFloat = 2+ static let centerGap: CGFloat = 1+ static let singleSweepAngle = 180 + 2 * asin(5.0 / 11.0) * 180 / .pi+ static let splitSweepAngle = 234.0+ static let halfGapAngle = asin((lineWidth + centerGap) / (2 * splitRadius)) * 180 / .pi+ }+}- var animatableData: CGFloat {- get { percent }- set { percent = newValue }+private nonisolated struct StatusItemIndicatorArc: Shape {+ var radius: CGFloat+ var startAngle: Double+ var sweepAngle: Double+ var percent: Double = 100++ var animatableData: AnimatablePair<AnimatablePair<CGFloat, Double>, AnimatablePair<Double, Double>> {+ get { AnimatablePair(AnimatablePair(radius, startAngle), AnimatablePair(sweepAngle, percent)) }+ set {+ radius = newValue.first.first+ startAngle = newValue.first.second+ sweepAngle = newValue.second.first+ percent = newValue.second.second+ }}func path(in _: CGRect) -> Path {guard percent > 0 else { return Path() }- let radius: CGFloat = 11- let extraAngle = asin(CGFloat(5) / radius) * 180 / .pi- let startAngle = 180 + extraAngle- let endAngle = startAngle - (180 + 2 * extraAngle) * min(percent, 100) / 100+ let endAngle = startAngle + sweepAngle * min(percent, 100) / 100var path = Path()path.addArc(center: CGPoint(x: 13, y: 14),radius: radius,- startAngle: .degrees(-Double(startAngle)),- endAngle: .degrees(-Double(endAngle)),- clockwise: false+ startAngle: .degrees(startAngle),+ endAngle: .degrees(endAngle),+ clockwise: sweepAngle < 0)return path}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 0197ef5..cde0e8b 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -13,7 +13,7 @@ struct AppSettingsView: View {@StateObject private var codexVersions = CodexVersionViewModel()@ObservedObject var syncSettings: SyncSettings@ObservedObject var globalHotKeySettings: GlobalHotKeySettings- @ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings+ let menuBarIndicatorSettings: MenuBarIndicatorSettings@ObservedObject var appearanceSettings: AppearanceSettingslet mainPanelSettings: MainPanelSettingslet taskGlowSettings: TaskGlowSettings@@ -87,7 +87,7 @@ struct AppSettingsView: View {.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ inloginItemSettings.refresh()syncSettings.refresh()- menuBarQuotaSettings.refresh()+ menuBarIndicatorSettings.refresh()appearanceSettings.refresh()mainPanelSettings.refresh()taskGlowSettings.refresh()@@ -296,7 +296,7 @@ private extension AppSettingsView {LiquidGlassDivider()automaticUpdateCheckRowLiquidGlassDivider()- menuBarQuotaRow+ menuBarIndicatorRowLiquidGlassDivider()hotKeyRow}@@ -425,65 +425,8 @@ private extension AppSettingsView {HotKeyRecorderRow(settings: globalHotKeySettings)}- var menuBarQuotaRow: some View {- let isEnabled = isMenuBarQuotaEnabled-- return SettingsToggleRow(- icon: "gauge.with.dots.needle.50percent",- title: "settings.menu-bar-quota.title",- help: "settings.menu-bar-quota.title.help",- isOn: Binding(- get: { isMenuBarQuotaEnabled },- set: { menuBarQuotaSettings.setEnabled($0) }- )- ) {- if isEnabled {- Picker(- "settings.menu-bar-quota.window",- selection: Binding(- get: { menuBarQuotaSettings.activeWindowSelection },- set: { menuBarQuotaSettings.setSelection($0) }- )- ) {- ForEach(menuBarQuotaWindowOptions) { option in- Text(option.title).tag(option.selection)- }- }- .labelsHidden()- .pickerStyle(.menu)- .controlSize(.small)- .font(SettingsRowMetrics.controlFont.monospacedDigit())- .fixedSize(horizontal: true, vertical: false)- .transition(.opacity.combined(with: .move(edge: .trailing)))- }- }- .animation(Metrics.statusAnimation, value: isEnabled)- }-- var menuBarQuotaWindowOptions: [MenuBarQuotaOption] {- var options = (statusViewModel.snapshot?.codexLimit?.windows ?? [])- .map { window in- MenuBarQuotaOption(- selection: MenuBarQuotaSelection(windowKind: window.kind),- title: window.label- )- }-- let selectedWindow = menuBarQuotaSettings.activeWindowSelection- if !options.contains(where: { $0.selection == selectedWindow }) {- options.append(- MenuBarQuotaOption(- selection: selectedWindow,- title: selectedWindow.fallbackTitle- )- )- }-- return options- }-- var isMenuBarQuotaEnabled: Bool {- menuBarQuotaSettings.selection != .off+ var menuBarIndicatorRow: some View {+ MenuBarIndicatorSettingsRow(settings: menuBarIndicatorSettings, onOptionsAction: onOptionsAction)}var mainPanelLayoutRow: some View {@@ -928,8 +871,8 @@ private extension AppSettingsView {}}- if notificationSettings.needsAuthorization {- NotificationAuthorizationRow(settings: notificationSettings)+ if let message = notificationSettings.authorizationMessage {+ NotificationAuthorizationRow(settings: notificationSettings, message: message).transition(.identity).transaction { transaction intransaction.animation = nil@@ -1139,12 +1082,3 @@ private struct SyncRowState {isActive && (isSyncing || lastSyncText != nil)}}--private struct MenuBarQuotaOption: Identifiable {- let selection: MenuBarQuotaSelection- let title: String-- var id: String {- selection.id- }-}diff --git a/CodexBar/Views/Settings/AutoResetOptionsView.swift b/CodexBar/Views/Settings/AutoResetOptionsView.swiftindex 9f060a5..80b26e1 100644--- a/CodexBar/Views/Settings/AutoResetOptionsView.swift+++ b/CodexBar/Views/Settings/AutoResetOptionsView.swift@@ -20,32 +20,27 @@ struct AutoResetOptionsView: View {),options: AutoResetLeadTime.allCases,label: { $0.title },- width: Metrics.pickerWidth,alignment: .trailing)}.frame(height: Metrics.rowHeight).padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)- .frame(width: Metrics.panelWidth, alignment: .topLeading)- .sidePanelChrome(cornerRadius: Metrics.cornerRadius)- }-- static var initialPanelSize: CGSize {- CGSize(- width: Metrics.panelWidth,- height: Metrics.verticalPadding * 2- + Metrics.rowHeight+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading)+ .fixedSize(horizontal: true, vertical: true)+ .sidePanelChrome(cornerRadius: Metrics.cornerRadius)}private enum Metrics {- static let panelWidth: CGFloat = 250static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingstatic let rowHeight = SettingsOptionsPanelMetrics.rowHeightstatic let controlSpacing = SettingsOptionsPanelMetrics.controlSpacing- static let pickerWidth: CGFloat = 88+static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius}}diff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftindex b88f738..aa98c8b 100644--- a/CodexBar/Views/Settings/KeepAliveOptionsView.swift+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -1,36 +1,42 @@import SwiftUI/// 防睡眠子选项面板, 挂在设置窗口右侧, 顶边对齐设置页的防睡眠主开关行-/// 行样式与度量沿用通知子面板, 只有面板宽度按内容收窄struct KeepAliveOptionsView: View {@ObservedObject var keepAliveController: KeepAliveController@ObservedObject var protectionSettings: ProtectionSettings+ @Environment(\.contentAnimationsEnabled) private var allowsAnimationsvar body: some View {- VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ VStack(alignment: .leading, spacing: 0) {waitingApprovalRowdisplayAwakeRow+ .padding(.top, Metrics.rowSpacing)maximumDurationRow+ .padding(.top, Metrics.rowSpacing)protectionRow+ .padding(.top, Metrics.rowSpacing)// 无内置电池时隐藏低电量保护行- if keepAliveController.hasBattery {- lowBatteryRow- }+ lowBatteryRow+ .settingsOptionsReveal(+ isExpanded: keepAliveController.hasBattery,+ height: Metrics.rowHeight,+ spacing: Metrics.rowSpacing+ )}.padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)- .frame(width: Metrics.panelWidth, alignment: .topLeading)- .sidePanelChrome(cornerRadius: Metrics.cornerRadius)- }-- /// 按有电池时的最大内容给初始值, 实际高度在展开前由 fitting size 覆盖- static var initialPanelSize: CGSize {- CGSize(- width: Metrics.panelWidth,- height: Metrics.verticalPadding * 2- + Metrics.rowHeight * CGFloat(Metrics.maximumRowCount)- + Metrics.rowSpacing * CGFloat(Metrics.maximumRowCount - 1)+ .fixedSize(horizontal: false, vertical: true)+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading+ )+ .fixedSize(horizontal: true, vertical: true)+ .settingsOptionsPanel(height: SettingsOptionsPanelMetrics.height(rowCount: keepAliveController.hasBattery ? 5 : 4))+ .animation(+ allowsAnimations ? SettingsOptionsPanelMetrics.contentAnimation : nil,+ value: keepAliveController.hasBattery)}@@ -110,7 +116,6 @@ struct KeepAliveOptionsView: View {selection: selection,options: options,label: { $0[keyPath: label] },- width: Metrics.pickerWidth,alignment: .trailing)}@@ -148,15 +153,10 @@ struct KeepAliveOptionsView: View {}private enum Metrics {- static let panelWidth: CGFloat = 280- /// 有内置电池设备的行数, 无内置电池时少一行低电量保护- static let maximumRowCount = 5static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingstatic let rowHeight = SettingsOptionsPanelMetrics.rowHeightstatic let controlSpacing = SettingsOptionsPanelMetrics.controlSpacing- static let pickerWidth: CGFloat = 88- static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius}}diff --git a/CodexBar/Views/Settings/MainPanelOptionsView.swift b/CodexBar/Views/Settings/MainPanelOptionsView.swiftindex 80be14e..1f2e140 100644--- a/CodexBar/Views/Settings/MainPanelOptionsView.swift+++ b/CodexBar/Views/Settings/MainPanelOptionsView.swift@@ -67,7 +67,12 @@ struct MainPanelOptionsView: View {}.padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)- .frame(width: Metrics.panelWidth, alignment: .topLeading)+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading+ )+ .fixedSize(horizontal: true, vertical: true).sidePanelChrome(cornerRadius: Metrics.cornerRadius).onDisappear {dragState = nil@@ -75,15 +80,6 @@ struct MainPanelOptionsView: View {}}- static var initialPanelSize: CGSize {- CGSize(- width: Metrics.panelWidth,- height: Metrics.verticalPadding * 2- + Metrics.rowHeight * CGFloat(MainPanelSection.allCases.count)- + Metrics.dividerHeight * CGFloat(MainPanelSection.allCases.count - 1)- )- }-private func sectionRow(_ section: MainPanelSection) -> some View {let isVisible = settings.layout.isVisible(section)let canToggle = !isVisible || settings.layout.visibleSections.count > 1@@ -213,7 +209,6 @@ struct MainPanelOptionsView: View {}private enum Metrics {- static let panelWidth: CGFloat = 270static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingstatic let rowHeight: CGFloat = 28diff --git a/CodexBar/Views/Settings/MenuBarIndicatorOptionsView.swift b/CodexBar/Views/Settings/MenuBarIndicatorOptionsView.swiftnew file mode 100644index 0000000..1104147--- /dev/null+++ b/CodexBar/Views/Settings/MenuBarIndicatorOptionsView.swift@@ -0,0 +1,162 @@+import SwiftUI++struct MenuBarIndicatorSettingsRow: View {+ @ObservedObject var settings: MenuBarIndicatorSettings+ let onOptionsAction: (SettingsOptionsPanelAction) -> Void+ @State private var anchorProvider = ScreenFrameProvider()++ var body: some View {+ SettingsToggleRow(+ icon: "gauge.with.dots.needle.50percent",+ title: "settings.menu-bar-indicator.title",+ help: "settings.menu-bar-indicator.title.help",+ isOn: Binding(+ get: { settings.configuration.isEnabled },+ set: { settings.setEnabled($0) }+ )+ ) {+ SettingsOptionsButton(isAvailable: settings.configuration.isEnabled) {+ onOptionsAction(.toggle(panel: .menuBarIndicator, anchorProvider: anchorProvider))+ }+ }+ .background {+ ScreenFrameReader(provider: anchorProvider)+ }+ .onChange(of: settings.configuration.isEnabled) { _, isEnabled in+ if !isEnabled {+ onOptionsAction(.close(panel: .menuBarIndicator))+ }+ }+ }+}++struct MenuBarIndicatorOptionsView: View {+ @ObservedObject var settings: MenuBarIndicatorSettings+ @ObservedObject var statusViewModel: CodexStatusViewModel+ @Environment(\.contentAnimationsEnabled) private var allowsAnimations++ var body: some View {+ let windows = statusViewModel.snapshot?.codexLimit?.windows ?? []+ let metrics = Array(settings.configuration.metrics(in: windows).enumerated())++ HStack(alignment: .top, spacing: SettingsOptionsPanelMetrics.controlSpacing) {+ VStack(alignment: .leading, spacing: 0) {+ Text("menu-bar-indicator.layout.title")+ .frame(height: SettingsOptionsPanelMetrics.rowHeight)++ ForEach(metrics, id: \.offset) { index, _ in+ Text(indicatorTitle(at: index))+ .contentTransition(.opacity)+ .settingsOptionsReveal(+ isExpanded: index < settings.configuration.count.rawValue,+ height: SettingsOptionsPanelMetrics.rowHeight,+ spacing: SettingsOptionsPanelMetrics.rowSpacing+ )+ }+ }+ .font(SettingsRowMetrics.captionFont)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: true, vertical: false)++ Spacer(minLength: 8)++ VStack(alignment: .trailing, spacing: 0) {+ SettingsOptionsPicker(+ title: "menu-bar-indicator.layout.title",+ selection: Binding(+ get: { settings.configuration.count },+ set: { settings.setCount($0) }+ ),+ options: MenuBarIndicatorCount.allCases,+ label: { $0.title },+ alignment: .trailing+ )+ .frame(height: SettingsOptionsPanelMetrics.rowHeight)++ Grid(+ alignment: .trailing,+ horizontalSpacing: SettingsOptionsPanelMetrics.controlSpacing,+ verticalSpacing: 0+ ) {+ ForEach(metrics, id: \.offset) { index, metric in+ indicatorControls(index: index, metric: metric)+ }+ }+ }+ .fixedSize(horizontal: true, vertical: false)+ }+ .padding(.horizontal, SettingsOptionsPanelMetrics.horizontalPadding)+ .padding(.vertical, SettingsOptionsPanelMetrics.verticalPadding)+ .fixedSize(horizontal: false, vertical: true)+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading+ )+ .fixedSize(horizontal: true, vertical: true)+ .settingsOptionsPanel(height: panelHeight)+ .animation(+ allowsAnimations ? SettingsOptionsPanelMetrics.contentAnimation : nil,+ value: settings.configuration.count+ )+ }++ private var panelHeight: CGFloat {+ SettingsOptionsPanelMetrics.height(rowCount: settings.configuration.count.rawValue + 1)+ }++ private func indicatorTitle(at index: Int) -> LocalizedStringResource {+ index == 0+ ? (settings.configuration.count == .one ? "menu-bar-indicator.single" : "menu-bar-indicator.left")+ : "menu-bar-indicator.right"+ }++ private func indicatorControls(index: Int, metric: MenuBarIndicatorMetric) -> some View {+ let windows = statusViewModel.snapshot?.codexLimit?.windows ?? []+ var windowKinds = windows.map(\.kind)+ if !windowKinds.contains(metric.windowKind) {+ windowKinds.append(metric.windowKind)+ }++ return GridRow {+ SettingsOptionsPicker(+ title: "menu-bar-indicator.metric.title",+ selection: Binding(+ get: { metric.isResetTime },+ set: { settings.setMetric(isResetTime: $0, at: index, windows: windows) }+ ),+ options: [false, true],+ label: { $0 ? String(localized: "menu-bar-indicator.metric.time") : String(localized: "menu-bar-indicator.metric.quota") },+ alignment: .trailing+ )+ .fixedSize(horizontal: true, vertical: false)+ .settingsOptionsReveal(+ isExpanded: index < settings.configuration.count.rawValue,+ height: SettingsOptionsPanelMetrics.rowHeight,+ spacing: SettingsOptionsPanelMetrics.rowSpacing+ )+ Picker(indicatorTitle(at: index), selection: Binding(+ get: { metric.windowKind },+ set: { settings.setMetric(windowKind: $0, at: index, windows: windows) }+ )) {+ ForEach(windowKinds, id: \.self) { kind in+ let window = windows.first { $0.kind == kind }+ Text(window?.label ?? (kind == .primary ? "5 Hours" : "Weekly"))+ .tag(kind)+ .disabled(window == nil)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .controlSize(.small)+ .font(SettingsRowMetrics.controlFont.monospacedDigit())+ .fixedSize(horizontal: true, vertical: false)+ .settingsOptionsReveal(+ isExpanded: index < settings.configuration.count.rawValue,+ height: SettingsOptionsPanelMetrics.rowHeight,+ spacing: SettingsOptionsPanelMetrics.rowSpacing+ )+ .gridColumnAlignment(.trailing)+ }+ }+}diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex aa19290..2d50cec 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -8,6 +8,7 @@ struct NotificationOptionsView: View {@ObservedObject var tuiNotificationSettings: TUINotificationSettings@ObservedObject var autoResetSettings: AutoResetSettings@ObservedObject var keepAliveController: KeepAliveController+ @Environment(\.contentAnimationsEnabled) private var allowsAnimations@State private var previewSound: NSSound?var body: some View {@@ -25,23 +26,39 @@ struct NotificationOptionsView: View {}.padding(.horizontal, Metrics.horizontalPadding).padding(.vertical, Metrics.verticalPadding)- .frame(width: Metrics.panelWidth, alignment: .topLeading)- .sidePanelChrome(cornerRadius: Metrics.cornerRadius)- .onDisappear(perform: stopPreview)- }-- static var initialPanelSize: CGSize {- CGSize(- width: Metrics.panelWidth,- height: Metrics.verticalPadding * 2- + Metrics.notificationRowHeight * CGFloat(Metrics.notificationRowCount)- + Metrics.rowHeight * CGFloat(Metrics.optionRowCount)- + Metrics.rowSpacing * CGFloat(Metrics.totalRowCount - 1)+ .fixedSize(horizontal: false, vertical: true)+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading)+ .fixedSize(horizontal: true, vertical: true)+ .settingsOptionsPanel(height: SettingsOptionsPanelMetrics.height(+ rowCount: soundRowVisibility.count + 2,+ secondaryRowCount: soundRowVisibility.filter(\.self).count+ ))+ .animation(+ allowsAnimations ? SettingsOptionsPanelMetrics.contentAnimation : nil,+ value: soundRowVisibility+ )+ .onDisappear(perform: stopPreview)}// MARK: - 各通知行+ private var soundRowVisibility: [Bool] {+ [+ notificationSettings.isTaskCompletionEnabled,+ notificationSettings.isTaskWaitingEnabled,+ notificationSettings.isLowQuotaEnabled,+ notificationSettings.isQuotaResetEnabled,+ notificationSettings.isCreditExpiryEnabled,+ autoResetSettings.isEnabled && notificationSettings.isAutoResetEnabled,+ keepAliveController.isLowBatteryProtectionEnabled && notificationSettings.isLowBatteryEnabled,+ keepAliveController.isMaximumDurationEnabled && notificationSettings.isKeepAliveLimitEnabled+ ]+ }+private var lowQuotaRow: some View {notificationOptionRow(title: "settings.notifications.low-quota.title",@@ -317,9 +334,10 @@ struct NotificationOptionsView: View {Spacer(minLength: 0)- if showsSoundControls {- accessory()- }+ accessory()+ .opacity(showsSoundControls ? 1 : 0)+ .disabled(!showsSoundControls)+ .allowsHitTesting(showsSoundControls)Toggle(title, isOn: isOn).labelsHidden()@@ -329,32 +347,30 @@ struct NotificationOptionsView: View {}.frame(height: Metrics.rowHeight)- if showsSoundControls {- HStack(spacing: Metrics.notificationControlSpacing) {- Text("settings.notifications.sound.title")- .font(SettingsRowMetrics.captionFont)- .foregroundStyle(.tertiary)+ HStack(spacing: Metrics.notificationControlSpacing) {+ Text("settings.notifications.sound.title")+ .font(SettingsRowMetrics.captionFont)+ .foregroundStyle(.tertiary)- Spacer(minLength: 8)+ Spacer(minLength: 8)- soundMenu(selection: sound)+ soundMenu(selection: sound)- Button {- playPreview(for: sound.wrappedValue)- } label: {- Image(systemName: "play.circle")- .font(.system(size: Metrics.soundPreviewIconSize))- .frame(- width: Metrics.soundPreviewButtonSize,- height: Metrics.soundPreviewButtonSize- )- }- .buttonStyle(.borderless)- .foregroundStyle(canPreviewSound ? .secondary : .tertiary)- .disabled(!canPreviewSound)+ Button {+ playPreview(for: sound.wrappedValue)+ } label: {+ Image(systemName: "play.circle")+ .font(.system(size: Metrics.soundPreviewIconSize))+ .frame(+ width: Metrics.soundPreviewButtonSize,+ height: Metrics.soundPreviewButtonSize+ )}- .frame(height: Metrics.soundRowHeight)+ .buttonStyle(.borderless)+ .foregroundStyle(canPreviewSound ? .secondary : .tertiary)+ .disabled(!canPreviewSound)}+ .settingsOptionsReveal(isExpanded: showsSoundControls, height: Metrics.soundRowHeight)}}@@ -368,8 +384,7 @@ struct NotificationOptionsView: View {title: title,selection: selection,options: options,- label: label,- width: Metrics.pickerWidth+ label: label)}@@ -390,18 +405,30 @@ struct NotificationOptionsView: View {}}} label: {- Text(selection.wrappedValue.localizedTitle)+ Text(Self.soundMenuSizingTitle).font(SettingsRowMetrics.captionFont)- .foregroundStyle(.secondary)- .lineLimit(1)- .frame(maxWidth: .infinity, alignment: .trailing)+ .hidden()+ .overlay(alignment: .trailing) {+ Text(selection.wrappedValue.localizedTitle)+ .font(SettingsRowMetrics.captionFont)+ .foregroundStyle(.secondary)+ }.contentShape(Rectangle())}.menuStyle(.borderlessButton).controlSize(.small)- .frame(width: Metrics.soundMenuWidth, alignment: .trailing)}+ private static let soundMenuSizingTitle: String = {+ let sounds = [NotificationSoundOption.systemDefault, .silent]+ + NotificationSoundOption.categories.flatMap(\.sounds)+ let font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize)+ return sounds.map(\.localizedTitle).max {+ ($0 as NSString).size(withAttributes: [.font: font]).width+ < ($1 as NSString).size(withAttributes: [.font: font]).width+ } ?? ""+ }()+private func soundMenuButton(_ sound: NotificationSoundOption,selection: Binding<NotificationSoundOption>@@ -441,44 +468,39 @@ struct NotificationOptionsView: View {}private enum Metrics {- static let panelWidth: CGFloat = 320static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding- static let notificationRowCount = 8- static let optionRowCount = 2- static let totalRowCount = notificationRowCount + optionRowCountstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingstatic let rowHeight = SettingsOptionsPanelMetrics.rowHeightstatic let soundRowHeight = SettingsOptionsPanelMetrics.secondaryRowHeight- static let notificationRowHeight = rowHeight + soundRowHeightstatic let notificationControlSpacing = SettingsOptionsPanelMetrics.controlSpacing- static let pickerWidth: CGFloat = 68- static let soundMenuWidth: CGFloat = 160static let soundPreviewButtonSize: CGFloat = 18static let soundPreviewIconSize: CGFloat = 13static let statusIconSize: CGFloat = 16- static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius}}struct NotificationAuthorizationRow: View {let settings: NotificationSettings+ let message: Stringvar body: some View {SettingsIndentedRow {- Text("settings.notifications.system.permission-disabled")+ Text(message).font(SettingsRowMetrics.captionFont).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)Spacer(minLength: 8)- Button("common.action.open-system-settings") {- settings.openSystemNotificationSettings()+ if settings.needsAuthorization {+ Button("common.action.open-system-settings") {+ settings.openSystemNotificationSettings()+ }+ .controlSize(.small)+ .font(SettingsRowMetrics.controlFont)+ .fixedSize()}- .controlSize(.small)- .font(SettingsRowMetrics.controlFont)- .fixedSize()}}}diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex 9400c7d..a267cec 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -42,8 +42,10 @@ struct SettingsOptionsButton: View {}}-/// 设置子选项面板共用的尺寸, 仅面板和 picker 的宽度由各面板定义+/// 设置子选项面板共用的间距和控件高度enum SettingsOptionsPanelMetrics {+ static let minimumWidth: CGFloat = 300+ static let maximumWidth: CGFloat = 380static let horizontalPadding: CGFloat = 12static let verticalPadding: CGFloat = 10static let rowSpacing: CGFloat = 5@@ -52,16 +54,94 @@ enum SettingsOptionsPanelMetrics {static let secondaryRowHeight: CGFloat = 18static let controlSpacing: CGFloat = 6static let cornerRadius: CGFloat = 12+ static let resizeDuration: TimeInterval = 0.24+ static let contentAnimation = Animation.easeInOut(duration: resizeDuration)++ static func height(rowCount: Int, secondaryRowCount: Int = 0) -> CGFloat {+ verticalPadding * 2+ + rowHeight * CGFloat(rowCount)+ + rowSpacing * CGFloat(max(rowCount - 1, 0))+ + secondaryRowHeight * CGFloat(secondaryRowCount)+ }+}++@MainActor+final class SettingsOptionsPanelSizeObserver {+ let onChange: @MainActor (CGSize) -> Void++ init(onChange: @escaping @MainActor (CGSize) -> Void) {+ self.onChange = onChange+ }+}++extension EnvironmentValues {+ @Entry var settingsOptionsPanelSizeObserver: SettingsOptionsPanelSizeObserver?+}++extension View {+ func settingsOptionsReveal(isExpanded: Bool, height: CGFloat, spacing: CGFloat = 0) -> some View {+ frame(height: height)+ .padding(.top, spacing)+ .frame(height: isExpanded ? height + spacing : 0, alignment: .top)+ .clipped()+ .disabled(!isExpanded)+ .allowsHitTesting(isExpanded)+ }++ func settingsOptionsPanel(height: CGFloat) -> some View {+ modifier(SettingsOptionsPanelSurface(height: height))+ }+}++private struct SettingsOptionsPanelSurface: AnimatableModifier {+ var height: CGFloat+ @Environment(\.settingsOptionsPanelSizeObserver) private var sizeObserver++ var animatableData: CGFloat {+ get { height }+ set { height = newValue }+ }++ func body(content: Content) -> some View {+ let panelHeight = height.rounded(.up)+ content+ .frame(height: panelHeight, alignment: .top)+ .sidePanelChrome(cornerRadius: SettingsOptionsPanelMetrics.cornerRadius)+ .background {+ GeometryReader { geometry in+ SettingsOptionsPanelSizeReporter(+ size: CGSize(width: geometry.size.width, height: panelHeight),+ observer: sizeObserver+ )+ }+ }+ // 窗口高度向上取整, 取整余量和布局尚未同步的高度差都留在底部+ .frame(minHeight: 0, maxHeight: .infinity, alignment: .top)+ }+}++private struct SettingsOptionsPanelSizeReporter: NSViewRepresentable {+ let size: CGSize+ let observer: SettingsOptionsPanelSizeObserver?++ func makeNSView(context _: Context) -> NSView {+ NSView()+ }++ func updateNSView(_: NSView, context _: Context) {+ // 使用同一帧的可见高度调整窗口, 避免叠加 AppKit 尺寸动画+ observer?.onChange(size)+ }}/// 子选项面板共用的下拉选择器-/// 各面板仅定义宽度和对齐方式, 其余样式共用+/// 子面板按最长选项使用固有宽度, 主设置页可显式指定宽度struct SettingsOptionsPicker<Option: Hashable>: View {let title: LocalizedStringResource@Binding var selection: Optionlet options: [Option]let label: (Option) -> String- let width: CGFloat+ var width: CGFloat?var alignment: Alignment = .centervar body: some View {diff --git a/CodexBar/Views/Settings/TaskGlowOptionsView.swift b/CodexBar/Views/Settings/TaskGlowOptionsView.swiftindex fc2067e..7cbe74c 100644--- a/CodexBar/Views/Settings/TaskGlowOptionsView.swift+++ b/CodexBar/Views/Settings/TaskGlowOptionsView.swift@@ -23,7 +23,6 @@ struct TaskGlowOptionsView: View {),options: TaskGlowAnimationSpeed.allCases,label: { $0.title },- width: 100,alignment: .trailing)}@@ -36,7 +35,6 @@ struct TaskGlowOptionsView: View {),options: TaskGlowSettings.terminalDurationOptions,label: { String(localized: "duration.seconds", defaultValue: "\(Int($0), specifier: "%lld")") },- width: 100,alignment: .trailing)}@@ -51,16 +49,15 @@ struct TaskGlowOptionsView: View {.controlSize(.small).padding(.horizontal, SettingsOptionsPanelMetrics.horizontalPadding).padding(.vertical, SettingsOptionsPanelMetrics.verticalPadding)- .frame(width: Self.panelWidth)+ .frame(+ minWidth: SettingsOptionsPanelMetrics.minimumWidth,+ maxWidth: SettingsOptionsPanelMetrics.maximumWidth,+ alignment: .topLeading+ )+ .fixedSize(horizontal: true, vertical: true).sidePanelChrome(cornerRadius: SettingsOptionsPanelMetrics.cornerRadius)}- private static let panelWidth: CGFloat = 280-- static var initialPanelSize: CGSize {- CGSize(width: panelWidth, height: 220)- }-private func optionRow(_ title: LocalizedStringResource, help: LocalizedStringResource, @ViewBuilder content: () -> some View) -> some View {HStack(spacing: SettingsOptionsPanelMetrics.controlSpacing) {SettingsHelpLabel(title: title, help: help)@@ -78,12 +75,18 @@ private struct TaskGlowBrightnessControl: View {var body: some View {HStack(spacing: 7) {TaskGlowBrightnessSlider(value: $value)- .frame(width: 88, height: 22)- Text(value, format: .percent.precision(.fractionLength(0)))+ .frame(minWidth: 88, maxWidth: .infinity)+ .frame(height: 22)+ Text(1.0, format: .percent.precision(.fractionLength(0))).font(SettingsRowMetrics.captionFont.monospacedDigit())- .foregroundStyle(Color.codexSecondaryLabel)- .numericTransition(value: Int((value * 100).rounded()), comparison: value)- .frame(width: 32, alignment: .trailing)+ .hidden()+ .overlay(alignment: .trailing) {+ Text(value, format: .percent.precision(.fractionLength(0)))+ .font(SettingsRowMetrics.captionFont.monospacedDigit())+ .foregroundStyle(Color.codexSecondaryLabel)+ .numericTransition(value: Int((value * 100).rounded()), comparison: value)+ }+ .fixedSize()}.padding(.horizontal, 8).frame(height: 22)@@ -197,7 +200,7 @@ private struct TaskGlowColorHexField: View {Text(verbatim: "#").font(SettingsRowMetrics.captionFont.monospaced()).foregroundStyle(.secondary)- .frame(width: 8)+ .fixedSize()TaskGlowHexInput(text: $draft,@@ -216,7 +219,7 @@ private struct TaskGlowColorHexField: View {.strokeBorder(isValid ? .clear : .red, lineWidth: 1).allowsHitTesting(false)}- .frame(width: 74)+ .fixedSize(horizontal: true, vertical: false)}.onChange(of: settings.appearance.colors[role]) { _, _ inif !isFocused {@@ -234,6 +237,15 @@ private struct TaskGlowHexInput: NSViewRepresentable {let onEndEditing: (String) -> Stringlet onCancel: () -> String+ func sizeThatFits(_: ProposedViewSize, nsView: NSTextField, context _: Context) -> CGSize? {+ let sizingField = NSTextField(string: "FFFFFF")+ sizingField.controlSize = nsView.controlSize+ sizingField.font = nsView.font+ sizingField.bezelStyle = nsView.bezelStyle+ // NSTextField 默认没有固有宽度, 用完整颜色值的 cell 尺寸保留编辑空间+ return sizingField.cell?.cellSize+ }+func makeCoordinator() -> Coordinator {Coordinator(self)}diff --git a/CodexBar/Views/Shared/QuotaPalette.swift b/CodexBar/Views/Shared/QuotaPalette.swiftindex 6288bab..ba05dad 100644--- a/CodexBar/Views/Shared/QuotaPalette.swift+++ b/CodexBar/Views/Shared/QuotaPalette.swift@@ -3,11 +3,16 @@ import SwiftUI/// 额度颜色按剩余百分比分档, 菜单栏图标与面板额度条共用同一套阈值和色值nonisolated enum QuotaPalette {static let tiers: [(lowerBound: Int, hex: Int)] = [- (0, 0xEE3F3F),- (20, 0xFF7A59),- (40, 0xF5B041),- (60, 0x5DADE2),- (80, 0x16A085)+ (0, 0xE8605B),+ (10, 0xF57349),+ (20, 0xFD8733),+ (30, 0xFD9A10),+ (40, 0xF2AA06),+ (50, 0xE0B503),+ (60, 0xC7BB06),+ (70, 0xA5BC1A),+ (80, 0x7CB939),+ (90, 0x46B250)]static func hex(for percent: Int) -> Int {diff --git a/Config/BuildNumber.xcconfig b/Config/BuildNumber.xcconfigindex ac86891..46740ff 100644--- a/Config/BuildNumber.xcconfig+++ b/Config/BuildNumber.xcconfig@@ -1,3 +1,3 @@// 请勿手动修改// Do not modify manually-CURRENT_PROJECT_VERSION = 315\ No newline at end of file+CURRENT_PROJECT_VERSION = 381\ No newline at end of filediff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex ed24eb5..802c96d 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@#include "BuildNumber.xcconfig"-MARKETING_VERSION = 5.2.1+MARKETING_VERSION = 5.2.2diff --git a/Tests/App/Activity/ActivityLiveLabelTests.swift b/Tests/App/Activity/ActivityLiveLabelTests.swiftindex 56c0c56..79475e7 100644--- a/Tests/App/Activity/ActivityLiveLabelTests.swift+++ b/Tests/App/Activity/ActivityLiveLabelTests.swift@@ -44,7 +44,7 @@ struct ActivityLiveLabelTests {"""#)#expect(item.commandSummary == nil)#expect(item.liveLabel == ActivityLiveLabel("command", detail: ActivityLiveLabel("actions-read").text))- #expect(item.liveCompletionLabel == ActivityLiveLabel("action-completed", detail: ActivityLiveLabel("actions-read").text))+ #expect(item.liveCompletionLabel == ActivityLiveLabel("action-completed", detail: ActivityLiveLabel("actions-read").text, symbolName: "terminal"))}@Test(arguments: ["git", "git, ls"])@@ -135,6 +135,23 @@ struct ActivityLiveLabelTests {#expect(ActivityDisplayFormat.toolActionText(itemType: nil, toolName: nil) == nil)}+ @Test(arguments: [+ (#""type":"webSearch","action":{"type":"search"}"#, "web-search"),+ (#""type":"webSearch","action":{"type":"openPage"}"#, "web-open"),+ (#""type":"webSearch","action":{"type":"findInPage"}"#, "web-find"),+ (#""type":"webSearch""#, "web-browse"),+ (#""type":"webSearch","action":{"type":"future"}"#, "web-browse"),+ (#""type":"imageView""#, "image-view")+ ], ["completed", "failed", "declined"])+ func namedOperationsPreserveResultText(example: (fields: String, actionKey: String), status: String) throws {+ let item = try TestFixtures.decode(ActivityItem.self, """+ {"id":"operation",\(example.fields),"status":"\(status)"}+ """)+ let expected = ActivityLiveLabel("action-" + status, detail: ActivityLiveLabel(example.actionKey).text)+ #expect(item.liveCompletionLabel?.detail == expected.detail)+ #expect(item.liveCompletionLabel?.text == expected.text)+ }+@Test(arguments: ["completed", "failed", "declined", "unknown"])func toolOutcomeDoesNotAssumeSuccess(status: String) {let item = ActivityItem(id: "image", type: .imageGeneration, status: status)diff --git a/Tests/App/Activity/ActivityLivePresentationTests.swift b/Tests/App/Activity/ActivityLivePresentationTests.swiftindex edab5fe..ca1ea12 100644--- a/Tests/App/Activity/ActivityLivePresentationTests.swift+++ b/Tests/App/Activity/ActivityLivePresentationTests.swift@@ -155,8 +155,10 @@ struct ActivityLivePresentationTests {#expect(try summary(reducer).current.key == (method == "item/tool/requestUserInput" ? "waiting-input" : "waiting-approval"))#expect(try summary(reducer).hasBlockingInputRequest == (method == "item/tool/requestUserInput"))#expect(reducer.states.values.first?.isWaitingApproval == approval)+ let symbolName = try summary(reducer).current.symbolName_ = try reducer.consume(message("serverRequest/resolved", #""requestId":7"#, turn: false), now: now.addingTimeInterval(3))#expect(try summary(reducer).waiting == nil)+ #expect(try summary(reducer).recent?.label.symbolName == symbolName)}@Test(arguments: ["thread-a", "thread-b"])@@ -236,6 +238,7 @@ struct ActivityLivePresentationTests {#expect(try summary(reducer).current.key == "processing")let recent = try summary(reducer).recent#expect(recent?.label.key == "action-completed")+ #expect(recent?.label.symbolName == "book")let events = try reducer.consume(message("item/reasoning/summaryTextDelta", #""itemId":"reason","delta":"Test response""#), now: now.addingTimeInterval(2))#expect(events.isEmpty)#expect(try summary(reducer).current.key == "thinking")@@ -317,6 +320,7 @@ struct ActivityLivePresentationTests {let recent = try #require(try summary(reducer).recent)#expect(recent.label.key == "action-" + status)#expect(recent.label.detail == String(localized: "activity.live.actions-read-search"))+ #expect(recent.label.symbolName == "doc.text.magnifyingglass")let action = String(localized: "activity.live.actions-read-search")let expected = switch status {case "completed": String(localized: "activity.live.action-completed", defaultValue: "\(action)")@@ -327,6 +331,53 @@ struct ActivityLivePresentationTests {#expect(!recent.label.text.contains(" • "))}+ @Test(arguments: [+ (#""type":"commandExecution","commandActions":[{"type":"read"}]"#, ("book", "action")),+ (#""type":"commandExecution","commandActions":[{"type":"listFiles"}]"#, ("folder", "action")),+ (#""type":"commandExecution","commandActions":[{"type":"search"}]"#, ("magnifyingglass", "action")),+ (#""type":"commandExecution","commandActions":[{"type":"read"},{"type":"search"}]"#, ("doc.text.magnifyingglass", "action")),+ (#""type":"commandExecution""#, ("terminal", "command")),+ (#""type":"fileChange""#, ("square.and.pencil", "file")),+ (#""type":"webSearch","action":{"type":"search"}"#, ("globe", "action")),+ (#""type":"webSearch","action":{"type":"openPage"}"#, ("globe", "action")),+ (#""type":"webSearch","action":{"type":"findInPage"}"#, ("globe", "action")),+ (#""type":"webSearch""#, ("globe", "action")),+ (#""type":"webSearch","action":{"type":"future"}"#, ("globe", "action")),+ (#""type":"imageView""#, ("photo", "action")),+ (#""type":"imageGeneration""#, ("wand.and.stars", "image")),+ (#""type":"sleep""#, ("hourglass", "timer")),+ (#""type":"mcpToolCall","server":"server","tool":"tool""#, ("wrench.and.screwdriver", "tool")),+ (#""type":"mcpToolCall""#, ("wrench.and.screwdriver", "tool")),+ (#""type":"dynamicToolCall","tool":"tool""#, ("wrench.and.screwdriver", "tool")),+ (#""type":"dynamicToolCall""#, ("wrench.and.screwdriver", "tool")),+ (#""type":"collabAgentToolCall","tool":"spawnAgent""#, ("person.2", "action"))+ ], ["completed", "failed", "declined"])+ func toolResultsKeepOperationAndOutcome(example: (fields: String, expected: (symbol: String, completionPrefix: String)), status: String) throws {+ for observesStart in [false, true] {+ var live = ActivityLivePresentation()+ if observesStart {+ try live.consume(message("item/started", """+ "item":{"id":"operation",\(example.fields),"status":"inProgress"}+ """), at: now)+ #expect(live.summary.current.symbolName == example.expected.symbol)+ }+ try live.consume(message("item/completed", """+ "item":{"id":"operation",\(example.fields),"status":"\(status)"}+ """), at: now.addingTimeInterval(1))+ #expect(live.summary.recent?.label.symbolName == example.expected.symbol)+ #expect(live.summary.recent?.label.key == example.expected.completionPrefix + "-" + status)+ }+ }++ @Test func partialCompletionKeepsItsOwnOperationSymbolWhileAnotherToolRuns() throws {+ var live = ActivityLivePresentation()+ try live.consume(message("item/started", #""item":{"id":"read","type":"commandExecution","commandActions":[{"type":"read"}]}"#), at: now)+ try live.consume(message("item/started", #""item":{"id":"edit","type":"fileChange"}"#), at: now.addingTimeInterval(1))+ try live.consume(message("item/completed", #""item":{"id":"read","type":"commandExecution","status":"failed"}"#), at: now.addingTimeInterval(2))+ #expect(live.summary.current.symbolName == "square.and.pencil")+ #expect(live.summary.recent?.label.symbolName == "book")+ }+struct CommandPresentationCase {let command: Stringlet started: ActivityLiveLabel@@ -399,7 +450,7 @@ struct ActivityLivePresentationTests {let detail = String(localized: ActivityDisplayFormat.agentAction(tool: tool).action)#expect(presentation.current.key == "processing")#expect(presentation.toolCount == 0)- #expect(presentation.recent?.label == ActivityLiveLabel("action-interrupted", detail: detail))+ #expect(presentation.recent?.label == ActivityLiveLabel("action-interrupted", detail: detail, symbolName: "person.2"))#expect(presentation.recent?.label.text == String(localized: "activity.live.action-interrupted", defaultValue: "\(detail)"))#expect(ActivityItem(id: "child", type: .subAgentActivity, kind: "interrupted").liveCompletionLabel?.key == "agent-interrupted")}@@ -606,7 +657,7 @@ struct ActivityLivePresentationTests {#expect(snapshot.waitingCount == 0)#expect(snapshot.panelWaitingTasks.count == 1)#expect(snapshot.panelRunningTasks.isEmpty)- #expect(snapshot.primaryActivity == .running(task.snapshot))+ #expect(snapshot.runningTasks == [task.snapshot])var selection = ActivityCardSelection()selection.update(snapshot: snapshot, isHealthy: true, now: now)#expect(selection.current == .waiting(task.snapshot))diff --git a/Tests/App/CodexStatus/CodexQuotaAndIdentityTests.swift b/Tests/App/CodexStatus/CodexQuotaAndIdentityTests.swiftindex 483e9ca..5ee3bb5 100644--- a/Tests/App/CodexStatus/CodexQuotaAndIdentityTests.swift+++ b/Tests/App/CodexStatus/CodexQuotaAndIdentityTests.swift@@ -21,10 +21,9 @@ struct CodexQuotaAndIdentityTests {#expect(snapshot.ordinaryUsageAllowed == allowed)for percent: Int? in [100, 0, nil] {presentation.update(- symbolName: "person.fill",+ isUnavailable: false,ordinaryUsageAllowed: snapshot.ordinaryUsageAllowed,- percent: percent,- isStale: false,+ indicators: [percent.map { StatusItemIconPresentation.Indicator(percent: Double($0), isStale: false) }],animated: false)#expect(presentation.state.isOrdinaryUsageRestricted == (allowed == false))diff --git a/Tests/App/Notifications/NotificationSettingsTests.swift b/Tests/App/Notifications/NotificationSettingsTests.swiftnew file mode 100644index 0000000..dc3d148--- /dev/null+++ b/Tests/App/Notifications/NotificationSettingsTests.swift@@ -0,0 +1,351 @@+import Foundation+import Testing+import UserNotifications++struct NotificationSettingsTests {+ @Test(arguments: [UNAuthorizationStatus.authorized, .provisional])+ func temporaryFailurePreservesPreferencesAndRecovers(status: UNAuthorizationStatus) async throws {+ let fixture = try AuthorizationFixture(status: status)+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.settings.setTaskCompletionEnabled(false)++ fixture.client.status = .notDetermined+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.pendingSleep != nil }+ #expect(fixture.settings.authorizationState == .unavailable)+ #expect(fixture.settings.isEnabled)+ #expect(fixture.preferences.defaults.bool(forKey: "Notification.isEnabled"))+ #expect(!fixture.settings.isTaskCompletionEnabled)+ #expect(!fixture.settings.canShowOptions)+ #expect(!fixture.settings.needsAuthorization)+ #expect(!fixture.settings.canDeliver)+ #expect(fixture.settings.authorizationMessage == String(localized: "settings.notifications.system.permission-unavailable"))++ fixture.client.status = status+ fixture.client.resumeSleep()+ try await fixture.wait { fixture.settings.canDeliver }+ #expect(fixture.settings.authorizationMessage == nil)+ #expect(fixture.client.delays == [.seconds(1)])+ #expect(fixture.client.requestCount == 0)+ #expect(!fixture.settings.isTaskCompletionEnabled)+ }++ @Test(arguments: [UNAuthorizationStatus.notDetermined, .authorized, .denied])+ func enablingReadsCurrentStatusBeforeRequesting(status: UNAuthorizationStatus) async throws {+ let fixture = try AuthorizationFixture(status: status, enabled: false)+ defer { fixture.cleanUp() }+ #expect(!fixture.settings.needsAuthorization)+ #expect(fixture.settings.authorizationMessage == nil)+ fixture.settings.setEnabled(true)+ let expectedState: NotificationSettings.AuthorizationState = status == .denied ? .denied : .authorized+ try await fixture.wait { fixture.settings.authorizationState == expectedState }+ #expect(fixture.client.requestCount == (status == .notDetermined ? 1 : 0))+ #expect(fixture.settings.isEnabled)+ #expect(fixture.settings.needsAuthorization == (status == .denied))+ #expect(fixture.settings.canDeliver == (status != .denied))+ }++ @Test func ordinaryRefreshNeverRequestsInitialPermission() async throws {+ let fixture = try AuthorizationFixture(status: .notDetermined)+ defer { fixture.cleanUp() }+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.authorizationState == .notDetermined }+ #expect(fixture.settings.isEnabled)+ #expect(fixture.settings.needsAuthorization)+ #expect(fixture.settings.authorizationMessage == String(localized: "settings.notifications.system.permission-disabled"))+ #expect(!fixture.settings.canDeliver)+ #expect(fixture.client.requestCount == 0)+ #expect(fixture.client.delays.isEmpty)+ }++ @Test func rejectingInitialPromptIsAConfirmedDenial() async throws {+ let fixture = try AuthorizationFixture(status: .notDetermined, enabled: false)+ defer { fixture.cleanUp() }+ fixture.client.requestGranted = false+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.settings.authorizationState == .denied }+ #expect(fixture.settings.needsAuthorization)+ #expect(!fixture.settings.canDeliver)+ #expect(!fixture.settings.canShowOptions)+ #expect(fixture.client.requestCount == 1)+ #expect(fixture.client.delays.isEmpty)+ }++ @Test func explicitDenialClosesOptionsWithoutChangingPreference() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.client.status = .denied+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.authorizationState == .denied }+ #expect(fixture.settings.isEnabled)+ #expect(fixture.settings.needsAuthorization)+ #expect(!fixture.settings.canShowOptions)+ #expect(!fixture.settings.canDeliver)+ #expect(fixture.client.requestCount == 0)+ #expect(fixture.client.delays.isEmpty)+ }++ @Test func recoveryHasFiniteRetriesAndCanRestartOnLaterRefresh() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.client.suspendsSleep = false+ fixture.client.status = .notDetermined+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.readCount == 5 }+ try await Task.sleep(for: .milliseconds(20))+ #expect(fixture.client.readCount == 5)+ #expect(fixture.client.delays == [.seconds(1), .seconds(3), .seconds(10)])+ #expect(fixture.settings.authorizationState == .unavailable)+ #expect(!fixture.settings.canDeliver)+ #expect(fixture.client.requestCount == 0)++ fixture.client.status = .authorized+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.canDeliver }+ #expect(fixture.client.readCount == 6)+ }++ @Test func denialAfterFailureReplacesUnconfirmedMessage() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.client.status = .notDetermined+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.pendingSleep != nil }+ #expect(fixture.settings.authorizationMessage == String(localized: "settings.notifications.system.permission-unavailable"))+ #expect(!fixture.settings.needsAuthorization)++ fixture.client.status = .denied+ fixture.client.resumeSleep()+ try await fixture.wait { fixture.settings.authorizationState == .denied }+ #expect(fixture.settings.authorizationMessage == String(localized: "settings.notifications.system.permission-disabled"))+ #expect(fixture.settings.needsAuthorization)+ #expect(!fixture.settings.canShowOptions)+ #expect(!fixture.settings.canDeliver)+ #expect(fixture.settings.isEnabled)+ #expect(fixture.preferences.defaults.bool(forKey: "Notification.isEnabled"))+ #expect(fixture.client.requestCount == 0)+ }++ @Test func togglingAfterFailureDoesNotRequestPermissionAgain() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.client.status = .notDetermined+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.pendingSleep != nil }+ fixture.settings.setEnabled(false)+ fixture.client.resumeSleep()+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.client.delays.count == 2 }+ #expect(fixture.settings.authorizationState == .unavailable)+ #expect(fixture.client.requestCount == 0)+ #expect(fixture.settings.isEnabled)+ #expect(!fixture.settings.canShowOptions)+ #expect(!fixture.settings.canDeliver)+ #expect(!fixture.settings.needsAuthorization)+ }++ @Test func failedAuthorizationRequestIsUnavailableUntilConfirmed() async throws {+ let fixture = try AuthorizationFixture(status: .notDetermined, enabled: false)+ defer { fixture.cleanUp() }+ fixture.client.requestError = NSError(domain: UNErrorDomain, code: 1)+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.client.pendingSleep != nil }+ #expect(fixture.settings.authorizationState == .unavailable)+ #expect(fixture.settings.isEnabled)+ #expect(!fixture.settings.needsAuthorization)+ #expect(!fixture.settings.canDeliver)+ #expect(!fixture.settings.canShowOptions)+ #expect(fixture.settings.authorizationMessage == String(localized: "settings.notifications.system.permission-unavailable"))++ fixture.settings.setEnabled(false)+ fixture.client.resumeSleep()+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.client.delays.count == 2 }+ #expect(fixture.client.requestCount == 1)+ fixture.client.status = .authorized+ fixture.client.resumeSleep()+ try await fixture.wait { fixture.settings.canDeliver }+ #expect(fixture.settings.canShowOptions)+ }++ @Test func staleQueryCannotOverwriteNewerDecision() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ fixture.client.suspendsRead = true+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.pendingRead != nil }++ fixture.client.suspendsRead = false+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.canDeliver }+ fixture.client.resumeRead(.denied)+ try await Task.sleep(for: .milliseconds(20))+ #expect(fixture.settings.canDeliver)+ #expect(!fixture.settings.needsAuthorization)+ }++ @Test func disablingCancelsRecoveryAndLaterReadsDoNotEnablePreference() async throws {+ let fixture = try AuthorizationFixture()+ defer { fixture.cleanUp() }+ try await fixture.confirmAuthorization()+ fixture.client.status = .notDetermined+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.client.pendingSleep != nil }+ fixture.settings.setEnabled(false)+ #expect(fixture.settings.authorizationMessage == nil)+ fixture.client.status = .authorized+ fixture.client.resumeSleep()+ try await Task.sleep(for: .milliseconds(20))+ #expect(fixture.client.readCount == 2)++ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.authorizationState == .authorized }+ #expect(!fixture.settings.isEnabled)+ #expect(!fixture.preferences.defaults.bool(forKey: "Notification.isEnabled"))+ #expect(!fixture.settings.canDeliver)+ #expect(!fixture.settings.canShowOptions)+ }++ @Test func refreshDuringEnableQueryPreservesRequestIntent() async throws {+ let fixture = try AuthorizationFixture(status: .notDetermined, enabled: false)+ defer { fixture.cleanUp() }+ fixture.client.suspendsRead = true+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.client.pendingRead != nil }+ fixture.client.suspendsRead = false+ fixture.settings.refreshAuthorizationStatus()+ try await fixture.wait { fixture.settings.canDeliver }+ fixture.client.resumeRead(.denied)+ try await Task.sleep(for: .milliseconds(20))+ #expect(fixture.client.requestCount == 1)+ #expect(fixture.settings.canDeliver)+ }++ @Test func pendingSystemPromptSurvivesRefreshWithoutOverwritingManualDisable() async throws {+ let fixture = try AuthorizationFixture(status: .notDetermined, enabled: false)+ defer { fixture.cleanUp() }+ fixture.client.suspendsRequest = true+ fixture.settings.setEnabled(true)+ try await fixture.wait { fixture.client.pendingRequest != nil }+ fixture.settings.refreshAuthorizationStatus()+ fixture.settings.setEnabled(false)+ fixture.settings.setEnabled(true)+ fixture.settings.setEnabled(false)+ fixture.settings.refreshAuthorizationStatus()+ #expect(fixture.client.readCount == 1)+ #expect(fixture.client.requestCount == 1)++ fixture.client.status = .authorized+ fixture.client.resumeRequest()+ try await fixture.wait { fixture.settings.authorizationState == .authorized }+ #expect(!fixture.settings.isEnabled)+ #expect(!fixture.preferences.defaults.bool(forKey: "Notification.isEnabled"))+ #expect(!fixture.settings.canDeliver)+ #expect(!fixture.settings.canShowOptions)+ }+}++private final class AuthorizationFixture {+ let preferences: TestPreferences+ let client: AuthorizationClient+ let settings: NotificationSettings++ init(status: UNAuthorizationStatus = .authorized, enabled: Bool = true) throws {+ preferences = try TestPreferences()+ preferences.defaults.set(enabled, forKey: "Notification.isEnabled")+ client = AuthorizationClient(status: status)+ settings = NotificationSettings(+ defaults: preferences.defaults,+ readAuthorizationStatus: client.read,+ requestSystemAuthorization: client.request,+ sleep: client.sleep+ )+ }++ func confirmAuthorization() async throws {+ settings.refreshAuthorizationStatus()+ try await wait { self.settings.canDeliver }+ }++ func wait(_ condition: () -> Bool) async throws {+ try #require(try await waitForCondition(timeout: .seconds(2), pollInterval: .milliseconds(5), condition))+ }++ func cleanUp() {+ settings.setEnabled(false)+ client.resumeRead(.notDetermined)+ client.resumeSleep()+ client.resumeRequest()+ preferences.remove()+ }+}++private final class AuthorizationClient {+ var status: UNAuthorizationStatus+ var requestError: NSError?+ var requestGranted = true+ var suspendsRead = false+ var suspendsSleep = true+ var suspendsRequest = false+ var readCount = 0+ var requestCount = 0+ var delays: [Duration] = []+ var pendingRead: CheckedContinuation<UNAuthorizationStatus, Never>?+ var pendingSleep: CheckedContinuation<Void, Never>?+ var pendingRequest: CheckedContinuation<Bool, any Error>?++ init(status: UNAuthorizationStatus) {+ self.status = status+ }++ func read() async -> UNAuthorizationStatus {+ readCount += 1+ if suspendsRead {+ return await withCheckedContinuation { pendingRead = $0 }+ }+ return status+ }++ func request() async throws -> Bool {+ requestCount += 1+ if suspendsRequest {+ return try await withCheckedThrowingContinuation { pendingRequest = $0 }+ }+ if let requestError {+ throw requestError+ }+ status = requestGranted ? .authorized : .denied+ return requestGranted+ }++ func sleep(for duration: Duration) async throws {+ delays.append(duration)+ if suspendsSleep {+ await withCheckedContinuation { pendingSleep = $0 }+ }+ try Task.checkCancellation()+ }++ func resumeRead(_ status: UNAuthorizationStatus) {+ let continuation = pendingRead+ pendingRead = nil+ continuation?.resume(returning: status)+ }++ func resumeSleep() {+ let continuation = pendingSleep+ pendingSleep = nil+ continuation?.resume()+ }++ func resumeRequest() {+ let continuation = pendingRequest+ pendingRequest = nil+ continuation?.resume(returning: true)+ }+}diff --git a/Tests/App/Presentation/ActivityCardSwipeTests.swift b/Tests/App/Presentation/ActivityCardSwipeTests.swiftindex 0c741ac..251fd27 100644--- a/Tests/App/Presentation/ActivityCardSwipeTests.swift+++ b/Tests/App/Presentation/ActivityCardSwipeTests.swift@@ -7,7 +7,7 @@ struct ActivityCardSwipeTests {private let now = Date(timeIntervalSince1970: 1800000000)@Test func draggingFollowsSmallDeltasAndCanReverseBeforeCommitting() {- var swipe = ActivityCardSwipe()+ let swipe = ActivityCardSwipe()_ = swipe.begin(width: 400, now: now)swipe.move(by: -3, width: 400)#expect(swipe.offset(at: now) == -3)@@ -38,10 +38,11 @@ struct ActivityCardSwipeTests {swipe.move(by: delta * 300, width: 400)swipe.end(velocity: delta * 1200, width: 400, cancelled: true, now: now)#expect(swipe.settlement?.step == 0)+ #expect(swipe.offset(at: now.addingTimeInterval(1)) == 0)}@Test func reversingVelocityCanCancelButCannotChooseAnUnseenOppositePage() {- var swipe = ActivityCardSwipe()+ let swipe = ActivityCardSwipe()_ = swipe.begin(width: 400, now: now)swipe.move(by: -140, width: 400)swipe.end(velocity: 1800, width: 400, cancelled: false, now: now)@@ -49,7 +50,7 @@ struct ActivityCardSwipeTests {}@Test func newGestureRebasesUnfinishedPageWithoutChangingItsVisiblePosition() {- var swipe = ActivityCardSwipe()+ let swipe = ActivityCardSwipe()_ = swipe.begin(width: 400, now: now)swipe.move(by: -120, width: 400)swipe.end(velocity: 0, width: 400, cancelled: false, now: now)@@ -62,29 +63,9 @@ struct ActivityCardSwipeTests {#expect(swipe.settlement == nil)}- @Test func offscreenHeightTracksBothDirectionsAndReturnsWithThePages() {- var swipe = ActivityCardSwipe()- #expect(renderedHeight(swipe) == 100)- _ = swipe.begin(width: 400, now: now)- // 使用整点高度, 避免离屏宿主的 backing scale 影响断言- swipe.move(by: -40, width: 400)- #expect(renderedHeight(swipe) == 108)- swipe.move(by: 20, width: 400)- #expect(renderedHeight(swipe) == 104)- swipe.move(by: 220, width: 400)- #expect(abs(renderedHeight(swipe) - 80) < 0.5)- swipe.end(velocity: 0, width: 400, cancelled: true, now: now)- var returned = ActivityCardSwipe()- _ = returned.begin(width: 400, now: now)- returned.move(by: swipe.offset(at: now.addingTimeInterval(1)), width: 400)- #expect(abs(renderedHeight(returned) - 100) < 0.5)- returned.move(by: -160, width: 320)- #expect(abs(renderedHeight(returned, width: 320) - 140) < 0.5)- }-@Test(arguments: [-1, 1])func offscreenRebasingPreservesInterpolatedHeight(direction: Int) {- var swipe = ActivityCardSwipe()+ let swipe = ActivityCardSwipe()_ = swipe.begin(width: 400, now: now)swipe.move(by: CGFloat(direction) * 200, width: 400)let height = renderedHeight(swipe)@@ -96,11 +77,39 @@ struct ActivityCardSwipeTests {#expect(abs(renderedHeight(swipe, pageHeights: heights) - heights[1]) < 0.5)}- private func renderedHeight(_ swipe: ActivityCardSwipe, pageHeights: [CGFloat] = [60, 100, 180], width: CGFloat = 400) -> CGFloat {+ @Test(arguments: [CGFloat(320), 400])+ func mountedPagesFollowEveryDragWithoutReplacingTheRootView(width: CGFloat) {+ let swipe = ActivityCardSwipe()+ var currentPageX: CGFloat = 0let root = ActivityCardSwipePages(swipe: swipe, width: 400) { step in- Color.clear.frame(height: pageHeights[step + 1])+ Color.clear.frame(height: [60.0, 100, 180][step + 1])+ .onGeometryChange(for: CGFloat.self) { $0.frame(in: .global).minX } action: {+ if step == 0 {+ currentPageX = $0+ }+ }}.frame(width: width)+ let host = NSHostingView(rootView: root)+ host.setFrameSize(host.fittingSize)+ host.layoutSubtreeIfNeeded()+ #expect(host.frame.height == 100)+ _ = swipe.begin(width: width, now: now)+ for (delta, offset, height) in [(-0.1, -0.1, 108.0), (0.05, -0.05, 104), (0.55, 0.5, 80), (-1, -0.5, 140)] {+ swipe.move(by: delta * width, width: width)+ host.layoutSubtreeIfNeeded()+ host.setFrameSize(host.fittingSize)+ host.layoutSubtreeIfNeeded()+ #expect(abs(host.frame.height - height) < 0.5)+ #expect(abs(currentPageX - offset * width) < 0.5)+ }+ }++ private func renderedHeight(_ swipe: ActivityCardSwipe, pageHeights: [CGFloat] = [60, 100, 180]) -> CGFloat {+ let root = ActivityCardSwipePages(swipe: swipe, width: 400) { step in+ Color.clear.frame(height: pageHeights[step + 1])+ }+ .frame(width: 400)return NSHostingView(rootView: root).fittingSize.height}}diff --git a/Tests/App/Presentation/ActivityPresentationTests.swift b/Tests/App/Presentation/ActivityPresentationTests.swiftindex ec90c89..df128f8 100644--- a/Tests/App/Presentation/ActivityPresentationTests.swift+++ b/Tests/App/Presentation/ActivityPresentationTests.swift@@ -169,15 +169,15 @@ struct ActivityPresentationTests {}}- @Test func statusItemTerminalExpiresAtTenSecondsWhileCardKeepsHistory() {+ @Test func completedTaskRemainsAvailableInCardHistory() {let completion = ActivityCompletion(id: UUID(), projectName: nil, modelName: nil, effort: nil,completedAt: TestFixtures.now, duration: 30, threadID: "completed-thread")let snapshot = ActivitySnapshot(waitingTasks: [], runningTasks: [], recentCompletions: [completion], recentTerminations: [])- #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(9.999)) == .completed(completion))- #expect(snapshot.statusItemActivity(at: TestFixtures.now.addingTimeInterval(10)) == .idle)- #expect(snapshot.primaryActivity == .completed(completion))+ var selection = ActivityCardSelection()+ selection.update(snapshot: snapshot, isHealthy: true, now: TestFixtures.now)+ #expect(selection.current == .completed(completion))#expect(snapshot.hasTaskCenterContent)#expect(!snapshot.hasActiveTasks)}@@ -186,22 +186,10 @@ struct ActivityPresentationTests {let waiting = task(thread: "waiting-thread")let running = task(thread: "running-thread")let snapshot = ActivitySnapshot(waitingTasks: [waiting], runningTasks: [running], recentCompletions: [], recentTerminations: [])- #expect(snapshot.primaryActivity == .waiting(waiting))+ var selection = ActivityCardSelection()+ selection.update(snapshot: snapshot, isHealthy: true, now: TestFixtures.now)+ #expect(selection.current == .waiting(waiting))#expect(snapshot.activeCount == 2)- #expect(snapshot.statusItemActivityExpiration == nil)- }-- @Test(arguments: [false, true])- func accountFailureKeepsLiveTaskIcon(waiting: Bool) {- let task = task(thread: "thread-a")- let activity = ActivitySnapshot(- waitingTasks: waiting ? [task] : [], runningTasks: waiting ? [] : [task],- recentCompletions: [], recentTerminations: []- )- let state = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: activity)- #expect(state.symbolName(at: TestFixtures.now) == (waiting ? "person.badge.key.fill" : "person.badge.clock.fill"))- let idle = StatusIconState(usesErrorImage: true, ordinaryUsageAllowed: nil, progress: nil, activity: .empty)- #expect(idle.symbolName(at: TestFixtures.now) == "person.slash.fill")}private func task(thread: String) -> ActivityTaskSnapshot {diff --git a/Tests/App/Presentation/LogMethodFilterTests.swift b/Tests/App/Presentation/LogMethodFilterTests.swiftindex fdfb909..5ddd73b 100644--- a/Tests/App/Presentation/LogMethodFilterTests.swift+++ b/Tests/App/Presentation/LogMethodFilterTests.swift@@ -3,7 +3,7 @@ import SwiftUIimport Testingstruct LogMethodFilterTests {- @Test(arguments: [CGFloat(120), 320, 600], [0, 1, 8])+ @Test(arguments: [CGFloat(120), 320, 600], [1, 8])func selectionsKeepTheHeaderCompact(width: CGFloat, selectionCount: Int) throws {let directory = try TestDirectory()defer { try? directory.remove() }diff --git a/Tests/App/Presentation/SettingsOptionsPanelLayoutTests.swift b/Tests/App/Presentation/SettingsOptionsPanelLayoutTests.swiftnew file mode 100644index 0000000..795a180--- /dev/null+++ b/Tests/App/Presentation/SettingsOptionsPanelLayoutTests.swift@@ -0,0 +1,94 @@+import AppKit+import Combine+import SwiftUI+import Testing++@MainActor+struct SettingsOptionsPanelLayoutTests {+ @Test(arguments: [(67.25, 68), (93.75, 94), (67.25, 94), (93.75, 67)] as [(CGFloat, CGFloat)])+ func resizingKeepsFirstRowAtTopWithRoundedOrPreviousHeight(height: CGFloat, hostHeight: CGFloat) {+ var reportedSize = CGSize.zero+ var contentTop: CGFloat = -1+ let view = Color.blue+ .frame(width: 300, height: 22)+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.frame(in: .global).minY+ } action: { contentTop = $0 }+ .frame(height: height, alignment: .top)+ .settingsOptionsPanel(height: height)+ .environment(\.settingsOptionsPanelSizeObserver, SettingsOptionsPanelSizeObserver {+ reportedSize = $0+ })+ let host = NSHostingView(rootView: view)+ host.frame = CGRect(x: 0, y: 0, width: 300, height: hostHeight)+ host.layoutSubtreeIfNeeded()++ #expect(reportedSize == CGSize(width: 300, height: height.rounded(.up)))+ #expect(host.fittingSize.height == height.rounded(.up))+ #expect(contentTop == 0)+ }++ @Test func animatedExpansionAndCollapseKeepFirstRowStable() async throws {+ let state = ExpansionState()+ let measurements = Measurements()+ let host = NSHostingView(rootView: AnimatedPanel(state: state, measurements: measurements))+ host.frame = CGRect(x: 0, y: 0, width: 300, height: 67)+ host.layoutSubtreeIfNeeded()+ let initialBitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: initialBitmap)+ try await Task.sleep(for: .milliseconds(20))++ for expanded in [true, false] {+ state.isExpanded = expanded+ var heights: [CGFloat] = []+ for _ in 0 ..< 40 {+ host.setFrameSize(host.fittingSize)+ host.layoutSubtreeIfNeeded()+ let bitmap = try #require(host.bitmapImageRepForCachingDisplay(in: host.bounds))+ host.cacheDisplay(in: host.bounds, to: bitmap)+ #expect(measurements.contentTop == 10)+ heights.append(measurements.size.height)+ try await Task.sleep(for: .milliseconds(10))+ }+ #expect(heights.last == (expanded ? 94 : 67))+ #expect(heights.contains { $0 > 67 && $0 < 94 })+ #expect(heights.allSatisfy { $0 >= 67 && $0 <= 94 })+ }+ }++ private final class ExpansionState: ObservableObject {+ @Published var isExpanded = false+ }++ private final class Measurements {+ var size = CGSize(width: 300, height: 67)+ var contentTop: CGFloat = -1+ }++ private struct AnimatedPanel: View {+ @ObservedObject var state: ExpansionState+ let measurements: Measurements++ var body: some View {+ VStack(spacing: 0) {+ Color.blue+ .frame(height: 22)+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.frame(in: .global).minY+ } action: { measurements.contentTop = $0 }+ Color.clear+ .settingsOptionsReveal(isExpanded: true, height: 22, spacing: 5)+ Color.clear+ .settingsOptionsReveal(isExpanded: state.isExpanded, height: 22, spacing: 5)+ }+ .padding(.vertical, 10)+ .frame(width: 300)+ .fixedSize(horizontal: true, vertical: true)+ .settingsOptionsPanel(height: state.isExpanded ? 94 : 67)+ .animation(SettingsOptionsPanelMetrics.contentAnimation, value: state.isExpanded)+ .environment(\.settingsOptionsPanelSizeObserver, SettingsOptionsPanelSizeObserver {+ measurements.size = $0+ })+ }+ }+}diff --git a/Tests/App/Presentation/TaskGlowTests.swift b/Tests/App/Presentation/TaskGlowTests.swiftindex f20d9df..96e6383 100644--- a/Tests/App/Presentation/TaskGlowTests.swift+++ b/Tests/App/Presentation/TaskGlowTests.swift@@ -154,14 +154,13 @@ struct TaskGlowTests {}@Test(arguments: TaskGlowSettings.terminalDurationOptions)- func terminalDurationOnlyChangesGlowExpiration(_ duration: TimeInterval) {+ func terminalDurationControlsGlowExpiration(_ duration: TimeInterval) {let snapshot = completedSnapshot()var presentation = TaskGlowPresentationState()presentation.update(snapshot: snapshot, terminalEvents: [], isEnabled: true, acceptsBriefEvents: true, now: TestFixtures.now)presentation.refresh(now: TestFixtures.now, terminalDuration: duration)#expect(presentation.state == .completed)#expect(presentation.terminal?.expiresAt == TestFixtures.now.addingTimeInterval(duration))- #expect(snapshot.statusItemActivityExpiration == TestFixtures.now.addingTimeInterval(10))presentation.refresh(now: TestFixtures.now.addingTimeInterval(duration), terminalDuration: duration)#expect(presentation.state == .hidden)#expect(presentation.terminal == nil)diff --git a/Tests/App/Settings/MenuBarIndicatorSettingsTests.swift b/Tests/App/Settings/MenuBarIndicatorSettingsTests.swiftnew file mode 100644index 0000000..8c493c9--- /dev/null+++ b/Tests/App/Settings/MenuBarIndicatorSettingsTests.swift@@ -0,0 +1,155 @@+import Foundation+import Testing++struct MenuBarIndicatorSettingsTests {+ @Test(arguments: [QuotaWindowKind.primary, .secondary])+ func defaultWeeklyUsesActualWindowAndReachesIcon(_ kind: QuotaWindowKind) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set("primary", forKey: "MenuBarQuota.selection")+ let settings = MenuBarIndicatorSettings(defaults: preferences.defaults)+ settings.setEnabled(true)+ let restored = MenuBarIndicatorSettings(defaults: preferences.defaults)+ let snapshot = try snapshot(weeklyKind: kind)+ let metrics = restored.configuration.visibleMetrics(in: snapshot.codexLimit?.windows ?? [])+ let metric = try #require(metrics.first)+ let window = try #require(snapshot.codexLimit?.window(ofKind: metric.windowKind))+ #expect(window.label == "Weekly")+ #expect(metrics.count == 1)+ let progress = try #require(StatusIconProgress(snapshot: snapshot, metric: metric))+ let presentation = StatusItemIconPresentation()+ presentation.update(+ isUnavailable: false,+ ordinaryUsageAllowed: nil,+ indicators: [.init(percent: progress.percent(at: TestFixtures.now), isStale: progress.isStale)],+ animated: false+ )+ #expect(presentation.state.showsIndicators)+ #expect(presentation.state.indicators.first?.percent == 41)+ #expect(!presentation.state.usesSplitRingStyle)+ }++ @Test(arguments: [nil, "off", "primary", "secondary"] as [String?])+ func defaultsOffAndIgnoresLegacyPreferences(_ legacySelection: String?) throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ preferences.defaults.set(legacySelection, forKey: "MenuBarQuota.selection")+ preferences.defaults.set("primary", forKey: "MenuBarQuota.lastWindowSelection")+ let configuration = MenuBarIndicatorSettings(defaults: preferences.defaults).configuration+ #expect(!configuration.isEnabled)+ #expect(configuration.count == .one)+ #expect(configuration.visibleMetrics(in: []).isEmpty)+ #expect(configuration.firstMetric == nil)+ #expect(configuration.secondMetric == nil)+ #expect(preferences.defaults.string(forKey: "MenuBarQuota.selection") == legacySelection)+ }++ @Test func toolTipFollowsEnabledMetricsAndTheirLeftToRightOrder() throws {+ let snapshot = try snapshot(weeklyKind: .secondary)+ let resetDate = try #require(snapshot.codexLimit?.window(ofKind: .secondary)?.resetsAt)+ let now = resetDate.addingTimeInterval(-93780)+ let percent = CodexPercentageFormat.string(from: 41)+ let quota = String(localized: "menu-bar-indicator.tooltip.quota", defaultValue: "\(percent)")+ let duration = String(localized: "menu-bar-indicator.tooltip.duration", defaultValue: "\(1) \(2) \(3)")+ let reset = String(localized: "menu-bar-indicator.tooltip.reset", defaultValue: "\(duration)")+ let missing = "--"+ let missingQuota = String(localized: "menu-bar-indicator.tooltip.quota", defaultValue: "\(missing)")+ let missingReset = String(localized: "menu-bar-indicator.tooltip.reset", defaultValue: "\(missing)")+ let cases: [(MenuBarIndicatorConfiguration, String)] = [+ (.init(isEnabled: true, count: .one, firstMetric: .secondaryQuota, secondMetric: .secondaryReset), quota),+ (.init(isEnabled: true, count: .one, firstMetric: .secondaryReset, secondMetric: .secondaryQuota), reset),+ (.init(isEnabled: true, count: .two, firstMetric: .secondaryQuota, secondMetric: .secondaryReset), quota + " | " + reset),+ (.init(isEnabled: true, count: .two, firstMetric: .secondaryReset, secondMetric: .secondaryQuota), reset + " | " + quota),+ (.init(isEnabled: true, count: .two, firstMetric: .primaryQuota, secondMetric: .secondaryQuota), missingQuota + " | " + quota)+ ]+ for (configuration, expected) in cases {+ let state = StatusIconState(loadState: .loaded, snapshot: snapshot, configuration: configuration)+ #expect(state.toolTip(at: now) == expected)+ }+ var configuration = MenuBarIndicatorConfiguration(isEnabled: true, count: .two)+ #expect(StatusIconState(loadState: .loaded, snapshot: snapshot, configuration: configuration).toolTip(at: now) == quota + " | " + reset)+ #expect(StatusIconState(loadState: .loading, snapshot: nil, configuration: configuration).toolTip(at: now) == missingQuota + " | " + missingReset)+ configuration.isEnabled = false+ let disabled = StatusIconState(loadState: .loaded, snapshot: snapshot, configuration: configuration)+ #expect(disabled.toolTip(at: now) == nil)+ #expect(disabled.nextRefreshDate(after: now) == nil)+ }++ @Test(arguments: [+ (93780.0, String(localized: "menu-bar-indicator.tooltip.duration", defaultValue: "\(1) \(2) \(3)"), 60.0 as TimeInterval?),+ (86400, String(localized: "menu-bar-indicator.tooltip.duration", defaultValue: "\(1) \(0) \(0)"), 60),+ (7380, String(localized: "menu-bar-indicator.tooltip.duration-hours", defaultValue: "\(2) \(3)"), 60),+ (3600, String(localized: "menu-bar-indicator.tooltip.duration-hours", defaultValue: "\(1) \(0)"), 60),+ (60.25, String(localized: "menu-bar-indicator.tooltip.duration-minutes", defaultValue: "\(2)"), 0.25),+ (60, String(localized: "menu-bar-indicator.tooltip.duration-minutes", defaultValue: "\(1)"), 60),+ (1, String(localized: "menu-bar-indicator.tooltip.duration-minutes", defaultValue: "\(1)"), 1),+ (0, String(localized: "menu-bar-indicator.tooltip.reset-now"), nil),+ (-60, String(localized: "menu-bar-indicator.tooltip.reset-now"), nil)+ ])+ func resetToolTipRoundsUpAndRefreshesAtMinuteBoundaries(remaining: TimeInterval, expected: String, refreshDelay: TimeInterval?) throws {+ let snapshot = try snapshot(weeklyKind: .secondary)+ let resetDate = try #require(snapshot.codexLimit?.window(ofKind: .secondary)?.resetsAt)+ let progress = try #require(StatusIconProgress(snapshot: snapshot, metric: .secondaryReset))+ let now = resetDate.addingTimeInterval(-remaining)+ #expect(progress.toolTipValue(at: now) == expected)+ #expect(progress.nextRefreshDate(after: now) == refreshDelay.map { now.addingTimeInterval($0) })+ }++ @Test func defaultWeeklyResolvesAfterDataArrivesAndPrefersWeeklyOverFirstWindow() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = MenuBarIndicatorSettings(defaults: preferences.defaults)+ settings.setEnabled(true)+ let configuration = MenuBarIndicatorSettings(defaults: preferences.defaults).configuration+ #expect(configuration.visibleMetrics(in: []).count == 1)+ let primaryWeekly = try #require(snapshot(weeklyKind: .primary).codexLimit).windows+ #expect(configuration.visibleMetrics(in: primaryWeekly) == [.primaryQuota])+ let secondaryWeekly = try #require(snapshot(weeklyKind: .secondary).codexLimit).windows+ let primary = QuotaWindow(kind: .primary, windowDurationMins: 300, usedPercent: 20, resetsAt: nil)+ #expect(configuration.visibleMetrics(in: [primary] + secondaryWeekly) == [.secondaryQuota])+ #expect(configuration.visibleMetrics(in: [primary]) == [.primaryQuota])+ #expect(preferences.defaults.object(forKey: "MenuBarIndicator.firstMetric") == nil)+ }++ @Test func togglingAndChangingLayoutKeepUnselectedDefaultsDynamic() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = MenuBarIndicatorSettings(defaults: preferences.defaults)+ settings.setEnabled(true)+ settings.setCount(.two)+ let configuration = MenuBarIndicatorSettings(defaults: preferences.defaults).configuration+ let windows = try #require(snapshot(weeklyKind: .primary).codexLimit).windows+ #expect(configuration.visibleMetrics(in: windows) == [.primaryQuota, .primaryReset])+ #expect(configuration.firstMetric == nil)+ #expect(configuration.secondMetric == nil)+ settings.setEnabled(false)+ #expect(!MenuBarIndicatorSettings(defaults: preferences.defaults).configuration.isEnabled)+ }++ @Test func metricEditsUseResolvedWindowAndPreserveExplicitPreferences() throws {+ let preferences = try TestPreferences()+ defer { preferences.remove() }+ let settings = MenuBarIndicatorSettings(defaults: preferences.defaults)+ let windows = try #require(snapshot(weeklyKind: .primary).codexLimit).windows+ settings.setEnabled(true)+ settings.setMetric(isResetTime: true, at: 0, windows: windows)+ settings.setMetric(windowKind: .secondary, at: 1, windows: windows)+ let configuration = MenuBarIndicatorSettings(defaults: preferences.defaults).configuration+ #expect(configuration.isEnabled)+ #expect(configuration.firstMetric == .primaryReset)+ #expect(configuration.secondMetric == .secondaryReset)+ #expect(configuration.metrics(in: []) == [.primaryReset, .secondaryReset])+ let secondaryWeekly = try #require(snapshot(weeklyKind: .secondary).codexLimit).windows+ #expect(configuration.metrics(in: secondaryWeekly) == [.primaryReset, .secondaryReset])+ }++ private func snapshot(weeklyKind: QuotaWindowKind) throws -> CodexQuotaSnapshot {+ let response = try TestFixtures.decode(AccountRateLimitsResponse.self, """+ {"rateLimits":{"\(weeklyKind.rawValue)":{"usedPercent":59,"windowDurationMins":10080,"resetsAt":1793905434}}}+ """)+ return try CodexQuotaSnapshot(+ accountResponse: AccountReadResponse(account: CodexAccount(type: "chatgpt", email: nil, planType: nil)),+ rateLimitsResponse: response+ )+ }+}diff --git a/appcast.xml b/appcast.xmlindex 9b4954f..adf864f 100644--- a/appcast.xml+++ b/appcast.xml@@ -5,6 +5,20 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar 5.2.2</title>+ <sparkle:version>381</sparkle:version>+ <sparkle:shortVersionString>5.2.2</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:minimumAutoupdateVersion>200</sparkle:minimumAutoupdateVersion>+ <sparkle:informationalUpdate><sparkle:belowVersion>200</sparkle:belowVersion></sparkle:informationalUpdate>+ <link xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.0.0-Guide</link>+ <link xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.0.0-Guide</link>+ <sparkle:releaseNotesLink xml:lang="en-US">https://codexbar.zabrian.app/notes?lang=en-US#5.2.2</sparkle:releaseNotesLink>+ <sparkle:releaseNotesLink xml:lang="zh-CN">https://codexbar.zabrian.app/notes?lang=zh-CN#5.2.2</sparkle:releaseNotesLink>+ <pubDate>Thu, 05 Nov 2026 15:10:42 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v5.2.2.dmg" sparkle:edSignature="DNX8U9hJzarJplPw6ykPxTMPwUPGznqdcrGAqjSEhxTuTGGgs8jO+gmyGFEIo5E6Nx8Cdh2qJmHQHoJCZRpUAw==" length="11433472" type="application/octet-stream"/>+ </item><item><title>CodexBar 5.2.1</title><sparkle:version>294</sparkle:version>