CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 支持自动使用临期重置
Bob5e5fef6925ed
diff --git a/AGENTS.md b/AGENTS.mdindex 3342659..2d43630 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -51,7 +51,7 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用,使用 Swift 6,工程默认采用 `MainActor` 隔离。UI, Controller, ViewModel 和 Settings 依赖默认隔离,共享可变状态放入 actor,DTO 和跨 actor 值类型按需添加 `nonisolated` 标记,禁止在主 actor 执行阻塞 I/O。类型命名使用 `UpperCamelCase` 风格,成员命名使用 `lowerCamelCase` 风格。注释只解释非显然的生命周期、焦点、actor 或系统 API 约束。-保持三条数据链路独立:app-server 额度与用量、Hook 历史聚合、`CodexActivityMonitor` 实时任务。helper 只能控制睡眠,不得增加网络、任意命令执行或额外文件访问。修改 Hook 配置时必须保留用户和其他应用已有的 handler。启用和校验 Hook 必须检查当前 app-server 的实际版本不低于 `0.145.0`。新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界。+保持三条数据链路独立:app-server 额度与用量、Hook 历史聚合、`CodexActivityMonitor` 实时任务。helper 只能控制睡眠,不得增加网络、任意命令执行或额外文件访问。账户主链路必须检查当前 app-server 的实际版本不低于 `0.143.0`。修改 Hook 配置时必须保留用户和其他应用已有的 handler。启用和校验 Hook 必须额外检查当前 app-server 的实际版本不低于 `0.145.0`。新增网络访问、日志数据或 CloudKit 字段前先核对隐私边界。缺少 session ID 的 Hook 事件使用匿名 project key。匿名任务保留在实时快照和 UI 中,活动卡片与任务中心统一显示橙色 `person.crop.circle.dashed` 图标,`help` 为 `匿名任务不参与防睡眠`。匿名任务不发布任务通知或触觉反馈,不参与防睡眠和异常会话保护,不生成保护状态持久化标识。活动卡片的 `+N` 只显示其他活跃任务总数。diff --git a/CLAUDE.md b/CLAUDE.mdindex 01b5055..0667cc1 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -109,7 +109,7 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读- 带 `--hook-event` 启动 -> **Hook 子进程模式**:从 `stdin` 读取 JSON payload,在 `flock` 锁内追加一行 JSONL 后立即调用 `exit(EXIT_SUCCESS)` 退出,绝不初始化菜单栏 UI;写入失败时静默吞掉,不阻断 Codex- Hook handler 超时统一由 `WorkflowHookEventRecorder.hookTimeoutSeconds(for:)` 提供,`SessionEnd` 是 3 秒,其他事件是 5 秒;等锁预算固定比对应事件超时少 2 秒,当前分别是 1 秒和 3 秒-- 普通启动 -> `CodexBarAppDelegate` 创建全部长期对象,它在 `Controllers/StatusItemController.swift` 内,再由 `StatusItemController.install()` 装配菜单栏;AppDelegate 是唯一的装配点,新增服务在这里注入+- 普通启动 -> `Controllers/CodexBarAppDelegate.swift` 中的 `CodexBarAppDelegate` 创建全部长期对象,再由 `StatusItemController.install()` 装配菜单栏;AppDelegate 是唯一的装配点,新增服务在这里注入### 三条数据链路@@ -281,21 +281,21 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 菜单栏按钮左键切换主面板;右键或 Control+点击打开上下文菜单;`⌘,` 打开自定义设置窗口,菜单面板打开时 `⌘L` 打开日志窗口;默认全局快捷键 `⌘⇧W` 由 `GlobalHotKeySettings` 与 `GlobalHotKeyController` 管理- 主面板是锚定 status item 的 `NSPopover` 弹窗,锚点不可信时回退到 `FallbackPanelController` 提供的屏幕顶部居中 `NSPanel` 面板,处理快捷键、屏幕选择和焦点时要保留这两个分支- 关闭逻辑统一由 `MenuSurfaceDismissMonitor` 管理,淡出由 `MenuSurfaceFadeCoordinator` 负责-- 侧边面板都是 borderless nonactivating child panel,热力图详情、重置次数和任务中心挂在主面板上,通知选项和防睡眠选项挂在设置窗口上-- 设置窗口的子面板占同一位置,展开一个必须先 `hide(immediate: true)` 收掉其余的;动作走 `SettingsOptionsPanelAction` 并带上目标 `SettingsOptionsPanel`,互斥与 `closeAll` 都只写在 `SettingsWindowController.handleOptionsAction` 一处,加第三个面板不会漏配对+- 侧边面板都是 borderless nonactivating child panel,热力图详情、重置次数和任务中心挂在主面板上,通知、自动使用临期重置和防睡眠选项挂在设置窗口上+- 设置窗口的子面板占同一位置,展开一个必须先 `hide(immediate: true)` 收掉其余的;动作走 `SettingsOptionsPanelAction` 并带上目标 `SettingsOptionsPanel`,互斥与 `closeAll` 都只写在 `SettingsWindowController.handleOptionsAction` 一处,新增面板不会漏配对- 面板控制器只在首次展开时构造,收起动作走 `existingOptionsPanelController` 而不触发构造:它一建就挂上内容变化订阅并常驻到 App 结束,而用户可能一次子面板都没开过-- 两个子面板的顶边对齐各自主开关行,anchor 由设置页的 `ScreenFrameProvider` 随展开动作传出,定位走 `SidePanelSupport.anchoredPosition` 而不是宿主底边+- 三个设置子面板的顶边对齐各自主开关行,anchor 由设置页的 `ScreenFrameProvider` 随展开动作传出,定位走 `SidePanelSupport.anchoredPosition` 而不是宿主底边- 设置窗口的子面板要传 `clampsToSurfaceBottom: false` 让底边可以探出窗口,否则放不下时会把整个面板上推而错开主开关行;主面板那三个面板走默认的 `true`-- 两个子面板的高度都会变,通知面板随音效行增删,防睡眠面板随 `hasBattery` 增删低电量那一行;resize 时要固定顶边向下生长,直接改 size 会保持底边不动而把顶边顶离主开关行-- 高度重算只订阅真正会改变行数的那几项,通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange` 再加 `KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled` 两条,防睡眠面板只订 `$hasBattery` 一条;订整个防睡眠控制器会让任务每起停一次都白排一轮 resize+- 通知和防睡眠面板的高度会动态变化,前者随音效行增删,后者随 `hasBattery` 增删低电量那一行;自动使用临期重置面板只有固定的一行;resize 时要固定顶边向下生长,直接改 size 会保持底边不动而把顶边顶离主开关行+- 内容变化订阅要保持最小:通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange`,再加 `resetCreditAutomationSettings.$isEnabled`、`KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled`;自动使用临期重置面板只订 `resetCreditAutomationSettings.objectWillChange`;防睡眠面板只订 `$hasBattery`;订整个防睡眠控制器会让任务每起停一次都白排一轮 resize- 置灰也会改高度:带音效的行置灰时音效子行跟着收起,所以每个置灰依赖都要有一个对应的订阅源- 增删行或改行的显示条件时要同步补上对应的订阅源,漏一项会让面板裁掉底部或留下空白- resize 的竖向夹紧走 `SidePanelSupport.clampedVertically`,与初次展开的 `position` 同一条规则,否则放不下时两边会把面板推向相反的边-- 子面板入口只在开关开着且依赖就绪时出现,通知看 `NotificationSettings.canShowOptions` 那个值,防睡眠看 `KeepAliveController.canShowOptions` 这个值;两者都只控制入口显隐,不回写用户保存的开关-- 两个子面板都只由滑杆按钮展开,动作只有 `toggle` 与 `close` 两种,开启主开关不自动弹出+- 子面板入口只在开关开着且依赖就绪时出现,通知看 `NotificationSettings.canShowOptions`,自动使用临期重置看 `ResetCreditAutomationSettings.isEnabled`,防睡眠看 `KeepAliveController.canShowOptions`;这些值只控制入口显隐,不回写用户保存的开关+- 三个设置子面板都只由滑杆按钮展开,动作只有 `toggle` 与 `close` 两种,开启主开关不自动弹出- 侧边面板公共能力集中在 `Controllers/SidePanelSupport.swift` 里,含 `SidePanelDrawerPresenter`、`SidePanelContentHost`、`SidePanelDrawerAnimator`、panel 工厂和定位夹紧;挂在主面板上的那三个面板优先复用 `SidePanelDrawerPresenter` 这一层,不要另起一套- 设置窗口的子面板直接复用 `Controllers/SettingsOptionsPanelController.swift`,它在 presenter 之上补齐了装配、两套关闭观察者、顶边对齐定位和高度重算;新增设置子面板只要给它内容工厂与内容变化来源,不要再写一层壳-- 两个设置子面板的行高与间距从 `SettingsOptionsPanelMetrics` 取,下拉控件共用 `SettingsOptionsPicker` 这一个,只有面板宽度和 picker 宽度各自定义,这样两个面板看起来才是同一套控件+- 三个设置子面板的行高与间距从 `SettingsOptionsPanelMetrics` 取,下拉控件共用 `SettingsOptionsPicker`,只有面板宽度和 picker 宽度各自定义,这样三个面板看起来才是同一套控件- 设置子面板的内容工厂必须走 `SettingsOptionsPanelController.makeContentController(_:rebuiltBy:)`,否则首次展开时原生 Switch 只剩一条空轨道;重建信号由它接在内容外面,内容视图不必知道 `SidePanelEntryCue`- 原因是 thumb 由 `WindowPortal` 投射而不是画在开关上,面板首次布局那一轮 portal 建不起来,而且不会自愈,只有一次内容重建才补得上;第二次展开正常是因为 hosting controller 常驻,复用了已经建好的那份- 不要再用 `@_optimize(none)` 规避这个漏绘:它当年在通知子面板管用只是因为逼着 body 重算时判定那些行变过,与优化等级无关,换个写法就失效;`SidePanelSupport` 里剩下那一处标注规避的是编译器崩溃,与此无关@@ -323,9 +323,9 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev改动涉及网络、日志或同步时必须遵守:-- App 只有四类出网行为,分别是本机 app-server stdio 通信(不算网络)、重置机会过期时间只读查询、Sparkle 更新、用户显式开启后的 CloudKit 同步;新增网络请求需要非常明确的理由-- 只读查询打到 `https://chatgpt.com/backend-api/wham/rate-limit-reset-credits` 这一个地址,也是全仓库唯一的 `URLSession` 调用点,位于 `CodexResetCreditsService` 内;Sparkle 更新走 `https://codexbar.zabrian.app/appcast.xml` 这个 feed-- 不展示 app-server stderr;不展示或记录 Codex OAuth token 与 `auth.json` 内容;不把原始敏感 RPC 响应写进文档+- App 只有三类外部通信行为,分别是本机 app-server stdio 通信(不算网络)、Sparkle 更新、用户显式开启后的 CloudKit 同步;新增网络请求需要非常明确的理由+- 账户、额度、Token 用量和 Reset Credits 明细统一通过本机 app-server 获取;Sparkle 更新走 `https://codexbar.zabrian.app/appcast.xml` 这个 feed+- 不展示 app-server stderr;不展示或记录 Codex OAuth token;不把原始敏感 RPC 响应写进文档- CloudKit 只同步去掉 `sessionIds` 与 `turnIds` 的 daily 聚合,不同步原始 Hook events、账号、额度或 Token 用量- 异常会话保护状态只保存在本机,不同步 CloudKit;记录不含原始 session ID、turn ID、项目名或任务内容- CloudKit 的 `sessionEndCount`、`userPromptSubmitCount` 与其他 Hook 计数字段保持可选,远端缺失表示历史来源没有提供,不能在读取时补成 `0`;改变远端格式时同时评估并更新 `syncSchemaVersion`diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swiftnew file mode 100644index 0000000..9519187--- /dev/null+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift@@ -0,0 +1,159 @@+import AppKit+import os++/// 应用级对象装配点, 持有共享服务和 ViewModel 生命周期+@MainActor+final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {+ private let codexStatusService = CodexStatusService()+ lazy var viewModel = CodexStatusViewModel(service: codexStatusService)+ let workflowViewModel = WorkflowViewModel()+ lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)+ lazy var codexCLINotificationSettings = CodexCLINotificationSettings(+ codexStatusService: codexStatusService+ )+ let activityProtectionSettings = ActivityProtectionSettings()+ lazy var activityMonitor = CodexActivityMonitor(+ codexHookSettings: codexHookSettings,+ activityProtectionSettings: activityProtectionSettings+ )+ lazy var keepAliveController = KeepAliveController(+ activityMonitor: activityMonitor,+ codexHookSettings: codexHookSettings+ )+ let syncSettings = WorkflowSyncSettings()+ let globalHotKeySettings = GlobalHotKeySettings()+ let menuBarQuotaSettings = MenuBarQuotaSettings()+ let mainPanelSettings = MainPanelSettings()+ let notificationSettings = NotificationSettings()+ let resetCreditAutomationSettings = ResetCreditAutomationSettings()+ let appUpdater = AppUpdater()++ private var statusItemController: StatusItemController?+ private var notificationService: CodexNotificationService?+ private var resetCreditAutomationController: ResetCreditAutomationController?+ private var terminationPreparationTask: Task<Void, Never>?+ private var hasPreparedForTermination = false++ // MARK: - App 生命周期++ func applicationDidFinishLaunching(_: Notification) {+ // Hook 子进程模式绝不会走到这里, 干净退出标志因此不会被它改写+ AppProcessDiagnostics.install()+ let controller = StatusItemController(+ viewModel: viewModel,+ workflowViewModel: workflowViewModel,+ codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings,+ activityMonitor: activityMonitor,+ syncSettings: syncSettings,+ globalHotKeySettings: globalHotKeySettings,+ menuBarQuotaSettings: menuBarQuotaSettings,+ mainPanelSettings: mainPanelSettings,+ notificationSettings: notificationSettings,+ resetCreditAutomationSettings: resetCreditAutomationSettings,+ keepAliveController: keepAliveController,+ appUpdater: appUpdater+ )+ controller.install()+ statusItemController = controller++ let notificationService = CodexNotificationService(+ settings: notificationSettings,+ statusViewModel: viewModel,+ activityMonitor: activityMonitor+ ) { [weak controller] in+ controller?.openMenuSurfaceFromNotification()+ }+ notificationService.start()+ self.notificationService = notificationService++ let resetCreditAutomationController = ResetCreditAutomationController(+ settings: resetCreditAutomationSettings,+ statusViewModel: viewModel,+ service: codexStatusService,+ notificationService: notificationService+ )+ resetCreditAutomationController.start()+ self.resetCreditAutomationController = resetCreditAutomationController+ // 低电量触发会中断正在跑的任务, 得让用户知道是谁干的+ keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent in+ await notificationService?.notifyLowBatteryProtection(percent: percent) ?? false+ }+ keepAliveController.onKeepAliveLimitTriggered = { [weak notificationService] duration in+ await notificationService?.notifyKeepAliveLimitReached(durationText: duration.title) ?? false+ }+ activityMonitor.onInactivityProtectionTriggered = { [weak notificationService] notice in+ await notificationService?.notifyActivityProtection(notice) ?? false+ }+ activityMonitor.onInactivityProtectionInvalidated = { [weak notificationService] taskID, attemptID in+ notificationService?.invalidateActivityProtectionNotification(taskID: taskID, attemptID: attemptID)+ }+ activityMonitor.start()+ keepAliveController.start()+ logLaunchState()+ }++ func applicationWillTerminate(_: Notification) {+ AppLog.app.notice("App 即将退出: reason=userQuit")+ terminationPreparationTask?.cancel()+ terminationPreparationTask = nil+ AppProcessDiagnostics.recordCleanExit()+ statusItemController?.uninstall()+ resetCreditAutomationController?.stop()+ keepAliveController.stop()+ activityMonitor.stop()+ }++ func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {+ if hasPreparedForTermination {+ return .terminateNow+ }+ if terminationPreparationTask != nil {+ return .terminateLater+ }++ terminationPreparationTask = Task { @MainActor [weak self] in+ guard let self else {+ NSApplication.shared.reply(toApplicationShouldTerminate: false)+ return+ }+ let success = await keepAliveController.prepareForTermination()+ guard !Task.isCancelled else {+ return+ }+ terminationPreparationTask = nil+ hasPreparedForTermination = success+ NSApplication.shared.reply(toApplicationShouldTerminate: success)+ }+ return .terminateLater+ }++ /// 启动时把各开关的初始值记成一条基线, 之后的变更日志都是相对这条基线的增量+ /// 排查时先看这条就知道当时的配置, 不必让用户逐项回忆+ private func logLaunchState() {+ // 先拼成普通字符串再交给 Logger, 避免在日志 autoclosure 中直接捕获属性+ let state = LogFields.joined(+ "version=\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "-")",+ "build=\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "-")",+ "hook=\(codexHookSettings.isEnabled ? 1 : 0)",+ "keepAlive=\(keepAliveController.isEnabled ? 1 : 0)",+ "keepAliveLimit=\(keepAliveController.maximumDuration.loggedHours)",+ "keepAliveBattery=\(keepAliveController.lowBatteryThreshold.rawValue)",+ "keepAliveWaiting=\(keepAliveController.keepsAwakeWhileWaiting ? 1 : 0)",+ "keepAliveDisplay=\(keepAliveController.keepsDisplayAwake ? 1 : 0)",+ "activityProtectionMinutes=\(activityProtectionSettings.inactivityDuration.loggedMinutes)",+ "sync=\(syncSettings.isEnabled ? 1 : 0)",+ "notification=\(notificationSettings.isEnabled ? 1 : 0)",+ "resetCreditAutoUse=\(resetCreditAutomationSettings.isEnabled ? 1 : 0)",+ "resetCreditLeadSeconds=\(resetCreditAutomationSettings.leadTime.rawValue)",+ "menuBarQuota=\(menuBarQuotaSettings.selection.rawValue)",+ "taskCenter=\(mainPanelSettings.showsTaskCenter ? 1 : 0)",+ "hotKey=\(globalHotKeySettings.shortcut == nil ? 0 : 1)"+ )+ AppLog.app.notice("App 已启动: \(state, privacy: .public)")+ }++ func openSettingsFromCommand() {+ statusItemController?.openSettingsFromCommand()+ }+}diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swiftindex 54b35e1..fe3f3e5 100644--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift@@ -3,8 +3,9 @@ import Combineimport SwiftUI/// 设置窗口右侧的子选项面板, 同一时刻只展开一个-enum SettingsOptionsPanel: CaseIterable {+enum SettingsOptionsPanel: CaseIterable, Hashable {case notification+ case resetCreditAutomationcase keepAlive}@@ -40,7 +41,7 @@ private struct SidePanelEntryRebuildHost<Content: View>: View {}/// 设置窗口右侧子选项面板的公共装配-/// 通知与防睡眠两个子面板只差内容视图和高度变化的来源, 定位 关闭 高度重算这套脚手架全在这里+/// 各子面板只差内容视图和高度变化的来源, 定位 关闭 高度重算这套脚手架全在这里/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView@MainActorfinal class SettingsOptionsPanelController {diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 13be5d6..ef91ff4 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -14,14 +14,13 @@ final class SettingsWindowController: HostingWindowController {private let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let notificationSettings: NotificationSettings+ private let resetCreditAutomationSettings: ResetCreditAutomationSettingsprivate let activityProtectionSettings: ActivityProtectionSettingsprivate let keepAliveController: KeepAliveControllerprivate let onSyncChanged: (Bool) -> Voidprivate let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler- /// 只在真的要展开时构造: 控制器一建就挂上内容变化订阅并常驻到 App 结束- /// 而用户可能一次子面板都没开过- private var notificationOptionsPanelController: SettingsOptionsPanelController?- private var keepAliveOptionsPanelController: SettingsOptionsPanelController?+ /// 只在真的要展开时构造: 控制器一建就挂上内容变化订阅并常驻到 App 结束, 而用户可能一次子面板都没开过+ private var optionsPanelControllers: [SettingsOptionsPanel: SettingsOptionsPanelController] = [:]init(viewModel: CodexStatusViewModel,@@ -33,6 +32,7 @@ final class SettingsWindowController: HostingWindowController {menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,notificationSettings: NotificationSettings,+ resetCreditAutomationSettings: ResetCreditAutomationSettings,activityProtectionSettings: ActivityProtectionSettings,keepAliveController: KeepAliveController,screenProvider: @escaping () -> NSScreen?,@@ -48,6 +48,7 @@ final class SettingsWindowController: HostingWindowController {self.menuBarQuotaSettings = menuBarQuotaSettingsself.mainPanelSettings = mainPanelSettingsself.notificationSettings = notificationSettings+ self.resetCreditAutomationSettings = resetCreditAutomationSettingsself.activityProtectionSettings = activityProtectionSettingsself.keepAliveController = keepAliveControllerself.onSyncChanged = onSyncChanged@@ -70,6 +71,7 @@ final class SettingsWindowController: HostingWindowController {menuBarQuotaSettings: menuBarQuotaSettings,mainPanelSettings: mainPanelSettings,notificationSettings: notificationSettings,+ resetCreditAutomationSettings: resetCreditAutomationSettings,keepAliveController: keepAliveController,onSyncChanged: onSyncChanged,onRebuildWorkflowData: onRebuildWorkflowData,@@ -113,6 +115,7 @@ final class SettingsWindowController: HostingWindowController {syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()+ resetCreditAutomationSettings.refresh()activityProtectionSettings.refresh()keepAliveController.refresh()}@@ -125,12 +128,7 @@ final class SettingsWindowController: HostingWindowController {}let controller = makeOptionsPanelController(panel)- switch panel {- case .notification:- notificationOptionsPanelController = controller- case .keepAlive:- keepAliveOptionsPanelController = controller- }+ optionsPanelControllers[panel] = controllerreturn controller}@@ -138,12 +136,7 @@ final class SettingsWindowController: HostingWindowController {private func existingOptionsPanelController(_ panel: SettingsOptionsPanel) -> SettingsOptionsPanelController? {- switch panel {- case .notification:- notificationOptionsPanelController- case .keepAlive:- keepAliveOptionsPanelController- }+ optionsPanelControllers[panel]}private func makeOptionsPanelController(@@ -157,23 +150,27 @@ final class SettingsWindowController: HostingWindowController {willShow: { [codexCLINotificationSettings] incodexCLINotificationSettings.refresh()},- contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, keepAliveController] entryCue in+ contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, resetCreditAutomationSettings, keepAliveController] entryCue inSettingsOptionsPanelController.makeContentController(NotificationOptionsView(notificationSettings: notificationSettings,codexHookSettings: codexHookSettings,codexCLINotificationSettings: codexCLINotificationSettings,+ resetCreditAutomationSettings: resetCreditAutomationSettings,keepAliveController: keepAliveController),rebuiltBy: entryCue)},- // 音效子行随各开关增删, 低电量与上限那两行还跟着各自的依赖置灰- // 置灰会连带收起音效子行, 所以两个依赖的派生值都要订上+ // 音效子行随各开关增删, 自动使用 低电量与上限三行还跟着各自的依赖置灰+ // 置灰会连带收起音效子行, 所以三个依赖的派生值都要订上// 防睡眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度contentChanges: Publishers.MergeMany([notificationSettings.objectWillChange.eraseToAnyPublisher(),codexHookSettings.objectWillChange.eraseToAnyPublisher(),+ resetCreditAutomationSettings.$isEnabled+ .map { _ in () }+ .eraseToAnyPublisher(),keepAliveController.$isLowBatteryProtectionEnabled.map { _ in () }.eraseToAnyPublisher(),@@ -182,6 +179,21 @@ final class SettingsWindowController: HostingWindowController {.eraseToAnyPublisher()]).eraseToAnyPublisher())+ case .resetCreditAutomation:+ SettingsOptionsPanelController(+ animationKey: "CodexBar.resetCreditAutomationOptionsDrawerTransform",+ initialPanelSize: ResetCreditAutomationOptionsView.initialPanelSize,+ contentControllerProvider: { [resetCreditAutomationSettings] entryCue in+ SettingsOptionsPanelController.makeContentController(+ ResetCreditAutomationOptionsView(+ settings: resetCreditAutomationSettings+ ),+ rebuiltBy: entryCue+ )+ },+ contentChanges: resetCreditAutomationSettings.objectWillChange+ .eraseToAnyPublisher()+ )case .keepAlive:SettingsOptionsPanelController(animationKey: "CodexBar.keepAliveOptionsDrawerTransform",diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 7287f94..3da1ae3 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -3,151 +3,9 @@ import Combineimport osimport SwiftUI-/// 应用级对象装配点, 持有共享服务和 ViewModel 生命周期-@MainActor-final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {- private let codexStatusService = CodexStatusService()- lazy var viewModel = CodexStatusViewModel(service: codexStatusService)- let workflowViewModel = WorkflowViewModel()- lazy var codexHookSettings = CodexHookSettings(codexStatusService: codexStatusService)- lazy var codexCLINotificationSettings = CodexCLINotificationSettings(- codexStatusService: codexStatusService- )- let activityProtectionSettings = ActivityProtectionSettings()- lazy var activityMonitor = CodexActivityMonitor(- codexHookSettings: codexHookSettings,- activityProtectionSettings: activityProtectionSettings- )- lazy var keepAliveController = KeepAliveController(- activityMonitor: activityMonitor,- codexHookSettings: codexHookSettings- )- let syncSettings = WorkflowSyncSettings()- let globalHotKeySettings = GlobalHotKeySettings()- let menuBarQuotaSettings = MenuBarQuotaSettings()- let mainPanelSettings = MainPanelSettings()- let notificationSettings = NotificationSettings()- let appUpdater = AppUpdater()-- private var statusItemController: StatusItemController?- private var notificationService: CodexNotificationService?- private var terminationPreparationTask: Task<Void, Never>?- private var hasPreparedForTermination = false-- // MARK: - App 生命周期-- func applicationDidFinishLaunching(_: Notification) {- // Hook 子进程模式绝不会走到这里, 干净退出标志因此不会被它改写- AppProcessDiagnostics.install()- let controller = StatusItemController(- viewModel: viewModel,- workflowViewModel: workflowViewModel,- codexHookSettings: codexHookSettings,- codexCLINotificationSettings: codexCLINotificationSettings,- activityMonitor: activityMonitor,- syncSettings: syncSettings,- globalHotKeySettings: globalHotKeySettings,- menuBarQuotaSettings: menuBarQuotaSettings,- mainPanelSettings: mainPanelSettings,- notificationSettings: notificationSettings,- keepAliveController: keepAliveController,- appUpdater: appUpdater- )- controller.install()- statusItemController = controller-- let notificationService = CodexNotificationService(- settings: notificationSettings,- statusViewModel: viewModel,- activityMonitor: activityMonitor- ) { [weak controller] in- controller?.openMenuSurfaceFromNotification()- }- notificationService.start()- self.notificationService = notificationService- // 低电量触发会中断正在跑的任务, 得让用户知道是谁干的- keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent in- await notificationService?.notifyLowBatteryProtection(percent: percent) ?? false- }- keepAliveController.onKeepAliveLimitTriggered = { [weak notificationService] duration in- await notificationService?.notifyKeepAliveLimitReached(durationText: duration.title) ?? false- }- activityMonitor.onInactivityProtectionTriggered = { [weak notificationService] notice in- await notificationService?.notifyActivityProtection(notice) ?? false- }- activityMonitor.onInactivityProtectionInvalidated = { [weak notificationService] taskID, attemptID in- notificationService?.invalidateActivityProtectionNotification(taskID: taskID, attemptID: attemptID)- }- activityMonitor.start()- keepAliveController.start()- logLaunchState()- }-- func applicationWillTerminate(_: Notification) {- AppLog.app.notice("App 即将退出: reason=userQuit")- terminationPreparationTask?.cancel()- terminationPreparationTask = nil- AppProcessDiagnostics.recordCleanExit()- statusItemController?.uninstall()- keepAliveController.stop()- activityMonitor.stop()- }-- func applicationShouldTerminate(_: NSApplication) -> NSApplication.TerminateReply {- if hasPreparedForTermination {- return .terminateNow- }- if terminationPreparationTask != nil {- return .terminateLater- }-- terminationPreparationTask = Task { @MainActor [weak self] in- guard let self else {- NSApplication.shared.reply(toApplicationShouldTerminate: false)- return- }- let success = await keepAliveController.prepareForTermination()- guard !Task.isCancelled else {- return- }- terminationPreparationTask = nil- hasPreparedForTermination = success- NSApplication.shared.reply(toApplicationShouldTerminate: success)- }- return .terminateLater- }-- /// 启动时把各开关的初始值记成一条基线, 之后的变更日志都是相对这条基线的增量- /// 排查时先看这条就知道当时的配置, 不必让用户逐项回忆- private func logLaunchState() {- // 先拼成普通字符串再交给 Logger, 避免在日志 autoclosure 中直接捕获属性- let state = LogFields.joined(- "version=\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "-")",- "build=\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "-")",- "hook=\(codexHookSettings.isEnabled ? 1 : 0)",- "keepAlive=\(keepAliveController.isEnabled ? 1 : 0)",- "keepAliveLimit=\(keepAliveController.maximumDuration.loggedHours)",- "keepAliveBattery=\(keepAliveController.lowBatteryThreshold.rawValue)",- "keepAliveWaiting=\(keepAliveController.keepsAwakeWhileWaiting ? 1 : 0)",- "keepAliveDisplay=\(keepAliveController.keepsDisplayAwake ? 1 : 0)",- "activityProtectionMinutes=\(activityProtectionSettings.inactivityDuration.loggedMinutes)",- "sync=\(syncSettings.isEnabled ? 1 : 0)",- "notification=\(notificationSettings.isEnabled ? 1 : 0)",- "menuBarQuota=\(menuBarQuotaSettings.selection.rawValue)",- "taskCenter=\(mainPanelSettings.showsTaskCenter ? 1 : 0)",- "hotKey=\(globalHotKeySettings.shortcut == nil ? 0 : 1)"- )- AppLog.app.notice("App 已启动: \(state, privacy: .public)")- }-- func openSettingsFromCommand() {- statusItemController?.openSettingsFromCommand()- }-}-/// 菜单栏入口控制器, 统一管理状态图标, 菜单面板, 右键菜单和全局快捷键@MainActor-private final class StatusItemController: NSObject, NSMenuDelegate {+final class StatusItemController: NSObject, NSMenuDelegate {private let viewModel: CodexStatusViewModelprivate let workflowViewModel: WorkflowViewModelprivate let codexHookSettings: CodexHookSettings@@ -158,6 +16,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let notificationSettings: NotificationSettings+ private let resetCreditAutomationSettings: ResetCreditAutomationSettingsprivate let keepAliveController: KeepAliveControllerprivate let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)@@ -189,6 +48,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {menuBarQuotaSettings: menuBarQuotaSettings,mainPanelSettings: mainPanelSettings,notificationSettings: notificationSettings,+ resetCreditAutomationSettings: resetCreditAutomationSettings,activityProtectionSettings: activityMonitor.activityProtectionSettings,keepAliveController: keepAliveController) { [weak self] in@@ -259,6 +119,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,notificationSettings: NotificationSettings,+ resetCreditAutomationSettings: ResetCreditAutomationSettings,keepAliveController: KeepAliveController,appUpdater: AppUpdater) {@@ -272,6 +133,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {self.menuBarQuotaSettings = menuBarQuotaSettingsself.mainPanelSettings = mainPanelSettingsself.notificationSettings = notificationSettings+ self.resetCreditAutomationSettings = resetCreditAutomationSettingsself.keepAliveController = keepAliveControllerself.appUpdater = appUpdatersuper.init()diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swiftindex cbbf57b..46d88c3 100644--- a/CodexBar/Models/CodexQuotaModels.swift+++ b/CodexBar/Models/CodexQuotaModels.swift@@ -18,6 +18,7 @@ nonisolated struct CodexQuotaSnapshot: Equatable {let credits: RateLimitCreditsSnapshot?let resetCreditsAvailableCount: Int?let resetCreditExpirationDates: [Date]?+ let resetCreditAutomationCandidates: [ResetCreditAutomationCandidate]?let generatedAt: Datelet limits: [CodexQuotaLimitSnapshot]let usage: CodexUsageSnapshot?@@ -142,9 +143,92 @@ nonisolated struct AccountRateLimitsResponse: Decodable {let rateLimitResetCredits: RateLimitResetCreditsSummary?}-/// app-server 返回的可用额度重置次数+/// app-server 返回的可用额度重置次数和明细nonisolated struct RateLimitResetCreditsSummary: Decodable {let availableCount: Int+ let credits: [RateLimitResetCredit]?++ func availableExpirationDates(now: Date) -> [Date]? {+ guard availableCount > 0, let credits else {+ return nil+ }++ return credits.compactMap { credit in+ guard credit.status == "available", let expirationDate = credit.expirationDate,+ expirationDate > now else {+ return nil+ }++ return expirationDate+ }+ .sorted()+ }++ /// 自动使用只接受 app-server 明确返回的可用 Codex 额度重置凭证+ var automationCandidates: [ResetCreditAutomationCandidate]? {+ guard let credits else {+ return nil+ }++ return credits.compactMap { credit in+ guard credit.status == "available",+ credit.resetType == "codexRateLimits",+ let expirationDate = credit.expirationDate else {+ return nil+ }++ return ResetCreditAutomationCandidate(+ id: credit.id,+ expirationDate: expirationDate+ )+ }+ }+}++/// app-server 返回的单个额度重置凭证+nonisolated struct RateLimitResetCredit: Decodable {+ let id: String+ let status: String+ let resetType: String+ let expiresAt: Int64?++ var expirationDate: Date? {+ expiresAt.map { Date(timeIntervalSince1970: TimeInterval($0)) }+ }+}++/// 自动使用链路需要的最小凭证快照+nonisolated struct ResetCreditAutomationCandidate: Equatable, Sendable {+ let id: String+ let expirationDate: Date+}++/// 自动使用前强制读取的账号和重置凭证明细+nonisolated struct ResetCreditAutomationRead: Sendable {+ let accountIdentity: String+ let availableCount: Int?+ let candidates: [ResetCreditAutomationCandidate]?+}++/// app-server 消费重置凭证的稳定结果集合+nonisolated enum ResetCreditConsumeOutcome: String, Decodable, Sendable {+ case reset+ case nothingToReset+ case noCredit+ case alreadyRedeemed+}++nonisolated struct ResetCreditConsumeResponse: Decodable, Sendable {+ let outcome: ResetCreditConsumeOutcome+}++nonisolated struct ResetCreditConsumeResult: Sendable {+ let outcome: ResetCreditConsumeOutcome+ let refreshedRead: ResetCreditAutomationRead?+}++nonisolated enum ResetCreditAutomationServiceError: Error, Sendable {+ case accountChanged}/// app-server 返回的单个 limit, primary/secondary 可能独立缺失@@ -180,7 +264,6 @@ nonisolated extension CodexQuotaSnapshot {init(accountResponse: AccountReadResponse,rateLimitsResponse: AccountRateLimitsResponse?,- resetCreditExpirationDates: [Date]? = nil,usageResponse: AccountUsageResponse? = nil,isRateLimitsStale: Bool = false,isUsageStale: Bool = false,@@ -199,6 +282,12 @@ nonisolated extension CodexQuotaSnapshot {let usage = usageResponse.map {CodexUsageSnapshot(summary: $0.summary, dailyBuckets: $0.dailyUsageBuckets)}+ let resetCreditExpirationDates = rateLimitsResponse?+ .rateLimitResetCredits?+ .availableExpirationDates(now: generatedAt)+ let resetCreditAutomationCandidates = rateLimitsResponse?+ .rateLimitResetCredits?+ .automationCandidates// rateLimits/usage 可同时为空// 账户有效时仍生成快照给 UI 展示 `暂无数据`@@ -209,6 +298,7 @@ nonisolated extension CodexQuotaSnapshot {credits: rateLimitsResponse.flatMap { Self.primaryCredits(from: $0) },resetCreditsAvailableCount: rateLimitsResponse?.rateLimitResetCredits?.availableCount,resetCreditExpirationDates: resetCreditExpirationDates,+ resetCreditAutomationCandidates: resetCreditAutomationCandidates,generatedAt: generatedAt,limits: limits,usage: usage,diff --git a/CodexBar/Models/CodexStatusError.swift b/CodexBar/Models/CodexStatusError.swiftindex 15219b0..b32f6fc 100644--- a/CodexBar/Models/CodexStatusError.swift+++ b/CodexBar/Models/CodexStatusError.swift@@ -8,6 +8,7 @@ nonisolated enum CodexStatusError: LocalizedError {case invalidServerResponsecase serverError(String)case unsupportedMethod+ case unsupportedVersion(minimum: String)case notLoggedInvar errorDescription: String? {@@ -39,6 +40,8 @@ nonisolated enum CodexStatusError: LocalizedError {localized: "codex-status.error.unsupported-method",defaultValue: "Codex app-server 不支持该接口")+ case let .unsupportedVersion(minimum):+ String(localized: "需要 Codex \(minimum) 或更高版本")case .notLoggedIn:String(localized: "codex-status.error.not-logged-in",@@ -49,7 +52,12 @@ nonisolated enum CodexStatusError: LocalizedError {/// codex app-server 未登录var isAuthenticationRequired: Bool {- serverErrorMessageContains("codex account authentication required")+ switch self {+ case .notLoggedIn:+ true+ default:+ serverErrorMessageContains("codex account authentication required")+ }}/// codex app-server 不支持的方法@@ -70,6 +78,22 @@ nonisolated enum CodexStatusError: LocalizedError {return !isAuthenticationRequired && !isUnsupportedMethod}+ /// 参数或协议形状不正确时继续用同一请求重试不会恢复+ var isProtocolOrParameterFailure: Bool {+ switch self {+ case .unsupportedMethod, .unsupportedVersion:+ true+ case .serverError:+ serverErrorMessageContains("invalid params")+ || serverErrorMessageContains("invalid request")+ || serverErrorMessageContains("missing field")+ || serverErrorMessageContains("unknown field")+ || serverErrorMessageContains("invalid type")+ default:+ false+ }+ }+/// 连接断开, 超时, 无法解析都需要重建 app-server 会话var isTransportFailure: Bool {switch self {diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 5e69b38..1c7f56a 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -1522,6 +1522,102 @@}}},+ "notification.reset-credit-auto-use-failed.body.authentication" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Codex sign-in expired"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Codex 登录状态已失效"+ }+ }+ }+ },+ "notification.reset-credit-auto-use-failed.body.expired" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Expired; could not be used automatically"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已过期, 未能自动使用"+ }+ }+ }+ },+ "notification.reset-credit-auto-use-failed.body.permanent" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "The request could not be completed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请求无法完成"+ }+ }+ }+ },+ "notification.reset-credit-auto-use-failed.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Automatic Reset Credit Use Failed"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动使用重置失败"+ }+ }+ }+ },+ "notification.reset-credit-auto-use.body.count" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reset credits remaining: %lld"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "剩余重置次数: %lld"+ }+ }+ }+ },+ "notification.reset-credit-auto-use.title" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Reset Credit Used Automatically"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动使用重置"+ }+ }+ }+ },"notification.sound.default" : {"localizations" : {"en" : {@@ -2834,7 +2930,7 @@}}},- "将从本机原始 Hook 事件重新统计 %@\n并在下次同步时替换当前设备对应日期的云端聚合" : {+ "将从本机原始 Hook 事件重新统计 %@\n并在下次同步时替换当前设备对应日期的云端数据" : {"localizations" : {"en" : {"stringUnit" : {@@ -2845,7 +2941,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "将从本机原始 Hook 事件重新统计 %@\n并在下次同步时替换当前设备对应日期的云端聚合"+ "value" : "将从本机原始 Hook 事件重新统计 %@\n并在下次同步时替换当前设备对应日期的云端数据"}}}@@ -4322,6 +4418,22 @@}}},+ "需要 Codex %@ 或更高版本" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Codex %@ or later is required"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要 Codex %@ 或更高版本"+ }+ }+ }+ },"需要启用 CodexBar Hook" : {"localizations" : {"en" : {@@ -4450,6 +4562,198 @@}}},+ "1 小时" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "1 Hour"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "1 小时"+ }+ }+ }+ },+ "12 小时" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "12 Hours"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "12 小时"+ }+ }+ }+ },+ "2 小时" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "2 Hours"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "2 小时"+ }+ }+ }+ },+ "30 分钟" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "30 Minutes"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "30 分钟"+ }+ }+ }+ },+ "4 小时" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "4 Hours"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "4 小时"+ }+ }+ }+ },+ "6 小时" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "6 Hours"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "6 小时"+ }+ }+ }+ },+ "开启" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enable"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开启"+ }+ }+ }+ },+ "开启自动使用重置?" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Enable Automatic Reset Credit Use?"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开启自动使用重置?"+ }+ }+ }+ },+ "开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "At the selected time before a manual reset credit expires, CodexBar automatically uses it to reset your Codex quota.\nThis action cannot be undone. Sleep, network outages, or service errors may cause it to fail, and each device attempts it independently."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销"+ }+ }+ }+ },+ "临期时间" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Time Before Expiry"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "临期时间"+ }+ }+ }+ },+ "自动使用临期重置" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Use Expiring Reset Credit Automatically"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动使用临期重置"+ }+ }+ }+ },+ "自动使用重置通知" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Automatic Reset Use"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动使用重置通知"+ }+ }+ }+ },"默认快捷键 %@ 已被占用" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift b/CodexBar/Services/CodexCLI/CodexCLIResolver.swiftindex a902372..befd54f 100644--- a/CodexBar/Services/CodexCLI/CodexCLIResolver.swift+++ b/CodexBar/Services/CodexCLI/CodexCLIResolver.swift@@ -77,7 +77,7 @@ nonisolated enum CodexCLIResolver {}/// Codex 配置目录: 优先 CODEX_HOME, 回退真实用户 HOME 下的 .codex- /// auth.json / hooks.json 等配置文件统一从这里解析+ /// hooks.json 等配置文件统一从这里解析static func codexHomeDirectory(environment: [String: String] = environment) -> URL {if let codexHome = nonEmptyEnvironmentValue("CODEX_HOME", in: environment) {return URL(fileURLWithPath: codexHome, isDirectory: true)diff --git a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swiftindex 34199f3..2f66a72 100644--- a/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift+++ b/CodexBar/Services/CodexCLI/CodexCLIVersionService.swift@@ -385,6 +385,12 @@ private final nonisolated class ProcessExitWaiter: Sendable {}}+/// CodexBar 各能力依赖的 app-server 最低版本+nonisolated enum CodexCLIMinimumVersion {+ static let global = "0.143.0"+ static let hook = "0.145.0"+}+/// 从 ` codex --version` 的输出中提取用户可读版本号nonisolated enum CodexCLIVersionReader {static func displayVersion(from output: String) -> String {diff --git a/CodexBar/Services/CodexStatus/CodexResetCreditsService.swift b/CodexBar/Services/CodexStatus/CodexResetCreditsService.swiftdeleted file mode 100644index 454d32e..0000000--- a/CodexBar/Services/CodexStatus/CodexResetCreditsService.swift+++ /dev/null@@ -1,127 +0,0 @@-import Foundation--nonisolated enum CodexResetCreditsService {- enum FetchError: Error {- case invalidResponse- case unauthorized- }-- private static let endpoint = URL(string: "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits")!- private static let timeout: TimeInterval = 4-- static func fetchExpirationDates(environment: [String: String]) async throws -> [Date] {- let credentials = try CodexOAuthCredentials.load(environment: environment)- let request = makeRequest(credentials: credentials)- let (data, response) = try await URLSession.shared.data(for: request)- guard let httpResponse = response as? HTTPURLResponse else {- throw FetchError.invalidResponse- }-- switch httpResponse.statusCode {- case 200 ... 299:- return try decodeExpirationDates(from: data)- case 401, 403:- throw FetchError.unauthorized- default:- throw FetchError.invalidResponse- }- }-- private static func makeRequest(credentials: CodexOAuthCredentials) -> URLRequest {- var request = URLRequest(url: endpoint, timeoutInterval: timeout)- request.httpMethod = "GET"- request.setValue("Bearer \(credentials.accessToken)", forHTTPHeaderField: "Authorization")- request.setValue("CodexBar", forHTTPHeaderField: "User-Agent")- request.setValue("application/json", forHTTPHeaderField: "Accept")- request.setValue("Codex Desktop", forHTTPHeaderField: "originator")-- if let accountId = credentials.accountId, !accountId.isEmpty {- request.setValue(accountId, forHTTPHeaderField: "ChatGPT-Account-ID")- }-- return request- }-- private static func decodeExpirationDates(from data: Data) throws -> [Date] {- let decoder = JSONDecoder()- decoder.dateDecodingStrategy = .custom(Self.decodeISO8601Date)- let payload = try decoder.decode(RateLimitResetCreditsResponse.self, from: data)- let now = Date()-- return payload.credits- .compactMap { credit in- guard credit.status == "available",- let expiresAt = credit.expiresAt,- expiresAt > now else {- return nil- }-- return expiresAt- }- .sorted()- }-- private static func decodeISO8601Date(from decoder: Decoder) throws -> Date {- let container = try decoder.singleValueContainer()- let raw = try container.decode(String.self)- if let date = CodexDateFormat.iso8601Date(from: raw) {- return date- }-- throw DecodingError.dataCorruptedError(- in: container,- debugDescription: "Invalid ISO-8601 date: \(raw)"- )- }-}--/// DTO 与凭据放在文件级而不是 extension 内-/// 套进类型里会让 CodingKeys 落到第二层嵌套-private nonisolated struct RateLimitResetCreditsResponse: Decodable {- let credits: [RateLimitResetCredit]-}--private nonisolated struct RateLimitResetCredit: Decodable {- let status: String- let expiresAt: Date?-- private enum CodingKeys: String, CodingKey {- case status- case expiresAt = "expires_at"- }-}--private nonisolated struct CodexOAuthCredentials {- let accessToken: String- let accountId: String?-- static func load(environment: [String: String]) throws -> Self {- let authURL = authFileURL(environment: environment)- let data = try Data(contentsOf: authURL)- let authFile = try JSONDecoder().decode(CodexAuthFile.self, from: data)- guard let accessToken = authFile.tokens?.accessToken, !accessToken.isEmpty else {- throw CodexResetCreditsService.FetchError.invalidResponse- }-- return Self(accessToken: accessToken, accountId: authFile.tokens?.accountId)- }-- private static func authFileURL(environment: [String: String]) -> URL {- CodexCLIResolver.codexHomeDirectory(environment: environment)- .appendingPathComponent("auth.json")- }-}--private nonisolated struct CodexAuthFile: Decodable {- let tokens: CodexAuthTokens?-}--private nonisolated struct CodexAuthTokens: Decodable {- let accessToken: String?- let accountId: String?-- private enum CodingKeys: String, CodingKey {- case accessToken = "access_token"- case accountId = "account_id"- }-}diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 526a8f2..09108d5 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -5,6 +5,7 @@ import osnonisolated enum CodexFetchOutcome {case data(CodexQuotaSnapshot)case notLoggedIn+ case unsupportedVersion(minimum: String)case initializationFailed}@@ -48,6 +49,7 @@ nonisolated struct CodexFetchResult {private nonisolated enum ConnectionResolution {case ready(connection: AppServerConnection, reused: Bool)case notLoggedIn+ case unsupportedVersion(minimum: String)case initializationFailed}@@ -197,6 +199,52 @@ actor CodexStatusService {)}+ /// 自动使用前必须绕过补充数据缓存读取一份新凭证明细+ func readResetCreditsForAutomation() throws -> ResetCreditAutomationRead {+ try withAutomationConnection { connection in+ try readResetCreditsForAutomation(using: connection)+ }+ }++ /// creditId 始终显式传入, 同一凭证的重试始终复用调用方给出的幂等键+ func consumeResetCredit(+ id creditID: String,+ idempotencyKey: String,+ expectedAccountIdentity: String+ ) throws -> ResetCreditConsumeResult {+ let response: ResetCreditConsumeResponse = try withAutomationConnection { connection in+ let accountResponse = try connection.session.request(+ "account/read",+ params: ["refreshToken": false],+ as: AccountReadResponse.self+ )+ guard let account = accountResponse.account else {+ throw CodexStatusError.notLoggedIn+ }+ guard ResetCreditAutomationIdentity.accountIdentity(for: account) == expectedAccountIdentity else {+ throw ResetCreditAutomationServiceError.accountChanged+ }++ connection.accountResponse = accountResponse+ return try connection.session.request(+ "account/rateLimitResetCredit/consume",+ params: [+ "creditId": creditID,+ "idempotencyKey": idempotencyKey+ ],+ as: ResetCreditConsumeResponse.self+ )+ }++ // 消费结果已经确定时刷新失败不能覆盖结果+ // 控制器仍会触发完整额度刷新, 这里先满足协议要求并尽快取得剩余次数+ let refreshedRead = try? readResetCreditsForAutomation()+ return ResetCreditConsumeResult(+ outcome: response.outcome,+ refreshedRead: refreshedRead+ )+ }+/// 复用连接出现传输故障时只重建重试一次/// 避免故障状态下反复拉起进程private func resolveOutcome(@@ -207,6 +255,9 @@ actor CodexStatusService {case .notLoggedIn:trace.failureStage = .connectreturn .notLoggedIn+ case let .unsupportedVersion(minimum):+ trace.failureStage = .connect+ return .unsupportedVersion(minimum: minimum)case .initializationFailed:trace.failureStage = .connectreturn .initializationFailed@@ -245,11 +296,59 @@ actor CodexStatusService {return connectioncase .notLoggedIn:throw CodexStatusError.notLoggedIn+ case let .unsupportedVersion(minimum):+ throw CodexStatusError.unsupportedVersion(minimum: minimum)case .initializationFailed:throw CodexStatusError.serverConnectionClosed}}+ /// 自动使用链路在传输故障后重建一次连接+ /// 每次逻辑操作最多刷新一次认证, 不在业务错误上创建新进程+ private func withAutomationConnection<Value>(+ _ operation: (AppServerConnection) throws -> Value+ ) throws -> Value {+ var canRebuild = true++ while true {+ let activeConnection = try readyConnection()++ do {+ return try performAutomationOperation(+ using: activeConnection,+ operation: operation+ )+ } catch let error as CodexStatusError where error.isTransportFailure && canRebuild {+ canRebuild = false+ teardownConnection()+ AppLog.app.notice("自动使用重置连接已重建: reason=transportError")+ }+ }+ }++ private func performAutomationOperation<Value>(+ using connection: AppServerConnection,+ operation: (AppServerConnection) throws -> Value+ ) throws -> Value {+ do {+ return try operation(connection)+ } catch let error as CodexStatusError where error.isAuthenticationRequired {+ do {+ try Self.refreshAccount(using: connection)+ } catch FetchFailure.notLoggedIn {+ throw CodexStatusError.notLoggedIn+ } catch FetchFailure.needsRebuild {+ throw CodexStatusError.serverConnectionClosed+ }++ do {+ return try operation(connection)+ } catch let error as CodexStatusError where error.isAuthenticationRequired {+ throw CodexStatusError.notLoggedIn+ }+ }+ }+private func ensureConnection() -> ConnectionResolution {if let connection, connection.session.process.isRunning,Date().timeIntervalSince(connection.openedAt) < Self.connectionMaxAge {@@ -295,6 +394,8 @@ actor CodexStatusService {switch resolution {case let .ready(newConnection, _):connection = newConnection+ case .unsupportedVersion:+ AppLog.app.error("codex 连接失败: stage=version")case .initializationFailed:AppLog.app.error("codex 连接失败: stage=open")case .notLoggedIn:@@ -310,6 +411,37 @@ actor CodexStatusService {// MARK: - 数据抓取与缓存+ private func readResetCreditsForAutomation(+ using connection: AppServerConnection+ ) throws -> ResetCreditAutomationRead {+ let accountResponse = try connection.session.request(+ "account/read",+ params: ["refreshToken": false],+ as: AccountReadResponse.self+ )+ guard let account = accountResponse.account else {+ throw CodexStatusError.notLoggedIn+ }++ connection.accountResponse = accountResponse+ if supplementalDataCache.useAccount(account) {+ AppLog.app.notice("额度缓存已丢弃: reason=accountChanged")+ }++ let rateLimitsResponse = try connection.session.request(+ "account/rateLimits/read",+ as: AccountRateLimitsResponse.self+ )+ supplementalDataCache.rateLimits = rateLimitsResponse++ let summary = rateLimitsResponse.rateLimitResetCredits+ return ResetCreditAutomationRead(+ accountIdentity: ResetCreditAutomationIdentity.accountIdentity(for: account),+ availableCount: summary?.availableCount,+ candidates: summary?.automationCandidates+ )+ }+/// 额度与用量独立读取/// 认证失败全程只刷新一次 token/// 传输故障交给外层重建连接@@ -389,23 +521,16 @@ actor CodexStatusService {)trace.usage = usageRead.step- let availableResetCredits = rateLimitsRead.value?.rateLimitResetCredits?.availableCount- let resetCreditExpirationDates = await fetchResetCreditExpirationDates(- availableCount: availableResetCredits,- refreshTokenIfNeeded: refreshTokenIfNeeded+ trace.resetCredits = Self.resetCreditsStepResult(+ summary: rateLimitsRead.value?.rateLimitResetCredits,+ rateLimitsStep: rateLimitsRead.step)- if let availableResetCredits, availableResetCredits > 0 {- trace.resetCredits = resetCreditExpirationDates == nil ? .failed : .ok- } else {- trace.resetCredits = .skipped- }// rateLimits/usage 都可为空, 只要账户有效就让 UI 展示"暂无数据"guard let snapshot = try? CodexQuotaSnapshot(accountResponse: connection.accountResponse,rateLimitsResponse: rateLimitsRead.value,- resetCreditExpirationDates: resetCreditExpirationDates,usageResponse: usageRead.value,isRateLimitsStale: rateLimitsRead.isStale,isUsageStale: usageRead.isStale@@ -417,41 +542,21 @@ actor CodexStatusService {return snapshot}- private func fetchResetCreditExpirationDates(- availableCount: Int?,- refreshTokenIfNeeded: () throws -> Void- ) async -> [Date]? {- guard let availableCount, availableCount > 0 else {- return nil+ private static func resetCreditsStepResult(+ summary: RateLimitResetCreditsSummary?,+ rateLimitsStep: CodexFetchTrace.StepResult+ ) -> CodexFetchTrace.StepResult {+ guard let summary else {+ return .missing}-- func fetchExpirationDates() async throws -> [Date] {- try await CodexResetCreditsService.fetchExpirationDates(environment: Self.environment)+ guard summary.availableCount > 0 else {+ return .skipped}-- do {- return try await fetchExpirationDates()- } catch CodexResetCreditsService.FetchError.unauthorized {- do {- try refreshTokenIfNeeded()- } catch {- let details = LogFields.joined(- "stage=refreshToken",- "detail=\(error.localizedDescription)"- )- AppLog.app.error("重置次数查询失败: \(details, privacy: .public)")- return nil- }-- return try? await fetchExpirationDates()- } catch {- let details = LogFields.joined(- "stage=fetch",- "detail=\(error.localizedDescription)"- )- AppLog.app.error("重置次数查询失败: \(details, privacy: .public)")- return nil+ guard summary.credits != nil else {+ return .missing}++ return rateLimitsStep == .cached ? .cached : .ok}/// 读不到账号时后面会沿用连接上缓存的那份@@ -581,6 +686,20 @@ actor CodexStatusService {timeout: timeout)+ return initializeConnection(+ session: session,+ command: command,+ clientVersion: clientVersion,+ openedAt: openedAt+ )+ }++ private static func initializeConnection(+ session: AppServerSession,+ command: AppServerCommand,+ clientVersion: String,+ openedAt: Date+ ) -> ConnectionResolution {do {let initializeResult = try session.request("initialize",@@ -594,6 +713,13 @@ actor CodexStatusService {as: InitializeResult.self)+ guard let serverVersion = Self.validatedServerVersion(+ fromUserAgent: initializeResult.userAgent+ ) else {+ session.close()+ return .unsupportedVersion(minimum: CodexCLIMinimumVersion.global)+ }+try session.notify("initialized")let accountResponse = try session.request(@@ -610,7 +736,7 @@ actor CodexStatusService {let commandInfo = CodexCLIConnectionInfo(source: command.source,executablePath: command.executablePath,- version: Self.serverVersion(fromUserAgent: initializeResult.userAgent),+ version: serverVersion,openedAt: openedAt)@@ -643,6 +769,25 @@ actor CodexStatusService {return version}+ private nonisolated static func validatedServerVersion(fromUserAgent userAgent: String?) -> String? {+ let version = serverVersion(fromUserAgent: userAgent)+ let minimumVersion = CodexCLIMinimumVersion.global+ guard let version,+ CodexCLIVersionReader.isVersion(version, atLeast: minimumVersion) == true else {+ let details = LogFields.joined(+ "current=\(version ?? "unknown")",+ "minimum=\(minimumVersion)"+ )+ AppLog.codexCLI.notice("Codex 版本不支持: \(details, privacy: .public)")+ RequestLogStorage.shared.recordFailure(+ message: CodexStatusError.unsupportedVersion(minimum: minimumVersion).localizedDescription+ )+ return nil+ }++ return version+ }+/// userAgent 形如 "codex_bar/0.139.0 (...)"; 取首个 token 中 "/" 之后的运行版本号private nonisolated static func serverVersion(fromUserAgent userAgent: String?) -> String? {guard let firstToken = userAgent?.split(separator: " ").first,diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex e8da400..ecd1bbe 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -7,11 +7,12 @@ nonisolated enum CodexLoadState: Equatable {case loadingcase loadedcase notLoggedIn+ case unsupportedVersion(minimum: String)case initializationFailedvar isError: Bool {switch self {- case .notLoggedIn, .initializationFailed: true+ case .notLoggedIn, .unsupportedVersion, .initializationFailed: truecase .loading, .loaded: false}}@@ -37,6 +38,8 @@ final class CodexStatusViewModel: ObservableObject {private let service: CodexStatusServiceprivate var autoRefreshTask: Task<Void, Never>?+ private var pendingRefreshTask: Task<Void, Never>?+ private var pendingForcedRefreshTrigger: LogTrigger?private let refreshCoordinator = RefreshTaskCoordinator()init(service: CodexStatusService = CodexStatusService()) {@@ -45,6 +48,7 @@ final class CodexStatusViewModel: ObservableObject {deinit {autoRefreshTask?.cancel()+ pendingRefreshTask?.cancel()refreshCoordinator.cancel()}@@ -86,7 +90,7 @@ final class CodexStatusViewModel: ObservableObject {let duration = LogDuration()refreshCoordinator.run(- setRefreshing: { [weak self] in self?.isRefreshing = $0 },+ setRefreshing: { [weak self] in self?.setRefreshing($0) },operation: { [service = self.service] inawait (fetch: service.fetchOutcome(), connectionInfo: service.currentConnectionInfo())},@@ -102,6 +106,9 @@ final class CodexStatusViewModel: ObservableObject {case .notLoggedIn:snapshot = nilloadState = .notLoggedIn+ case let .unsupportedVersion(minimum):+ snapshot = nil+ loadState = .unsupportedVersion(minimum: minimum)case .initializationFailed:snapshot = nilloadState = .initializationFailed@@ -120,6 +127,35 @@ final class CodexStatusViewModel: ObservableObject {)}+ /// 自动消费完成后不能因为普通刷新正在运行而丢掉最终对账+ func refreshAfterCurrent(trigger: LogTrigger) {+ guard isRefreshing else {+ refresh(trigger: trigger)+ return+ }++ pendingForcedRefreshTrigger = trigger+ }++ private func setRefreshing(_ refreshing: Bool) {+ isRefreshing = refreshing+ guard !refreshing, let trigger = pendingForcedRefreshTrigger else {+ return+ }++ pendingForcedRefreshTrigger = nil+ pendingRefreshTask?.cancel()+ pendingRefreshTask = Task { @MainActor [weak self] in+ await Task.yield()+ guard let self, !Task.isCancelled else {+ return+ }++ pendingRefreshTask = nil+ refresh(trigger: trigger)+ }+ }+/// 成功路径把各步结果压进一条, 失败才带上定位到哪一步private func logRefreshOutcome(trigger: LogTrigger,@@ -154,6 +190,14 @@ final class CodexStatusViewModel: ObservableObject {"elapsed=\(elapsed)")AppLog.app.notice("额度刷新已跳过: \(details, privacy: .public)")+ case let .unsupportedVersion(minimum):+ let details = LogFields.joined(+ "trigger=\(triggerName)",+ "reason=unsupportedCodexVersion",+ "minimum=\(minimum)",+ "elapsed=\(elapsed)"+ )+ AppLog.app.error("额度刷新失败: \(details, privacy: .public)")case .initializationFailed, .loading:let stage = trace.failureStage?.rawValue ?? "-"let details = LogFields.joined(diff --git a/CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift b/CodexBar/Services/CodexStatus/ResetCreditAutomationController.swiftnew file mode 100644index 0000000..efe4f9c--- /dev/null+++ b/CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift@@ -0,0 +1,655 @@+import AppKit+import Combine+import Foundation+import os++/// 自动使用临期重置的本机状态机+/// 系统睡眠时不申请唤醒, 唤醒后经新鲜读取决定是否补试+@MainActor+final class ResetCreditAutomationController {+ private enum ScheduledKind: Equatable {+ case threshold+ case retry+ }++ private enum RetryCause: Equatable {+ case transient+ case detailsUnavailable+ case nothingToReset+ case noCredit+ }++ private enum BlockReason: Equatable {+ case authentication+ case permanent+ }++ private struct Target {+ let accountIdentity: String+ let candidate: ResetCreditAutomationCandidate+ let key: String++ var idempotencyKey: String {+ ResetCreditAutomationIdentity.idempotencyKey(forCreditID: candidate.id)+ }+ }++ private static let retryDelays: [TimeInterval] = [15, 30, 60, 120, 300]+ private static let finalNothingToResetWindow: TimeInterval = 10 * 60+ private static let finalNothingToResetDelay: TimeInterval = 60++ private let settings: ResetCreditAutomationSettings+ private let statusViewModel: CodexStatusViewModel+ private let service: CodexStatusService+ private let notificationService: CodexNotificationService++ private var cancellables = Set<AnyCancellable>()+ private var scheduledTask: Task<Void, Never>?+ private var evaluationTask: Task<Void, Never>?+ private var settingsActivationTask: Task<Void, Never>?+ private var evaluationGeneration = 0+ private var pendingEvaluation = false+ private var latestSnapshot: CodexQuotaSnapshot?+ private var target: Target?+ private var retryIndex = 0+ private var consumedTargetKeys = Set<String>()+ private var expiredTargetDates: [String: Date] = [:]+ private var blockedTargets: [String: BlockReason] = [:]+ private var isStarted = false++ init(+ settings: ResetCreditAutomationSettings,+ statusViewModel: CodexStatusViewModel,+ service: CodexStatusService,+ notificationService: CodexNotificationService+ ) {+ self.settings = settings+ self.statusViewModel = statusViewModel+ self.service = service+ self.notificationService = notificationService+ }++ deinit {+ scheduledTask?.cancel()+ evaluationTask?.cancel()+ settingsActivationTask?.cancel()+ }++ func start() {+ guard !isStarted else {+ return+ }+ isStarted = true++ statusViewModel.$snapshot+ .sink { [weak self] snapshot in+ self?.handleSnapshot(snapshot)+ }+ .store(in: &cancellables)++ settings.$isEnabled+ .dropFirst()+ .sink { [weak self] enabled in+ self?.handleEnabledChange(enabled)+ }+ .store(in: &cancellables)++ settings.$leadTime+ .dropFirst()+ .sink { [weak self] leadTime in+ self?.handleLeadTimeChange(leadTime)+ }+ .store(in: &cancellables)++ NSWorkspace.shared.notificationCenter+ .publisher(for: NSWorkspace.didWakeNotification)+ .receive(on: DispatchQueue.main)+ .sink { [weak self] _ in+ self?.requestEvaluation(trigger: .wake)+ }+ .store(in: &cancellables)++ if settings.isEnabled {+ requestEvaluation(trigger: .launch)+ }+ }++ func stop() {+ guard isStarted else {+ return+ }+ isStarted = false+ cancellables.removeAll()+ cancelWork()+ target = nil+ retryIndex = 0+ }++ private func handleEnabledChange(_ enabled: Bool) {+ guard enabled else {+ cancelWork()+ target = nil+ retryIndex = 0+ return+ }++ settingsActivationTask?.cancel()+ settingsActivationTask = Task { @MainActor [weak self] in+ await Task.yield()+ guard let self,+ !Task.isCancelled,+ settings.isEnabled else {+ return+ }++ settingsActivationTask = nil+ if let latestSnapshot {+ handleSnapshot(latestSnapshot)+ }+ requestEvaluation(trigger: .settings)+ }+ }++ private func handleLeadTimeChange(_: ResetCreditAutomationLeadTime) {+ guard settings.isEnabled else {+ return+ }+ requestEvaluation(trigger: .settings)+ }++ private func handleSnapshot(_ snapshot: CodexQuotaSnapshot?) {+ latestSnapshot = snapshot+ guard settings.isEnabled,+ let snapshot,+ !snapshot.isRateLimitsStale else {+ return+ }++ reconcile(+ accountIdentity: ResetCreditAutomationIdentity.accountIdentity(for: snapshot.account),+ availableCount: snapshot.resetCreditsAvailableCount,+ candidates: snapshot.resetCreditAutomationCandidates,+ now: Date()+ )+ scheduleCurrentTargetIfNeeded()+ }++ private func requestEvaluation(+ trigger: LogTrigger,+ expectedTargetKey: String? = nil+ ) {+ guard isStarted, settings.isEnabled else {+ return+ }+ guard evaluationTask == nil else {+ pendingEvaluation = true+ return+ }++ cancelScheduledTask()+ evaluationGeneration += 1+ let generation = evaluationGeneration+ evaluationTask = Task { @MainActor [weak self] in+ guard let self else {+ return+ }+ await performEvaluation(+ trigger: trigger,+ expectedTargetKey: expectedTargetKey+ )+ finishEvaluation(generation: generation)+ }+ }++ private func finishEvaluation(generation: Int) {+ guard generation == evaluationGeneration else {+ return+ }++ evaluationTask = nil+ guard pendingEvaluation else {+ scheduleCurrentTargetIfNeeded()+ return+ }++ pendingEvaluation = false+ requestEvaluation(trigger: .retry)+ }++ private func performEvaluation(+ trigger: LogTrigger,+ expectedTargetKey: String?+ ) async {+ let freshRead: ResetCreditAutomationRead+ do {+ freshRead = try await service.readResetCreditsForAutomation()+ } catch {+ guard !Task.isCancelled, settings.isEnabled else {+ return+ }+ handleRequestFailure(error)+ return+ }++ guard !Task.isCancelled, settings.isEnabled else {+ return+ }++ let now = Date()+ reconcile(freshRead, now: now)++ guard freshRead.candidates != nil else {+ if target != nil || (freshRead.availableCount ?? 0) > 0 {+ scheduleRetry(cause: .detailsUnavailable)+ }+ return+ }+ guard let target else {+ return+ }+ if let expectedTargetKey, expectedTargetKey != target.key {+ scheduleCurrentTargetIfNeeded()+ return+ }+ guard blockedTargets[target.key] == nil else {+ return+ }+ guard target.candidate.expirationDate > now else {+ finishExpiredTarget(target)+ return+ }++ let thresholdDate = target.candidate.expirationDate+ .addingTimeInterval(-settings.leadTime.duration)+ guard thresholdDate <= now else {+ scheduleCurrentTargetIfNeeded()+ return+ }++ AppLog.app.notice(+ "自动使用重置开始: trigger=\(trigger.rawValue, privacy: .public)"+ )+ let attemptedTarget = target+ do {+ let result = try await service.consumeResetCredit(+ id: attemptedTarget.candidate.id,+ idempotencyKey: attemptedTarget.idempotencyKey,+ expectedAccountIdentity: attemptedTarget.accountIdentity+ )+ handleConsumeResult(result, attemptedTarget: attemptedTarget)+ } catch {+ handleConsumeFailure(error, attemptedTarget: attemptedTarget)+ }+ }++ private func handleConsumeResult(+ _ result: ResetCreditConsumeResult,+ attemptedTarget: Target+ ) {+ switch result.outcome {+ case .reset, .alreadyRedeemed:+ consumedTargetKeys.insert(attemptedTarget.key)+ expiredTargetDates.removeValue(forKey: attemptedTarget.key)+ blockedTargets.removeValue(forKey: attemptedTarget.key)+ clearTarget(ifMatching: attemptedTarget.key)++ let refreshedRead = result.refreshedRead+ let remainingCount = refreshedRead?.accountIdentity == attemptedTarget.accountIdentity+ ? refreshedRead?.availableCount+ : nil+ notificationService.notifyResetCreditAutoUseSucceeded(+ remainingCount: remainingCount,+ dedupToken: attemptedTarget.key+ )+ AppLog.app.notice(+ "自动使用重置完成: outcome=\(result.outcome.rawValue, privacy: .public)"+ )++ if settings.isEnabled,+ let refreshedRead,+ refreshedRead.accountIdentity == attemptedTarget.accountIdentity {+ reconcile(refreshedRead)+ scheduleCurrentTargetIfNeeded()+ }+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)++ case .nothingToReset, .noCredit:+ if let refreshedRead = result.refreshedRead {+ reconcile(refreshedRead)+ }++ guard settings.isEnabled,+ target?.key == attemptedTarget.key else {+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)+ return+ }++ let cause: RetryCause = result.outcome == .nothingToReset+ ? .nothingToReset+ : .noCredit+ AppLog.app.notice(+ "自动使用重置未完成: outcome=\(result.outcome.rawValue, privacy: .public)"+ )+ scheduleRetry(cause: cause)++ if result.outcome == .noCredit {+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)+ }+ }+ }++ private func handleConsumeFailure(_ error: Error, attemptedTarget: Target) {+ guard !Task.isCancelled,+ settings.isEnabled,+ target?.key == attemptedTarget.key else {+ return+ }+ handleRequestFailure(error)+ }++ private func handleRequestFailure(_ error: Error) {+ if error is ResetCreditAutomationServiceError {+ clearTarget()+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)+ return+ }++ if let error = error as? CodexStatusError {+ if error.isAuthenticationRequired {+ blockCurrentTarget(reason: .authentication)+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)+ return+ }+ if error.isProtocolOrParameterFailure {+ blockCurrentTarget(reason: .permanent)+ return+ }++ AppLog.app.notice("自动使用重置稍后重试: reason=requestFailed")+ scheduleRetry(cause: .transient)+ return+ }++ blockCurrentTarget(reason: .permanent)+ }++ private func blockCurrentTarget(reason: BlockReason) {+ guard let target else {+ return+ }++ blockedTargets[target.key] = reason+ cancelScheduledTask()+ switch reason {+ case .authentication:+ notificationService.notifyResetCreditAutoUseFailed(+ reason: .authentication,+ dedupToken: target.key+ )+ AppLog.app.error("自动使用重置已暂停: reason=authentication")+ case .permanent:+ notificationService.notifyResetCreditAutoUseFailed(+ reason: .permanent,+ dedupToken: target.key+ )+ AppLog.app.error("自动使用重置已停止: reason=permanentFailure")+ }+ }++ private func scheduleRetry(cause: RetryCause) {+ guard settings.isEnabled else {+ return+ }+ guard let target else {+ schedule(after: nextRetryDelay(), kind: .retry, expectedTargetKey: nil)+ return+ }+ guard blockedTargets[target.key] == nil else {+ return+ }++ let remaining = target.candidate.expirationDate.timeIntervalSinceNow+ guard remaining > 0 else {+ finishExpiredTarget(target)+ return+ }++ var delay = nextRetryDelay()+ if cause == .nothingToReset, remaining <= Self.finalNothingToResetWindow {+ delay = Self.finalNothingToResetDelay+ }+ delay = min(delay, remaining)+ schedule(+ after: delay,+ kind: .retry,+ expectedTargetKey: target.key+ )+ }++ private func nextRetryDelay() -> TimeInterval {+ let index = min(retryIndex, Self.retryDelays.count - 1)+ retryIndex += 1+ return Self.retryDelays[index]+ }++ private func scheduleCurrentTargetIfNeeded() {+ guard isStarted,+ settings.isEnabled,+ evaluationTask == nil,+ scheduledTask == nil,+ let target,+ blockedTargets[target.key] == nil else {+ return+ }++ let delay = target.candidate.expirationDate+ .addingTimeInterval(-settings.leadTime.duration)+ .timeIntervalSinceNow+ schedule(+ after: delay,+ kind: .threshold,+ expectedTargetKey: target.key+ )+ }++ private func schedule(+ after delay: TimeInterval,+ kind: ScheduledKind,+ expectedTargetKey: String?+ ) {+ cancelScheduledTask()+ scheduledTask = Task { @MainActor [weak self] in+ do {+ try await Task.sleep(for: .seconds(max(0, delay)))+ } catch {+ return+ }+ guard let self, !Task.isCancelled else {+ return+ }++ scheduledTask = nil+ requestEvaluation(+ trigger: kind == .threshold ? .auto : .retry,+ expectedTargetKey: expectedTargetKey+ )+ }+ }++ private func reconcile(+ accountIdentity: String,+ availableCount: Int?,+ candidates: [ResetCreditAutomationCandidate]?,+ now: Date+ ) {+ if let target, target.accountIdentity != accountIdentity {+ clearTarget()+ }++ if availableCount == 0 {+ clearTarget()+ return+ }++ guard let candidates else {+ return+ }++ if let currentTarget = target,+ currentTarget.accountIdentity == accountIdentity {+ if let matchingCandidate = candidates.first(where: {+ $0.id == currentTarget.candidate.id+ }) {+ let expirationChanged = matchingCandidate.expirationDate+ != currentTarget.candidate.expirationDate+ let updatedTarget = makeTarget(+ accountIdentity: accountIdentity,+ candidate: matchingCandidate+ )+ target = updatedTarget+ if expirationChanged {+ // creditId 决定幂等身份, expiresAt 是可变调度数据+ // 取消阈值或重试任务, 由当前调用链按新时间重建+ cancelScheduledTask()+ let direction = matchingCandidate.expirationDate+ < currentTarget.candidate.expirationDate ? "earlier" : "later"+ AppLog.app.notice(+ "自动使用重置计划已更新: reason=expirationChanged direction=\(direction, privacy: .public)"+ )+ }+ if blockedTargets[currentTarget.key] == .authentication {+ blockedTargets.removeValue(forKey: currentTarget.key)+ }+ if matchingCandidate.expirationDate <= now {+ finishExpiredTarget(updatedTarget)+ return+ }+ } else {+ // 凭证消失无法区分手动使用 其他设备使用或服务端过期+ // 因此只停止本机任务, 不发送自动使用通知+ clearTarget()+ }+ }++ let nextCandidate = candidates+ .filter { candidate in+ isCandidateEligible(+ candidate,+ accountIdentity: accountIdentity,+ now: now+ )+ }+ .sorted { lhs, rhs in+ if lhs.expirationDate != rhs.expirationDate {+ return lhs.expirationDate < rhs.expirationDate+ }+ return lhs.id < rhs.id+ }+ .first++ guard let nextCandidate else {+ return+ }++ let nextTarget = makeTarget(+ accountIdentity: accountIdentity,+ candidate: nextCandidate+ )+ if expiredTargetDates.removeValue(forKey: nextTarget.key) != nil {+ AppLog.app.notice("自动使用重置计划已恢复: reason=expirationExtended")+ }+ if target?.key == nextTarget.key {+ return+ }++ cancelScheduledTask()+ target = nextTarget+ retryIndex = 0+ if blockedTargets[nextTarget.key] == .authentication {+ blockedTargets.removeValue(forKey: nextTarget.key)+ }+ }++ private func reconcile(+ _ read: ResetCreditAutomationRead,+ now: Date = Date()+ ) {+ reconcile(+ accountIdentity: read.accountIdentity,+ availableCount: read.availableCount,+ candidates: read.candidates,+ now: now+ )+ }++ private func isCandidateEligible(+ _ candidate: ResetCreditAutomationCandidate,+ accountIdentity: String,+ now: Date+ ) -> Bool {+ guard candidate.expirationDate > now else {+ return false+ }++ let key = ResetCreditAutomationIdentity.notificationToken(+ accountIdentity: accountIdentity,+ creditID: candidate.id+ )+ guard !consumedTargetKeys.contains(key) else {+ return false+ }+ guard let expiredDate = expiredTargetDates[key] else {+ return true+ }+ return candidate.expirationDate > expiredDate+ }++ private func makeTarget(+ accountIdentity: String,+ candidate: ResetCreditAutomationCandidate+ ) -> Target {+ Target(+ accountIdentity: accountIdentity,+ candidate: candidate,+ key: ResetCreditAutomationIdentity.notificationToken(+ accountIdentity: accountIdentity,+ creditID: candidate.id+ )+ )+ }++ private func finishExpiredTarget(_ expiredTarget: Target) {+ expiredTargetDates[expiredTarget.key] = expiredTarget.candidate.expirationDate+ clearTarget(ifMatching: expiredTarget.key)+ notificationService.notifyResetCreditAutoUseFailed(+ reason: .expired,+ dedupToken: expiredTarget.key+ )+ AppLog.app.error("自动使用重置失败: reason=expired")+ statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)+ }++ private func clearTarget(ifMatching key: String? = nil) {+ if let key, target?.key != key {+ return+ }+ cancelScheduledTask()+ target = nil+ retryIndex = 0+ }++ private func cancelScheduledTask() {+ scheduledTask?.cancel()+ scheduledTask = nil+ }++ private func cancelWork() {+ cancelScheduledTask()+ settingsActivationTask?.cancel()+ settingsActivationTask = nil+ evaluationGeneration += 1+ evaluationTask?.cancel()+ evaluationTask = nil+ pendingEvaluation = false+ }+}diff --git a/CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift b/CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swiftnew file mode 100644index 0000000..2dc4fc4--- /dev/null+++ b/CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift@@ -0,0 +1,50 @@+import CryptoKit+import Foundation++/// 自动使用重置的跨设备身份规则+/// namespace 和 UUIDv5 输入一旦发布就属于兼容性协议+nonisolated enum ResetCreditAutomationIdentity {+ static let namespaceString = "8abd477b-2320-5e39-9518-2a2adfc542fa"++ private static let namespace = UUID(uuidString: namespaceString)!++ static func idempotencyKey(forCreditID creditID: String) -> String {+ var input = uuidData(namespace)+ input.append(contentsOf: creditID.utf8)++ var bytes = Array(Insecure.SHA1.hash(data: input).prefix(16))+ bytes[6] = (bytes[6] & 0x0F) | 0x50+ bytes[8] = (bytes[8] & 0x3F) | 0x80+ return uuid(from: bytes).uuidString.lowercased()+ }++ static func accountIdentity(for account: CodexAccount) -> String {+ let email = account.email?+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .lowercased() ?? ""+ return "\(account.type)\u{0}\(email)"+ }++ /// 通知去重键只保留哈希, 不把账号和 creditId 写入 UserDefaults+ static func notificationToken(accountIdentity: String, creditID: String) -> String {+ var input = Data(accountIdentity.utf8)+ input.append(0)+ input.append(contentsOf: creditID.utf8)+ return SHA256.hash(data: input).map { String(format: "%02x", $0) }.joined()+ }++ private static func uuidData(_ uuid: UUID) -> Data {+ var bytes = uuid.uuid+ return withUnsafeBytes(of: &bytes) { Data($0) }+ }++ private static func uuid(from bytes: [UInt8]) -> UUID {+ precondition(bytes.count == 16)+ return UUID(uuid: (+ bytes[0], bytes[1], bytes[2], bytes[3],+ bytes[4], bytes[5], bytes[6], bytes[7],+ bytes[8], bytes[9], bytes[10], bytes[11],+ bytes[12], bytes[13], bytes[14], bytes[15]+ ))+ }+}diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 55c0d17..c150bdd 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -4,6 +4,12 @@ import Foundationimport osimport UserNotifications+nonisolated enum ResetCreditAutomationFailureNotice: String, Sendable {+ case expired+ case authentication+ case permanent+}+/// 集中式提醒服务: 订阅额度与实时活动, 负责触觉反馈; 阈值判定; 去重; 重置识别与本地通知发送@MainActorfinal class CodexNotificationService: NSObject {@@ -444,6 +450,38 @@ final class CodexNotificationService: NSObject {}}+ // MARK: - 自动使用重置++ func notifyResetCreditAutoUseSucceeded(+ remainingCount: Int?,+ dedupToken: String+ ) {+ guard settings.canDeliver, settings.isResetCreditAutoUseEnabled else {+ return+ }++ send(+ .resetCreditAutoUseSucceeded(remainingCount: remainingCount),+ sound: settings.resetCreditAutoUseSound,+ dedupKey: "autoResetSuccess|\(dedupToken)"+ )+ }++ func notifyResetCreditAutoUseFailed(+ reason: ResetCreditAutomationFailureNotice,+ dedupToken: String+ ) {+ guard settings.canDeliver, settings.isResetCreditAutoUseEnabled else {+ return+ }++ send(+ .resetCreditAutoUseFailed(reason: reason),+ sound: settings.resetCreditAutoUseSound,+ dedupKey: "autoResetFailure|\(dedupToken)|\(reason.rawValue)"+ )+ }+// MARK: - 低电量保护/// 由 KeepAliveController 在低电量导致睡眠恢复成功之后调用, 恢复失败不会走到这里@@ -479,7 +517,8 @@ final class CodexNotificationService: NSObject {// MARK: - 重置次数临期提醒private func processCreditExpirations(_ snapshot: CodexQuotaSnapshot) {- guard settings.isCreditExpiryEnabled,+ guard !snapshot.isRateLimitsStale,+ settings.isCreditExpiryEnabled,let dates = snapshot.resetCreditExpirationDates else {scheduleNextCreditExpiryCheck(dates: [])return@@ -787,6 +826,57 @@ nonisolated struct CodexNotificationContent: Equatable {)}+ static func resetCreditAutoUseSucceeded(remainingCount: Int?) -> CodexNotificationContent {+ let body = if let remainingCount {+ String(+ localized: "notification.reset-credit-auto-use.body.count",+ defaultValue: "剩余重置次数: \(remainingCount)"+ )+ } else {+ ""+ }++ return CodexNotificationContent(+ kind: "resetCreditAutoUse",+ title: String(+ localized: "notification.reset-credit-auto-use.title",+ defaultValue: "自动使用重置"+ ),+ body: body+ )+ }++ static func resetCreditAutoUseFailed(+ reason: ResetCreditAutomationFailureNotice+ ) -> CodexNotificationContent {+ let body = switch reason {+ case .expired:+ String(+ localized: "notification.reset-credit-auto-use-failed.body.expired",+ defaultValue: "已过期, 未能自动使用"+ )+ case .authentication:+ String(+ localized: "notification.reset-credit-auto-use-failed.body.authentication",+ defaultValue: "Codex 登录状态已失效"+ )+ case .permanent:+ String(+ localized: "notification.reset-credit-auto-use-failed.body.permanent",+ defaultValue: "请求无法完成"+ )+ }++ return CodexNotificationContent(+ kind: "resetCreditAutoUseFailed",+ title: String(+ localized: "notification.reset-credit-auto-use-failed.title",+ defaultValue: "自动使用重置失败"+ ),+ body: body+ )+ }+static func taskCompleted(project: String?, duration: TimeInterval) -> CodexNotificationContent {let durationText = CodexActivityDisplayFormat.elapsedDurationFragment(for: duration)let body = if let project {diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex f50202b..f785b12 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -5,7 +5,7 @@ import os/// 设置页的 Codex Hook 开关状态机, 同时管理 hooks.json 和 Codex 信任状态@MainActorfinal class CodexHookSettings: ObservableObject {- static let minimumSupportedCodexVersion = "0.145.0"+ static let minimumSupportedCodexVersion = CodexCLIMinimumVersion.hook@Published private(set) var isEnabled = false@Published private(set) var isUpdating = falsediff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex 4ffa70d..b42466f 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 {@@ -15,6 +15,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var isTaskWaitingEnabled: Bool@Published private(set) var isTaskHapticEnabled: Bool@Published private(set) var isCreditExpiryEnabled: Bool+ @Published private(set) var isResetCreditAutoUseEnabled: Bool@Published private(set) var isLowBatteryEnabled: Bool@Published private(set) var isKeepAliveLimitEnabled: Bool@Published private(set) var lowQuotaThresholdPercent: Int@@ -24,6 +25,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var taskCompletionSound: NotificationSoundOption@Published private(set) var taskWaitingSound: NotificationSoundOption@Published private(set) var creditExpirySound: NotificationSoundOption+ @Published private(set) var resetCreditAutoUseSound: NotificationSoundOption@Published private(set) var lowBatterySound: NotificationSoundOption@Published private(set) var keepAliveLimitSound: NotificationSoundOption@Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined@@ -78,6 +80,11 @@ final class NotificationSettings: ObservableObject {isTaskWaitingEnabled = Self.bool(from: defaults, key: Self.taskWaitingEnabledKey, defaultValue: true)isTaskHapticEnabled = Self.bool(from: defaults, key: Self.taskHapticEnabledKey, defaultValue: false)isCreditExpiryEnabled = Self.bool(from: defaults, key: Self.creditExpiryEnabledKey, defaultValue: true)+ isResetCreditAutoUseEnabled = Self.bool(+ from: defaults,+ key: Self.resetCreditAutoUseEnabledKey,+ 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(@@ -95,6 +102,7 @@ final class NotificationSettings: ObservableObject {taskCompletionSound = Self.sound(from: defaults, key: Self.taskCompletionSoundKey)taskWaitingSound = Self.sound(from: defaults, key: Self.taskWaitingSoundKey)creditExpirySound = Self.sound(from: defaults, key: Self.creditExpirySoundKey)+ resetCreditAutoUseSound = Self.sound(from: defaults, key: Self.resetCreditAutoUseSoundKey)lowBatterySound = Self.sound(from: defaults, key: Self.lowBatterySoundKey)keepAliveLimitSound = Self.sound(from: defaults, key: Self.keepAliveLimitSoundKey)}@@ -140,6 +148,10 @@ final class NotificationSettings: ObservableObject {setBool(enabled, current: &isCreditExpiryEnabled, key: Self.creditExpiryEnabledKey)}+ func setResetCreditAutoUseEnabled(_ enabled: Bool) {+ setBool(enabled, current: &isResetCreditAutoUseEnabled, key: Self.resetCreditAutoUseEnabledKey)+ }+func setLowBatteryEnabled(_ enabled: Bool) {setBool(enabled, current: &isLowBatteryEnabled, key: Self.lowBatteryEnabledKey)}@@ -188,6 +200,10 @@ final class NotificationSettings: ObservableObject {setSound(sound, current: &creditExpirySound, key: Self.creditExpirySoundKey)}+ func setResetCreditAutoUseSound(_ sound: NotificationSoundOption) {+ setSound(sound, current: &resetCreditAutoUseSound, key: Self.resetCreditAutoUseSoundKey)+ }+func setLowBatterySound(_ sound: NotificationSoundOption) {setSound(sound, current: &lowBatterySound, key: Self.lowBatterySoundKey)}@@ -261,7 +277,7 @@ final class NotificationSettings: ObservableObject {return}- // 七个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志+ // 八个通知细项都走这里, 用持久化 key 区分是哪一项, 不必逐个 setter 铺日志let details = LogFields.joined("key=\(key)","enabled=\(value ? 1 : 0)"@@ -317,6 +333,7 @@ final class NotificationSettings: ObservableObject {private static let taskWaitingEnabledKey = "Notification.taskWaitingEnabled"private static let taskHapticEnabledKey = "Notification.taskHapticEnabled"private static let creditExpiryEnabledKey = "Notification.creditExpiryEnabled"+ private static let resetCreditAutoUseEnabledKey = "Notification.resetCreditAutoUseEnabled"private static let lowBatteryEnabledKey = "Notification.lowBatteryEnabled"private static let keepAliveLimitEnabledKey = "Notification.keepAliveLimitEnabled"private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"@@ -326,6 +343,7 @@ final class NotificationSettings: ObservableObject {private static let taskCompletionSoundKey = "Notification.taskCompletionSound"private static let taskWaitingSoundKey = "Notification.taskWaitingSound"private static let creditExpirySoundKey = "Notification.creditExpirySound"+ private static let resetCreditAutoUseSoundKey = "Notification.resetCreditAutoUseSound"private static let lowBatterySoundKey = "Notification.lowBatterySound"private static let keepAliveLimitSoundKey = "Notification.keepAliveLimitSound"}diff --git a/CodexBar/Services/Settings/ResetCreditAutomationSettings.swift b/CodexBar/Services/Settings/ResetCreditAutomationSettings.swiftnew file mode 100644index 0000000..4c39d9e--- /dev/null+++ b/CodexBar/Services/Settings/ResetCreditAutomationSettings.swift@@ -0,0 +1,92 @@+import Combine+import Foundation+import os++nonisolated enum ResetCreditAutomationLeadTime: Int, CaseIterable, Hashable, Sendable {+ case thirtyMinutes = 1800+ case oneHour = 3600+ case twoHours = 7200+ case fourHours = 14400+ case sixHours = 21600+ case twelveHours = 43200++ var duration: TimeInterval {+ TimeInterval(rawValue)+ }++ var title: String {+ switch self {+ case .thirtyMinutes:+ String(localized: "30 分钟")+ case .oneHour:+ String(localized: "1 小时")+ case .twoHours:+ String(localized: "2 小时")+ case .fourHours:+ String(localized: "4 小时")+ case .sixHours:+ String(localized: "6 小时")+ case .twelveHours:+ String(localized: "12 小时")+ }+ }+}++/// 自动使用临期重置的本机设置+@MainActor+final class ResetCreditAutomationSettings: ObservableObject {+ @Published private(set) var isEnabled: Bool+ @Published private(set) var leadTime: ResetCreditAutomationLeadTime++ private let defaults: UserDefaults++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ isEnabled = defaults.bool(forKey: Self.enabledKey)+ leadTime = Self.loadLeadTime(from: defaults)+ }++ func refresh() {+ let isEnabled = defaults.bool(forKey: Self.enabledKey)+ if isEnabled != self.isEnabled {+ self.isEnabled = isEnabled+ }++ let leadTime = Self.loadLeadTime(from: defaults)+ if leadTime != self.leadTime {+ self.leadTime = leadTime+ }+ }++ func setEnabled(_ enabled: Bool) {+ guard enabled != isEnabled else {+ return+ }++ AppLog.settings.notice("自动使用重置变更: enabled=\(enabled ? 1 : 0)")+ isEnabled = enabled+ defaults.set(enabled, forKey: Self.enabledKey)+ }++ func setLeadTime(_ leadTime: ResetCreditAutomationLeadTime) {+ guard leadTime != self.leadTime else {+ return+ }++ AppLog.settings.notice("自动使用重置临期时间变更: seconds=\(leadTime.rawValue)")+ self.leadTime = leadTime+ defaults.set(leadTime.rawValue, forKey: Self.leadTimeKey)+ }++ private static func loadLeadTime(from defaults: UserDefaults) -> ResetCreditAutomationLeadTime {+ guard let rawValue = defaults.object(forKey: leadTimeKey) as? Int,+ let leadTime = ResetCreditAutomationLeadTime(rawValue: rawValue) else {+ return .twoHours+ }++ return leadTime+ }++ private static let enabledKey = "ResetCreditAutomation.enabled"+ private static let leadTimeKey = "ResetCreditAutomation.leadTimeSeconds"+}diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 9ad10c7..747cf37 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -56,6 +56,7 @@ nonisolated enum LogTrigger: String {/// 电量或供电方式变化case batterycase statusRefresh+ case resetCreditAutoUse}/// 日志里耗时字段的统一取值方式, 保留两位小数并带单位diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex a4d004e..b7b4a1c 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -76,7 +76,7 @@ struct AccountCard: View {]}-/// 未登录或初始化失败时的账号行, 不展示底层错误细节+/// 账户主链路不可用时的账号行, 不展示底层错误细节struct StatusAccountCard: View {let loadState: CodexLoadStatelet isRefreshing: Bool@@ -115,6 +115,8 @@ struct StatusAccountCard: View {switch loadState {case .notLoggedIn:("未登录", .orange)+ case let .unsupportedVersion(minimum):+ ("需要 Codex \(minimum) 或更高版本", .red)case .initializationFailed:("初始化失败", .red)case .loading, .loaded:diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 54288ee..8c4f44d 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -65,7 +65,7 @@ private extension CodexStatusMenuView {dataSection(snapshot)} else {- // 仅展示未登录/初始化失败两种特殊状态, 其余错误只进日志+ // 展示用户可处理的账户主链路状态, 其余错误只进日志StatusAccountCard(loadState: viewModel.loadState,isRefreshing: viewModel.isRefreshing,diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 2e15d2f..69c67a2 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -13,6 +13,7 @@ struct AppSettingsView: View {@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings@ObservedObject var mainPanelSettings: MainPanelSettings@ObservedObject var notificationSettings: NotificationSettings+ @ObservedObject var resetCreditAutomationSettings: ResetCreditAutomationSettings@ObservedObject var keepAliveController: KeepAliveControllerlet onSyncChanged: (Bool) -> Voidlet onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler@@ -21,12 +22,14 @@ struct AppSettingsView: View {@State private var selectedTab = SettingsTab.general@State private var isTabContentSettled = true@State private var notificationAnchorProvider = ScreenFrameProvider()+ @State private var resetCreditAutomationAnchorProvider = ScreenFrameProvider()@State private var keepAliveAnchorProvider = ScreenFrameProvider()@State private var rebuildableDates = [String]()@State private var selectedRebuildRange: RebuildDateRange?@State private var isShowingRebuildConfirmation = false@State private var isRebuildingWorkflowData = false@State private var rebuildStatus: RebuildStatus?+ @State private var isShowingResetCreditAutomationConfirmation = falsevar body: some View {VStack(spacing: 0) {@@ -73,6 +76,7 @@ struct AppSettingsView: View {syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()+ resetCreditAutomationSettings.refresh()appUpdater.refreshAutomaticCheckSetting()refreshStatusRows()}@@ -81,12 +85,14 @@ struct AppSettingsView: View {syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()+ resetCreditAutomationSettings.refresh()codexHookSettings.verifyInstalledHooks()refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: .settingsWindowDidOpen)) { _ inselectedRebuildRange = nilisShowingRebuildConfirmation = false+ isShowingResetCreditAutomationConfirmation = falseclearRebuildStatus()}.onChange(of: selectedTab) { _, _ in@@ -122,7 +128,18 @@ struct AppSettingsView: View {rebuildWorkflowData()}} message: {- Text("将从本机原始 Hook 事件重新统计 \(selectedRebuildRange?.displayText ?? "")\n并在下次同步时替换当前设备对应日期的云端聚合")+ Text("将从本机原始 Hook 事件重新统计 \(selectedRebuildRange?.displayText ?? "")\n并在下次同步时替换当前设备对应日期的云端数据")+ }+ .alert(+ "开启自动使用重置?",+ isPresented: $isShowingResetCreditAutomationConfirmation+ ) {+ Button("取消", role: .cancel) {}+ Button("开启", role: .destructive) {+ resetCreditAutomationSettings.setEnabled(true)+ }+ } message: {+ Text("开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销")}}}@@ -248,6 +265,8 @@ private extension AppSettingsView {LiquidGlassDivider()notificationRowLiquidGlassDivider()+ resetCreditAutomationRow+ LiquidGlassDivider()keepAliveRowLiquidGlassDivider()syncRow@@ -403,6 +422,47 @@ private extension AppSettingsView {}}+ var resetCreditAutomationRow: some View {+ let isEnabled = resetCreditAutomationSettings.isEnabled++ return VStack(alignment: .leading, spacing: 4) {+ SettingsToggleRow(+ icon: "arrow.counterclockwise.circle",+ title: "自动使用临期重置",+ isOn: Binding(+ get: { resetCreditAutomationSettings.isEnabled },+ set: { enabled in+ if enabled {+ isShowingResetCreditAutomationConfirmation = true+ } else {+ resetCreditAutomationSettings.setEnabled(enabled)+ }+ }+ )+ ) {+ optionsButton(isAvailable: isEnabled) {+ onOptionsAction(+ .toggle(+ panel: .resetCreditAutomation,+ anchorProvider: resetCreditAutomationAnchorProvider+ )+ )+ }+ }+ }+ .background {+ ScreenFrameReader(provider: resetCreditAutomationAnchorProvider)+ }+ .animation(Metrics.statusAnimation, value: isEnabled)+ .onChange(of: isEnabled) { _, isEnabled in+ guard !isEnabled else {+ return+ }++ onOptionsAction(.close(panel: .resetCreditAutomation))+ }+ }+// MARK: - 防睡眠var keepAliveRow: some View {@@ -461,7 +521,7 @@ private extension AppSettingsView {}}- /// 两个子面板入口共用的滑杆按钮; 依赖没就绪时只隐藏入口, 不回写用户保存的开关+ /// 子面板入口共用的滑杆按钮; 依赖没就绪时只隐藏入口, 不回写用户保存的开关func optionsButton(isAvailable: Bool, action: @escaping () -> Void) -> some View {Button(action: action) {Image(systemName: "slider.horizontal.3")diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex b344f3e..5013ef7 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -7,6 +7,7 @@ struct NotificationOptionsView: View {@ObservedObject var notificationSettings: NotificationSettings@ObservedObject var codexHookSettings: CodexHookSettings@ObservedObject var codexCLINotificationSettings: CodexCLINotificationSettings+ @ObservedObject var resetCreditAutomationSettings: ResetCreditAutomationSettings@ObservedObject var keepAliveController: KeepAliveController@State private var previewSound: NSSound?@@ -17,6 +18,7 @@ struct NotificationOptionsView: View {lowQuotaRowquotaResetRowcreditExpiryRow+ resetCreditAutoUseRowlowBatteryRowkeepAliveLimitRowtaskHapticRow@@ -157,6 +159,25 @@ struct NotificationOptionsView: View {)}+ /// 自动使用关着时显示为关闭并置灰, 不修改持久化的 isResetCreditAutoUseEnabled+ private var resetCreditAutoUseRow: some View {+ let isAutomationEnabled = resetCreditAutomationSettings.isEnabled+ let isDisplayedOn = isAutomationEnabled && notificationSettings.isResetCreditAutoUseEnabled++ return notificationOptionRow(+ title: "自动使用重置通知",+ isOn: Binding(+ get: { isDisplayedOn },+ set: { notificationSettings.setResetCreditAutoUseEnabled($0) }+ ),+ isEnabled: isAutomationEnabled,+ sound: Binding(+ get: { notificationSettings.resetCreditAutoUseSound },+ set: { notificationSettings.setResetCreditAutoUseSound($0) }+ )+ )+ }+/// 防睡眠关着或低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled/// 保护默认就是关的, 不置灰会让这一行在任何默认安装上都亮着, 而对应通知永远发不出来/// "保护是不是真的在起作用"由 KeepAliveController 判定, 这里只读结论@@ -434,7 +455,7 @@ struct NotificationOptionsView: View {static let panelWidth: CGFloat = 320static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding- static let notificationRowCount = 7+ static let notificationRowCount = 8static let captionedRowCount = 2static let totalRowCount = notificationRowCount + captionedRowCountstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingdiff --git a/CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swift b/CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swiftnew file mode 100644index 0000000..1f65dbd--- /dev/null+++ b/CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swift@@ -0,0 +1,51 @@+import SwiftUI++/// 自动使用重置子选项面板, 顶边对齐设置页的自动使用主开关行+struct ResetCreditAutomationOptionsView: View {+ @ObservedObject var settings: ResetCreditAutomationSettings++ var body: some View {+ HStack(spacing: Metrics.controlSpacing) {+ Text("临期时间")+ .font(.caption)+ .foregroundStyle(.secondary)++ Spacer(minLength: 8)++ SettingsOptionsPicker(+ title: "临期时间",+ selection: Binding(+ get: { settings.leadTime },+ set: { settings.setLeadTime($0) }+ ),+ options: ResetCreditAutomationLeadTime.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+ )+ }++ private enum Metrics {+ static let panelWidth: CGFloat = 250+ static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPadding+ static let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding+ static let rowHeight = SettingsOptionsPanelMetrics.rowHeight+ static let controlSpacing = SettingsOptionsPanelMetrics.controlSpacing+ static let pickerWidth: CGFloat = 88+ static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius+ }+}diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex 1677525..800524d 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -6,8 +6,8 @@ enum SettingsRowMetrics {static let spacing: CGFloat = 10}-/// 设置窗口右侧两个子选项面板共用的度量-/// 两个面板要看起来是同一套控件, 所以除了面板宽度和 picker 宽度以外都从这里取+/// 设置窗口右侧子选项面板共用的度量+/// 各面板要看起来是同一套控件, 所以除了面板宽度和 picker 宽度以外都从这里取enum SettingsOptionsPanelMetrics {static let horizontalPadding: CGFloat = 12static let verticalPadding: CGFloat = 10@@ -19,8 +19,8 @@ enum SettingsOptionsPanelMetrics {static let cornerRadius: CGFloat = 12}-/// 两个子选项面板共用的下拉选择器-/// 只有宽度和对齐各自定义, 其余样式必须同源, 否则两个面板看起来就不是同一套控件+/// 子选项面板共用的下拉选择器+/// 只有宽度和对齐各自定义, 其余样式必须同源, 否则各面板看起来就不是同一套控件struct SettingsOptionsPicker<Option: Hashable>: View {let title: LocalizedStringResource@Binding var selection: Optiondiff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex 599156f..fd87172 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 3.6.1-CURRENT_PROJECT_VERSION = 68+MARKETING_VERSION = 3.6.2+CURRENT_PROJECT_VERSION = 69diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.mdindex 4aac3ae..a33d6a7 100644--- a/Docs/DeveloperGuide/README.md+++ b/Docs/DeveloperGuide/README.md@@ -118,7 +118,7 @@ CodexActivityTask## 主要入口- App 启动入口:[`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift)-- 服务装配入口:[`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift)+- 服务装配入口:[`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift)- app-server 服务:[`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)- Hook 子进程入口:[`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)- 实时任务状态机:[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.mdindex 8fd94e7..b616d14 100644--- a/Docs/DeveloperGuide/app-server.md+++ b/Docs/DeveloperGuide/app-server.md@@ -8,7 +8,7 @@ CodexBar 不重新实现 Codex 登录、token 刷新和账户协议,而是把- 认证和服务端协议由 Codex 自己维护,CodexBar 不复制一套容易漂移的客户端- App 通过 stdio 与本机子进程通信,账户主链路不需要直接暴露额外网络实现-- 当前真正运行的 Codex 版本可以从 handshake 获得,能用于 Hook 能力判断+- 当前真正运行的 Codex 版本可以从 handshake 获得,能用于全局和 Hook 能力判断- 全局 CLI 与 App 内置 CLI 可以共享同一套上层数据模型代价是菜单栏 App 必须自己解决 shell 环境缺失、子进程生命周期、pipe 背压、混杂 stdout、超时和升级后的连接换代。@@ -81,9 +81,9 @@ resolver 会做 3 层归一化:### 磁盘版本和运行版本为什么分开-设置页可以读取磁盘上两个候选 CLI 的版本,但 Hook 能力检查只使用 `initialize` 返回的 app-server `userAgent`+设置页可以读取磁盘上两个候选 CLI 的版本,但全局和 Hook 最低版本检查只使用 `initialize` 返回的 app-server `userAgent`-原因是连接最长复用 1 小时。用户在连接存活期间升级磁盘 binary 后,当前进程仍然是旧版本。用磁盘版本判断会让 UI 声称 Hook 可用,实际调用的旧 app-server 却不支持对应方法。+原因是连接最长复用 1 小时。用户在连接存活期间升级磁盘 binary 后,当前进程仍然是旧版本。用磁盘版本判断会让 UI 声称能力可用,实际调用的旧 app-server 却不支持对应方法。## 进程与协议@@ -98,6 +98,7 @@ codex app-server --listen stdio://```text启动子进程-> initialize(clientInfo)+ -> 校验实际版本 >= 0.143.0-> initialized-> account/read-> account/rateLimits/read@@ -114,13 +115,14 @@ stdout 可能包含非 JSON 输出。pipe reader 会持续读取完整行,只-> 启动 Process-> initialize(clientInfo)-> 从 userAgent 保存实际版本+ -> 校验实际版本 >= 0.143.0-> initialized notification-> account/read(refreshToken: false)-> account 存在: 提交 connection-> account 缺失: 关闭进程并返回 notLoggedIn```-只有 handshake 与首次账户读取都成功,connection 才进入 service 状态。半初始化 session 不会被留给下一轮复用。+只有实际版本满足全局门槛,并且 handshake 与首次账户读取都成功,connection 才进入 service 状态。版本低于 `0.143.0` 或无法解析时按不支持处理,关闭半初始化 session,不继续发送账户请求。### 为什么 stdout reader 只暴露完整行@@ -159,6 +161,7 @@ session 关闭时按以下顺序收口:| --- | --- || `account/read` | 读取账户、套餐和认证状态 || `account/rateLimits/read` | 读取额度窗口 |+| `account/rateLimitResetCredit/consume` | 使用指定的 Reset Credit || `account/usage/read` | 读取 token 和历史用量 || `config/read` | 读取 Codex 配置 || `hooks/list` | 校验 Hook 来源和事件能力 |@@ -223,11 +226,11 @@ ready### 为什么认证刷新全程只有一次-一次刷新会读取 account, rate limits, usage 和 Reset Credits。多个接口可能同时发现 token 过期。+一次刷新会读取 account、rate limits 和 usage,Reset Credits 明细包含在 rate limits 响应中。多个接口可能同时发现 token 过期。`fetchData` 内部用同一个 `didRefresh` 锁存本轮刷新资格。第一个认证失败触发 `account/read(refreshToken: true)`,后续接口复用刷新结果。再次需要认证时直接归类为未登录。-这避免一轮 UI 刷新对同一凭据连续触发多次 token refresh,也让 Reset Credits 的 `401` 或 `403` 与 app-server 方法共享同一个认证预算。+这避免一轮 UI 刷新对同一凭据连续触发多次 token refresh。## 刷新模型@@ -248,9 +251,8 @@ ready确认或新建 connection-> 复用连接时 account/read-> 确认 account identity- -> account/rateLimits/read+ -> account/rateLimits/read(包含 Reset Credits 明细)-> account/usage/read- -> 有 Reset Credits 时读取 expiration endpoint-> 组合 CodexQuotaSnapshot-> MainActor 提交 loadState 与连接信息```@@ -302,26 +304,88 @@ stale 是数据可信度的一部分,新增展示时不能只复制数值而## Reset Credits-Reset Credits 到期时间不来自 app-server。当可用数量大于 `0` 时,[`CodexResetCreditsService.swift`](../../CodexBar/Services/CodexStatus/CodexResetCreditsService.swift) 使用现有 `auth.json` token 请求:+`account/rateLimits/read` 的 `rateLimitResetCredits` 同时返回可用数量和可选明细:++- `availableCount` 是权威总数+- `credits == nil` 表示只知道数量+- 空数组表示服务端已获取明细,但没有返回可用凭证+- 明细列表可能被服务端截断,长度可以小于 `availableCount`+- 每条明细包含 opaque `id`、`status` 和可空的 Unix 秒级 `expiresAt`+- 每条明细还包含 `resetType`,自动使用只接受 `codexRateLimits`++模型层只保留 `status == available` 且晚于快照生成时间的过期日,并按时间排序。数量仍独立使用 `availableCount`,不能从过滤后的日期数量反推。++过期明细属于增强信息。`credits == nil` 时主面板仍展示可用数量,详情显示未知过期时间,不影响额度和用量。额度响应来自同账户缓存时,UI 可以继续展示旧明细,但通知服务不会用 stale 数据触发新的临期通知。++### 自动使用临期重置++用户主动开启自动使用后,[`ResetCreditAutomationController.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift) 只处理最新 `account/rateLimits/read` 明确返回的凭证明细:++- 快照为 stale、`credits == nil`、缺少 `expiresAt`、状态不是 `available` 或 `resetType` 不是 `codexRateLimits` 时不调用消费接口+- 明细可能被截断,只处理实际返回的凭证,不从 `availableCount` 猜测未列出的 `creditId`+- 同一时间只处理返回明细中最早到期的一条,完成或消失后再选择下一条+- 进入用户设置的临期时间窗口后,消费前再次强制读取账户和凭证明细+- 请求始终显式传入 `creditId`,不会让后端代选+- 消费结果返回后立即再读一次 rate limits+- `reset`、`alreadyRedeemed` 和 `noCredit` 会请求完整额度刷新;`nothingToReset` 在目标仍存在时只安排下一次重试,目标已经变化时再请求完整刷新++调用形状如下:```text-https://chatgpt.com/backend-api/wham/rate-limit-reset-credits+account/rateLimitResetCredit/consume+ creditId: <exact opaque id>+ idempotencyKey: <deterministic UUIDv5>```-- 请求超时为 4 秒-- 首次请求只读取现有 token-- 收到 `401` 或 `403` 时,复用本轮统一认证刷新额度最多刷新 1 次,再重新读取 `auth.json`-- 不把 token 写入其他位置-- 数量为 `0` 时不发起请求-- 请求失败不会影响主账户和额度刷新+结果按以下语义处理:++| `outcome` | 结论 | 后续动作 |+| --- | --- | --- |+| `reset` | 本次调用完成消费 | 成功通知、刷新额度、停止该凭证重试 |+| `alreadyRedeemed` | 相同幂等键此前已经完成消费 | 与 `reset` 相同,按成功处理 |+| `nothingToReset` | 当前没有可重置的额度窗口 | 凭证未消费,继续使用同一幂等键重试 |+| `noCredit` | 当前账户没有可用凭证 | 强制刷新;目标消失时静默停止,否则按暂时不一致重试 |++`alreadyRedeemed` 不是失败,也不是再次消费。它是同一逻辑请求已经成功的确认,因此收到这个结果的设备会停止重试并发送本机的“自动使用重置”通知。++### 跨设备幂等契约++同一个 Codex 账户可能同时在多台 Mac 上运行 CodexBar。设备之间不依赖 CloudKit 协调,而是对相同 `creditId` 计算完全相同的 UUIDv5:++```text+namespace = 8abd477b-2320-5e39-9518-2a2adfc542fa+name = creditId 的原始 UTF-8 字节+output = lowercase UUID string+```++namespace 来自 URL namespace 对 `https://codexbar.zabrian.app/idempotency/reset-credit-auto-use/v1` 执行 UUIDv5。这个 URL 只用于确定 namespace,不代表运行时网络请求。++固定测试向量为:++```text+creditId = RateLimitResetCredit_123+idempotencyKey = 9538d0a1-be12-587a-a1c0-d59f49029e3a+```++namespace、UUID 版本、原始 UTF-8 输入和小写输出共同构成跨版本兼容协议,不能在普通重构中修改。最先成功的设备完成消费,其他设备用同一个 key 调用时会得到 `alreadyRedeemed`,或者在前置刷新时发现凭证已经消失。++凭证消失无法区分手动使用、其他设备使用和服务端过期,因此只停止本机任务,不发送自动使用成功通知。只有明确收到 `reset` 或 `alreadyRedeemed` 的设备才发送成功通知。++### 调度与重试-### 为什么这是唯一单独的账户网络请求+自动使用状态机完全位于普通 App 进程:-app-server 返回可用 Reset Credits 数量,但不返回每一批的过期时间。UI 和临期通知需要过期日,因此只在数量大于 `0` 时补充查询。+- 不使用 helper,不申请防睡眠,也不会为 deadline 唤醒 Mac+- App 启动、用户开启功能或系统唤醒时先做新鲜读取;已经进入临期窗口且尚未过期时立即补试,否则按临期时间重新调度+- App 退出后不持久化原始 `creditId`;下次启动通过新鲜明细重建任务和同一确定性幂等键+- 同一 `creditId` 的 `expiresAt` 变化时保留幂等身份,但取消当前阈值或重试任务并按新时间重排;新临期点已经过去时立即补检+- 网络、超时、连接断开或暂时服务错误按 `15s, 30s, 1m, 2m, 5m` 退避,之后保持 `5m`+- `nothingToReset` 在最后 10 分钟内最多每分钟重试一次+- 认证失败先沿用 service 的单次 token refresh;仍失败时暂停当前凭证并按通知设置告知用户,后续可信快照证明认证恢复后再继续+- 参数、协议或方法错误停止当前凭证,不进行无意义重试-请求使用现有 `auth.json`,不另建登录流程。凭据只活在本次请求内,返回模型只保留仍为 available 且晚于当前时间的日期并排序。+自动使用触发完整额度刷新时,如果普通额度刷新正在执行,新刷新会排队到当前刷新结束后运行,不能被 `isRefreshing` guard 丢弃。-这个请求是增强信息,不是账户快照的必要条件。4 秒超时或任何解析错误只让过期日缺失,不应让额度和用量一起失败。## Hook 版本与配置校验@@ -359,7 +423,7 @@ Hook 设置也复用 app-server 链路,但采用独立的可用性状态:App 内 `RequestLog` 保存最多 500 条请求交互预览,只存在进程内存,适合用户主动检查协议细节。-即使内存日志生命周期短,也不能记录 Reset Credits Authorization header。对新 RPC 增加日志时,需要检查 payload 是否可能包含凭据或内容字段。+Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原始响应,App 内请求日志仍只按既有规则保存在当前进程内存。对新 RPC 增加日志时,需要检查 payload 是否可能包含凭据或内容字段。## 扩展 app-server 字段的步骤@@ -380,10 +444,24 @@ App 内 `RequestLog` 保存最多 500 条请求交互预览,只存在进程内- stderr 持续输出时请求不会因 pipe 背压卡住- 复用连接的 transport failure 只重建一次- 磁盘 CLI 升级后,当前连接版本与磁盘版本能被区分+- app-server 低于 `0.143.0` 时阻断账户主链路并提示升级+- app-server 为 `0.143.x` 或 `0.144.x` 时账户主链路可用,但 Hook 仍提示需要 `0.145.0`+- app-server 不低于 `0.145.0` 时账户主链路和 Hook 校验均可用- rate limits 失败但同账户有缓存时展示 stale,通知不误触发- 账户切换后旧额度和用量立即清空- unsupported method 不会每分钟重复请求-- Reset Credits `401` 后只共享一次认证刷新,失败不影响主快照+- Reset Credits `credits == nil` 时保留权威数量并显示未知过期时间+- Reset Credits 明细为空或被截断时不从明细长度反推可用数量+- 过期、非 available 的 Reset Credits 不进入详情或通知+- stale rate limits 可以展示旧明细,但不触发临期通知+- 自动使用关闭时不会调用消费接口,缺失设置默认关闭且临期时间默认 2 小时+- 自动使用不会消费 stale、缺少明细、缺少过期时间或未列出的凭证+- 两台设备对固定 `creditId` 生成相同幂等键,并与固定测试向量一致+- 同一 `creditId` 的过期时间提前或推迟时都重新调度,幂等键保持不变+- `reset` 和 `alreadyRedeemed` 均停止重试并发送成功通知+- `nothingToReset` 保留凭证并按退避策略重试+- 睡眠期间不会唤醒 Mac;唤醒后重新读取,已经进入临期窗口且尚未过期时补试,否则重新调度+- 消费成功后的完整额度刷新不会被并发普通刷新丢弃- 手动刷新后 60 秒倒计时重新对齐## 关键源码@@ -393,4 +471,5 @@ App 内 `RequestLog` 保存最多 500 条请求交互预览,只存在进程内- [`AppServerPipeReaders.swift`](../../CodexBar/Services/CodexStatus/AppServerPipeReaders.swift)- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)- [`CodexStatusViewModel.swift`](../../CodexBar/Services/CodexStatus/CodexStatusViewModel.swift)-- [`CodexResetCreditsService.swift`](../../CodexBar/Services/CodexStatus/CodexResetCreditsService.swift)+- [`ResetCreditAutomationController.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift)+- [`ResetCreditAutomationIdentity.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift)diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.mdindex 0f6e0d5..59c66d3 100644--- a/Docs/DeveloperGuide/architecture.md+++ b/Docs/DeveloperGuide/architecture.md@@ -42,9 +42,9 @@ CodexBar executable|-- Hook 模式: 最小解析 + flock + JSONL append + exit|`-- 普通模式- |-- stdio JSON-RPC <-> codex app-server+ |-- stdio JSON-RPC <-> codex app-server(账户、额度、Reset Credits)|-- 本地只读 <-> Hook JSONL / rollout JSONL- |-- HTTPS <-> Reset Credits / Sparkle+ |-- HTTPS <-> Sparkle|-- CloudKit private database <-> 日级聚合`-- signed XPC lease <-> root CodexBarHelper <-> fixed pmset commands```@@ -144,7 +144,7 @@ CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、| 链路 | 输入 | 输出 | 主要消费者 || --- | --- | --- | --- |-| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Hook 配置能力 | 主面板、菜单栏额度、设置 |+| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Reset Credit 使用、Hook 配置能力 | 主面板、菜单栏额度、设置、自动使用状态机 || Hook 历史 | Hook JSONL | 日级事件、session, turn, tool, model 聚合 | 活跃度热力图、历史统计、CloudKit || 实时任务 | Hook 增量事件加 rollout 生命周期 | 运行、等待批准、完成、中断 | 菜单栏状态、任务中心、通知、防睡眠 |@@ -158,14 +158,18 @@ CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、### 依赖方向```text-CodexStatusService ----> CodexStatusViewModel ----+- |-WorkflowService -------> WorkflowViewModel -------+--> UI- |-Hook + rollout --------> CodexActivityMonitor ----++CodexStatusService ----------------> CodexStatusViewModel ----------------> UI+CodexStatusViewModel --------------> CodexNotificationService+CodexStatusService ----------------> ResetCreditAutomationController+CodexStatusViewModel --------------> ResetCreditAutomationController+ResetCreditAutomationController ---> CodexNotificationService++WorkflowService -------> WorkflowViewModel -----------> UI++Hook + rollout --------> CodexActivityMonitor --------> UI| |- | +--> CodexNotificationService- `-------------> KeepAliveController --> helper+ | +------------> CodexNotificationService+ `-----------------------> KeepAliveController --> helper```箭头表示数据或只读状态的消费方向。下游不能反向成为上游的事实来源。@@ -193,6 +197,7 @@ Hook + rollout --------> CodexActivityMonitor ----+- `CodexActivityMonitor`- `KeepAliveController`- `CodexNotificationService`+- `ResetCreditAutomationController`这些对象负责可观察状态和 UI 协调,不应直接执行阻塞 I/O。@@ -288,6 +293,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护| --- | --- | --- || app-server 连接与同账户缓存 | `CodexStatusService` | 请求只读结果 || 主面板账户加载状态 | `CodexStatusViewModel` | 观察发布值 |+| 自动使用临期重置的目标、deadline 和重试 | `ResetCreditAutomationController` | 设置页只修改开关和临期时间 || Hook 安装与验证 | `CodexHookSettings` | 读取 `isOperable` || 历史聚合和维护游标 | `WorkflowService` | 请求快照或重建 || 实时任务 | `CodexActivityMonitor` | 读取 snapshot 或 transition |@@ -376,7 +382,8 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护## 关键源码- [`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 定义启动入口-- [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 包含 AppDelegate 和菜单栏编排+- [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 负责普通模式服务装配+- [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 负责菜单栏编排- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift) 管理 app-server- [`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift) 管理 Hook 历史聚合- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 管理实时任务diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.mdindex 85ff1d2..6225936 100644--- a/Docs/DeveloperGuide/data-and-privacy.md+++ b/Docs/DeveloperGuide/data-and-privacy.md@@ -17,7 +17,6 @@ CodexBar 只读取实现账户展示、Hook 统计、实时任务和防睡眠所| 分类 | 示例 | 默认处理 || --- | --- | --- |-| 凭据 | OAuth token、`auth.json` | 只在请求期间使用、不复制、不记录 || 内容 | prompt, response, tool 参数和输出 | 不采集 || 身份和上下文 | session ID、完整路径、project 名 | 仅在必要链路最小化使用,上传前脱敏或删除 || 聚合指标 | 每日事件数、model 计数 | 可本地持久化,用户 opt-in 后上传规定字段 |@@ -27,16 +26,16 @@ CodexBar 只读取实现账户展示、Hook 统计、实时任务和防睡眠所## 信任边界```text-Codex hook stdin / rollout / auth.json / app-server- |- v- 普通用户权限的 CodexBar- | |- v v- CloudKit private DB 受限 XPC 接口- |- v- root CodexBarHelper+Codex hook stdin / rollout / app-server+ |+ v+ 普通用户权限的 CodexBar+ | |+ v v+ CloudKit private DB 受限 XPC 接口+ |+ v+ root CodexBarHelper```边界含义如下:@@ -64,10 +63,9 @@ CodexBar 的最小化顺序是:| 来源 | CodexBar 使用方式 | 是否持久化 | 是否上传 CloudKit || --- | --- | --- | --- |-| app-server 账户和额度 | 主面板和通知判断 | 仅设置和短期状态 | 否 |+| app-server 账户、额度和 Reset Credits | 主面板、通知判断和用户启用的自动使用 | 仅短期状态 | 否 || Hook 结构化事件 | 历史聚合和实时任务 | 是,最长 210 天 | 只上传日聚合 || rollout 生命周期 | terminal 和进展对账 | 不单独持久化 | 否 |-| `auth.json` token | 查询 Reset Credits 到期时间 | 不复制 | 否 || App 设置 | 功能开关和阈值 | UserDefaults | 否 || Activity Protection | 异常会话恢复 | 哈希身份,最长 24 小时 | 否 || CodexBarHelper ownership | 系统睡眠恢复 | root 状态文件 | 否 |@@ -87,11 +85,11 @@ app-server、Hook 历史和实时活动读取不同事实,具有不同的新### Codex app-server-App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、token 用量和 Codex 配置。+App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、token 用量、Reset Credits 明细和 Codex 配置。用户主动开启自动使用后,App 还会通过同一 stdio 会话调用 Reset Credit 消费方法。CodexBar 不自行实现账户登录。app-server 是否访问 OpenAI 服务由 Codex CLI 的正常认证和协议行为决定。-CodexBar 只通过 stdio 与本机进程通信,不从 app-server 响应中复制认证材料。request log 保存协议方法和结果摘要,不是原始 wire dump。+CodexBar 只通过 stdio 与本机进程通信,不从 app-server 响应中复制认证材料。request log 保存规范化后的完整请求与响应 JSON,只存在当前 App 进程内存,不持久化。内容可能包含账户响应、opaque credit ID 和幂等键,不能把它当作脱敏摘要。### Hook 事件@@ -117,18 +115,20 @@ rollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方这不是对 rollout 文件的完整隐私隔离,因为 reader 仍需打开原文件。因此如果未来加入全文搜索或 prompt 展示,应视为新的产品隐私能力,不能当作现有 reader 的自然扩展。-### Codex 凭据+### Reset Credits 明细-Reset Credits 数量大于 `0` 时,App 读取现有 `auth.json` access token,只用于调用到期时间接口:+`account/rateLimits/read` 在 app-server 响应中返回 Reset Credits 数量和可选明细。-- 不修改 `auth.json`-- 不保存 token 副本-- 不把 token 写入 UserDefaults、Hook 文件、CloudKit 或日志-- 请求结束后只保留解析出的业务结果+- `availableCount` 是可用总数的权威值+- `credits == nil` 表示服务端只提供数量+- 空明细数组表示服务端已读取明细,但没有返回可用凭证+- 明细列表可能被截断,不能用数组长度覆盖总数+- 菜单和临期通知只使用仍为 `available` 且尚未过期的 `expiresAt`+- 自动使用只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 明细+- opaque credit ID 和确定性幂等键只存在于当前进程内存,包括 app-server 响应与缓存、额度快照、自动使用状态机和内存请求日志,不持久化或上传+- 自动使用通知写入 UserDefaults 的去重 key 只包含账户与 credit ID 的 SHA-256 组合,不保存原值-access token 只在 Reset Credits 数量大于 0 且需要到期信息时读取。这个条件把凭据读取限制到确有业务价值的路径,常规额度刷新不触碰 `auth.json`--网络错误中可能包含请求描述,记录前必须确认不会把 Authorization header 拼进错误文本。当前日志只记录错误分类和非敏感 detail。+额度响应来自旧缓存时可以继续展示,但不能触发新的临期通知或消费操作。自动使用设置和调度状态不进入 CloudKit,Mac 之间只通过服务端消费接口的确定性幂等键收敛。## 本地持久化@@ -174,6 +174,7 @@ UserDefaults 保存:- 通知阈值和声音名称- 全局快捷键- 菜单栏显示选择+- 自动使用重置开关和临期时间- 有界的通知去重 key- CodexBarHelper fingerprint 等运行配置@@ -220,11 +221,10 @@ ring buffer 的 500 条上限既控制内存,也限制打开日志窗口时的| 目标 | 用途 | 触发条件 || --- | --- | --- |-| OpenAI Reset Credits endpoint | 查询手动重置次数到期时间 | 可用数量大于 `0` || CloudKit private database | 同步日级 Hook 聚合 | 用户主动开启同步 || Sparkle appcast 和更新资源 | 检查或安装更新 | 自动检查或用户手动检查 |-账户、额度和 token 用量通过本机 app-server stdio 获取,CodexBar 不直接请求对应账户 API。+账户、额度、token 用量、Reset Credits 明细和用户明确开启的 Reset Credit 消费通过本机 app-server stdio 完成。CodexBar 不为自动使用增加独立 HTTP 客户端。CodexBarHelper 不进行任何网络访问。@@ -247,6 +247,7 @@ CloudKit 不上传:- 完整工作目录- prompt, response, tool 参数或输出- Codex 账户、额度和 token 用量+- Reset Credits 明细、自动使用设置和消费状态- access token- App 请求日志- Activity Protection 状态diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.mdindex 9516a59..da4aa2b 100644--- a/Docs/DeveloperGuide/development.md+++ b/Docs/DeveloperGuide/development.md@@ -31,10 +31,11 @@不要从 View 反向猜业务状态。推荐沿事实流阅读:1. 从 [`CodexBarApp.swift`](../../CodexBar/App/CodexBarApp.swift) 确认 Hook 子进程分流-2. 从 [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 查看普通模式 composition root-3. 选择一条数据链路阅读 source, service, snapshot 和 ViewModel-4. 再看通知或防睡眠如何订阅上游结果-5. 最后查看 SwiftUI 如何展示状态和发出用户意图+2. 从 [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 查看普通模式 composition root+3. 从 [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 查看菜单栏和窗口编排+4. 选择一条数据链路阅读 source, service, snapshot 和 ViewModel+5. 再看通知或防睡眠如何订阅上游结果+6. 最后查看 SwiftUI 如何展示状态和发出用户意图以实时任务为例:diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex fff1f39..38e3555 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -4,10 +4,11 @@[`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift) 是通知副作用的统一入口。-它观察两类状态:+它接收三类状态:- app-server 账户、额度和 Reset Credits 快照- `CodexActivityMonitor` 任务转场和防睡眠恢复事件+- `ResetCreditAutomationController` 已确认的消费结果或需要告知用户的失败状态View 和其他服务不直接创建系统通知。它们发布状态变化,通知服务负责资格判断、去重、声音和点击行为。@@ -38,6 +39,7 @@ View 和其他服务不直接创建系统通知。它们发布状态变化,通| 低额度 | 连续可信快照 | 需要比较阈值上下两帧 || 额度重置 | 连续可信快照 | 需要先观察消费再观察归零 || Reset Credits 到期 | 当前快照加时间调度 | 到期提醒由未来 deadline 触发 |+| 自动使用重置 | app-server mutation 结果 | 只有明确结果才能说明本机自动操作发生过 || 任务完成 | monitor 转场 | 历史 terminal 快照不能补发 || 等待批准 | monitor 转场加当前快照 | 先通知新等待,再撤回过时等待 || 异常会话保护 | 已提交保护结果 | 必须描述已经隐藏的任务 |@@ -71,7 +73,8 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings| --- | --- | --- || 额度重置 | app-server 额度窗口 | 独立子开关 || 低额度 | app-server 剩余额度 | 独立子开关和阈值 |-| Reset Credits 到期 | Reset Credits endpoint | 独立子开关 |+| Reset Credits 到期 | app-server 重置凭证明细 | 独立子开关 |+| 自动使用重置 | 已确认消费结果或需要告知用户的失败状态 | 自动使用开关、独立通知子开关和通知总开关 || 任务完成 | 实时任务 terminal 转场 | 独立子开关和最短时长 || 等待批准 | 实时任务 waiting 转场 | 独立子开关 || 异常会话保护 | Activity Protection | 防睡眠主开关和通知总开关 |@@ -94,6 +97,29 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings重置状态不持久化。App 启动时必须重新观察到消费后才通知重置,这是主动接受漏掉离线期间重置,以换取绝不在启动时对 0% 用量误报。+## 自动使用重置++自动使用和额度重置是两个独立事件,因此保留两条通知:++- “自动使用重置”说明 CodexBar 的自动操作收到 `reset` 或 `alreadyRedeemed`+- “额度已重置”说明普通额度快照先观察到消耗,随后观察到归零++一次自动使用可能同时满足两者,所以同一台设备可以先后收到两条通知。不能因为内容接近就合并:前者证明自动化动作,后者是额度生命周期通知,来源和开关都不同。++成功通知正文优先带上消费后新鲜读取的剩余重置次数,包括明确的 `0`。后置读取失败时仍保留已经明确的成功结果,并发送只有标题、没有正文的通知。++`alreadyRedeemed` 表示相同幂等键此前已经成功,不应继续重试。多台设备同时调用时,每台明确收到 `reset` 或 `alreadyRedeemed` 的设备都可以发送本机成功通知。某台设备只在刷新中看到凭证消失时无法区分手动使用、其他设备使用或过期,因此静默停止,不发送成功通知。++失败通知使用“自动使用重置失败”,当前包括:++- 单次认证刷新后仍未登录,当前凭证暂停到可信快照证明认证恢复+- 参数、协议或方法错误,当前凭证停止重试+- 本机明确观察到目标已经过期,当前凭证停止重试++短暂网络和服务错误只进入退避重试,不在每次失败时打扰用户。同一凭证的同一失败原因最多通知一次;认证、永久错误和本机明确观察到的过期使用不同去重键,因此同一凭证可能先后出现不同失败通知。目标从服务端明细消失时无法判断原因,状态机会静默停止,不补发过期通知。++成功和失败通知共用“自动使用重置通知”子开关及声音,默认开启并使用系统默认声音。自动使用功能关闭时设置行置灰,但不覆盖已经保存的通知和声音选择;重新开启后恢复原值。+## 低额度低额度阈值可选 5%, 10% 或 25%,默认 10%。@@ -312,6 +338,12 @@ App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继- 系统拒绝权限时设置页展示可理解状态- 低额度只在向下跨越阈值时通知- 初次加载 100% 额度不误报重置+- 自动使用明确返回 `reset` 时发送“自动使用重置”,后续额度归零时仍可独立发送“额度已重置”+- 自动使用明确返回 `alreadyRedeemed` 时按成功通知并停止重试+- 只看到目标凭证消失时不发送自动使用通知+- 网络重试期间不发送失败通知,同一凭证的同一失败原因最多通知一次+- 自动使用关闭时通知子项置灰,重新开启后恢复原来的开关和音效+- 成功和失败通知使用“自动使用重置通知”所选音效,选择静音时两者都无声- 完成时长低于和高于阈值时行为正确- `Stop` 与 rollout terminal 同时出现时只通知一次- 自动审批不发送等待批准通知diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.mdindex 8fbc582..6d16e3a 100644--- a/Docs/DeveloperGuide/sync.md+++ b/Docs/DeveloperGuide/sync.md@@ -14,7 +14,7 @@ CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统-> 按日期合并展示```-账户、额度、token 总量、实时任务和防睡眠状态不参与同步。+账户、额度、token 总量、Reset Credits、自动使用设置与状态、实时任务和防睡眠状态不参与同步。## 设计目标和非目标@@ -32,6 +32,7 @@ CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统- 实时任务状态,因为它变化快且需要本机低延迟判断- 账户额度,因为它属于 Codex 账户而不是设备工作历史+- 自动使用临期重置,因为多设备收敛依赖相同 `creditId` 的确定性幂等键,不依赖 CloudKit 锁或任务记录- 防睡眠状态,因为它是当前 Mac 的系统副作用- 原始事件,因为跨设备统计只需要可合并的日级事实@@ -117,7 +118,7 @@ salt 存在同一个 private custom zone 中。多台设备先后创建时通过- 完整工作目录- prompt 或 response 内容- Codex 账户和额度-- token 或 `auth.json`+- token 或 `auth.json` 等- App 请求日志- 异常会话保护状态diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex 3c22072..9fa3988 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -35,7 +35,7 @@ SwiftUI 负责声明内容,AppKit 负责窗口和事件生命周期:## 服务装配-[`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 同时包含 AppDelegate 和菜单栏主控制器。+[`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift) 是普通模式的 composition root,[`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift) 只负责菜单栏和相关窗口编排。AppDelegate 负责:@@ -303,6 +303,7 @@ app-server 状态默认每 60 秒刷新。面板打开时会安排约 160 ms 的## 关键源码+- [`CodexBarAppDelegate.swift`](../../CodexBar/Controllers/CodexBarAppDelegate.swift)- [`StatusItemController.swift`](../../CodexBar/Controllers/StatusItemController.swift)- [`FallbackPanelController.swift`](../../CodexBar/Controllers/FallbackPanelController.swift)- [`MenuSurfaceDismissMonitor.swift`](../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift)diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.mdindex 34f66ae..c92f8e6 100644--- a/Docs/UserGuide/getting-started.md+++ b/Docs/UserGuide/getting-started.md@@ -4,6 +4,7 @@- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex),或安装了内置 Codex 的 ChatGPT App 或 Codex App+- 当前运行的 Codex app-server 版本需要为 `0.143.0` 或更高版本- 使用 Hook 相关功能时,当前运行的 Codex app-server 版本需要为 `0.145.0` 或更高版本- 使用跨设备同步时,Mac 需要登录可用的 iCloud 账户@@ -49,6 +50,7 @@ CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主| 悬停热力图方块 | 查看当天 Token 和 Hook 统计 || 点击活动卡片 | 打开并发任务中心 || 点击手动重置次数 | 查看各批次过期时间 |+| `设置 > 高级 > 自动使用临期重置` | 配置是否自动使用临期重置以及过期前多久使用 |全局快捷键优先在鼠标所在屏幕打开主面板,菜单栏锚点不可用时会使用独立浮动面板。@@ -56,11 +58,12 @@ CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主| 功能 | CodexBar Hook | 其他条件 || --- | --- | --- |-| 账户、套餐和额度 | 不需要 | Codex 已登录 |-| Token 汇总和热力图 | 不需要 | 当前 Codex 支持用量接口 |+| 账户、套餐和额度 | 不需要 | Codex 已登录,app-server 不低于 `0.143.0` |+| Token 汇总和热力图 | 不需要 | app-server 不低于 `0.143.0` || 实时任务和任务中心 | 需要 | Hook 已通过校验 || 每日 Hook 统计 | 需要 | 本机存在 Hook 原始事件 || 额度类通知 | 不需要 | 系统通知总开关和权限已开启 |+| 自动使用临期重置 | 不需要 | 用户主动开启;默认提前 2 小时,本机睡眠时不会主动唤醒 || 任务类通知 | 需要 | Hook 已通过校验且通知已开启 || 防止系统睡眠 | 需要 | CodexBarHelper 已注册并获得系统批准 || 跨设备同步 | 需要 | iCloud 可用且用户主动开启同步 |diff --git a/Docs/UserGuide/notifications.md b/Docs/UserGuide/notifications.mdindex 8e46f04..ddccf00 100644--- a/Docs/UserGuide/notifications.md+++ b/Docs/UserGuide/notifications.md@@ -20,6 +20,8 @@| 额度预警 | 可信额度首次跌到阈值或以下 | 开启,10% | 无 || 额度重置 | 已观察到消耗的额度窗口回到未消耗状态 | 开启 | 无 || 重置临期 | 手动重置次数进入过期前 7 天窗口 | 开启 | 存在可用重置次数 |+| 自动使用重置 | 自动使用明确返回成功或此前已成功 | 开启 | 自动使用开关、通知子开关和通知总开关 |+| 自动使用重置失败 | 认证失败导致暂停、协议错误导致停止,或本机明确观察到过期 | 与成功通知共用设置 | 自动使用开关、通知子开关和通知总开关 || 低电量保护 | 低电量保护成功恢复系统睡眠 | 开启 | 防睡眠和低电量保护 || 防睡眠上限 | 达到时长上限并成功恢复系统睡眠 | 开启 | 防睡眠和有限时长上限 || 异常会话保护 | 运行中任务超过静默阈值且候选仍有效 | 固定行为 | CodexBar Hook 和防睡眠主开关 |@@ -43,6 +45,21 @@手动重置次数会在过期前 7, 6, 5, 4, 3, 2 和 1 天分别判断是否需要提醒。+## 自动使用通知++“自动使用重置”和“额度已重置”来自两个独立事实:++- “自动使用重置”说明本机自动调用收到 `reset` 或 `alreadyRedeemed`+- “额度已重置”说明额度窗口从已消费状态回到未消费状态++因此一次自动使用可能产生两条通知。它们不互相替代,也分别遵守各自的触发条件。++多台设备同时尝试时,明确收到成功结果的设备会发送自己的成功通知;只在刷新中看到凭证消失的设备不会通知,因为无法判断是手动使用、其他设备使用还是过期。++网络、超时和暂时服务错误只会在后台重试,不会每次通知。认证仍失败时当前任务暂停,后续可信快照确认认证恢复后继续;确定的协议错误会停止当前任务;本机明确观察到凭证过期时停止并通知。如果凭证直接从服务端明细消失,因为无法判断是手动使用、其他设备使用还是过期,本机会静默停止。++同一凭证的同一失败原因最多通知一次,不同失败原因可能分别通知。成功和失败通知共用“自动使用重置通知”子开关及音效。自动使用功能关闭时该选项不可用,重新开启后恢复此前的通知和音效选择。+## 通知音效每类可配置通知都可以选择以下声音:diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.mdindex 7a49d2b..5a610fa 100644--- a/Docs/UserGuide/settings.md+++ b/Docs/UserGuide/settings.md@@ -35,6 +35,7 @@| CodexBar Hook | 安装并校验 Codex 事件 handler | 未安装时关闭 || 主面板任务中心 | 控制活动卡片和任务中心是否显示 | 开启,Hook 关闭时不可用 || 系统通知 | 控制 CodexBar 本地通知和任务触觉反馈 | 关闭 |+| 自动使用临期重置 | 按所选时间在过期前自动使用尚未消费的重置次数 | 关闭,提前 2 小时 || 防止系统睡眠 | 根据实时 Codex 任务自动切换系统睡眠 | 关闭 || 跨设备同步 | 通过 iCloud 同步每日 Hook 聚合 | 关闭 || 重建数据 | 从所选日期的本机原始事件重新生成聚合 | 手动操作 |@@ -64,6 +65,7 @@ Hook 关闭时该选项会显示为关闭并置灰,保存的选择不会被覆| 额度预警通知 | 开启,10% | 阈值可选 5%, 10%, 25% || 额度重置通知 | 开启 | 只在观察到消耗后识别重置 || 重置临期通知 | 开启 | 提醒 7 天内到期的手动重置次数 |+| 自动使用重置通知 | 开启 | 只有自动使用临期重置开启时可用,成功和失败共用音效 || 低电量保护通知 | 开启 | 只有低电量保护实际可用时生效 || 防睡眠上限通知 | 开启 | 只有最长时间不是无限制时生效 || 任务触觉反馈 | 关闭 | 任务完成或等待批准时触发触摸板震动 |@@ -73,6 +75,28 @@ Hook 关闭时该选项会显示为关闭并置灰,保存的选择不会被覆完整说明见 [通知与提醒](notifications.md)+### 自动使用临期重置++每次开启都会显示操作确认。开启后点击主开关行右侧的选项按钮,在侧边面板选择到期前 `30 分钟`、`1 小时`、`2 小时`、`4 小时`、`6 小时` 或 `12 小时` 开始尝试,默认是 `2 小时`。++- 只处理 app-server 最新响应明确列出的可用重置次数+- 每次使用前重新确认账号、凭证状态和过期时间+- 同一时间只处理最早到期的一次+- 电脑睡眠时不会主动唤醒,也不会为了这个功能阻止睡眠+- 系统唤醒或 App 下次启动时会立即补检;已经进入临期窗口且尚未过期时补试,否则按临期时间重新安排+- 网络或暂时服务错误会逐步退避重试,最长间隔 5 分钟+- 当前没有可重置额度时不会消费次数,并会继续使用同一幂等键重试+- 服务端更新同一重置次数的过期时间后,会保留其幂等身份并按新时间重新安排+- 认证失效或确定的协议错误会暂停或停止当前任务,并在通知设置允许时通过系统通知说明++多台 Mac 同时开启时,每台设备独立调度,但会为相同 `creditId` 生成相同幂等键。最先成功的设备完成消费;其他设备收到已成功结果后停止,或者在刷新时发现凭证已经消失并静默停止。++成功后会发送“自动使用重置”通知。普通“额度已重置”通知来自额度窗口变化,因此两条通知可能同时出现。自动使用本身不依赖系统通知开关;通知关闭时仍会执行,只是不展示结果通知。++通知侧面板中的“自动使用重置通知”同时控制成功和失败通知,并为两者配置同一个音效。自动使用功能关闭时该项显示为关闭并置灰,保存的通知和音效选择不会被覆盖。++该设置只保存在当前 Mac,不通过 CloudKit 同步。+### 防止系统睡眠子选项| 选项 | 默认值 | 可选值 |diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.mdindex 8ce363d..aacb81e 100644--- a/Docs/UserGuide/sync-data-privacy.md+++ b/Docs/UserGuide/sync-data-privacy.md@@ -2,7 +2,7 @@## 跨设备同步的内容-跨设备同步用于合并多台 Mac 的每日 Hook 聚合,不同步账户、额度或 Token 用量。+跨设备同步用于合并多台 Mac 的每日 Hook 聚合,不同步账户、额度、Token 用量、重置次数或自动使用设置。启用条件如下:@@ -60,7 +60,7 @@| 同步缓存 | CloudKit 缓存、游标和上传状态 | `~/Library/Application Support/CodexBar/HookEvents/Sync` || 异常会话保护 | 哈希任务标识和时间戳 | `~/Library/Application Support/CodexBar/ActivityProtection/state.json`,最长 24 小时 || CodexBarHelper 所有权 | 睡眠所有权状态和恢复事务 | `/Library/Application Support/CodexBar/helper-state.json` |-| App 偏好 | 开关、阈值、快捷键和通知去重状态 | macOS UserDefaults |+| App 偏好 | 开关、阈值、快捷键、自动使用临期时间和通知去重状态 | macOS UserDefaults || app-server 交互日志 | 最近 500 条请求和响应 | 只存在当前 App 进程内存 |每日聚合只在最近 3 天保留 session 和 turn ID 列表,更早日期转换为计数并删除列表。@@ -91,6 +91,7 @@ CodexBarHelper 所有权文件由 root 持有,用于 App 或 CodexBarHelper- 完整工作目录路径- prompt、Codex 回复、工具参数或工具输出- Codex 账户、额度和 Token 用量+- 重置次数明细、自动使用设置和消费状态- app-server 交互日志- 异常会话保护记录- Codex 认证 token@@ -101,24 +102,24 @@ CodexBarHelper 所有权文件由 root 持有,用于 App 或 CodexBarHelperCodexBar 会读取以下本机数据:-- 通过本机 app-server 获取账户、额度、Token 用量和 Codex 配置+- 通过本机 app-server 获取账户、额度、Token 用量、手动重置次数明细和 Codex 配置- 读取 Hook 原始事件以生成统计和实时任务- 读取本机 Codex rollout 的生命周期字段以区分完成与终止并补充进展时间-- 在查询手动重置次数过期时间时读取 Codex `auth.json` 中的现有凭据rollout 读取只提取生命周期、时间和推理强度等字段,不展示或保存会话正文和工具内容。+用户主动开启自动使用后,CodexBar 通过同一个本机 app-server 使用明确列出的临期重置次数。原始 `creditId` 和幂等键不写入磁盘或 CloudKit;`UserDefaults` 只保存功能开关、临期时间、自动使用通知开关、音效选择和哈希后的通知去重键。+CodexBar 不复制或持久化 Codex 认证 token。## 网络行为| 网络访问 | 目的 | 触发条件 || --- | --- | --- |-| OpenAI 重置次数接口 | 查询可用手动重置次数的过期时间 | Codex 返回可用重置次数时 || Sparkle 更新源 | 检查并安装 CodexBar 更新 | 自动检查开启或用户手动检查时 || CloudKit private database | 同步多设备每日 Hook 聚合 | 用户开启跨设备同步时 |-账户、额度和 Token 用量通过本机 app-server 的 stdio 通信获取,不是由 CodexBar 直接请求对应 OpenAI 接口。+账户、额度、Token 用量、手动重置次数明细和用户开启的自动使用操作通过本机 app-server 的 stdio 通信完成。自动使用不会增加 CloudKit 请求,也不会使用 CodexBarHelper。## 日志隐私diff --git a/README.md b/README.mdindex 07e40c7..83ce06d 100644--- a/README.md+++ b/README.md@@ -30,6 +30,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App, 用于集中展示- 展示当前 Codex 账户和套餐- 展示全部额度窗口, 剩余比例和重置时间- 展示可用积分和手动重置次数+- 可设置在过期前 30 分钟到 12 小时自动使用临期重置, 默认提前 2 小时- 可在菜单栏图标旁直接显示所选额度窗口### 看见自己的 Codex 使用节奏@@ -76,7 +77,8 @@ brew install --cask bob-zebedy/tap/codexbar- macOS 15.0 或更高版本- 已安装并登录 [Codex CLI](https://github.com/openai/codex) 或安装了内置 Codex 的 ChatGPT App 或 Codex App-- 使用实时任务等 Hook 功能时, 当前运行的 Codex app-server 版本需要为 `0.145.0` 或更高版本+- 当前运行的 Codex 版本需要为 `0.143.0` 或更高版本+- 使用实时任务等 Hook 功能时, 当前运行的 Codex 版本需要为 `0.145.0` 或更高版本- 使用跨设备同步时, Mac 需要登录可用的 iCloud 账户## 快速开始diff --git a/appcast.xml b/appcast.xmlindex bdadc7f..15ef197 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.6.2</title>+ <sparkle:version>69</sparkle:version>+ <sparkle:shortVersionString>3.6.2</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.6.2</sparkle:releaseNotesLink>+ <pubDate>Wed, 12 Aug 2026 15:45:59 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.6.2.dmg" sparkle:edSignature="HUViGbpYVc+CKjBaRy9lAi4AESb+2JfdbvMsAt7u4OSCtJI76Tf/NGMCgJqI49zk4OiMZsTA7Fx1hlTg9JR0BA==" length="7047070" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.6.1</title><sparkle:version>68</sparkle:version>