CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 修复额度重置通知
Bob8811f26207b9
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 91a9c92..424d167 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -282,7 +282,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 40;+ CURRENT_PROJECT_VERSION = 41;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -298,7 +298,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.3.2;+ MARKETING_VERSION = 3.3.3;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -321,7 +321,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 40;+ CURRENT_PROJECT_VERSION = 41;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -337,7 +337,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.3.2;+ MARKETING_VERSION = 3.3.3;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 165a554..cfad12b 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -3,7 +3,7 @@ import Combineimport Foundationimport UserNotifications-/// 集中式提醒服务: 订阅额度与实时活动,负责触觉反馈、阈值判定、去重、重置调度与本地通知发送。+/// 集中式提醒服务: 订阅额度与实时活动,负责触觉反馈、阈值判定、去重、重置识别与本地通知发送。@MainActorfinal class CodexNotificationService: NSObject {private let settings: NotificationSettings@@ -14,17 +14,19 @@ final class CodexNotificationService: NSObject {private var cancellables = Set<AnyCancellable>()private var taskHapticFeedbackTask: Task<Void, Never>?- private let resetReminderScheduler = ReminderCheckScheduler()private let creditExpiryReminderScheduler = ReminderCheckScheduler()private var latestQuotaSnapshot: CodexQuotaSnapshot?- /// 待发送的重置完成提醒与已发送去重键的内存镜像, 变更时才写回 UserDefaults- private var pendingResetReminders: [PendingQuotaResetReminder]+ /// 已发送去重键的内存镜像, 变更时才写回 UserDefaultsprivate var sentDedupKeys: [String]+ private var submittingDedupKeys = Set<String>()/// 阈值穿越判定的会话内上一帧剩余比例, key 为 account|limitId|windowIdprivate var lastRemainingPercents: [String: Int] = [:]+ /// 可信快照中每个额度窗口的重置观察状态;窗口消失后重现会获得新的生命周期标记。+ private var quotaWindowResetObservations: [String: QuotaWindowResetObservation] = [:]+init(settings: NotificationSettings,statusViewModel: CodexStatusViewModel,@@ -37,8 +39,12 @@ final class CodexNotificationService: NSObject {self.activityMonitor = activityMonitorself.defaults = defaultsself.openMenuSurface = openMenuSurface- pendingResetReminders = Self.loadPendingResetReminders(from: defaults)- sentDedupKeys = defaults.stringArray(forKey: Self.sentKeysKey) ?? []+ let storedDedupKeys = defaults.stringArray(forKey: Self.sentKeysKey) ?? []+ sentDedupKeys = storedDedupKeys.filter { !$0.hasPrefix(Self.legacyResetDedupKeyPrefix) }+ if sentDedupKeys.count != storedDedupKeys.count {+ defaults.set(sentDedupKeys, forKey: Self.sentKeysKey)+ }+ defaults.removeObject(forKey: Self.legacyPendingResetReminderKey)super.init()}@@ -62,12 +68,11 @@ final class CodexNotificationService: NSObject {}.store(in: &cancellables)- // 休眠可能错过 resetsAt, 唤醒时补检+ // 休眠可能错过重置次数的临期检查, 唤醒时补检NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.didWakeNotification).receive(on: DispatchQueue.main).sink { [weak self] _ in- self?.deliverDueResetReminders()self?.deliverDueCreditExpiryReminders()}.store(in: &cancellables)@@ -133,35 +138,54 @@ final class CodexNotificationService: NSObject {private func handleSnapshot(_ snapshot: CodexQuotaSnapshot?) {guard let snapshot else {latestQuotaSnapshot = nil+ quotaWindowResetObservations.removeAll()scheduleNextCreditExpiryCheck(dates: [])return}latestQuotaSnapshot = snapshot- guard settings.canDeliver else {- scheduleNextCreditExpiryCheck(dates: [])- return- }-// stale 快照是旧缓存, 不参与额度判定, 避免误报if !snapshot.isRateLimitsStale {processQuotaWindows(snapshot)}+ guard settings.canDeliver else {+ scheduleNextCreditExpiryCheck(dates: [])+ return+ }+processCreditExpirations(snapshot)- deliverDueResetReminders()}private func processQuotaWindows(_ snapshot: CodexQuotaSnapshot) {+ var observedWindowKeys = Set<String>()+ forEachQuotaWindowWithData(in: snapshot) { window, limit, stateKey in+ observedWindowKeys.insert(stateKey)+ if quotaWindowResetObservations[stateKey] == nil {+ quotaWindowResetObservations[stateKey] = QuotaWindowResetObservation()+ }+ processQuotaWindow(window, limit: limit, stateKey: stateKey)+ }+ quotaWindowResetObservations = quotaWindowResetObservations.filter {+ observedWindowKeys.contains($0.key)+ }+ }++ /// 枚举可信快照中有数据的额度窗口, 窗口过滤与 stateKey 口径的唯一定义处+ private func forEachQuotaWindowWithData(+ in snapshot: CodexQuotaSnapshot,+ _ body: (QuotaWindow, CodexQuotaLimitSnapshot, String) -> Void+ ) {let accountKey = Self.accountKey(for: snapshot)for limit in snapshot.limits {for window in limit.windows where window.hasData {- processQuotaWindow(- window,- limit: limit,- accountKey: accountKey+ let stateKey = Self.quotaWindowStateKey(+ accountKey: accountKey,+ limitId: limit.limitId,+ windowId: window.id)+ body(window, limit, stateKey)}}}@@ -174,137 +198,98 @@ final class CodexNotificationService: NSObject {return}- resetQuotaObservation(for: snapshot)+ resetLowQuotaObservation(for: snapshot)processQuotaWindows(snapshot)}- private func resetQuotaObservation(for snapshot: CodexQuotaSnapshot) {- let accountKey = Self.accountKey(for: snapshot)- for limit in snapshot.limits {- for window in limit.windows where window.hasData {- let stateKey = Self.quotaWindowStateKey(- accountKey: accountKey,- limitId: limit.limitId,- windowId: window.id- )- lastRemainingPercents.removeValue(forKey: stateKey)- }+ private func resetLowQuotaObservation(for snapshot: CodexQuotaSnapshot) {+ forEachQuotaWindowWithData(in: snapshot) { _, _, stateKey in+ lastRemainingPercents.removeValue(forKey: stateKey)}}private func processQuotaWindow(_ window: QuotaWindow,limit: CodexQuotaLimitSnapshot,- accountKey: String+ stateKey: String) {- let stateKey = Self.quotaWindowStateKey(- accountKey: accountKey,- limitId: limit.limitId,- windowId: window.id+ guard let usedPercent = window.usedPercent else {+ return+ }++ trackQuotaResetTransition(+ stateKey: stateKey,+ usedPercent: usedPercent,+ limit: limit,+ window: window)- let previous = lastRemainingPercents[stateKey]- lastRemainingPercents[stateKey] = window.remainingPercent- guard let resetsAt = window.resetsAt else {+ guard settings.canDeliver else {return}- // 每个可信额度窗口都登记本周期重置提醒, 不依赖低额度阈值或子开关- rememberPendingResetReminder(- accountKey: accountKey,- limitId: limit.limitId,- window: window,- resetsAt: resetsAt- )+ let previousRemainingPercent = lastRemainingPercents[stateKey]+ lastRemainingPercents[stateKey] = window.remainingPercent- guard window.remainingPercent <= settings.lowQuotaThresholdPercent,+ guard let resetsAt = window.resetsAt,+ window.remainingPercent <= settings.lowQuotaThresholdPercent,settings.isLowQuotaEnabled else {return}// 穿越判定: 上一帧高于阈值才提醒; 会话内首次观察即低于也视为穿越// (App 可能在跌破后才启动), 持久化去重键保证每周期只发一次- if let previous, previous <= settings.lowQuotaThresholdPercent {- return- }-- let dedupKey = "low|\(accountKey)|\(limit.limitId)|\(window.id)|\(Self.epoch(resetsAt))"- guard consumeDedupKey(dedupKey) else {+ if let previousRemainingPercent,+ previousRemainingPercent <= settings.lowQuotaThresholdPercent {return}+ let dedupKey = "low|\(stateKey)|\(Self.epoch(resetsAt))"send(.lowQuota(limitTitle: limit.title,windowLabel: window.label,thresholdPercent: settings.lowQuotaThresholdPercent- )- )- }-- // MARK: - 重置完成提醒-- private func rememberPendingResetReminder(- accountKey: String,- limitId: String,- window: QuotaWindow,- resetsAt: Date- ) {- let reminder = PendingQuotaResetReminder(- accountKey: accountKey,- limitId: limitId,- windowId: window.id,- windowLabel: window.label,- resetsAt: resetsAt,- windowDurationMins: window.windowDurationMins- )-- guard !pendingResetReminders.contains(reminder), !hasSent(reminder.dedupKey) else {- return+ ),+ dedupKey: dedupKey+ ) { [weak self] in+ self?.lastRemainingPercents.removeValue(forKey: stateKey)}-- pendingResetReminders.append(reminder)- persistPendingResetReminders()}- private func deliverDueResetReminders() {- let now = Date()- var remaining: [PendingQuotaResetReminder] = []-- for reminder in pendingResetReminders {- if reminder.resetsAt > now {- remaining.append(reminder)- continue- }-- // 已到重置时刻: 超时效或已发过的直接丢弃- guard now < reminder.validUntil, !hasSent(reminder.dedupKey) else {- continue- }+ // MARK: - 额度重置提醒- // 开关或授权此刻关闭时保留, 时效内等下一次快照/唤醒重试+ private func trackQuotaResetTransition(+ stateKey: String,+ usedPercent: Int,+ limit: CodexQuotaLimitSnapshot,+ window: QuotaWindow+ ) {+ if usedPercent > 0 {+ quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true+ } else if usedPercent == 0,+ quotaWindowResetObservations[stateKey]?.hasObservedConsumption == true {+ // 归零即消费待重置状态; 开关或授权此刻不可用时不保留补发。+ quotaWindowResetObservations[stateKey]?.hasObservedConsumption = falseguard settings.canDeliver,settings.isQuotaResetEnabled,- consumeDedupKey(reminder.dedupKey) else {- remaining.append(reminder)- continue+ let lifecycleToken = quotaWindowResetObservations[stateKey]?.lifecycleToken else {+ return}- send(.quotaReset(windowLabel: reminder.windowLabel))- }-- if remaining != pendingResetReminders {- pendingResetReminders = remaining- persistPendingResetReminders()- }- scheduleNextResetCheck()- }+ send(+ .quotaReset(+ limitTitle: limit.title,+ windowLabel: window.label+ )+ ) { [weak self] in+ guard let self,+ quotaWindowResetObservations[stateKey]?.lifecycleToken == lifecycleToken else {+ return+ }- private func scheduleNextResetCheck() {- let now = Date()- let nextDate = pendingResetReminders.map(\.resetsAt).filter { $0 > now }.min()- resetReminderScheduler.schedule(at: nextDate) { [weak self] in- self?.deliverDueResetReminders()+ quotaWindowResetObservations[stateKey]?.hasObservedConsumption = true+ }}}@@ -331,11 +316,10 @@ final class CodexNotificationService: NSObject {}let dedupKey = "credit|\(accountKey)|\(epochSecond)|\(reminderDay)d"- guard consumeDedupKey(dedupKey) else {- continue- }-- send(.creditExpiry(count: groupedDates.count, expirationDate: date))+ send(+ .creditExpiry(count: groupedDates.count, expirationDate: date),+ dedupKey: dedupKey+ )}scheduleNextCreditExpiryCheck(dates: dates)@@ -363,48 +347,29 @@ final class CodexNotificationService: NSObject {// MARK: - 去重与持久化- /// 未发过则记录并返回 true; 已发过返回 false- private func consumeDedupKey(_ key: String) -> Bool {- guard !sentDedupKeys.contains(key) else {- return false- }-+ private func rememberSentDedupKey(_ key: String) {sentDedupKeys.append(key)if sentDedupKeys.count > Self.sentKeysLimit {sentDedupKeys.removeFirst(sentDedupKeys.count - Self.sentKeysLimit)}defaults.set(sentDedupKeys, forKey: Self.sentKeysKey)- return true- }-- private func hasSent(_ key: String) -> Bool {- sentDedupKeys.contains(key)}- private static func loadPendingResetReminders(from defaults: UserDefaults) -> [PendingQuotaResetReminder] {- guard let data = defaults.data(forKey: pendingResetRemindersKey),- let reminders = try? JSONDecoder().decode(- [PendingQuotaResetReminder].self,- from: data- ) else {- return []- }-- return reminders- }+ // MARK: - 发送与文案- private func persistPendingResetReminders() {- guard let data = try? JSONEncoder().encode(pendingResetReminders) else {- return+ private func send(+ _ notification: CodexNotificationContent,+ dedupKey: String? = nil,+ onFailure: (() -> Void)? = nil+ ) {+ if let dedupKey {+ guard !sentDedupKeys.contains(dedupKey),+ submittingDedupKeys.insert(dedupKey).inserted else {+ return+ }}- defaults.set(data, forKey: Self.pendingResetRemindersKey)- }-- // MARK: - 发送与文案-- private func send(_ notification: CodexNotificationContent) {let content = UNMutableNotificationContent()content.title = notification.titlecontent.body = notification.body@@ -415,7 +380,31 @@ final class CodexNotificationService: NSObject {content: content,trigger: nil)- UNUserNotificationCenter.current().add(request)+ Task { @MainActor [weak self] in+ guard let self else {+ return+ }++ defer {+ if let dedupKey {+ submittingDedupKeys.remove(dedupKey)+ }+ }++ for _ in 0 ... Self.notificationSubmissionRetryCount {+ do {+ try await UNUserNotificationCenter.current().add(request)+ if let dedupKey {+ rememberSentDedupKey(dedupKey)+ }+ return+ } catch {+ continue+ }+ }++ onFailure?()+ }}private nonisolated static func accountKey(for snapshot: CodexQuotaSnapshot) -> String {@@ -461,9 +450,18 @@ final class CodexNotificationService: NSObject {private nonisolated static let creditExpiryLeadTime: TimeInterval = 7 * dayprivate static let taskHapticPulseCount = 10private static let taskHapticPulseInterval = Duration.milliseconds(100)+ private static let notificationSubmissionRetryCount = 1private static let sentKeysLimit = 300private static let sentKeysKey = "Notification.sentKeys"- private static let pendingResetRemindersKey = "Notification.pendingResetReminders"+ private static let legacyResetDedupKeyPrefix = "reset|"+ private static let legacyPendingResetReminderKey = "Notification.pendingResetReminders"++ /// 单个额度窗口的重置观察状态: 记录大于 0 的消耗, 归零时消费并发送+ private struct QuotaWindowResetObservation {+ /// 窗口生命周期标记, 迟到的发送失败回调据此丢弃+ let lifecycleToken = UUID()+ var hasObservedConsumption = false+ }}nonisolated struct CodexNotificationContent: Equatable {@@ -481,10 +479,13 @@ nonisolated struct CodexNotificationContent: Equatable {)}- static func quotaReset(windowLabel: String) -> CodexNotificationContent {+ static func quotaReset(+ limitTitle: String,+ windowLabel: String+ ) -> CodexNotificationContent {CodexNotificationContent(- title: "Codex 额度重置",- body: "\(windowLabel) 窗口额度即将重置"+ title: "额度已重置",+ body: "\(limitTitle) \(windowLabel)")}@@ -516,12 +517,12 @@ nonisolated struct CodexNotificationContent: Equatable {// MARK: - UNUserNotificationCenterDelegateextension CodexNotificationService: UNUserNotificationCenterDelegate {- /// 菜单栏常驻应用处于前台时也要展示横幅+ /// 菜单栏常驻应用处于前台时也要展示横幅并播放声音nonisolated func userNotificationCenter(_: UNUserNotificationCenter,willPresent _: UNNotification) async -> UNNotificationPresentationOptions {- [.banner, .list]+ [.banner, .list, .sound]}nonisolated func userNotificationCenter(@@ -563,22 +564,3 @@ private final class ReminderCheckScheduler {}}}--/// 已知下次重置时间的额度窗口, 在 resetsAt 到达时发送提醒-private nonisolated struct PendingQuotaResetReminder: Codable, Equatable {- let accountKey: String- let limitId: String- let windowId: String- let windowLabel: String- let resetsAt: Date- let windowDurationMins: Int?-- var dedupKey: String {- "reset|\(accountKey)|\(limitId)|\(windowId)|\(Int(resetsAt.timeIntervalSince1970))"- }-- /// 补发时效: 超过一个窗口周期不再提醒, 周期未知按 24h- var validUntil: Date {- resetsAt.addingTimeInterval(TimeInterval((windowDurationMins ?? 1440) * 60))- }-}diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 2724c23..5a4c2f3 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -23,9 +23,20 @@ final class NotificationSettings: ObservableObject {authorizationStatus == .denied}- /// 总开关开启且授权未被拒时才允许发送+ /// 总开关开启且系统已明确允许时才发送, 未决定或未知状态都按不可发送处理。var canDeliver: Bool {- isEnabled && !isAuthorizationDenied+ guard isEnabled else {+ return false+ }++ switch authorizationStatus {+ case .authorized, .provisional, .ephemeral:+ return true+ case .notDetermined, .denied:+ return false+ @unknown default:+ return false+ }}/// 触觉反馈不依赖系统通知授权,但服从 App 内通知总开关。@@ -35,7 +46,7 @@ final class NotificationSettings: ObservableObject {/// 子选项面板仅在总开关开启且授权已明确通过时可展示var canShowOptions: Bool {- isEnabled && authorizationStatus != .notDetermined && authorizationStatus != .denied+ canDeliver}static let lowQuotaThresholdOptions = [5, 10, 25]diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swiftindex 1924fef..f5d40be 100644--- a/CodexBar/Views/Menu/CodexActivityCard.swift+++ b/CodexBar/Views/Menu/CodexActivityCard.swift@@ -34,11 +34,13 @@ struct CodexActivityCard: View {.lineLimit(1).truncationMode(.middle)- Text(content.detail)- .font(.caption2)- .foregroundStyle(.secondary)- .lineLimit(1)- .truncationMode(.tail)+ if let detail = content.detail {+ Text(detail)+ .font(.caption2)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ .truncationMode(.tail)+ }}Spacer(minLength: 0)@@ -74,10 +76,11 @@ struct CodexActivityCard: View {otherTaskCount: otherTaskCount)case let .running(task):- var titles = [task.projectName ?? "Codex"]+ var titles: [String] = []if let modelName = task.modelName {titles.append(modelName)}+ titles.append(task.projectName ?? "Codex")var details: [String] = []if task.showsPreciseDuration, let startedAt = task.startedAt {@@ -111,7 +114,7 @@ struct CodexActivityCard: View {symbolName: "waveform.path",tint: .secondary,title: "暂无 Codex 活动",- detail: "Codex Hook 正在监测",+ detail: nil,otherTaskCount: 0)}@@ -162,6 +165,6 @@ private struct ActivityCardContent {let symbolName: Stringlet tint: Colorlet title: String- let detail: String+ let detail: String?let otherTaskCount: Int}diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.mdindex 058c82d..f80535a 100644--- a/Docs/DevelopmentGuide.md+++ b/Docs/DevelopmentGuide.md@@ -909,7 +909,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并| 开机自动启动 | `SMAppService.mainApp.status` | `register()` / `unregister()` || 自动检查更新 | Sparkle updater | 设置 `automaticallyChecksForUpdates` || 菜单栏额度指示 | `MenuBarQuotaSettings.selection` / `MenuBarQuota.lastWindowSelection` | 开关写入 `.off` 或恢复持久化的上次窗口选择, 窗口菜单写入所选窗口并同步记住; 标签优先来自当前账号 Codex limit 返回的额度窗口, 缺失时使用 fallback 标题 |-| 系统通知 | `NotificationSettings` + `UNUserNotificationCenter` | 总开关、五类通知子开关、任务触觉开关与阈值写入 `UserDefaults`; 首次开启时请求系统通知授权 |+| 系统通知 | `NotificationSettings` + `UNUserNotificationCenter` | 总开关、五类通知子开关、任务触觉开关与阈值写入 `UserDefaults`; 首次开启时请求系统通知授权 || 使用快捷键 | `GlobalHotKeySettings.shortcut` | 写入 `UserDefaults` 并注册 hot key || 启用 Codex Hook | app-server `config/read` / `hooks/list` / `config/batchWrite`, `~/.codex/hooks.json` | 检查全局 Hook 开关后追加或移除当前 CodexBar command hook, 并维护对应 `hooks.state` 信任状态 || 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |@@ -1084,7 +1084,7 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并通知与触觉反馈判定在 `CodexBar/Services/Notifications/`, 偏好类随其他设置类放在 `CodexBar/Services/Settings/`:- `NotificationSettings` (`Services/Settings/`): 总开关、五类通知子开关、任务触觉开关、低额度阈值 (5%/10%/25%, 默认 10%) 和长任务时长 (30s/1m/2m/5m, 默认 1m), 持久化到 UserDefaults; 负责系统授权请求、被拒状态镜像和设置页选项面板可展示状态-- `CodexNotificationService`: 集中判定、去重、调度与发送; 由 `CodexBarAppDelegate` 创建, 订阅 `CodexStatusViewModel.$snapshot`、`CodexActivityMonitor` live transition 与 `NSWorkspace.didWakeNotification`; 五类正式通知共用 `CodexNotificationContent` 文案工厂,等待与完成 transition 还会按偏好请求 AppKit `.levelChange` 触觉反馈+- `CodexNotificationService`: 集中判定、去重、调度与发送; 由 `CodexBarAppDelegate` 创建, 订阅 `CodexStatusViewModel.$snapshot`、`CodexActivityMonitor` live transition 与 `NSWorkspace.didWakeNotification`; 五类正式通知共用 `CodexNotificationContent` 文案工厂,系统提交失败时重试一次,等待与完成 transition 还会按偏好请求 AppKit `.levelChange` 触觉反馈- `CodexActivityMonitor`: Hook 开启期间始终运行并维护并发任务;向 UI 发布快照,向提醒服务发布 live transition。单个 live 批次先完整应用事件,再按任务键合并等待候选;只有批次结束后仍处于等待的任务会使用最终快照发布一次等待 transition,完成候选保持顺序并按 completion ID 做批内去重。通知与触觉开关不会停止活动监测- `HookEventTailReader` (`Services/Workflow/`): 后台 actor;bootstrap 以 512 KB 为单次分块流式读取滚动 24 小时事件,并用 start/events/end 三阶段恢复状态。当前文件用 inode + 完整行 offset 固定 bootstrap/live 边界;bootstrap 结束后 monitor 再发起一次定向回溯,为缺少起点的精确 turn 向旧日期文件最多回读 8 MB。之后每 2 秒 tail 当日增量,保留半行、跨日先读旧文件尾部;live 每成功处理一个分块就推进到最后完整行 offset,后续分块失败只重试未处理部分。旧文件异常触发 bootstrap 时保留 bootstrap 设置的新日期 offset,临时读取失败则保留旧日期等待下轮重试。bootstrap、定时轮询和 Mac 唤醒补读共用串行入口,读取期间到达的请求合并为当前读取结束后的一次补读;monitor generation 会丢弃停用 reader 的迟到批次- `CodexSessionLifecycleReader`: 后台 actor,只为 monitor 当前的精确 session + turn 定位对应 rollout;便宜目录每 10 秒重试,每个活跃生命周期最多递归 `sessions` 一次并保留负缓存,缓存文件移动、session 重新活跃或 Mac 唤醒时重置。rollout 初次最多读取末尾 512 KB,之后按 offset 增量读取;`task_started` 回填缺失起点,`task_complete` 补齐结束和精确耗时,`turn_aborted` 由 monitor 静默移除任务,读取失败时不改变 Hook 状态。轮询和即时 lifecycle 查询都绑定 reader generation,跨 actor 返回后仍会复核,旧查询不能落入新 reader 状态@@ -1095,29 +1095,30 @@ App 再次成为 active 时, 也会刷新 Codex 版本区、同步可用性, 并五类通知的触发与去重:-| 通知 | 触发 | 去重键 |-| ------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------ |-| 额度低阈值 | 非 stale 快照中窗口剩余比例穿越到 ≤ 阈值; 阈值或子开关变化时用当前快照立即重评估 | `low\|账号\|limitId\|windowId\|resetsAt` |-| 额度即将重置 | 可信额度窗口具有 `resetsAt`,在该时间发送“即将重置”通知;不要求本周期曾跌破低额度阈值,补发时效为一个窗口周期 | `reset\|账号\|limitId\|windowId\|resetsAt` |-| 长任务完成 | monitor 的 live Hook `Stop` 或 rollout `task_complete` transition 具有精确耗时且耗时 ≥ 阈值 | 状态机按精确任务键对两种完成信号去重 |-| 任务等待批准 | monitor 的 live 批次结束后任务最终仍处于 `waitingApproval` | 同批次按任务键合并,最终快照只发布一次 |-| 重置机会临期 | 过期时间距今 ≤ 7 天, 并在过期前 7/6/5/4/3/2/1 天各提醒一次; 正文使用本地时间 `yyyy-MM-dd HH:mm:ss` | `credit\|账号\|过期时间\|提醒档位` |+| 通知 | 触发 | 去重键 |+| ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- |+| 额度低阈值 | 非 stale 快照中窗口剩余比例穿越到 ≤ 阈值; 阈值或子开关变化时用当前快照立即重评估 | `low\|账号\|limitId\|windowId\|resetsAt` |+| 额度已重置 | 同一账号下每个 limit 的 primary/secondary 窗口独立观察;可信快照中消耗曾大于 0%,之后更新为 0% 时立即发送以面板 `limit.title` 和窗口周期命名的通知 | 进程内按 `账号\|limitId\|windowId` 状态转换 |+| 长任务完成 | monitor 的 live Hook `Stop` 或 rollout `task_complete` transition 具有精确耗时且耗时 ≥ 阈值 | 状态机按精确任务键对两种完成信号去重 |+| 任务等待批准 | monitor 的 live 批次结束后任务最终仍处于 `waitingApproval` | 同批次按任务键合并,最终快照只发布一次 |+| 重置机会临期 | 过期时间距今 ≤ 7 天, 并在过期前 7/6/5/4/3/2/1 天各提醒一次; 正文使用本地时间 `yyyy-MM-dd HH:mm:ss` | `credit\|账号\|过期时间\|提醒档位` |-额度和重置机会通知的已发送去重键持久化在 UserDefaults (`Notification.sentKeys`, 上限 300 条滚动淘汰), 账号维度包含在键中, 切换账号自动隔离。任务等待去重只保留在当前进程内。bootstrap 会恢复 App 启动前滚动 24 小时内的任务状态,但永远不发布 transition,因此不会补发历史权限通知、完成通知或触觉反馈;重新开启通知也不会回放旧事件。+额度低阈值和重置机会通知只在系统成功接收后才把已发送去重键持久化到 UserDefaults (`Notification.sentKeys`, 上限 300 条滚动淘汰), 账号维度包含在键中, 切换账号自动隔离。通知服务初始化时会移除旧版预测式额度重置留下的 `reset|` 去重键和 pending reminder 数据,保留有效的 `low|` / `credit|` 键。额度重置与任务等待状态只保留在当前进程内,不按预测时间调度或补发;可信额度快照即使在总开关关闭或授权不可用时也会继续消费重置状态转换但不发送,并移除当前快照中已经消失的窗口,整个快照变为空时清空全部待重置窗口。bootstrap 会恢复 App 启动前滚动 24 小时内的任务状态,但永远不发布 transition,因此不会补发历史权限通知、完成通知或触觉反馈;重新开启通知也不会回放旧事件。「任务触觉反馈」使用 `Notification.taskHapticEnabled` 持久化,缺失时默认开启。等待批准和任意任务完成 transition 都启动一段触觉反馈任务:每 100 ms 请求一次 `.levelChange`,连续 10 次;新 transition 会取消并重启当前序列,开关关闭后会在下一脉冲前停止。触觉反馈不受长任务阈值与系统通知授权影响;App 内「系统通知」总开关关闭时不触发。`NSHapticFeedbackManager.defaultPerformer` 会按当前输入设备、辅助功能与系统偏好决定是否实际反馈及震感强弱。通知错误处理 (延续"细节不打扰用户"原则, 不写入请求日志窗口):-| 场景 | 行为 |-| ---------------------------- | --------------------------------------------------------------- |-| 系统授权被拒 | 服务静默不发, 设置页显示引导与"打开系统设置"按钮 |-| 当日事件文件临时读取失败 | 提交已处理完整行的 offset,下轮只重试剩余部分 |-| Hook 或 rollout 单行解码失败 | 跳过坏行并继续处理同批其他完整行,不写入请求日志 |-| 跨日旧文件临时读取失败 | 暂不切换日期,下一轮继续读取旧尾部;bootstrap 接管时不重放 live |-| rollout 文件不存在或读取失败 | 保留 Hook 推导的任务状态,不猜测任务已经中断 |-| 休眠错过 resetsAt | 唤醒时补检, 超过一个窗口周期的恢复提醒直接丢弃 |-| Hook 关闭 | monitor 停止 tail 并清空实时状态 |-| 通知总开关或任务通知关闭 | 阻止对应通知;总开关关闭时也阻止触觉反馈,monitor 与菜单栏活动状态继续更新 |+| 场景 | 行为 |+| ------------------------------ | ------------------------------------------------------------------------ |+| 系统授权未决定或被拒 | 未决定时等待用户选择,被拒时静默不发并在设置页显示引导 |+| 当日事件文件临时读取失败 | 提交已处理完整行的 offset,下轮只重试剩余部分 |+| Hook 或 rollout 单行解码失败 | 跳过坏行并继续处理同批其他完整行,不写入请求日志 |+| 跨日旧文件临时读取失败 | 暂不切换日期,下一轮继续读取旧尾部;bootstrap 接管时不重放 live |+| rollout 文件不存在或读取失败 | 保留 Hook 推导的任务状态,不猜测任务已经中断 |+| 额度快照为空、stale 或窗口消失 | 空快照清空全部待重置窗口;stale 快照不参与转换;可信快照移除已消失窗口 |+| 系统通知提交失败 | 自动重试一次;最终失败不写去重键,额度通知在后续可信快照中重试;账号或窗口生命周期已变化时丢弃迟到的重置失败回调 |+| Hook 关闭 | monitor 停止 tail 并清空实时状态 |+| 通知总开关或任务通知关闭 | 阻止对应通知;额度重置状态仍继续推进但不补发,总开关关闭时也阻止触觉反馈 |通知点击通过 `UNUserNotificationCenterDelegate` 回调 `StatusItemController.openMenuSurfaceFromNotification()`, 复用全局快捷键的打开路径 (含 fallback 面板兜底)。diff --git a/README.md b/README.mdindex 946879c..523b549 100644--- a/README.md+++ b/README.md@@ -80,7 +80,7 @@ CodexBar 会把该设备的使用详情数据同步到当前 iCloud 账号的 Cl在设置中开启「系统通知」后,CodexBar 会在关键状态变化时发送本地通知:- 额度剩余比例跌破所选阈值 (5% / 10% / 25%)-- 额度窗口到达预计重置时间时提示即将重置+- 每个额度类型和时间窗口产生消耗后恢复至 100% 时提示额度已重置- Codex 完成一轮超过所选时长的任务 (需开启 Codex Hook)- Codex 请求批准工具操作并等待用户处理 (需开启 Codex Hook)- 手动重置机会将在 7 天内过期,并按 24 小时间隔提醒diff --git a/appcast.xml b/appcast.xmlindex 219105c..fb6b7ca 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.3.3</title>+ <sparkle:version>41</sparkle:version>+ <sparkle:shortVersionString>3.3.3</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.3.3</sparkle:releaseNotesLink>+ <pubDate>Sat, 11 Jul 2026 14:25:23 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.3.3.dmg" sparkle:edSignature="QKwjgbH2p2f1nkGm8aCfdP2+GALaw+NCwWlPzjFYFxFJerxHPTFnqfPx4To7UpnGKBzxBbV2QkFms4mkHD1LBA==" length="3862343" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.3.2</title><sparkle:version>40</sparkle:version>