Skip to content

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

fix: 修复设置子面板交互和权限状态同步

Bob2b0e85205b87
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxproj
index b5afafc..a2fbb24 100644
--- a/CodexBar.xcodeproj/project.pbxproj
+++ b/CodexBar.xcodeproj/project.pbxproj
@@ -44,7 +44,7 @@
/* Begin PBXFileReference section */
B10000000000000000000014 /* CodexBarHelper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CodexBarHelper; sourceTree = BUILT_PRODUCTS_DIR; };
C449FB5030203E0000ED2123 /* Version.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Version.xcconfig; sourceTree = "<group>"; };
- C4A0FD952FD9302E000263A7 /* CodexBar.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CodexBar.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "CodexBar Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */
@@ -129,7 +129,7 @@
C4A0FD962FD9302E000263A7 /* Products */ = {
isa = PBXGroup;
children = (
- C4A0FD952FD9302E000263A7 /* CodexBar.app */,
+ C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */,
B10000000000000000000014 /* CodexBarHelper */,
);
name = Products;
@@ -180,7 +180,7 @@
C42A52F02FDACDEC004A2B53 /* Sparkle */,
);
productName = CodexBar;
- productReference = C4A0FD952FD9302E000263A7 /* CodexBar.app */;
+ productReference = C4A0FD952FD9302E000263A7 /* CodexBar Debug.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
@@ -445,6 +445,7 @@
SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;
+ WRAPPER_NAME = "CodexBar Debug.app";
};
name = Debug;
};
diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swift
index fd1e66b..c34f3e2 100644
--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift
+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift
@@ -19,11 +19,11 @@ enum SettingsOptionsPanelAction {
case closeAll
}
-/// 子面板入场时的内容重建信号, 由 makeContentController 接进内容视图, 面板自己不必知道
+/// 子面板入场时的内容重建信号
/// 原生 Switch 的 thumb 由 WindowPortal 投射, 面板首次布局那一轮建不起来也不会自愈, 只有重建补得上
/// bump 排在 present 之后, 那时动画效果已经把内容 translation 到可视区外, 重建才看不见
@MainActor
-final class SidePanelEntryCue: ObservableObject {
+private final class SidePanelEntryCue: ObservableObject {
@Published private(set) var pass = 0
func bump() {
@@ -42,7 +42,7 @@ private struct SidePanelEntryRebuildHost<Content: View>: View {
}
/// 设置窗口右侧子选项面板的公共装配
-/// 各子面板只差内容视图, 动态高度面板再提供变化来源, 定位 关闭 高度重算这套脚手架全在这里
+/// 各子面板只差内容视图与高度变化来源, 窗口组关闭规则由 SettingsWindowController 统一维护
/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView
@MainActor
final class SettingsOptionsPanelController {
@@ -64,9 +64,6 @@ final class SettingsOptionsPanelController {
self?.hostingController?.view
}
)
- private weak var settingsWindow: NSWindow?
- private var panelDismissObserver: NSObjectProtocol?
- private var settingsWindowDismissObservers: [NSObjectProtocol] = []
private var panelResizeTask: Task<Void, Never>?
private var isEntryAnimationRunning = false
@@ -74,13 +71,21 @@ final class SettingsOptionsPanelController {
animationKey: String,
initialPanelSize: CGSize,
willShow: (() -> Void)? = nil,
- contentControllerProvider: @escaping (SidePanelEntryCue) -> NSViewController,
+ contentProvider: @escaping () -> some View,
contentChanges: AnyPublisher<Void, Never>? = nil
) {
self.animationKey = animationKey
self.initialPanelSize = initialPanelSize
self.willShow = willShow
- self.contentControllerProvider = contentControllerProvider
+ // 内容闭包在首次构造面板时才执行, 保留 SwiftUI 状态的创建时机
+ contentControllerProvider = { cue in
+ let controller = NSHostingController(
+ rootView: SidePanelEntryRebuildHost(cue: cue, content: contentProvider())
+ )
+ // 高度重算依赖 preferredContentSize 提交的 fitting size
+ controller.sizingOptions = [.preferredContentSize]
+ return controller
+ }
// 只有内容行数会动态增删的面板才传变化源
// 面板收着时由 scheduleResize 的守卫过滤变化
if let contentChanges {
@@ -92,23 +97,14 @@ final class SettingsOptionsPanelController {
}
}
- /// sizingOptions 必须是 preferredContentSize: 面板的高度重算靠的就是它提交的 fitting size
- /// 入场重建也在这里接上, 新增子面板照抄这一句即可, 内容视图不必知道 cue 的存在
- static func makeContentController(
- _ content: some View,
- rebuiltBy cue: SidePanelEntryCue
- ) -> NSViewController {
- let controller = NSHostingController(
- rootView: SidePanelEntryRebuildHost(cue: cue, content: content)
- )
- controller.sizingOptions = [.preferredContentSize]
- return controller
- }
-
var isVisible: Bool {
presenter.isVisible
}
+ func owns(_ window: NSWindow) -> Bool {
+ window === panel
+ }
+
func toggle(
relativeTo window: NSWindow?,
contentView: NSView?,
@@ -152,10 +148,6 @@ final class SettingsOptionsPanelController {
}
}
- private func owns(_ window: NSWindow?) -> Bool {
- window === panel
- }
-
private func show(
relativeTo window: NSWindow?,
contentView: NSView?,
@@ -193,7 +185,6 @@ final class SettingsOptionsPanelController {
)
panel.level = window.level
- installSettingsWindowDismissObservers(for: window)
panelResizeTask?.cancel()
isEntryAnimationRunning = true
presenter.present(panel, at: position, relativeTo: window) { [weak self] in
@@ -227,66 +218,11 @@ final class SettingsOptionsPanelController {
contentView: panel.contentView,
cornerRadius: SettingsOptionsPanelMetrics.cornerRadius
)
- panelDismissObserver = makeResignKeyDismissObserver(observing: panel) { [weak self] keyWindow in
- self?.owns(keyWindow) != true
- }
self.hostingController = hostingController
self.panel = panel
return panel
}
- /// 设置窗口和面板之间切换 key 不收起; 焦点离开这个窗口组或设置窗口关闭时收起
- private func installSettingsWindowDismissObservers(for window: NSWindow) {
- guard settingsWindow !== window || settingsWindowDismissObservers.isEmpty else {
- return
- }
-
- settingsWindow = window
- for observer in settingsWindowDismissObservers {
- NotificationCenter.default.removeObserver(observer)
- }
-
- settingsWindowDismissObservers = [
- makeResignKeyDismissObserver(observing: window) { [weak self, weak window] keyWindow in
- keyWindow !== window && self?.owns(keyWindow) != true
- },
- NotificationCenter.default.addObserver(
- forName: NSWindow.willCloseNotification,
- object: window,
- queue: .main
- ) { [weak self] _ in
- MainActor.assumeIsolated {
- self?.hide(immediate: true)
- }
- }
- ]
- }
-
- /// resignKey 后让出一轮 runloop, 等新 keyWindow 生效再判定
- private func makeResignKeyDismissObserver(
- observing window: NSWindow,
- shouldDismiss: @escaping @MainActor (NSWindow?) -> Bool
- ) -> NSObjectProtocol {
- NotificationCenter.default.addObserver(
- forName: NSWindow.didResignKeyNotification,
- object: window,
- queue: .main
- ) { [weak self] _ in
- Task { @MainActor [weak self] in
- guard let self else {
- return
- }
-
- await Task.yield()
- guard isVisible, shouldDismiss(NSApplication.shared.keyWindow) else {
- return
- }
-
- hide()
- }
- }
- }
-
private func measuredPanelSize() -> CGSize {
hostingController?.view.validFittingSize ?? initialPanelSize
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index a6cd097..6f9f975 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -20,8 +20,13 @@ final class SettingsWindowController: HostingWindowController {
private let onSyncChanged: (Bool) -> Void
private let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler
private let mainPanelUndoManager = UndoManager()
+ private var windowFocusObserver: AnyCancellable?
/// 只在真的要展开时构造: hosting controller 与动态面板订阅会常驻到 App 结束, 而用户可能一次子面板都没开过
private var optionsPanelControllers: [SettingsOptionsPanel: SettingsOptionsPanelController] = [:]
+ private var optionsDismissEventMonitor: Any?
+ private var optionsDismissFocusObserver: AnyCancellable?
+ private var optionsDismissWindowObserver: NSObjectProtocol?
+ private var optionsDismissedByClick: (panel: SettingsOptionsPanel, event: NSEvent)?
/// 首次构造窗口时 SwiftUI 可能先于 window 赋值上报高度 因此必须保留最近一次测量
private var preferredContentHeight: CGFloat?
@@ -62,6 +67,7 @@ final class SettingsWindowController: HostingWindowController {
override func open() {
refreshSettingsState()
super.open()
+ installOptionsDismissMonitor()
NotificationCenter.default.post(name: .settingsWindowDidOpen, object: nil)
}
@@ -96,6 +102,12 @@ final class SettingsWindowController: HostingWindowController {
window.styleMask = [.titled, .closable, .miniaturizable]
window.contentMinSize = Metrics.minimumContentSize
window.setContentSize(Metrics.initialContentSize)
+ // LSUIElement 窗口重新获得焦点时不一定伴随 App 激活事件
+ windowFocusObserver = NotificationCenter.default
+ .publisher(for: NSWindow.didBecomeKeyNotification, object: window)
+ .sink { [weak notificationSettings] _ in
+ notificationSettings?.refreshAuthorizationStatus()
+ }
return window
}
@@ -116,6 +128,7 @@ final class SettingsWindowController: HostingWindowController {
}
private func refreshSettingsState() {
+ notificationSettings.refreshAuthorizationStatus()
codexHookSettings.reconcileInstalledHooks()
codexCLINotificationSettings.refresh()
syncSettings.refresh()
@@ -158,16 +171,13 @@ final class SettingsWindowController: HostingWindowController {
willShow: { [codexCLINotificationSettings] in
codexCLINotificationSettings.refresh()
},
- contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, autoResetSettings, keepAliveController] entryCue in
- SettingsOptionsPanelController.makeContentController(
- NotificationOptionsView(
- notificationSettings: notificationSettings,
- codexHookSettings: codexHookSettings,
- codexCLINotificationSettings: codexCLINotificationSettings,
- autoResetSettings: autoResetSettings,
- keepAliveController: keepAliveController
- ),
- rebuiltBy: entryCue
+ contentProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, autoResetSettings, keepAliveController] in
+ NotificationOptionsView(
+ notificationSettings: notificationSettings,
+ codexHookSettings: codexHookSettings,
+ codexCLINotificationSettings: codexCLINotificationSettings,
+ autoResetSettings: autoResetSettings,
+ keepAliveController: keepAliveController
)
},
// 音效子行随各开关增删, 自动重置 低电量与上限三行还跟着各自的依赖置灰
@@ -191,26 +201,18 @@ final class SettingsWindowController: HostingWindowController {
SettingsOptionsPanelController(
animationKey: "CodexBar.autoResetOptionsDrawerTransform",
initialPanelSize: AutoResetOptionsView.initialPanelSize,
- contentControllerProvider: { [autoResetSettings] entryCue in
- SettingsOptionsPanelController.makeContentController(
- AutoResetOptionsView(
- settings: autoResetSettings
- ),
- rebuiltBy: entryCue
- )
+ contentProvider: { [autoResetSettings] in
+ AutoResetOptionsView(settings: autoResetSettings)
}
)
case .keepAlive:
SettingsOptionsPanelController(
animationKey: "CodexBar.keepAliveOptionsDrawerTransform",
initialPanelSize: KeepAliveOptionsView.initialPanelSize,
- contentControllerProvider: { [keepAliveController, activityProtectionSettings] entryCue in
- SettingsOptionsPanelController.makeContentController(
- KeepAliveOptionsView(
- keepAliveController: keepAliveController,
- activityProtectionSettings: activityProtectionSettings
- ),
- rebuiltBy: entryCue
+ contentProvider: { [keepAliveController, activityProtectionSettings] in
+ KeepAliveOptionsView(
+ keepAliveController: keepAliveController,
+ activityProtectionSettings: activityProtectionSettings
)
},
// 面板里只有 hasBattery 会增删行, 其余各行的取值不改高度
@@ -228,25 +230,110 @@ final class SettingsWindowController: HostingWindowController {
willShow: { [mainPanelSettings] in
mainPanelSettings.refresh()
},
- contentControllerProvider: { [mainPanelSettings, codexHookSettings, mainPanelUndoManager] entryCue in
- SettingsOptionsPanelController.makeContentController(
- MainPanelOptionsView(
- settings: mainPanelSettings,
- codexHookSettings: codexHookSettings,
- undoManager: mainPanelUndoManager
- ),
- rebuiltBy: entryCue
+ contentProvider: { [mainPanelSettings, codexHookSettings, mainPanelUndoManager] in
+ MainPanelOptionsView(
+ settings: mainPanelSettings,
+ codexHookSettings: codexHookSettings,
+ undoManager: mainPanelUndoManager
)
}
)
}
+ private func isInSettingsWindowGroup(_ window: NSWindow?) -> Bool {
+ guard let window else {
+ return false
+ }
+ return window === self.window || optionsPanelControllers.values.contains { $0.owns(window) }
+ }
+
+ private func installOptionsDismissMonitor() {
+ guard optionsDismissEventMonitor == nil, let window else {
+ return
+ }
+
+ optionsDismissEventMonitor = NSEvent.addLocalMonitorForEvents(
+ matching: [.leftMouseUp, .rightMouseUp, .otherMouseUp]
+ ) { [weak self, weak window] event in
+ guard let self else {
+ return event
+ }
+
+ optionsDismissedByClick = nil
+ guard event.window === window else {
+ return event
+ }
+
+ if let panel = SettingsOptionsPanel.allCases.first(where: {
+ existingOptionsPanelController($0)?.isVisible == true
+ }) {
+ optionsDismissedByClick = (panel, event)
+ }
+ handleOptionsAction(.closeAll)
+ // 保留到本次 mouseUp 分发完成, 避免影响之后的辅助功能按钮动作
+ DispatchQueue.main.async { [weak self] in
+ if self?.optionsDismissedByClick?.event === event {
+ self?.optionsDismissedByClick = nil
+ }
+ }
+ return event
+ }
+ optionsDismissFocusObserver = NotificationCenter.default
+ .publisher(for: NSWindow.didResignKeyNotification)
+ .sink { [weak self] notification in
+ guard let self,
+ let sourceWindow = notification.object as? NSWindow,
+ isInSettingsWindowGroup(sourceWindow) else {
+ return
+ }
+ Task { @MainActor [weak self] in
+ // 等新 keyWindow 生效再判断, 旧面板的失焦回调不能关闭刚切换到的新面板
+ await Task.yield()
+ guard let self, !isInSettingsWindowGroup(NSApplication.shared.keyWindow) else {
+ return
+ }
+ handleOptionsAction(.closeAll)
+ }
+ }
+ optionsDismissWindowObserver = NotificationCenter.default.addObserver(
+ forName: NSWindow.willCloseNotification,
+ object: window,
+ queue: .main
+ ) { [weak self] _ in
+ MainActor.assumeIsolated {
+ self?.removeOptionsDismissMonitor()
+ }
+ }
+ }
+
+ private func removeOptionsDismissMonitor() {
+ for controller in optionsPanelControllers.values {
+ controller.hide(immediate: true)
+ }
+ if let optionsDismissEventMonitor {
+ NSEvent.removeMonitor(optionsDismissEventMonitor)
+ }
+ if let optionsDismissWindowObserver {
+ NotificationCenter.default.removeObserver(optionsDismissWindowObserver)
+ }
+ optionsDismissEventMonitor = nil
+ optionsDismissFocusObserver = nil
+ optionsDismissWindowObserver = nil
+ optionsDismissedByClick = nil
+ }
+
/// 子面板占设置窗口右侧同一位置, 展开一个必须先收掉其余的
/// 收旧面板用 immediate, 否则滑回与滑出在同一处交叠
/// 互斥规则只写在这里, 再加一个面板也不会漏掉某一对
private func handleOptionsAction(_ action: SettingsOptionsPanelAction) {
switch action {
case let .toggle(panel, anchorProvider):
+ // mouseUp 监听器先于按钮动作收起面板, 同一事件不能再次展开它
+ if let optionsDismissedByClick,
+ optionsDismissedByClick.panel == panel,
+ optionsDismissedByClick.event === NSApplication.shared.currentEvent {
+ return
+ }
for other in SettingsOptionsPanel.allCases where other != panel {
existingOptionsPanelController(other)?.hide(immediate: true)
}
diff --git a/CodexBar/Resources/Info.plist b/CodexBar/Resources/Info.plist
index 6dd478b..cc8900d 100644
--- a/CodexBar/Resources/Info.plist
+++ b/CodexBar/Resources/Info.plist
@@ -15,7 +15,7 @@
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
- <string>$(PRODUCT_NAME)</string>
+ <string>$(INFOPLIST_KEY_CFBundleDisplayName)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 415df6c..4406b92 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -4006,7 +4006,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Notifications are disabled in System Settings"
+ "value" : "Notification permission has not been granted"
}
},
"zh-Hans" : {
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index dafdf98..2b16f44 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -40,7 +40,7 @@ final class KeepAliveController: ObservableObject {
/// helper 安装与注册状态的错误, 注册恢复正常时才清除
@Published private var registrationErrorMessage: String?
- /// 切换睡眠状态过程中的错误, 只能由下一次操作结果或用户动作覆盖
+ /// 切换睡眠状态过程中的错误, 由下一次操作结果 用户动作或明确的依赖失效覆盖
/// 与注册类错误分开存储: refreshHelperStatus 每次 App 激活都会跑, 不能抹掉操作结果
@Published private var operationErrorMessage: String?
@@ -708,9 +708,16 @@ final class KeepAliveController: ObservableObject {
// 注册已正常, 只撤回注册类抱怨
// 操作类结果 (例如重试耗尽) 必须留到下一次操作有结论为止
assign(nil, to: \.registrationErrorMessage)
- } else if helperStatus != .requiresApproval {
- releaseSleepPrevention()
- durationLimiter.reset()
+ } else {
+ // 明确失去授权后停止重连, 租约是否已释放仍由原有清理链路确认
+ cancelRetryTask()
+ invalidateConnection()
+ assign(nil, to: \.operationErrorMessage)
+ if helperStatus != .requiresApproval {
+ durationLimiter.reset()
+ }
+ publishDerivedState(blockReason: sleepBlockReason)
+ reconcileAutoResetWakeSchedule()
}
}
@@ -725,8 +732,8 @@ final class KeepAliveController: ObservableObject {
reconcileDisplayAwake()
logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)
- // Helper 刷新只允许 unregister/register, 普通租约请求必须等新 Helper 就绪后再恢复
- guard !isRefreshingHelper else {
+ // Helper 未授权或刷新期间不发普通租约请求, 未确认的租约留待恢复后清理
+ guard helperStatus == .enabled, !isRefreshingHelper else {
cancelRetryTask()
releaseSleepPrevention()
return
@@ -996,14 +1003,12 @@ final class KeepAliveController: ObservableObject {
generation: UInt64,
detail: String
) {
- invalidateConnection()
let details = LogFields.joined(
"generation=\(generation)",
"detail=\(detail)"
)
AppLog.keepAlive.error("系统睡眠切换失败: \(details, privacy: .public)")
- operationErrorMessage = KeepAliveLocalizedMessage.toggleSleepFailed
- scheduleRetryIfNeeded(for: requested)
+ handleHelperFailure(KeepAliveLocalizedMessage.toggleSleepFailed, retrying: requested)
}
private func updateSleepPreventionSource(
@@ -1154,13 +1159,10 @@ final class KeepAliveController: ObservableObject {
}
private func handleHelperStatusTimeout() {
- let shouldRetry = isPreventingSleep
- let desiredSleepPrevention = shouldDisableSleep
- invalidateConnection()
- operationErrorMessage = KeepAliveLocalizedMessage.noResponse
- if shouldRetry {
- scheduleRetryIfNeeded(for: desiredSleepPrevention)
- }
+ handleHelperFailure(
+ KeepAliveLocalizedMessage.noResponse,
+ retrying: isPreventingSleep ? shouldDisableSleep : nil
+ )
}
private func releaseHelperLeaseIfNeeded(trigger: LogTrigger) async -> Bool {
@@ -1193,21 +1195,18 @@ final class KeepAliveController: ObservableObject {
)
connection.invalidationHandler = { [weak self, weak connection] in
Task { @MainActor in
- guard let self, self.connection === connection else {
+ guard let self, let connection, self.connection === connection else {
return
}
- let shouldRetry = self.requestInFlight || self.isPreventingSleep
- let desiredSleepPrevention = self.shouldDisableSleep
- // 复用统一清理: 连接失效同样要释放 assertion, 否则空闲睡眠会被永久阻止
- self.invalidateConnection()
- if shouldRetry {
- self.scheduleRetryIfNeeded(for: desiredSleepPrevention)
- }
+ self.handleHelperFailure(nil, retrying: self.requestInFlight || self.isPreventingSleep ? self.shouldDisableSleep : nil)
}
}
- connection.interruptionHandler = { [weak self] in
+ connection.interruptionHandler = { [weak self, weak connection] in
Task { @MainActor in
- self?.handleConnectionFailure(KeepAliveError.connectionInterrupted)
+ guard let self, let connection, self.connection === connection else {
+ return
+ }
+ self.handleConnectionFailure(KeepAliveError.connectionInterrupted)
}
}
connection.resume()
@@ -1217,15 +1216,25 @@ final class KeepAliveController: ObservableObject {
}
private func handleConnectionFailure(_ error: Error) {
- let shouldRetry = requestInFlight || isPreventingSleep
- let desiredSleepPrevention = shouldDisableSleep
- invalidateConnection()
- AppLog.keepAlive.error(
- "Helper XPC 连接失败: detail=\(error.localizedDescription, privacy: .public)"
+ AppLog.keepAlive.error("Helper XPC 连接失败: detail=\(error.localizedDescription, privacy: .public)")
+ handleHelperFailure(
+ KeepAliveLocalizedMessage.connectionFailed,
+ retrying: requestInFlight || isPreventingSleep ? shouldDisableSleep : nil
)
- operationErrorMessage = KeepAliveLocalizedMessage.connectionFailed
- if shouldRetry {
- scheduleRetryIfNeeded(for: desiredSleepPrevention)
+ }
+
+ /// 断连和超时统一先复核授权, retrying 为 nil 时只收敛状态, 不重试租约
+ private func handleHelperFailure(_ message: String?, retrying requested: Bool?) {
+ invalidateConnection()
+ refreshHelperStatus()
+ guard helperStatus == .enabled else {
+ return
+ }
+ if let message {
+ operationErrorMessage = message
+ }
+ if let requested {
+ scheduleRetryIfNeeded(for: requested)
}
}
@@ -1248,10 +1257,7 @@ final class KeepAliveController: ObservableObject {
"timeout=\(timeout)"
)
AppLog.keepAlive.error("Helper XPC 请求超时: \(details, privacy: .public)")
- // 连接已经不可信, 收掉它再走既有的重试阶梯, 与切换失败同一条路径
- invalidateConnection()
- operationErrorMessage = KeepAliveLocalizedMessage.noResponse
- scheduleRetryIfNeeded(for: requested)
+ handleHelperFailure(KeepAliveLocalizedMessage.noResponse, retrying: requested)
}
}
@@ -1398,6 +1404,7 @@ final class KeepAliveController: ObservableObject {
}
private func scheduleRetryIfNeeded(for requested: Bool) {
+ refreshHelperStatus()
guard isStarted,
helperStatus == .enabled,
requested == shouldDisableSleep,
@@ -1432,6 +1439,10 @@ final class KeepAliveController: ObservableObject {
return
}
retryTask = nil
+ refreshHelperStatus()
+ guard helperStatus == .enabled else {
+ return
+ }
guard requested == shouldDisableSleep else {
reconcileSleepState(trigger: .retry)
return
@@ -1469,12 +1480,13 @@ final class KeepAliveController: ObservableObject {
if !isHookEnabled {
return .hookDisabled
}
- if !hasKeepAliveTasks {
- return .noTasks
- }
+ // 先检查依赖, 避免 Hook 恢复任务前以 noTasks 提前放出未授权 Helper 的设置入口
if helperStatus != .enabled {
return .helperUnavailable
}
+ if !hasKeepAliveTasks {
+ return .noTasks
+ }
if isRefreshingHelper {
return .helperRefreshing
}
diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swift
index a789d70..b9980b8 100644
--- a/CodexBar/Services/Settings/NotificationSettings.swift
+++ b/CodexBar/Services/Settings/NotificationSettings.swift
@@ -30,9 +30,9 @@ final class NotificationSettings: ObservableObject {
@Published private(set) var keepAliveLimitSound: NotificationSoundOption
@Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined
- /// 系统授权被拒时设置页展示引导, 通知服务停发
- var isAuthorizationDenied: Bool {
- authorizationStatus == .denied
+ /// 系统创建通知条目后仍可能等待用户回应, 申请中也需要显示未授权引导
+ var needsAuthorization: Bool {
+ isEnabled && !canDeliver
}
/// 总开关开启且系统已明确允许时才发送, 未决定或未知状态都按不可发送处理
@@ -66,6 +66,8 @@ final class NotificationSettings: ObservableObject {
private let defaults: UserDefaults
private var authorizationTask: Task<Void, Never>?
+ private var isRequestingAuthorization = false
+ private var appActivationObserver: AnyCancellable?
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
@@ -105,6 +107,11 @@ final class NotificationSettings: ObservableObject {
autoResetSound = Self.sound(from: defaults, key: Self.autoResetSoundKey)
lowBatterySound = Self.sound(from: defaults, key: Self.lowBatterySoundKey)
keepAliveLimitSound = Self.sound(from: defaults, key: Self.keepAliveLimitSoundKey)
+ appActivationObserver = NotificationCenter.default
+ .publisher(for: NSApplication.didBecomeActiveNotification)
+ .sink { [weak self] _ in
+ self?.refreshAuthorizationStatus()
+ }
}
deinit {
@@ -214,6 +221,10 @@ final class NotificationSettings: ObservableObject {
/// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取
func refreshAuthorizationStatus() {
+ // 系统授权弹窗也会改变 App 与窗口焦点, 查询不能取消正在等待用户回应的请求
+ guard !isRequestingAuthorization else {
+ return
+ }
authorizationTask?.cancel()
authorizationTask = Task { @MainActor [weak self] in
let status = await UNUserNotificationCenter.current()
@@ -222,12 +233,6 @@ final class NotificationSettings: ObservableObject {
return
}
- // 开关已开但用户从未回应过系统弹窗 (如开启后立即退出): 补一次请求, 避免静默丢通知
- if status == .notDetermined, isEnabled {
- requestAuthorization()
- return
- }
-
let previousStatus = authorizationStatus
if status != previousStatus {
let details = LogFields.joined(
@@ -237,6 +242,10 @@ final class NotificationSettings: ObservableObject {
AppLog.notification.notice("通知授权变化: \(details, privacy: .public)")
}
authorizationStatus = status
+ // 仅依据本轮系统查询判断重设, 初始化时的 notDetermined 占位不能清掉用户开关
+ if status == .notDetermined {
+ setEnabled(false)
+ }
}
}
@@ -254,21 +263,30 @@ final class NotificationSettings: ObservableObject {
}
private func requestAuthorization() {
+ guard isEnabled, !isRequestingAuthorization else {
+ return
+ }
authorizationTask?.cancel()
+ isRequestingAuthorization = true
authorizationTask = Task { @MainActor [weak self] in
- _ = try? await UNUserNotificationCenter.current()
- .requestAuthorization(options: [.alert, .sound])
- let status = await UNUserNotificationCenter.current()
- .notificationSettings().authorizationStatus
+ do {
+ _ = try await UNUserNotificationCenter.current()
+ .requestAuthorization(options: [.alert, .sound])
+ } catch {
+ guard !Task.isCancelled else {
+ return
+ }
+ let error = error as NSError
+ AppLog.notification.error("通知授权请求失败: domain=\(error.domain, privacy: .public); code=\(error.code)")
+ }
guard let self, !Task.isCancelled else {
return
}
- // 被拒时通知会静默不发, 这是最常见的"设置开了却收不到"来源, 必须留痕
- AppLog.notification.notice(
- "通知授权结果: status=\(String(describing: status), privacy: .public)"
- )
- authorizationStatus = status
+ // 授权等待结束后恢复普通查询, 后续焦点刷新才能替换尚未返回的旧查询
+ isRequestingAuthorization = false
+ authorizationTask = nil
+ refreshAuthorizationStatus()
}
}
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index e12b669..52f1030 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -577,9 +577,18 @@ private extension AppSettingsView {
guard keepAliveController.isEnabled else {
return nil
}
+ if keepAliveController.helperStatus == .requiresApproval {
+ return SettingsStatusCaption(
+ message: String(localized: "helper.status.authorization-required"),
+ showsSystemSettingsButton: true
+ )
+ }
if let errorMessage = keepAliveController.errorMessage {
return SettingsStatusCaption(message: errorMessage, isError: true)
}
+ guard keepAliveController.helperStatus == .enabled else {
+ return SettingsStatusCaption(message: String(localized: "helper.status.not-registered"))
+ }
guard codexHookSettings.isVerified else {
return SettingsStatusCaption(message: String(localized: "hook.status.inactive"))
}
@@ -599,24 +608,14 @@ private extension AppSettingsView {
return SettingsStatusCaption(message: String(localized: "keep-alive.status.low-battery"))
}
- switch keepAliveController.helperStatus {
- case .requiresApproval:
- return SettingsStatusCaption(
- message: String(localized: "helper.status.authorization-required"),
- showsSystemSettingsButton: true
- )
- case .notRegistered, .notFound:
- return SettingsStatusCaption(message: String(localized: "helper.status.not-registered"))
- case .enabled:
- // 上限之外的运行态都收起; 达到上限要留一句, 否则开关开着却没生效无从解释
- guard keepAliveController.hasReachedMaximumDuration else {
- return nil
- }
- let duration = keepAliveController.maximumDuration.title
- return SettingsStatusCaption(
- message: String(localized: "keep-alive.status.duration-limit-reached", defaultValue: "\(duration)")
- )
+ // 上限之外的运行态都收起; 达到上限要留一句, 否则开关开着却没生效无从解释
+ guard keepAliveController.hasReachedMaximumDuration else {
+ return nil
}
+ let duration = keepAliveController.maximumDuration.title
+ return SettingsStatusCaption(
+ message: String(localized: "keep-alive.status.duration-limit-reached", defaultValue: "\(duration)")
+ )
}
var syncRow: some View {
@@ -779,7 +778,6 @@ private extension AppSettingsView {
/// 再调一次会让每次激活都多跑一遍电源读取 helper 状态查询和 helper 二进制哈希
func refreshStatusRows() {
refreshCodexVersionSection()
- notificationSettings.refreshAuthorizationStatus()
refreshRebuildableDates()
}
@@ -880,8 +878,8 @@ private extension AppSettingsView {
}
}
- if notificationSettings.isEnabled, notificationSettings.isAuthorizationDenied {
- notificationDeniedRow
+ if notificationSettings.needsAuthorization {
+ NotificationAuthorizationRow(settings: notificationSettings)
.transition(.identity)
.transaction { transaction in
transaction.animation = nil
@@ -901,22 +899,6 @@ private extension AppSettingsView {
}
}
- var notificationDeniedRow: some View {
- SettingsIndentedRow {
- Text("settings.notifications.system.permission-disabled")
- .font(.caption)
- .foregroundStyle(.red)
-
- Spacer(minLength: 8)
-
- Button("common.action.open-system-settings") {
- notificationSettings.openSystemNotificationSettings()
- }
- .controlSize(.small)
- .fixedSize()
- }
- }
-
// MARK: - 关于页
var versionRow: some View {
diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swift
index 4d64213..f2d7011 100644
--- a/CodexBar/Views/Settings/NotificationOptionsView.swift
+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift
@@ -473,3 +473,24 @@ struct NotificationOptionsView: View {
static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius
}
}
+
+struct NotificationAuthorizationRow: View {
+ let settings: NotificationSettings
+
+ var body: some View {
+ SettingsIndentedRow {
+ Text("settings.notifications.system.permission-disabled")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Spacer(minLength: 8)
+
+ Button("common.action.open-system-settings") {
+ settings.openSystemNotificationSettings()
+ }
+ .controlSize(.small)
+ .fixedSize()
+ }
+ }
+}
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index f16c82c..ca54535 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -61,7 +61,11 @@ View 和其他服务不直接创建系统通知。它们发布状态变化,通
总开关默认关闭,因此 App 首次运行不会无缘由弹出系统权限请求。用户主动开启后才调用 authorization API。
-App 激活时会重新读取系统状态,因为用户可能在 System Settings 中改过权限。如果 App 开关已开但系统仍为 `notDetermined`,会补发一次请求,覆盖用户在首次弹窗完成前退出的情况。
+App 激活、设置窗口重新获得焦点或显式打开时会重新读取系统状态。系统返回 `denied` 时保留 App 内的通知开关,显示灰色未授权提示和“打开系统设置”按钮。实际查询返回 `notDetermined` 时关闭 App 内开关,用户再次开启后重新申请授权;初始化时的占位值不修改已保存的开关。
+
+授权请求期间不重复发起请求,焦点变化也不会取消正在等待用户回应的请求。只要 App 内开关开启且系统尚未授权,就显示未授权提示。请求结束后若系统仍返回 `notDetermined`,开关恢复关闭,允许用户再次开启重试。
+
+授权请求结束后,权限读取统一走普通刷新流程。查询期间再次收到焦点刷新时,新查询替换旧查询,旧结果不会覆盖最新权限状态。
触觉反馈不依赖 `UNUserNotificationCenter` 授权,但仍服从 App 内总开关。这是能力边界的区别,不是绕过用户意图。
diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.md
index 00e3aac..f25b305 100644
--- a/Docs/en/DeveloperGuide/notifications.md
+++ b/Docs/en/DeveloperGuide/notifications.md
@@ -61,7 +61,11 @@ Inferring task completion from a current snapshot looks simpler, but every app l
The master switch is off by default, so first launch does not present an unexplained permission request. CodexBar invokes the authorization API only after the user enables it.
-The app rereads system state on activation because permission may have changed in System Settings. If the app switch is on but system state remains `notDetermined`, it requests again, covering a quit before the first dialog finished.
+The app rereads system state on app activation, when the settings window regains focus, and when settings are explicitly opened. A `denied` result preserves the in-app switch and displays a secondary-color permission message with an Open System Settings button. An actual `notDetermined` result turns the in-app switch off; enabling it again requests authorization. The initial placeholder status does not modify the saved switch.
+
+While an authorization request is pending, duplicate requests are suppressed and focus changes do not cancel the request awaiting the user's response. The permission message remains visible whenever the in-app switch is on and system authorization is missing. If the system still returns `notDetermined` after the request, the switch returns to off so the user can enable it again to retry.
+
+After the authorization request finishes, permission reads use the normal refresh flow. If another focus refresh arrives during a query, the new query replaces the old one so stale results cannot overwrite the latest permission state.
Haptic feedback does not depend on `UNUserNotificationCenter` authorization but still follows the in-app master switch. This is a capability boundary, not a way around user intent.