CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 补齐防休眠通知与 Hook 可用性校验
Bob4548313255c9
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9866d17..80d3960 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -130,7 +130,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev关键约束- `shouldDisableSleep` 是用户意图与依赖可用性的唯一汇合点, 要求 `isStarted && isEnabled && isHookEnabled && hasRunningTasks && helperStatus == .enabled && !isRefreshingHelper && !isLowBatteryActive && !hasReachedMaximumDuration` 同时成立; **依赖不满足只让效果失效, 绝不回写用户保存的 `isEnabled`**-- Hook 状态在类内只认 `isHookEnabled` 这份镜像, 不要回读 `codexHookSettings.isEnabled` 那个属性: 订阅回调跑在 `willSet`, 那一刻它还是改动前的值+- Hook 状态在类内只认 `isHookEnabled` 这份镜像, 它跟的是 `codexHookSettings.isOperable`; 不要回读那个属性, 订阅回调跑在 `willSet`, 那一刻它的两个输入里正在变的那一项还是旧值, 只能认 `CombineLatest` 给的闭包参数- 新增拦截条件一律加进 `sleepBlockReason` 的顺序判断里, 它和 `shouldDisableSleep` 同源, 顺带保证日志的 `reason=` 不会漏项- UI 用的 `isLowBatteryBlocking` 与 `canShowOptions` 由 `reconcileSleepState` 从 `sleepBlockReason` 单点派生, 新增拦截条件时 `allowsOptions` 那个穷举 `switch` 会强制表态, 于是不会出现入口亮着却点不动- `hasRunningTasks` 与 `isRefreshingHelper` 都不带 `@Published` 标注, 它们变得比结论频繁, 各自发信号会把整个设置页拖着一起重算@@ -171,7 +171,10 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- `send` 是唯一的提交入口, 返回一个 `Task<Bool, Never>?` 值, 需要等通知真的发出去再做下一步的调用方 `await` 它的 `value` 即可; 不要另开一条 async 通道, 那会悄悄少掉去重 时效判定与提交失败回调三项能力- 去重判定留在 `send` 的同步段而不是挪进 `Task` 内部, 这样连续两次调用的第二次一定被挡下, 不依赖任务调度顺序- `NotificationSettings` 管 CodexBar 自身通知; `CodexCLINotificationSettings` 是另一回事, 它通过 app-server `config/read` 与 `config/batchWrite` 读写 Codex 自己的用户级 `config.toml`-- 通知面板里带依赖的行一律显示为关闭并置灰而不是隐藏, 任务类看 `codexHookSettings.isEnabled`, 低电量保护通知看 `KeepAliveController.isLowBatteryProtectionEnabled` (阈值开着且这台机器确实有电池); 都不回写用户保存的开关+- 通知面板里带依赖的行一律显示为关闭并置灰而不是隐藏, 任务类看 `codexHookSettings.isOperable`, 低电量保护通知看 `KeepAliveController.isLowBatteryProtectionEnabled` (防休眠可用, 阈值开着, 且这台机器确实有电池), 防休眠上限通知看 `KeepAliveController.isMaximumDurationEnabled` (防休眠可用且不是无限制); 都不回写用户保存的开关+- 两条防休眠通知的依赖里都含"防休眠可用"这一层, 即防休眠开关与 Hook 都开着, 判定收在 `publishNotificationDependencies` 一处; 只判各自的子设置会让防休眠关着时这两行还亮着+- 带依赖的行由 `KeepAliveController` 判定并派生成一个值, 视图只读结论, 不在各视图各写一遍 `!= .unlimited` 这类规则+- 防休眠上限通知与低电量通知共用同一个发送时机; 达到上限是粘滞状态, 一个计时周期只发一次, 不需要低电量那种本轮已通知的锁存### 并发与隔离@@ -220,7 +223,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 两个子面板的顶边对齐各自主开关行, anchor 由设置页的 `ScreenFrameProvider` 随展开动作传出, 定位走 `SidePanelSupport.anchoredPosition` 而不是宿主底边- 设置窗口的子面板要传 `clampsToSurfaceBottom: false` 让底边可以探出窗口, 否则放不下时会把整个面板上推而错开主开关行; 主面板那三个面板走默认的 true- 两个子面板的高度都会变, 通知面板随音效行增删, 防休眠面板随 `hasBattery` 增删低电量那一行; resize 时要固定顶边向下生长, 直接改 size 会保持底边不动而把顶边顶离主开关行-- 高度重算只订阅真正会改变行数的那几项, 通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange` 再加 `KeepAliveController.$isLowBatteryProtectionEnabled` 一条, 防休眠面板只订 `$hasBattery` 一条; 订整个防休眠控制器会让任务每起停一次都白排一轮 resize+- 高度重算只订阅真正会改变行数的那几项, 通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange` 再加 `KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled` 两条, 防休眠面板只订 `$hasBattery` 一条; 订整个防休眠控制器会让任务每起停一次都白排一轮 resize+- 置灰也会改高度: 带音效的行置灰时音效子行跟着收起, 所以每个置灰依赖都要有一个对应的订阅源- 增删行或改行的显示条件时要同步补上对应的订阅源, 漏一项会让面板裁掉底部或留下空白- resize 的竖向夹紧走 `SidePanelSupport.clampedVertically`, 与初次展开的 `position` 同一条规则, 否则放不下时两边会把面板推向相反的边- 子面板入口只在开关开着且依赖就绪时出现, 通知看 `NotificationSettings.canShowOptions` 那个值, 防休眠看 `KeepAliveController.canShowOptions` 这个值; 两者都只控制入口显隐, 不回写用户保存的开关@@ -237,8 +241,12 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev`~/.codex/hooks.json` 的读写全部在 `CodexHookSettings` 里完成, Codex 目录优先取 `CODEX_HOME` 环境变量, 找不到时回退真实用户 HOME 下的 `.codex` 目录- 只识别并移除 command 同时包含当前 CodexBar 可执行路径与 `--hook-event` 的 handler, 必须保留用户已有 Hook 以及其他 App 的 Hook 和同事件下的其他 handler-- 写入前通过 app-server `config/read` 确认全局未禁用 Hook, 写入后用 `hooks/list` 验证+- 写入前通过 app-server `config/read` 确认全局未禁用 Hook, 写入后用 `hooks/list` 验证; 两处读取共用 `readGlobalHookDisabled`, 开关流程与校验流程对"全局禁用"的判断不会分叉- 读取失败 (I/O 或 JSON 格式错误) 不提供 Hook 装没装的信息, 必须保留上次已知值, 不能当成用户关闭了 Hook+- `isEnabled` 只表示 `hooks.json` 里装着, `isVerified` 是最近一次校验的明确结论, 两者与出来的 `isOperable` 才是"事件真的送得过来"; 依赖 Hook 的下游一律看 `isOperable`+- `isVerified` 乐观默认为 true 且只由明确结论写入两个方向: 校验只在设置窗口打开与 App 激活时跑, 而 RPC 失败属于"验不了"不是"确认不通", 那时置灰会把好用的功能关掉+- 全局禁用要排在 `hooks/list` 之前判: 它一关列表里必然找不到我们的 handler, 那时报"已不完整"会把用户引去翻本来就完好的 `hooks.json`+- 校验不通过时防休眠那一行的说明写"CodexBar Hook 未生效"而不是"需要启用 CodexBar Hook", 后者会让用户去开一个已经开着的开关; 具体病因由 Hook 那一行自己的说明给出## 隐私与数据边界diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 1250025..f5913a4 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -424,7 +424,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 61;+ CURRENT_PROJECT_VERSION = 62;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -441,7 +441,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.7;+ MARKETING_VERSION = 3.5.8;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -464,7 +464,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 61;+ CURRENT_PROJECT_VERSION = 62;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -481,7 +481,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.7;+ MARKETING_VERSION = 3.5.8;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex ddca083..bd8751e 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -163,12 +163,16 @@ final class SettingsWindowController: HostingWindowController {))},- // 音效子行随各开关增删, 低电量那一行还跟着防休眠的保护状态置灰- // 防休眠只订这一个派生值: 订整个控制器会让任务每起停一次都白重算一次高度+ // 音效子行随各开关增删, 低电量与上限那两行还跟着各自的依赖置灰+ // 置灰会连带收起音效子行, 所以两个依赖的派生值都要订上+ // 防休眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度contentChanges: Publishers.MergeMany([notificationSettings.objectWillChange.eraseToAnyPublisher(),codexHookSettings.objectWillChange.eraseToAnyPublisher(),keepAliveController.$isLowBatteryProtectionEnabled+ .map { _ in () }+ .eraseToAnyPublisher(),+ keepAliveController.$isMaximumDurationEnabled.map { _ in () }.eraseToAnyPublisher()]).eraseToAnyPublisher()diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex dda10ee..26bd88e 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -63,6 +63,9 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent inawait notificationService?.notifyLowBatteryProtection(percent: percent) ?? false}+ keepAliveController.onKeepAliveLimitTriggered = { [weak notificationService] duration in+ await notificationService?.notifyKeepAliveLimitReached(durationText: duration.title) ?? false+ }activityMonitor.start()keepAliveController.start()logLaunchState()diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 9398fe1..97fc734 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -17,9 +17,13 @@ final class KeepAliveController: ObservableObject {/// 当前是否因低电量而停止防休眠, 带滞回所以不等于"电量低于阈值"/// 会随电量自己翻转, 不需要外部清除, 与 hasReachedMaximumDuration 那种粘滞标志不是一回事@Published private(set) var isLowBatteryActive = false- /// 低电量保护是不是真的在起作用: 阈值开着且这台机器确实有电池+ /// 低电量保护是不是真的在起作用: 防休眠本身可用, 阈值开着, 且这台机器确实有电池/// 规则收在这里而不是各视图各写一遍: 通知面板要据此置灰那一行, 防休眠面板据此决定显不显示阈值@Published private(set) var isLowBatteryProtectionEnabled = false+ /// 时长上限是不是真的会到点: 防休眠本身可用, 且没选无限制+ /// 与 isLowBatteryProtectionEnabled 同一个用法, 视图只读结论, 不各自再判一次 unlimited+ /// 只在跨越边界时发信号, 1 小时改 2 小时不必让通知面板白排一轮高度重算+ @Published private(set) var isMaximumDurationEnabled = false/// 低电量是不是当下唯一拦住防休眠的那一项/// 由 reconcileSleepState 从 sleepBlockReason 派生, 见那里的说明@@ -55,6 +59,13 @@ final class KeepAliveController: ObservableObject {/// 返回值是通知有没有真的发出去, 决定这一轮算不算已通知var onLowBatteryTriggered: ((Int) async -> Bool)?+ /// 达到防休眠时长上限且休眠恢复成功之后回调一次+ /// 时长上限本身是粘滞状态, 每个计时周期天然只会进入一次+ /// 所以返回值用不上, 也不像低电量那条需要锁存: hasReached 粘滞且此刻已不在防休眠,+ /// 同一个周期里排不进第二次, 周期边界本身就是重置点+ /// 提交失败这一条就丢了, 重新 flush 需要再来一次休眠恢复, 而休眠已经恢复完了+ var onKeepAliveLimitTriggered: ((MaximumDuration) async -> Bool)?+/// 用户开关仍开着, 且 helper 已经真的把休眠关掉/// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它)/// 叠这一层是为了关开关到 helper 回调之间的异步空窗: 用户意图先落地@@ -95,10 +106,12 @@ final class KeepAliveController: ObservableObject {/// 只看是否接电不足以收口: 适配器接触不良时供电状态会反复翻转, 每翻一次都会重发一条/// 由电量回到解除门槛以上清除, 也就是电量真的回来了才算下一轮private var hasNotifiedLowBattery = false+ /// 达到时长上限后等待休眠恢复成功再发送, 恢复失败时保留给重试路径+ private var pendingKeepAliveLimit: MaximumDuration?private var cancellables = Set<AnyCancellable>()private var isStarted = falseprivate var lastLoggedSleepConditions: SleepConditions?- /// codexHookSettings.isEnabled 的最新值, 由订阅维护+ /// codexHookSettings.isOperable 的最新值, 由订阅维护/// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值private var isHookEnabled: Bool@@ -139,7 +152,7 @@ final class KeepAliveController: ObservableObject {self.codexHookSettings = codexHookSettingsself.defaults = defaultsdurationLimiter = KeepAliveDurationLimiter(defaults: defaults)- isHookEnabled = codexHookSettings.isEnabled+ isHookEnabled = codexHookSettings.isOperableisEnabled = defaults.bool(forKey: Self.enabledKey)// 默认关闭: 老版本升上来的用户不该多出一条中断任务的路径lowBatteryThreshold = (defaults.object(forKey: Self.lowBatteryThresholdKey) as? Int)@@ -154,12 +167,15 @@ final class KeepAliveController: ObservableObject {// Hook 是本功能的依赖, 不是用户意图// 只重新求值当前该不该防止系统休眠, 绝不改写用户保存的开关- // @Published 在 willSet 就发信号, 此刻回读 codexHookSettings.isEnabled 拿到的还是旧值- // 因此把新值先存进 isHookEnabled, 判定与日志都只认它- codexHookSettings.$isEnabled+ // 看 isOperable 那两个输入而不是只看 isEnabled: Codex 那边全局关掉 hooks+ // 或者不信任我们的 handler 时事件送不过来, 任务恒为空, 防休眠也就不该显示成可用+ // @Published 在 willSet 就发信号, 此刻回读 codexHookSettings.isOperable 会拿到+ // 正在变的那一项的旧值; CombineLatest 的两个参数都是各自的新值, 所以只认闭包参数+ Publishers.CombineLatest(codexHookSettings.$isEnabled, codexHookSettings.$isVerified)+ .map { $0 && $1 }.removeDuplicates()- .sink { [weak self] isEnabled in- self?.isHookEnabled = isEnabled+ .sink { [weak self] isOperable in+ self?.isHookEnabled = isOperableself?.reconcileSleepState(trigger: .hookChanged)}.store(in: &cancellables)@@ -209,6 +225,7 @@ final class KeepAliveController: ObservableObject {powerSourceMonitor.stop()assign(false, to: \.isLowBatteryActive)clearPendingLowBatteryNotification()+ pendingKeepAliveLimit = nilif connection != nil {applySleepDisabled(false)@@ -257,6 +274,8 @@ final class KeepAliveController: ObservableObject {func setMaximumDuration(_ duration: MaximumDuration) {durationLimiter.setDuration(duration)+ // limiter 只在这一轮累计过时才回调, 所以派生值不能等 reconcileSleepState 来带+ publishNotificationDependencies()}func setLowBatteryThreshold(_ threshold: LowBatteryThreshold) {@@ -302,10 +321,9 @@ final class KeepAliveController: ObservableObject {assign(reading.hasBattery, to: \.hasBattery)}// 阈值与 hasBattery 都只在这条路径上变, 派生值跟着一起收在这里- assign(- hasBattery && lowBatteryThreshold != .off,- to: \.isLowBatteryProtectionEnabled- )+ // 走这里而不是等 reconcileSleepState: handlePowerSourceChange 在低电量结论没变时就返回了,+ // 而 hasBattery 可能在同一次读数里刚变过+ publishNotificationDependencies()// 保护关掉了就没有可维持的状态, 这一条要排在读数判断之前guard let threshold = lowBatteryThreshold.percent else {@@ -378,6 +396,29 @@ final class KeepAliveController: ObservableObject {hasNotifiedLowBattery = await onLowBatteryTriggered?(percent) ?? false}+ /// 恢复休眠成功之后按当下的拦截原因发对应的那一条, 顺带把另一条作废+ /// 作废低电量只写 pendingLowBatteryPercent, 不能改走 clearPendingLowBatteryNotification:+ /// 那个方法会连 hasNotifiedLowBattery 一起清, 而这一轮低电量还没结束 (电量没回到解除门槛),+ /// 清了会让下一次跌破阈值重发第二条, 也就是供电状态反复翻转时每翻一次一条+ private func flushPendingSleepRestoreNotification() async {+ switch sleepBlockReason {+ case .lowBattery:+ pendingKeepAliveLimit = nil+ await flushPendingLowBatteryNotification()+ case .limitReached:+ pendingLowBatteryPercent = nil+ guard let duration = pendingKeepAliveLimit else {+ return+ }++ pendingKeepAliveLimit = nil+ _ = await onKeepAliveLimitTriggered?(duration)+ default:+ pendingLowBatteryPercent = nil+ pendingKeepAliveLimit = nil+ }+ }+private func clearPendingLowBatteryNotification() {pendingLowBatteryPercent = nilhasNotifiedLowBattery = false@@ -577,6 +618,7 @@ final class KeepAliveController: ObservableObject {private func reconcileSleepState(trigger: LogTrigger, force: Bool = false) {let blockReason = sleepBlockReasonlet wantsSleepDisabled = blockReason == nil+ updatePendingKeepAliveLimitNotification(for: blockReason)publishDerivedState(blockReason: blockReason)logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)@@ -596,6 +638,21 @@ final class KeepAliveController: ObservableObject {applySleepDisabled(true)}+ /// 只有实际防休眠正在生效时达到上限才排队+ /// 其他原因先解除防休眠时即使累计时长足够, 也不能把恢复动作归因给时长上限+ private func updatePendingKeepAliveLimitNotification(for blockReason: SleepBlockReason?) {+ guard blockReason == .limitReached else {+ pendingKeepAliveLimit = nil+ return+ }++ guard pendingKeepAliveLimit == nil, isActivelyPreventingSleep else {+ return+ }++ pendingKeepAliveLimit = maximumDuration+ }+/// UI 关心的两个布尔都从 blockReason 派生, 且只在这里写/// 这么做是因为 sleepBlockReason 里的输入 (任务, helper 刷新中) 变化远比结论频繁,/// 让它们各自 @Published 会把整个设置页拖着一起重算@@ -603,6 +660,22 @@ final class KeepAliveController: ObservableObject {private func publishDerivedState(blockReason: SleepBlockReason?) {assign(blockReason == .lowBattery, to: \.isLowBatteryBlocking)assign(Self.allowsOptions(blockReason), to: \.canShowOptions)+ publishNotificationDependencies()+ }++ /// 通知面板那两行的置灰依据+ /// 输入分散在三条路径上 (用户开关与 Hook 走 reconcileSleepState, 电量与阈值走 updateBatteryState,+ /// 上限走 setMaximumDuration), 所以规则只写这一份, 三处都调它+ private func publishNotificationDependencies() {+ let isKeepAliveUsable = isEnabled && isHookEnabled+ assign(+ isKeepAliveUsable && hasBattery && lowBatteryThreshold != .off,+ to: \.isLowBatteryProtectionEnabled+ )+ assign(+ isKeepAliveUsable && maximumDuration != .unlimited,+ to: \.isMaximumDurationEnabled+ )}/// 缺依赖时收起入口, 只是没在防休眠 (没任务, 低电量, 已达上限) 时仍然要能改设置@@ -730,7 +803,7 @@ final class KeepAliveController: ObservableObject {self.durationLimiter.pause()// 通知同样要赶在补发休眠之前发出去, 理由与收表相同// 走到这里 pmset 已经恢复成功, 那句"已恢复系统休眠"才站得住- await self.flushPendingLowBatteryNotification()+ await self.flushPendingSleepRestoreNotification()// 上面这一步会挂起, 期间可能已经有新的禁用请求接管// 那时再走恢复会释放掉刚建立的空闲断言, 所以重新认一次代guard generation == self.requestGeneration else {diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 3f7b2cc..e18ee00 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -404,6 +404,21 @@ final class CodexNotificationService: NSObject {)?.value ?? false}+ // MARK: - 防休眠时长上限++ /// 由 KeepAliveController 在达到时长上限且休眠恢复成功之后调用+ /// 调用时机与低电量通知相同, 必须赶在可能补发合盖休眠之前完成提交+ func notifyKeepAliveLimitReached(durationText: String) async -> Bool {+ guard settings.canDeliver, settings.isKeepAliveLimitEnabled else {+ return false+ }++ return await send(+ .keepAliveLimit(durationText: durationText),+ sound: settings.keepAliveLimitSound+ )?.value ?? false+ }+// MARK: - 重置次数临期提醒private func processCreditExpirations(_ snapshot: CodexQuotaSnapshot) {@@ -692,6 +707,14 @@ nonisolated struct CodexNotificationContent: Equatable {body: "电量剩余 \(percent)%, 已停止防休眠")}++ static func keepAliveLimit(durationText: String) -> CodexNotificationContent {+ CodexNotificationContent(+ kind: "keepAliveLimit",+ title: "已恢复系统休眠",+ body: "已达防休眠上限 \(durationText), 已停止防休眠"+ )+ }}// MARK: - UNUserNotificationCenterDelegatediff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex 8a8d9a8..10df1b2 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -7,6 +7,18 @@ import osfinal class CodexHookSettings: ObservableObject {@Published private(set) var isEnabled = false@Published private(set) var isUpdating = false+ /// 最近一次校验的明确结论: Codex 会不会真的执行 CodexBar 的 Hook+ /// 乐观默认: 校验只在设置窗口打开时跑, 没有反证之前不能把依赖 Hook 的功能关掉+ /// 只由明确结论写入两个方向, RPC 失败或被取消时保留上次的值:+ /// 连不上 app-server 不说明 Hook 坏了, 那时置灰会把好用的功能关掉+ @Published private(set) var isVerified = true++ /// Hook 链路真的通不通: hooks.json 里装着, 且最近一次校验没有明确失败+ /// 依赖 Hook 的下游 (防休眠, 任务类通知) 一律看这个+ /// isEnabled 只说明装了, Codex 那边全局关掉 hooks 或者不信任我们的 handler 时它照样是 true+ var isOperable: Bool {+ isEnabled && isVerified+ }/// 读取 hooks.json 失败, 由 refresh() 独立维护@Published private var readErrorMessage: String?@@ -120,8 +132,19 @@ final class CodexHookSettings: ObservableObject {private func verifyInstalledHooksWithAppServer(generation: Int) async {do {+ // 全局开关排在 hooks/list 之前: 它一关, 列表里必然找不到我们的 handler,+ // 那时报"已不完整"会把用户引去翻本来就完好的 hooks.json+ let globallyDisabled = try await readGlobalHookDisabled()+ try ensureCurrentUpdate(generation)+ guard !globallyDisabled else {+ assignVerified(false, reason: .globallyDisabled)+ operationErrorMessage = HookConfigError.hooksGloballyDisabled.localizedDescription+ return+ }+try await validateInstalledHooksWithAppServer()try ensureCurrentUpdate(generation)+ assignVerified(true, reason: .verified)operationErrorMessage = nil} catch is CancellationError {return@@ -130,16 +153,34 @@ final class CodexHookSettings: ObservableObject {return}+ // HookConfigError 是明确结论: Codex 答复了, 只是答复说这条链路不通+ assignVerified(false, reason: .validationFailed)operationErrorMessage = error.localizedDescription} catch {guard isCurrentUpdate(generation) else {return}+ // 这一支是"验不了"而不是"确认不通", isVerified 保留上次的值operationErrorMessage = "无法验证 Codex Hook: \(error.localizedDescription)"}}+ /// @Published 在 willSet 无条件发信号, 而每次 App 激活都会跑一次校验+ /// 同值赋值会让设置页与两个子面板反复空转, 所以走这里+ /// reason 是排查依据: 用户只会说"防休眠灰了", 那时得能从日志看出是全局禁用还是校验没过+ /// "验不了"那一支不调这里, 结论保持不变也就不该记一条变化+ private func assignVerified(_ verified: Bool, reason: HookVerificationReason) {+ guard isVerified != verified else {+ return+ }++ AppLog.hooks.notice(+ "Hook 链路校验结论变化: verified=\(verified ? 1 : 0); reason=\(reason.rawValue, privacy: .public)"+ )+ isVerified = verified+ }+private func runLatestUpdate(showProgress: Bool,_ operation: @escaping @MainActor (CodexHookSettings, Int) async -> Void@@ -237,6 +278,13 @@ private extension CodexHookSettings {static let empty = Self(keys: [], discoveryError: nil)}+ /// Hook 链路校验结论的变化理由, 只用于日志的 reason= 取值+ enum HookVerificationReason: String {+ case globallyDisabled+ case validationFailed+ case verified+ }+enum HookConfigError: LocalizedError {case invalidFormatcase hooksGloballyDisabled@@ -276,9 +324,14 @@ private extension CodexHookSettings {fileManager.homeDirectoryForCurrentUser.path}+ /// Codex 的 config.toml 里 features.hooks 是不是关着+ /// 开关流程与校验流程共用这一处读取, 两边对"全局禁用"的判断不会分叉+ func readGlobalHookDisabled() async throws -> Bool {+ try await codexStatusService.readCodexConfig().hooksGloballyDisabled+ }+func ensureCodexHooksGloballyEnabled() async throws {- let response = try await codexStatusService.readCodexConfig()- if response.hooksGloballyDisabled {+ if try await readGlobalHookDisabled() {throw HookConfigError.hooksGloballyDisabled}}diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex a855c4c..6f095f3 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -4,7 +4,7 @@ import Foundationimport osimport UserNotifications-/// 通知偏好: 总开关; 五类通知子开关及声音; 任务触觉开关; 两个阈值和系统授权状态镜像+/// 通知偏好: 总开关; 七类通知子开关及声音; 任务触觉开关; 两个阈值和系统授权状态镜像/// 授权请求/查询集中在这里, 通知与触觉反馈判定在 CodexNotificationService@MainActorfinal class NotificationSettings: ObservableObject {@@ -16,6 +16,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var isTaskHapticEnabled: Bool@Published private(set) var isCreditExpiryEnabled: Bool@Published private(set) var isLowBatteryEnabled: Bool+ @Published private(set) var isKeepAliveLimitEnabled: Bool@Published private(set) var lowQuotaThresholdPercent: Int@Published private(set) var longTaskThresholdSeconds: Int@Published private(set) var lowQuotaSound: NotificationSoundOption@@ -24,6 +25,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var taskWaitingSound: NotificationSoundOption@Published private(set) var creditExpirySound: NotificationSoundOption@Published private(set) var lowBatterySound: NotificationSoundOption+ @Published private(set) var keepAliveLimitSound: NotificationSoundOption@Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined/// 系统授权被拒时设置页展示引导, 通知服务停发@@ -73,6 +75,7 @@ final class NotificationSettings: ObservableObject {isTaskHapticEnabled = Self.bool(from: defaults, key: Self.taskHapticEnabledKey, defaultValue: true)isCreditExpiryEnabled = Self.bool(from: defaults, key: Self.creditExpiryEnabledKey, defaultValue: true)isLowBatteryEnabled = Self.bool(from: defaults, key: Self.lowBatteryEnabledKey, defaultValue: true)+ isKeepAliveLimitEnabled = Self.bool(from: defaults, key: Self.keepAliveLimitEnabledKey, defaultValue: true)lowQuotaThresholdPercent = Self.option(defaults.object(forKey: Self.lowQuotaThresholdKey) as? Int,in: Self.lowQuotaThresholdOptions,@@ -89,6 +92,7 @@ final class NotificationSettings: ObservableObject {taskWaitingSound = Self.sound(from: defaults, key: Self.taskWaitingSoundKey)creditExpirySound = Self.sound(from: defaults, key: Self.creditExpirySoundKey)lowBatterySound = Self.sound(from: defaults, key: Self.lowBatterySoundKey)+ keepAliveLimitSound = Self.sound(from: defaults, key: Self.keepAliveLimitSoundKey)}deinit {@@ -136,6 +140,10 @@ final class NotificationSettings: ObservableObject {setBool(enabled, current: &isLowBatteryEnabled, key: Self.lowBatteryEnabledKey)}+ func setKeepAliveLimitEnabled(_ enabled: Bool) {+ setBool(enabled, current: &isKeepAliveLimitEnabled, key: Self.keepAliveLimitEnabledKey)+ }+func setLowQuotaThresholdPercent(_ percent: Int) {guard Self.lowQuotaThresholdOptions.contains(percent),percent != lowQuotaThresholdPercent else {@@ -180,6 +188,10 @@ final class NotificationSettings: ObservableObject {setSound(sound, current: &lowBatterySound, key: Self.lowBatterySoundKey)}+ func setKeepAliveLimitSound(_ sound: NotificationSoundOption) {+ setSound(sound, current: &keepAliveLimitSound, key: Self.keepAliveLimitSoundKey)+ }+/// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取func refreshAuthorizationStatus() {authorizationTask?.cancel()@@ -243,7 +255,7 @@ final class NotificationSettings: ObservableObject {return}- // 六个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志+ // 七个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志AppLog.notification.notice("通知选项变更: key=\(key, privacy: .public); enabled=\(value ? 1 : 0)")@@ -297,6 +309,7 @@ final class NotificationSettings: ObservableObject {private static let taskHapticEnabledKey = "Notification.taskHapticEnabled"private static let creditExpiryEnabledKey = "Notification.creditExpiryEnabled"private static let lowBatteryEnabledKey = "Notification.lowBatteryEnabled"+ private static let keepAliveLimitEnabledKey = "Notification.keepAliveLimitEnabled"private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"private static let longTaskThresholdKey = "Notification.longTaskThresholdSeconds"private static let lowQuotaSoundKey = "Notification.lowQuotaSound"@@ -305,4 +318,5 @@ final class NotificationSettings: ObservableObject {private static let taskWaitingSoundKey = "Notification.taskWaitingSound"private static let creditExpirySoundKey = "Notification.creditExpirySound"private static let lowBatterySoundKey = "Notification.lowBatterySound"+ private static let keepAliveLimitSoundKey = "Notification.keepAliveLimitSound"}diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 5c6e430..3805042 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -412,7 +412,7 @@ private extension AppSettingsView {get: { keepAliveController.isEnabled },set: { keepAliveController.setEnabled($0) }),- isEnabled: codexHookSettings.isEnabled && !codexHookSettings.isUpdating+ isEnabled: codexHookSettings.isOperable && !codexHookSettings.isUpdating) {optionsButton(isAvailable: canShowKeepAliveOptions) {onOptionsAction(@@ -486,6 +486,11 @@ private extension AppSettingsView {guard codexHookSettings.isEnabled else {return KeepAliveCaption(message: "需要启用 CodexBar Hook")}+ // 装着但校验不通过时不能说"需要启用", 那句会让用户去开一个已经开着的开关+ // 具体是全局禁用还是不被信任, 由上面 Hook 那一行的说明给出, 这里只说结果+ guard codexHookSettings.isVerified else {+ return KeepAliveCaption(message: "CodexBar Hook 未生效")+ }guard keepAliveController.isEnabled else {return KeepAliveCaption(message: "当有 Codex 任务运行时防止系统休眠, 任务结束后自动恢复")}diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex a9b932e..ce20441 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -18,6 +18,7 @@ struct NotificationOptionsView: View {quotaResetRowcreditExpiryRowlowBatteryRow+ keepAliveLimitRowtaskHapticRowcodexCLINotificationRow}@@ -78,9 +79,9 @@ struct NotificationOptionsView: View {)}- /// Hook 未开启时显示为关闭并置灰, 不修改持久化的 isLongTaskEnabled+ /// Hook 未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isLongTaskEnabledprivate var longTaskRow: some View {- let isDisplayedOn = codexHookSettings.isEnabled && notificationSettings.isLongTaskEnabled+ let isDisplayedOn = codexHookSettings.isOperable && notificationSettings.isLongTaskEnabledreturn notificationOptionRow(title: "任务完成通知",@@ -88,7 +89,7 @@ struct NotificationOptionsView: View {get: { isDisplayedOn },set: { notificationSettings.setLongTaskEnabled($0) }),- isEnabled: codexHookSettings.isEnabled,+ isEnabled: codexHookSettings.isOperable,sound: Binding(get: { notificationSettings.longTaskSound },set: { notificationSettings.setLongTaskSound($0) }@@ -106,9 +107,9 @@ struct NotificationOptionsView: View {}}- /// Hook 未开启时显示为关闭并置灰, 不修改持久化的 isTaskWaitingEnabled+ /// Hook 未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isTaskWaitingEnabledprivate var taskWaitingRow: some View {- let isDisplayedOn = codexHookSettings.isEnabled && notificationSettings.isTaskWaitingEnabled+ let isDisplayedOn = codexHookSettings.isOperable && notificationSettings.isTaskWaitingEnabledreturn notificationOptionRow(title: "任务等待通知",@@ -116,7 +117,7 @@ struct NotificationOptionsView: View {get: { isDisplayedOn },set: { notificationSettings.setTaskWaitingEnabled($0) }),- isEnabled: codexHookSettings.isEnabled,+ isEnabled: codexHookSettings.isOperable,sound: Binding(get: { notificationSettings.taskWaitingSound },set: { notificationSettings.setTaskWaitingSound($0) }@@ -124,9 +125,9 @@ struct NotificationOptionsView: View {)}- /// Hook 未开启时显示为关闭并置灰, 不修改持久化的 isTaskHapticEnabled+ /// Hook 未开启或链路校验不通时显示为关闭并置灰, 不修改持久化的 isTaskHapticEnabledprivate var taskHapticRow: some View {- let isDisplayedOn = codexHookSettings.isEnabled && notificationSettings.isTaskHapticEnabled+ let isDisplayedOn = codexHookSettings.isOperable && notificationSettings.isTaskHapticEnabledreturn optionRow(title: "任务触觉反馈",@@ -134,7 +135,7 @@ struct NotificationOptionsView: View {get: { isDisplayedOn },set: { notificationSettings.setTaskHapticEnabled($0) }),- isEnabled: codexHookSettings.isEnabled+ isEnabled: codexHookSettings.isOperable)}@@ -152,7 +153,7 @@ struct NotificationOptionsView: View {)}- /// 低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled+ /// 防休眠关着或低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled/// 保护默认就是关的, 不置灰会让这一行在任何默认安装上都亮着, 而对应通知永远发不出来/// "保护是不是真的在起作用"由 KeepAliveController 判定, 这里只读结论/// 它同时覆盖了台式机: 那时防休眠面板整行隐藏低电量保护, 而阈值可能是从笔记本迁移过来的非 off 值@@ -174,6 +175,26 @@ struct NotificationOptionsView: View {)}+ /// 防休眠关着或选了无限制时显示为关闭并置灰, 不修改持久化的 isKeepAliveLimitEnabled+ /// 与低电量那一行同一个做法, "上限会不会到点"由 KeepAliveController 判定, 这里只读结论+ private var keepAliveLimitRow: some View {+ let hasLimit = keepAliveController.isMaximumDurationEnabled+ let isDisplayedOn = hasLimit && notificationSettings.isKeepAliveLimitEnabled++ return notificationOptionRow(+ title: "防休眠上限通知",+ isOn: Binding(+ get: { isDisplayedOn },+ set: { notificationSettings.setKeepAliveLimitEnabled($0) }+ ),+ isEnabled: hasLimit,+ sound: Binding(+ get: { notificationSettings.keepAliveLimitSound },+ set: { notificationSettings.setKeepAliveLimitSound($0) }+ )+ )+ }+private var codexCLINotificationRow: some View {optionRow(title: "Codex TUI 通知",@@ -403,7 +424,7 @@ struct NotificationOptionsView: View {static let panelWidth: CGFloat = 320static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding- static let notificationRowCount = 6+ static let notificationRowCount = 7static let standardRowCount = 2static let totalRowCount = notificationRowCount + standardRowCountstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingdiff --git a/README.md b/README.mdindex 0c1eb6b..8f5af52 100644--- a/README.md+++ b/README.md@@ -61,7 +61,7 @@ CodexBar 把 Codex 的运行状态收进菜单栏: 账户信息, 剩余额度,### 通知与提醒-- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期, 低电量保护生效+- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期, 低电量保护生效, 防休眠阈值- 通知音效独立设置- 任务状态变化可设置触摸板震动反馈通知diff --git a/appcast.xml b/appcast.xmlindex 14c2252..9c8ced2 100644--- a/appcast.xml+++ b/appcast.xml@@ -7,6 +7,15 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 3.5.8</title>+ <sparkle:version>62</sparkle:version>+ <sparkle:shortVersionString>3.5.8</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.8</sparkle:releaseNotesLink>+ <pubDate>Thu, 30 Jul 2026 11:51:19 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.8.dmg" sparkle:edSignature="pG3e0I+c/8ePLmTImZiKtvXiavt+HAShuAXH7DgJYokmjxCCqPnn1v7cHtZ1cIncjE+eE3yVXl5ljEOKvPRKAg==" length="6001866" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.5.7</title><sparkle:version>61</sparkle:version>