Skip to content

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

feat: 完善自动重置与唤醒调度

Bob40793b850cbb
diff --git a/AGENTS.md b/AGENTS.md
index 2d43630..2b8493d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,7 +51,9 @@ 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 只能控制睡眠,不得增加网络、任意命令执行或额外文件访问。账户主链路必须检查当前 app-server 的实际版本不低于 `0.143.0`。修改 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 字段前先核对隐私边界。
+
+自动重置默认关闭,提前量可选 15 分钟、30 分钟、1 小时、2 小时、4 小时或 6 小时,默认 30 分钟。状态机只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 凭证,每轮连续重试最多 5 分钟。CodexBarHelper 只接收有限时间戳,使用固定 owner 和固定 `wake` 类型维护一个系统事件;目标变化、功能关闭、App 退出、对应 XPC 连接断开或 helper 启动时必须收敛并清理该事件。修改 owner 或事件类型属于清理兼容性问题。
缺少 session ID 的 Hook 事件使用匿名 project key。匿名任务保留在实时快照和 UI 中,活动卡片与任务中心统一显示橙色 `person.crop.circle.dashed` 图标,`help` 为 `匿名任务不参与防睡眠`。匿名任务不发布任务通知或触觉反馈,不参与防睡眠和异常会话保护,不生成保护状态持久化标识。活动卡片的 `+N` 只显示其他活跃任务总数。
@@ -89,4 +91,4 @@ Tag 名 `v{MARKETING_VERSION}` 里的版本号从 `Config/Version.xcconfig` 读
- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更;先说清影响面和几种做法的代价,等用户选定再动手
- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为
- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格
-- 改动涉及菜单面板、窗口焦点、Hook、同步、通知或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;防睡眠额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换和异常退出后的恢复
+- 改动涉及菜单面板、窗口焦点、Hook、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复
diff --git a/CLAUDE.md b/CLAUDE.md
index 0667cc1..5bef465 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -162,14 +162,16 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- Debug 与 Release 共用状态文件,actor 串行化进程内访问,`flock` 保护跨进程读写,文件权限固定为 `0600`,当前 schema 为 `1`;状态在 task reader 启动前完成加载
- 持久化操作按 `activityProtectionPersistenceTask` 串行排队,条件删除用 `markedAt` 防止旧 attempt 删除新记录,终态与保留期清理执行无条件删除
-### 防睡眠(KeepAlive)与 root helper
+### 系统电源控制与 root helper
两套机制叠加,职责不同:
- `SystemSleepService` 用进程内 `IOPMAssertion` 建立 `PreventUserIdleSystemSleep` 断言,只挡空闲睡眠,不需要提权;断言名必须是 ASCII,否则 `pmset -g assertions` 显示不出标识
-- `CodexBarHelper` 是 root LaunchDaemon,通过 XPC 接受 `setSleepPreventionRequested` 请求,执行 `/usr/bin/pmset -a disablesleep` 覆盖合盖睡眠
+- `CodexBarHelper` 是 root LaunchDaemon,通过 XPC 接受 `setSleepPreventionRequested` 和 `setAutoResetWakeSchedule` 请求;前者执行 `/usr/bin/pmset -a disablesleep` 覆盖合盖睡眠,后者使用固定 owner 和 `wake` 类型维护自动重置系统唤醒事件
-链路:`KeepAliveController`(MainActor)订阅 `activityMonitor.$snapshot` 以及合成 `codexHookSettings.isOperable` 的两个发布值 -> `SMAppService.daemon(plistName:)` 注册 -> `NSXPCConnection` -> helper
+防睡眠链路:`KeepAliveController`(MainActor)订阅 `activityMonitor.$snapshot` 以及合成 `codexHookSettings.isOperable` 的两个发布值 -> `SMAppService.daemon(plistName:)` 注册 -> `NSXPCConnection` -> helper
+
+自动重置唤醒链路:`AutoResetController` -> `KeepAliveController` -> `AutoResetWakeScheduler` -> 独立 `NSXPCConnection` -> helper
关键约束:
@@ -179,9 +181,15 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 新增拦截条件一律加进 `sleepBlockReason` 的顺序判断里,它和 `shouldDisableSleep` 同源,顺带保证日志的 `reason=` 不会漏项
- UI 用的 `isLowBatteryBlocking` 与 `canShowOptions` 由 `reconcileSleepState` 从 `sleepBlockReason` 单点派生,新增拦截条件时 `allowsOptions` 那个穷举 `switch` 会强制表态,于是不会出现入口亮着却点不动
- `hasRunningTasks` 与 `isRefreshingHelper` 都不带 `@Published` 标注,它们变得比结论频繁,各自发信号会把整个设置页拖着一起重算
-- helper 只做一件事;不要给 root helper 增加网络、任意命令执行或其他文件访问能力
+- helper 只做固定的系统电源操作;不要给 root helper 增加网络、任意命令执行或其他文件访问能力
+- helper 注册需求由防睡眠主开关与自动重置请求共同决定;自动重置开启时即使防睡眠关闭也要完成 `SMAppService` 注册和系统批准,设置行复用注册错误并单独展示唤醒计划同步错误
+- `AutoResetWakeScheduler` 与防睡眠租约使用独立 XPC 连接,只同步下一次唤醒时间;距现在不超过 5 秒的时间不交给 helper,由 App 内定时任务直接进入到点执行路径
+- helper 把自动重置事件 owner 固定为 `CodexBarHelperIPC.machServiceName + ".auto-reset"`,事件类型固定为 `kIOPMAutoWake`;替换时先取消这个 owner 的全部旧事件,设置后回读必须恰好得到一个 1 秒容差内的目标事件,取消后回读必须为空;修改 owner 或类型属于清理兼容性问题
+- 唤醒连接关闭时 helper 立即取消该连接拥有的事件,取消失败后清除内存所有者并每 5 秒继续收敛;helper 启动时在开放 listener 前按立即、250 毫秒、1 秒清理遗留事件,`SIGTERM` 与 `SIGINT` 退出前也执行取消
+- App 同步唤醒计划失败后按 2/4/8/16/32/64 秒重试;App 正常退出或 helper 更新前按立即、250 毫秒、1 秒取消,失败就保留错误并取消本次退出或更新
+- `Scripts/cleanup.swift` 注销 helper 前先通过 XPC 取消固定 owner 的事件并回读;事件仍存在时必须停止注销,不能让系统计划失去最后一个具备清理能力的进程
- 调用方校验由 XPC 层强制;helper 启动时用 `SecCodeCopySelf` 读自身签名,拼出形如 `anchor apple generic and certificate leaf[subject.OU] = "<team>" and identifier "<主 App identifier>"` 的 requirement 字符串,交给 `NSXPCListener.setConnectionCodeSigningRequirement` 生效;没有逐次连接的 audit token 检查,改签名或改 bundle ID 会直接连不上
-- 所有权记录固定放在 `/Library/Application Support/CodexBar/sleep-ownership.json`,由 root 在同目录写临时文件,完成 `F_FULLFSYNC` 后原子替换并同步目录,权限固定为 `0600`;只持久化 `idle`、`owned`、`restoring` 三态,`external` 只是任务期间的运行态,不落盘也不承担恢复责任
+- 所有权记录固定放在 `/Library/Application Support/CodexBar/helper-state.json`,由 root 在同目录写临时文件,完成 `F_FULLFSYNC` 后原子替换并同步目录,权限固定为 `0600`;只持久化 `idle`、`owned`、`restoring` 三态,`external` 只是任务期间的运行态,不落盘也不承担恢复责任
- 当前值为 0 时必须先写 `owned` 再写 `pmset 1`;释放时必须先写 `restoring` 再写 `pmset 0`;两次 pmset 都要重新读取 `pmset -g` 确认实际值,只有确认为 0 才能记回 `idle`
- 任务开始时实际值已为 1 就返回 `external`,不写 `pmset`;helper 每 5 秒观察一次,如果其他来源在任务期间改回 0,helper 立即按上一条顺序取得所有权
- helper 取得所有权后每 5 秒检查一次实际值与磁盘 transaction,值被改成 0 时重新写回 1,记录缺失、损坏或 transaction 不一致时先修复记录;修复失败也必须继续尝试恢复为 0
@@ -189,13 +197,13 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 每个 App 进程持有一个跨 XPC 重连不变的 client session ID,请求再带单调递增的 `generation`;helper 只释放对应进程的租约并拒绝延迟到达的旧 `generation`,不允许旧连接覆盖新状态
- 异常断连后租约宽限 15 秒;同一 App 在宽限内重连会续上原租约,watchdog 只会释放仍处于断连状态的那一个 client session
- helper 以 `owned` 或 `restoring` 启动时先恢复为 0 再接受新接管;以 `idle` 启动时不修改当前值,因为那个值可能属于其他来源
-- 更新 helper 前 App 先释放自己的租约,helper 原子确认全局没有活跃客户端且所有权为 `idle`,再用短期更新准备锁拒绝新的接管;注册新 helper 后必须收到状态查询回复才记录新指纹,系统仍在等待首次批准时除外
+- 更新 helper 前 App 冻结新防睡眠请求和自动重置唤醒同步,确认固定唤醒事件已取消后执行 unregister/register;旧 helper 终止时负责恢复 owned 睡眠状态,新 helper 就绪后对当前指纹执行一次 `resetSleepAfterUpdate` 并收到状态回复才完成更新,系统仍在等待首次批准时除外
- 切换失败按 2/4/8...256 秒重试,列表耗尽即放弃(延时累计约 8.5 分钟,每轮再等一次超时约 10 分钟),瞬时抖动能自愈,权限类故障不该无限重试
- XPC 请求带超时并汇进同一条重试路径;launchd 拉不起 helper 时 XPC 方法既不回复也不触发 `errorHandler`,没有它界面会显示防睡眠开着而实际没生效,日志里只剩没有配对回复的 `Helper XPC 请求已发送`
- 超时取值放在 `CodexBarHelperIPC.requestTimeoutSeconds` 而不是控制器里,它与 `watchdogGraceSeconds` 是一对:必须更小,App 先放手 helper 才能靠 watchdog 兜底,分处两个 module 会让人改了一边不知道另一边
- 开发期间用 `xcodebuild` 覆盖正在运行的 App bundle 会让 launchd 记的 daemon 与磁盘上的 helper 对不上,helper 从此拉不起来;重启 App 会由 `helperRegistrationNeedsRefresh` 的指纹比对自愈,排查时先看这一条
- helper 回传 `none`、`external`、`codexBar` 来源与操作后的实测值;App 只能在 `codexBar` 且实测为 0 时宣称系统睡眠已恢复或补发 `IOPMSleepSystem`,`external` 和 `none` 都只释放进程内断言
-- App 退出由 `applicationShouldTerminate` 返回 `terminateLater`,先冻结新接管并等 helper 释放回复再继续退出;helper 刷新同样先释放,旧 helper 无响应时由新 helper 的启动恢复兜底
+- App 退出由 `applicationShouldTerminate` 返回 `terminateLater`,先取消自动重置唤醒计划,再释放防睡眠租约;两项都经 helper 回读确认后才继续退出,任一失败都会取消本次退出并恢复协调
- `pmset` 是没有来源和引用计数的全局布尔值;CodexBar 取得所有权后如果另一个 App 也开始依赖这个 1,释放时仍会恢复为 0,系统层没有无歧义的方法判断另一个 App 的意图
- 低电量保护由 `PowerSourceMonitor` 供数,它只报事实(有没有内置电池、电量、是否靠电池供电),不知道阈值;读数保持 `unavailable`、`unreadable`、`present` 三态,把读取失败折叠成“没有电池”会让设置项凭空消失且保护静默失效
- 见过一次内置电池就记住 `hasSeenBattery`,之后读到空列表只能返回 `unreadable`;硬件不会中途消失,空列表只是 IOKit 重新枚举时的缺口,当成台式机会当场撤掉保护
@@ -227,6 +235,18 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 逐次声明不记日志,建立与释放各一条就够还原状态;两条断言都是进程级的,App 退出或崩溃时系统自动收回,不经过 helper
- **菜单栏图标不承载防睡眠状态**,它要保持模板渲染让系统按菜单栏外观着色,自行着色在深浅和带染色的菜单栏下都会失控
+### 自动重置
+
+- `AutoResetSettings` 默认关闭,提前量可选 15 分钟、30 分钟、1 小时、2 小时、4 小时、6 小时,缺失或无效值回退 30 分钟
+- `AutoResetController` 只处理新鲜 `account/rateLimits/read` 明确列出的 `available + codexRateLimits + expiresAt` 凭证,按过期时间和 ID 排序后一次只处理最早目标;数量不能反推缺失明细
+- App 启动、用户开启、系统唤醒和计划到点都会执行新鲜读取;阈值尚未到时重新调度,已经进入窗口且尚未过期时立即尝试
+- `creditId` 决定跨设备幂等键和通知身份,`expiresAt` 只是可变调度数据;同一 ID 的时间变化要取消当前阈值或重试并按新时间重排,不能换幂等身份
+- 阈值触发后单轮重试窗口固定为 5 分钟;暂时错误按 15/30/60/120/300 秒计算下一次退避,但落在截止点及之后的重试不安排,`nothingToReset` 在过期前最后 10 分钟内按 60 秒间隔处理
+- 单轮结束只取消本地任务和系统唤醒,不把目标标记成永久失败;后续普通额度快照仍可为有效目标开启新一轮
+- `.auto`、`.retry` 和 `.wake` 评估期间建立独立的 `PreventUserIdleSystemSleep` assertion,读取与消费结束后立即释放;不建立显示断言,不修改 `SleepDisabled`
+- `reset` 与 `alreadyRedeemed` 都视为成功并通知;认证失败暂停当前目标,协议或参数错误停止当前目标,明确过期发送失败通知,目标从明细消失时静默停止
+- 原始 `creditId` 和确定性幂等键只在当前进程内存中存在;`UserDefaults` 只保存开关、提前量、通知选项和哈希去重 key,CloudKit 不同步自动重置状态
+
### 通知
- `CodexNotificationService` 是集中式的 `MainActor` 服务,订阅额度快照与实时活动,负责阈值穿越判定、去重、额度重置识别、触觉反馈和本地通知;dedup key 落 `UserDefaults`
@@ -281,17 +301,17 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- 菜单栏按钮左键切换主面板;右键或 Control+点击打开上下文菜单;`⌘,` 打开自定义设置窗口,菜单面板打开时 `⌘L` 打开日志窗口;默认全局快捷键 `⌘⇧W` 由 `GlobalHotKeySettings` 与 `GlobalHotKeyController` 管理
- 主面板是锚定 status item 的 `NSPopover` 弹窗,锚点不可信时回退到 `FallbackPanelController` 提供的屏幕顶部居中 `NSPanel` 面板,处理快捷键、屏幕选择和焦点时要保留这两个分支
- 关闭逻辑统一由 `MenuSurfaceDismissMonitor` 管理,淡出由 `MenuSurfaceFadeCoordinator` 负责
-- 侧边面板都是 borderless nonactivating child panel,热力图详情、重置次数和任务中心挂在主面板上,通知、自动使用临期重置和防睡眠选项挂在设置窗口上
+- 侧边面板都是 borderless nonactivating child panel,热力图详情、重置次数和任务中心挂在主面板上,通知、自动重置和防睡眠选项挂在设置窗口上
- 设置窗口的子面板占同一位置,展开一个必须先 `hide(immediate: true)` 收掉其余的;动作走 `SettingsOptionsPanelAction` 并带上目标 `SettingsOptionsPanel`,互斥与 `closeAll` 都只写在 `SettingsWindowController.handleOptionsAction` 一处,新增面板不会漏配对
- 面板控制器只在首次展开时构造,收起动作走 `existingOptionsPanelController` 而不触发构造:它一建就挂上内容变化订阅并常驻到 App 结束,而用户可能一次子面板都没开过
- 三个设置子面板的顶边对齐各自主开关行,anchor 由设置页的 `ScreenFrameProvider` 随展开动作传出,定位走 `SidePanelSupport.anchoredPosition` 而不是宿主底边
- 设置窗口的子面板要传 `clampsToSurfaceBottom: false` 让底边可以探出窗口,否则放不下时会把整个面板上推而错开主开关行;主面板那三个面板走默认的 `true`
-- 通知和防睡眠面板的高度会动态变化,前者随音效行增删,后者随 `hasBattery` 增删低电量那一行;自动使用临期重置面板只有固定的一行;resize 时要固定顶边向下生长,直接改 size 会保持底边不动而把顶边顶离主开关行
-- 内容变化订阅要保持最小:通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange`,再加 `resetCreditAutomationSettings.$isEnabled`、`KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled`;自动使用临期重置面板只订 `resetCreditAutomationSettings.objectWillChange`;防睡眠面板只订 `$hasBattery`;订整个防睡眠控制器会让任务每起停一次都白排一轮 resize
+- 通知和防睡眠面板的高度会动态变化,前者随音效行增删,后者随 `hasBattery` 增删低电量那一行;自动重置面板只有固定的一行;resize 时要固定顶边向下生长,直接改 size 会保持底边不动而把顶边顶离主开关行
+- 内容变化订阅要保持最小:通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange`,再加 `autoResetSettings.$isEnabled`、`KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled`;自动重置面板只订 `autoResetSettings.objectWillChange`;防睡眠面板只订 `$hasBattery`;订整个防睡眠控制器会让任务每起停一次都白排一轮 resize
- 置灰也会改高度:带音效的行置灰时音效子行跟着收起,所以每个置灰依赖都要有一个对应的订阅源
- 增删行或改行的显示条件时要同步补上对应的订阅源,漏一项会让面板裁掉底部或留下空白
- resize 的竖向夹紧走 `SidePanelSupport.clampedVertically`,与初次展开的 `position` 同一条规则,否则放不下时两边会把面板推向相反的边
-- 子面板入口只在开关开着且依赖就绪时出现,通知看 `NotificationSettings.canShowOptions`,自动使用临期重置看 `ResetCreditAutomationSettings.isEnabled`,防睡眠看 `KeepAliveController.canShowOptions`;这些值只控制入口显隐,不回写用户保存的开关
+- 子面板入口只在开关开着且依赖就绪时出现,通知看 `NotificationSettings.canShowOptions`,自动重置看 `AutoResetSettings.isEnabled`,防睡眠看 `KeepAliveController.canShowOptions`;这些值只控制入口显隐,不回写用户保存的开关
- 三个设置子面板都只由滑杆按钮展开,动作只有 `toggle` 与 `close` 两种,开启主开关不自动弹出
- 侧边面板公共能力集中在 `Controllers/SidePanelSupport.swift` 里,含 `SidePanelDrawerPresenter`、`SidePanelContentHost`、`SidePanelDrawerAnimator`、panel 工厂和定位夹紧;挂在主面板上的那三个面板优先复用 `SidePanelDrawerPresenter` 这一层,不要另起一套
- 设置窗口的子面板直接复用 `Controllers/SettingsOptionsPanelController.swift`,它在 presenter 之上补齐了装配、两套关闭观察者、顶边对齐定位和高度重算;新增设置子面板只要给它内容工厂与内容变化来源,不要再写一层壳
@@ -339,5 +359,5 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev
- **任何兼容性问题都必须主动询问用户,不要自行决定**;只要改动会影响新旧共存就适用,不限于旧数据迁移或丢弃、持久化 key 改名或改结构、老版本升上来的降级路径、最低系统版本与 API 可用性取舍、云端记录格式变更;先说清影响面和几种做法的代价,等用户选定再动手
- 处理窗口、菜单、快捷键、App 激活或事件监听时,特别注意 `LSUIElement` 应用特有的焦点行为
- 注释保持克制,只解释非显然的生命周期、焦点、actor 或系统 API 约束;现有注释多为解释为什么的类型,沿用同样风格
-- 改动涉及菜单面板、窗口焦点、Hook、同步、通知或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;防睡眠额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换和异常退出后的恢复
+- 改动涉及菜单面板、窗口焦点、Hook、同步、通知、自动重置唤醒或防睡眠时,构建通过之外还要说明应手动覆盖的交互场景;helper 相关改动额外要验证 App 包内 helper 与 plist 位置、签名、首次系统授权、运行/等待切换、唤醒计划替换与清理和异常退出后的恢复
- 不要把发布产物、DerivedData、临时 DMG、签名文件或个人凭据提交进仓库
diff --git a/CodexBar/Controllers/CodexBarAppDelegate.swift b/CodexBar/Controllers/CodexBarAppDelegate.swift
index 9519187..3ad10a1 100644
--- a/CodexBar/Controllers/CodexBarAppDelegate.swift
+++ b/CodexBar/Controllers/CodexBarAppDelegate.swift
@@ -25,12 +25,12 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
let menuBarQuotaSettings = MenuBarQuotaSettings()
let mainPanelSettings = MainPanelSettings()
let notificationSettings = NotificationSettings()
- let resetCreditAutomationSettings = ResetCreditAutomationSettings()
+ let autoResetSettings = AutoResetSettings()
let appUpdater = AppUpdater()
private var statusItemController: StatusItemController?
private var notificationService: CodexNotificationService?
- private var resetCreditAutomationController: ResetCreditAutomationController?
+ private var autoResetController: AutoResetController?
private var terminationPreparationTask: Task<Void, Never>?
private var hasPreparedForTermination = false
@@ -50,7 +50,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
notificationSettings: notificationSettings,
- resetCreditAutomationSettings: resetCreditAutomationSettings,
+ autoResetSettings: autoResetSettings,
keepAliveController: keepAliveController,
appUpdater: appUpdater
)
@@ -67,14 +67,15 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
notificationService.start()
self.notificationService = notificationService
- let resetCreditAutomationController = ResetCreditAutomationController(
- settings: resetCreditAutomationSettings,
+ let autoResetController = AutoResetController(
+ settings: autoResetSettings,
statusViewModel: viewModel,
service: codexStatusService,
- notificationService: notificationService
+ notificationService: notificationService,
+ keepAliveController: keepAliveController
)
- resetCreditAutomationController.start()
- self.resetCreditAutomationController = resetCreditAutomationController
+ autoResetController.start()
+ self.autoResetController = autoResetController
// 低电量触发会中断正在跑的任务, 得让用户知道是谁干的
keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent in
await notificationService?.notifyLowBatteryProtection(percent: percent) ?? false
@@ -99,7 +100,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
terminationPreparationTask = nil
AppProcessDiagnostics.recordCleanExit()
statusItemController?.uninstall()
- resetCreditAutomationController?.stop()
+ autoResetController?.stop()
keepAliveController.stop()
activityMonitor.stop()
}
@@ -144,8 +145,8 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {
"activityProtectionMinutes=\(activityProtectionSettings.inactivityDuration.loggedMinutes)",
"sync=\(syncSettings.isEnabled ? 1 : 0)",
"notification=\(notificationSettings.isEnabled ? 1 : 0)",
- "resetCreditAutoUse=\(resetCreditAutomationSettings.isEnabled ? 1 : 0)",
- "resetCreditLeadSeconds=\(resetCreditAutomationSettings.leadTime.rawValue)",
+ "autoReset=\(autoResetSettings.isEnabled ? 1 : 0)",
+ "autoResetLeadTimeSeconds=\(autoResetSettings.leadTime.rawValue)",
"menuBarQuota=\(menuBarQuotaSettings.selection.rawValue)",
"taskCenter=\(mainPanelSettings.showsTaskCenter ? 1 : 0)",
"hotKey=\(globalHotKeySettings.shortcut == nil ? 0 : 1)"
diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swift
index fe3f3e5..4458be0 100644
--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift
+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift
@@ -5,7 +5,7 @@ import SwiftUI
/// 设置窗口右侧的子选项面板, 同一时刻只展开一个
enum SettingsOptionsPanel: CaseIterable, Hashable {
case notification
- case resetCreditAutomation
+ case autoReset
case keepAlive
}
diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swift
index ef91ff4..5614a7c 100644
--- a/CodexBar/Controllers/SettingsWindowController.swift
+++ b/CodexBar/Controllers/SettingsWindowController.swift
@@ -14,7 +14,7 @@ final class SettingsWindowController: HostingWindowController {
private let menuBarQuotaSettings: MenuBarQuotaSettings
private let mainPanelSettings: MainPanelSettings
private let notificationSettings: NotificationSettings
- private let resetCreditAutomationSettings: ResetCreditAutomationSettings
+ private let autoResetSettings: AutoResetSettings
private let activityProtectionSettings: ActivityProtectionSettings
private let keepAliveController: KeepAliveController
private let onSyncChanged: (Bool) -> Void
@@ -32,7 +32,7 @@ final class SettingsWindowController: HostingWindowController {
menuBarQuotaSettings: MenuBarQuotaSettings,
mainPanelSettings: MainPanelSettings,
notificationSettings: NotificationSettings,
- resetCreditAutomationSettings: ResetCreditAutomationSettings,
+ autoResetSettings: AutoResetSettings,
activityProtectionSettings: ActivityProtectionSettings,
keepAliveController: KeepAliveController,
screenProvider: @escaping () -> NSScreen?,
@@ -48,7 +48,7 @@ final class SettingsWindowController: HostingWindowController {
self.menuBarQuotaSettings = menuBarQuotaSettings
self.mainPanelSettings = mainPanelSettings
self.notificationSettings = notificationSettings
- self.resetCreditAutomationSettings = resetCreditAutomationSettings
+ self.autoResetSettings = autoResetSettings
self.activityProtectionSettings = activityProtectionSettings
self.keepAliveController = keepAliveController
self.onSyncChanged = onSyncChanged
@@ -71,7 +71,7 @@ final class SettingsWindowController: HostingWindowController {
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
notificationSettings: notificationSettings,
- resetCreditAutomationSettings: resetCreditAutomationSettings,
+ autoResetSettings: autoResetSettings,
keepAliveController: keepAliveController,
onSyncChanged: onSyncChanged,
onRebuildWorkflowData: onRebuildWorkflowData,
@@ -115,7 +115,7 @@ final class SettingsWindowController: HostingWindowController {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
- resetCreditAutomationSettings.refresh()
+ autoResetSettings.refresh()
activityProtectionSettings.refresh()
keepAliveController.refresh()
}
@@ -150,25 +150,25 @@ final class SettingsWindowController: HostingWindowController {
willShow: { [codexCLINotificationSettings] in
codexCLINotificationSettings.refresh()
},
- contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, resetCreditAutomationSettings, keepAliveController] entryCue in
+ contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, autoResetSettings, keepAliveController] entryCue in
SettingsOptionsPanelController.makeContentController(
NotificationOptionsView(
notificationSettings: notificationSettings,
codexHookSettings: codexHookSettings,
codexCLINotificationSettings: codexCLINotificationSettings,
- resetCreditAutomationSettings: resetCreditAutomationSettings,
+ autoResetSettings: autoResetSettings,
keepAliveController: keepAliveController
),
rebuiltBy: entryCue
)
},
- // 音效子行随各开关增删, 自动使用 低电量与上限三行还跟着各自的依赖置灰
+ // 音效子行随各开关增删, 自动重置 低电量与上限三行还跟着各自的依赖置灰
// 置灰会连带收起音效子行, 所以三个依赖的派生值都要订上
// 防睡眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度
contentChanges: Publishers.MergeMany([
notificationSettings.objectWillChange.eraseToAnyPublisher(),
codexHookSettings.objectWillChange.eraseToAnyPublisher(),
- resetCreditAutomationSettings.$isEnabled
+ autoResetSettings.$isEnabled
.map { _ in () }
.eraseToAnyPublisher(),
keepAliveController.$isLowBatteryProtectionEnabled
@@ -179,19 +179,19 @@ final class SettingsWindowController: HostingWindowController {
.eraseToAnyPublisher()
]).eraseToAnyPublisher()
)
- case .resetCreditAutomation:
+ case .autoReset:
SettingsOptionsPanelController(
- animationKey: "CodexBar.resetCreditAutomationOptionsDrawerTransform",
- initialPanelSize: ResetCreditAutomationOptionsView.initialPanelSize,
- contentControllerProvider: { [resetCreditAutomationSettings] entryCue in
+ animationKey: "CodexBar.autoResetOptionsDrawerTransform",
+ initialPanelSize: AutoResetOptionsView.initialPanelSize,
+ contentControllerProvider: { [autoResetSettings] entryCue in
SettingsOptionsPanelController.makeContentController(
- ResetCreditAutomationOptionsView(
- settings: resetCreditAutomationSettings
+ AutoResetOptionsView(
+ settings: autoResetSettings
),
rebuiltBy: entryCue
)
},
- contentChanges: resetCreditAutomationSettings.objectWillChange
+ contentChanges: autoResetSettings.objectWillChange
.eraseToAnyPublisher()
)
case .keepAlive:
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swift
index 3da1ae3..de8a4ae 100644
--- a/CodexBar/Controllers/StatusItemController.swift
+++ b/CodexBar/Controllers/StatusItemController.swift
@@ -16,7 +16,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
private let menuBarQuotaSettings: MenuBarQuotaSettings
private let mainPanelSettings: MainPanelSettings
private let notificationSettings: NotificationSettings
- private let resetCreditAutomationSettings: ResetCreditAutomationSettings
+ private let autoResetSettings: AutoResetSettings
private let keepAliveController: KeepAliveController
private let appUpdater: AppUpdater
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
@@ -48,7 +48,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
menuBarQuotaSettings: menuBarQuotaSettings,
mainPanelSettings: mainPanelSettings,
notificationSettings: notificationSettings,
- resetCreditAutomationSettings: resetCreditAutomationSettings,
+ autoResetSettings: autoResetSettings,
activityProtectionSettings: activityMonitor.activityProtectionSettings,
keepAliveController: keepAliveController
) { [weak self] in
@@ -119,7 +119,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
menuBarQuotaSettings: MenuBarQuotaSettings,
mainPanelSettings: MainPanelSettings,
notificationSettings: NotificationSettings,
- resetCreditAutomationSettings: ResetCreditAutomationSettings,
+ autoResetSettings: AutoResetSettings,
keepAliveController: KeepAliveController,
appUpdater: AppUpdater
) {
@@ -133,7 +133,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {
self.menuBarQuotaSettings = menuBarQuotaSettings
self.mainPanelSettings = mainPanelSettings
self.notificationSettings = notificationSettings
- self.resetCreditAutomationSettings = resetCreditAutomationSettings
+ self.autoResetSettings = autoResetSettings
self.keepAliveController = keepAliveController
self.appUpdater = appUpdater
super.init()
diff --git a/CodexBar/Models/CodexQuotaModels.swift b/CodexBar/Models/CodexQuotaModels.swift
index 46d88c3..0d8e498 100644
--- a/CodexBar/Models/CodexQuotaModels.swift
+++ b/CodexBar/Models/CodexQuotaModels.swift
@@ -18,7 +18,7 @@ nonisolated struct CodexQuotaSnapshot: Equatable {
let credits: RateLimitCreditsSnapshot?
let resetCreditsAvailableCount: Int?
let resetCreditExpirationDates: [Date]?
- let resetCreditAutomationCandidates: [ResetCreditAutomationCandidate]?
+ let autoResetCandidates: [AutoResetCandidate]?
let generatedAt: Date
let limits: [CodexQuotaLimitSnapshot]
let usage: CodexUsageSnapshot?
@@ -164,8 +164,8 @@ nonisolated struct RateLimitResetCreditsSummary: Decodable {
.sorted()
}
- /// 自动使用只接受 app-server 明确返回的可用 Codex 额度重置凭证
- var automationCandidates: [ResetCreditAutomationCandidate]? {
+ /// 自动重置只接受 app-server 明确返回的可用 Codex 额度重置凭证
+ var autoResetCandidates: [AutoResetCandidate]? {
guard let credits else {
return nil
}
@@ -177,7 +177,7 @@ nonisolated struct RateLimitResetCreditsSummary: Decodable {
return nil
}
- return ResetCreditAutomationCandidate(
+ return AutoResetCandidate(
id: credit.id,
expirationDate: expirationDate
)
@@ -197,17 +197,17 @@ nonisolated struct RateLimitResetCredit: Decodable {
}
}
-/// 自动使用链路需要的最小凭证快照
-nonisolated struct ResetCreditAutomationCandidate: Equatable, Sendable {
+/// 自动重置链路需要的最小凭证快照
+nonisolated struct AutoResetCandidate: Equatable, Sendable {
let id: String
let expirationDate: Date
}
-/// 自动使用前强制读取的账号和重置凭证明细
-nonisolated struct ResetCreditAutomationRead: Sendable {
+/// 自动重置前强制读取的账号和重置凭证明细
+nonisolated struct AutoResetRead: Sendable {
let accountIdentity: String
let availableCount: Int?
- let candidates: [ResetCreditAutomationCandidate]?
+ let candidates: [AutoResetCandidate]?
}
/// app-server 消费重置凭证的稳定结果集合
@@ -224,10 +224,10 @@ nonisolated struct ResetCreditConsumeResponse: Decodable, Sendable {
nonisolated struct ResetCreditConsumeResult: Sendable {
let outcome: ResetCreditConsumeOutcome
- let refreshedRead: ResetCreditAutomationRead?
+ let refreshedRead: AutoResetRead?
}
-nonisolated enum ResetCreditAutomationServiceError: Error, Sendable {
+nonisolated enum AutoResetServiceError: Error, Sendable {
case accountChanged
}
@@ -285,9 +285,9 @@ nonisolated extension CodexQuotaSnapshot {
let resetCreditExpirationDates = rateLimitsResponse?
.rateLimitResetCredits?
.availableExpirationDates(now: generatedAt)
- let resetCreditAutomationCandidates = rateLimitsResponse?
+ let autoResetCandidates = rateLimitsResponse?
.rateLimitResetCredits?
- .automationCandidates
+ .autoResetCandidates
// rateLimits/usage 可同时为空
// 账户有效时仍生成快照给 UI 展示 `暂无数据`
@@ -298,7 +298,7 @@ nonisolated extension CodexQuotaSnapshot {
credits: rateLimitsResponse.flatMap { Self.primaryCredits(from: $0) },
resetCreditsAvailableCount: rateLimitsResponse?.rateLimitResetCredits?.availableCount,
resetCreditExpirationDates: resetCreditExpirationDates,
- resetCreditAutomationCandidates: resetCreditAutomationCandidates,
+ autoResetCandidates: autoResetCandidates,
generatedAt: generatedAt,
limits: limits,
usage: usage,
diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstrings
index 1c7f56a..1b5c9b7 100644
--- a/CodexBar/Resources/Localizable.xcstrings
+++ b/CodexBar/Resources/Localizable.xcstrings
@@ -54,7 +54,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; invalid events skipped: %lld"
+ "value" : "; skipped %lld invalid events"
}
},
"zh-Hans" : {
@@ -327,7 +327,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Settings"
+ "value" : "Settings…"
}
},
"zh-Hans" : {
@@ -583,7 +583,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Hooks are disabled in the Codex configuration"
+ "value" : "Codex Hook is disabled in Codex settings"
}
},
"zh-Hans" : {
@@ -743,7 +743,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex CLI or Codex app not found"
+ "value" : "Could not find the Codex CLI or app"
}
},
"zh-Hans" : {
@@ -807,7 +807,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "This operation is not supported by the Codex app-server"
+ "value" : "The Codex app-server does not support this method"
}
},
"zh-Hans" : {
@@ -871,7 +871,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "CodexBar Hook comes from an unexpected source"
+ "value" : "Unexpected CodexBar Hook source"
}
},
"zh-Hans" : {
@@ -1031,7 +1031,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "This system shortcut cannot be used"
+ "value" : "This shortcut is reserved by the system"
}
},
"zh-Hans" : {
@@ -1202,6 +1202,22 @@
}
}
},
+ "keep-alive.error.auto-reset-wake-schedule-failed" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Could not schedule a wake event for Automatic Reset"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "设置自动重置唤醒计划失败"
+ }
+ }
+ }
+ },
"keep-alive.error.restore-idle-sleep-failed" : {
"localizations" : {
"en" : {
@@ -1335,7 +1351,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "No Codex task progress for %@; hidden and excluded from keep-awake"
+ "value" : "No progress on the Codex task for %@; hidden and excluded from keep-awake"
}
},
"zh-Hans" : {
@@ -1367,7 +1383,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex Task Has No Progress"
+ "value" : "Codex Task Stalled"
}
},
"zh-Hans" : {
@@ -1522,12 +1538,12 @@
}
}
},
- "notification.reset-credit-auto-use-failed.body.authentication" : {
+ "notification.auto-reset-failed.body.authentication" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Codex sign-in expired"
+ "value" : "Codex sign-in has expired"
}
},
"zh-Hans" : {
@@ -1538,23 +1554,23 @@
}
}
},
- "notification.reset-credit-auto-use-failed.body.expired" : {
+ "notification.auto-reset-failed.body.expired" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Expired; could not be used automatically"
+ "value" : "Expired before Automatic Reset could complete"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已过期, 未能自动使用"
+ "value" : "重置已过期, 自动重置未完成"
}
}
}
},
- "notification.reset-credit-auto-use-failed.body.permanent" : {
+ "notification.auto-reset-failed.body.permanent" : {
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1570,23 +1586,23 @@
}
}
},
- "notification.reset-credit-auto-use-failed.title" : {
+ "notification.auto-reset-failed.title" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Automatic Reset Credit Use Failed"
+ "value" : "Automatic Reset Failed"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "自动使用重置失败"
+ "value" : "自动重置失败"
}
}
}
},
- "notification.reset-credit-auto-use.body.count" : {
+ "notification.auto-reset.body.count" : {
"localizations" : {
"en" : {
"stringUnit" : {
@@ -1602,18 +1618,18 @@
}
}
},
- "notification.reset-credit-auto-use.title" : {
+ "notification.auto-reset.title" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Reset Credit Used Automatically"
+ "value" : "Automatic Reset"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "自动使用重置"
+ "value" : "自动重置"
}
}
}
@@ -1975,7 +1991,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Version %@ is available"
+ "value" : "Version v%@ is available"
}
},
"zh-Hans" : {
@@ -1991,7 +2007,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Tool calls"
+ "value" : "Tool Calls"
}
},
"zh-Hans" : {
@@ -2039,7 +2055,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "; cloud replacement could not be completed; rebuild these dates later"
+ "value" : "; could not replace cloud data; try rebuilding this data later"
}
},
"zh-Hans" : {
@@ -2151,7 +2167,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "No keep-awake for anonymous tasks"
+ "value" : "Anonymous tasks do not prevent sleep"
}
},
"zh-Hans" : {
@@ -2183,7 +2199,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Vibrate when tasks finish or await approval"
+ "value" : "Trackpad haptics when tasks finish or await approval"
}
},
"zh-Hans" : {
@@ -2295,7 +2311,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Low Battery Cutoff"
+ "value" : "Low Battery Protection"
}
},
"zh-Hans" : {
@@ -2359,7 +2375,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Lifetime tokens"
+ "value" : "Lifetime Tokens"
}
},
"zh-Hans" : {
@@ -2407,7 +2423,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Top model"
+ "value" : "Top Model"
}
},
"zh-Hans" : {
@@ -2519,7 +2535,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Inactive Task Protection"
+ "value" : "Stalled Task Protection"
}
},
"zh-Hans" : {
@@ -2551,7 +2567,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Longest chat"
+ "value" : "Longest Chat"
}
},
"zh-Hans" : {
@@ -2567,7 +2583,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Longest streak"
+ "value" : "Longest Streak"
}
},
"zh-Hans" : {
@@ -2647,7 +2663,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Peak tokens"
+ "value" : "Peak Tokens"
}
},
"zh-Hans" : {
@@ -2695,7 +2711,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Other tasks: %lld"
+ "value" : "%lld other tasks"
}
},
"zh-Hans" : {
@@ -3047,7 +3063,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Selected dates: %lld"
+ "value" : "Selected days: %lld"
}
},
"zh-Hans" : {
@@ -3063,7 +3079,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Rebuilt dates: %1$lld; events: %2$lld"
+ "value" : "Days rebuilt: %1$lld; events: %2$lld"
}
},
"zh-Hans" : {
@@ -3079,7 +3095,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "System sleep is prevented"
+ "value" : "System sleep is currently prevented"
}
},
"zh-Hans" : {
@@ -3127,7 +3143,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Current streak"
+ "value" : "Current Streak"
}
},
"zh-Hans" : {
@@ -3143,7 +3159,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Prevent sleep while Codex tasks run; restore it when they finish"
+ "value" : "Prevent sleep while Codex tasks run; restore normal sleep afterward"
}
},
"zh-Hans" : {
@@ -3399,7 +3415,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Expiration time unavailable"
+ "value" : "Expiration time unknown"
}
},
"zh-Hans" : {
@@ -3895,7 +3911,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Could not update the Launch at Login setting"
+ "value" : "Could not update Launch at Login"
}
},
"zh-Hans" : {
@@ -3943,7 +3959,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Set Shortcut"
+ "value" : "Press a Shortcut"
}
},
"zh-Hans" : {
@@ -4135,7 +4151,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Past %lld wk"
+ "value" : "Past %lld Weeks"
}
},
"zh-Hans" : {
@@ -4327,7 +4343,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Expiring Reset"
+ "value" : "Reset Expiration"
}
},
"zh-Hans" : {
@@ -4407,7 +4423,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Re-enable sleep when the limit is reached"
+ "value" : "Restore normal sleep when the limit is reached"
}
},
"zh-Hans" : {
@@ -4594,6 +4610,22 @@
}
}
},
+ "15 分钟" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "15 Minutes"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "15 分钟"
+ }
+ }
+ }
+ },
"2 小时" : {
"localizations" : {
"en" : {
@@ -4674,34 +4706,34 @@
}
}
},
- "开启自动使用重置?" : {
+ "开启自动重置?" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Enable Automatic Reset Credit Use?"
+ "value" : "Enable Automatic Reset?"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "开启自动使用重置?"
+ "value" : "开启自动重置?"
}
}
}
},
- "开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销" : {
+ "开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac" : {
"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."
+ "value" : "When enabled, CodexBar automatically uses a manual reset credit at the configured time before it expires and may briefly wake your Mac."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销"
+ "value" : "开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac"
}
}
}
@@ -4711,7 +4743,7 @@
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Time Before Expiry"
+ "value" : "Time Before Expiration"
}
},
"zh-Hans" : {
@@ -4722,34 +4754,34 @@
}
}
},
- "自动使用临期重置" : {
+ "自动重置" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Use Expiring Reset Credit Automatically"
+ "value" : "Automatic Reset"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "自动使用临期重置"
+ "value" : "自动重置"
}
}
}
},
- "自动使用重置通知" : {
+ "自动重置通知" : {
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Automatic Reset Use"
+ "value" : "Automatic Reset Notifications"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "自动使用重置通知"
+ "value" : "自动重置通知"
}
}
}
diff --git a/CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift b/CodexBar/Services/CodexStatus/AutoResetController.swift
similarity index 63%
rename from CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift
rename to CodexBar/Services/CodexStatus/AutoResetController.swift
index efe4f9c..df00fa6 100644
--- a/CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift
+++ b/CodexBar/Services/CodexStatus/AutoResetController.swift
@@ -1,12 +1,13 @@
import AppKit
import Combine
import Foundation
+import IOKit
import os
-/// 自动使用临期重置的本机状态机
-/// 系统睡眠时不申请唤醒, 唤醒后经新鲜读取决定是否补试
+/// 自动重置的本机状态机
+/// 计划执行前通过 helper 预约系统唤醒, 唤醒后仍经新鲜读取决定是否使用
@MainActor
-final class ResetCreditAutomationController {
+final class AutoResetController {
private enum ScheduledKind: Equatable {
case threshold
case retry
@@ -26,22 +27,32 @@ final class ResetCreditAutomationController {
private struct Target {
let accountIdentity: String
- let candidate: ResetCreditAutomationCandidate
+ let candidate: AutoResetCandidate
let key: String
var idempotencyKey: String {
- ResetCreditAutomationIdentity.idempotencyKey(forCreditID: candidate.id)
+ AutoResetIdentity.idempotencyKey(forCreditID: candidate.id)
}
}
+ private struct RetryWindow {
+ let targetKey: String
+ let deadline: Date
+ }
+
private static let retryDelays: [TimeInterval] = [15, 30, 60, 120, 300]
+ private static let retryWindowDuration: TimeInterval = 5 * 60
private static let finalNothingToResetWindow: TimeInterval = 10 * 60
private static let finalNothingToResetDelay: TimeInterval = 60
- private let settings: ResetCreditAutomationSettings
+ private let settings: AutoResetSettings
private let statusViewModel: CodexStatusViewModel
private let service: CodexStatusService
private let notificationService: CodexNotificationService
+ private let keepAliveController: KeepAliveController
+ private let wakeActivity = SystemSleepService(
+ sleepAssertionName: "CodexBar - Automatic Reset"
+ )
private var cancellables = Set<AnyCancellable>()
private var scheduledTask: Task<Void, Never>?
@@ -51,6 +62,7 @@ final class ResetCreditAutomationController {
private var pendingEvaluation = false
private var latestSnapshot: CodexQuotaSnapshot?
private var target: Target?
+ private var retryWindow: RetryWindow?
private var retryIndex = 0
private var consumedTargetKeys = Set<String>()
private var expiredTargetDates: [String: Date] = [:]
@@ -58,15 +70,17 @@ final class ResetCreditAutomationController {
private var isStarted = false
init(
- settings: ResetCreditAutomationSettings,
+ settings: AutoResetSettings,
statusViewModel: CodexStatusViewModel,
service: CodexStatusService,
- notificationService: CodexNotificationService
+ notificationService: CodexNotificationService,
+ keepAliveController: KeepAliveController
) {
self.settings = settings
self.statusViewModel = statusViewModel
self.service = service
self.notificationService = notificationService
+ self.keepAliveController = keepAliveController
}
deinit {
@@ -80,6 +94,10 @@ final class ResetCreditAutomationController {
return
}
isStarted = true
+ keepAliveController.setAutoResetRequested(
+ settings.isEnabled,
+ opensSystemSettings: false
+ )
statusViewModel.$snapshot
.sink { [weak self] snapshot in
@@ -119,17 +137,23 @@ final class ResetCreditAutomationController {
return
}
isStarted = false
+ keepAliveController.setAutoResetRequested(
+ false,
+ opensSystemSettings: false
+ )
cancellables.removeAll()
cancelWork()
target = nil
- retryIndex = 0
}
private func handleEnabledChange(_ enabled: Bool) {
+ keepAliveController.setAutoResetRequested(
+ enabled,
+ opensSystemSettings: enabled
+ )
guard enabled else {
cancelWork()
target = nil
- retryIndex = 0
return
}
@@ -150,7 +174,7 @@ final class ResetCreditAutomationController {
}
}
- private func handleLeadTimeChange(_: ResetCreditAutomationLeadTime) {
+ private func handleLeadTimeChange(_: AutoResetLeadTime) {
guard settings.isEnabled else {
return
}
@@ -166,9 +190,9 @@ final class ResetCreditAutomationController {
}
reconcile(
- accountIdentity: ResetCreditAutomationIdentity.accountIdentity(for: snapshot.account),
+ accountIdentity: AutoResetIdentity.accountIdentity(for: snapshot.account),
availableCount: snapshot.resetCreditsAvailableCount,
- candidates: snapshot.resetCreditAutomationCandidates,
+ candidates: snapshot.autoResetCandidates,
now: Date()
)
scheduleCurrentTargetIfNeeded()
@@ -186,6 +210,16 @@ final class ResetCreditAutomationController {
return
}
+ let startedAt = Date()
+ if let retryWindow,
+ retryWindow.deadline <= startedAt {
+ finishRetryWindow(ifMatching: retryWindow.targetKey)
+ if trigger == .retry {
+ cancelScheduledTask()
+ return
+ }
+ }
+
cancelScheduledTask()
evaluationGeneration += 1
let generation = evaluationGeneration
@@ -195,7 +229,8 @@ final class ResetCreditAutomationController {
}
await performEvaluation(
trigger: trigger,
- expectedTargetKey: expectedTargetKey
+ expectedTargetKey: expectedTargetKey,
+ startedAt: startedAt
)
finishEvaluation(generation: generation)
}
@@ -218,16 +253,28 @@ final class ResetCreditAutomationController {
private func performEvaluation(
trigger: LogTrigger,
- expectedTargetKey: String?
+ expectedTargetKey: String?,
+ startedAt: Date
) async {
- let freshRead: ResetCreditAutomationRead
+ let holdsWakeActivity = beginWakeActivityIfNeeded(trigger: trigger)
+ defer {
+ endWakeActivityIfNeeded(holdsWakeActivity)
+ }
+
+ if let target,
+ expectedTargetKey == nil || expectedTargetKey == target.key,
+ thresholdDate(for: target) <= startedAt {
+ startRetryWindowIfNeeded(for: target, startedAt: startedAt)
+ }
+
+ let freshRead: AutoResetRead
do {
- freshRead = try await service.readResetCreditsForAutomation()
+ freshRead = try await service.readCreditsForAutoReset()
} catch {
guard !Task.isCancelled, settings.isEnabled else {
return
}
- handleRequestFailure(error)
+ handleRequestFailure(error, windowStartedAt: startedAt)
return
}
@@ -240,7 +287,7 @@ final class ResetCreditAutomationController {
guard freshRead.candidates != nil else {
if target != nil || (freshRead.availableCount ?? 0) > 0 {
- scheduleRetry(cause: .detailsUnavailable)
+ scheduleRetry(cause: .detailsUnavailable, windowStartedAt: startedAt)
}
return
}
@@ -259,15 +306,16 @@ final class ResetCreditAutomationController {
return
}
- let thresholdDate = target.candidate.expirationDate
- .addingTimeInterval(-settings.leadTime.duration)
+ let thresholdDate = thresholdDate(for: target)
guard thresholdDate <= now else {
scheduleCurrentTargetIfNeeded()
return
}
+ startRetryWindowIfNeeded(for: target, startedAt: startedAt)
+
AppLog.app.notice(
- "自动使用重置开始: trigger=\(trigger.rawValue, privacy: .public)"
+ "自动重置开始: trigger=\(trigger.rawValue, privacy: .public)"
)
let attemptedTarget = target
do {
@@ -278,7 +326,11 @@ final class ResetCreditAutomationController {
)
handleConsumeResult(result, attemptedTarget: attemptedTarget)
} catch {
- handleConsumeFailure(error, attemptedTarget: attemptedTarget)
+ handleConsumeFailure(
+ error,
+ attemptedTarget: attemptedTarget,
+ windowStartedAt: startedAt
+ )
}
}
@@ -297,12 +349,12 @@ final class ResetCreditAutomationController {
let remainingCount = refreshedRead?.accountIdentity == attemptedTarget.accountIdentity
? refreshedRead?.availableCount
: nil
- notificationService.notifyResetCreditAutoUseSucceeded(
+ notificationService.notifyAutoResetSucceeded(
remainingCount: remainingCount,
dedupToken: attemptedTarget.key
)
AppLog.app.notice(
- "自动使用重置完成: outcome=\(result.outcome.rawValue, privacy: .public)"
+ "自动重置完成: outcome=\(result.outcome.rawValue, privacy: .public)"
)
if settings.isEnabled,
@@ -311,7 +363,7 @@ final class ResetCreditAutomationController {
reconcile(refreshedRead)
scheduleCurrentTargetIfNeeded()
}
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
case .nothingToReset, .noCredit:
if let refreshedRead = result.refreshedRead {
@@ -320,7 +372,7 @@ final class ResetCreditAutomationController {
guard settings.isEnabled,
target?.key == attemptedTarget.key else {
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
return
}
@@ -328,36 +380,40 @@ final class ResetCreditAutomationController {
? .nothingToReset
: .noCredit
AppLog.app.notice(
- "自动使用重置未完成: outcome=\(result.outcome.rawValue, privacy: .public)"
+ "自动重置未完成: outcome=\(result.outcome.rawValue, privacy: .public)"
)
scheduleRetry(cause: cause)
if result.outcome == .noCredit {
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
}
}
}
- private func handleConsumeFailure(_ error: Error, attemptedTarget: Target) {
+ private func handleConsumeFailure(
+ _ error: Error,
+ attemptedTarget: Target,
+ windowStartedAt: Date
+ ) {
guard !Task.isCancelled,
settings.isEnabled,
target?.key == attemptedTarget.key else {
return
}
- handleRequestFailure(error)
+ handleRequestFailure(error, windowStartedAt: windowStartedAt)
}
- private func handleRequestFailure(_ error: Error) {
- if error is ResetCreditAutomationServiceError {
+ private func handleRequestFailure(_ error: Error, windowStartedAt: Date) {
+ if error is AutoResetServiceError {
clearTarget()
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
return
}
if let error = error as? CodexStatusError {
if error.isAuthenticationRequired {
blockCurrentTarget(reason: .authentication)
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
return
}
if error.isProtocolOrParameterFailure {
@@ -365,8 +421,9 @@ final class ResetCreditAutomationController {
return
}
- AppLog.app.notice("自动使用重置稍后重试: reason=requestFailed")
- scheduleRetry(cause: .transient)
+ if scheduleRetry(cause: .transient, windowStartedAt: windowStartedAt) {
+ AppLog.app.notice("自动重置稍后重试: reason=requestFailed")
+ }
return
}
@@ -380,38 +437,54 @@ final class ResetCreditAutomationController {
blockedTargets[target.key] = reason
cancelScheduledTask()
+ resetRetryWindow(ifMatching: target.key)
switch reason {
case .authentication:
- notificationService.notifyResetCreditAutoUseFailed(
+ notificationService.notifyAutoResetFailed(
reason: .authentication,
dedupToken: target.key
)
- AppLog.app.error("自动使用重置已暂停: reason=authentication")
+ AppLog.app.error("自动重置已暂停: reason=authentication")
case .permanent:
- notificationService.notifyResetCreditAutoUseFailed(
+ notificationService.notifyAutoResetFailed(
reason: .permanent,
dedupToken: target.key
)
- AppLog.app.error("自动使用重置已停止: reason=permanentFailure")
+ 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
+ @discardableResult
+ private func scheduleRetry(
+ cause: RetryCause,
+ windowStartedAt: Date = Date()
+ ) -> Bool {
+ guard settings.isEnabled,
+ let target,
+ thresholdDate(for: target) <= windowStartedAt else {
+ return false
}
guard blockedTargets[target.key] == nil else {
- return
+ return false
}
- let remaining = target.candidate.expirationDate.timeIntervalSinceNow
+ let now = Date()
+ let remaining = target.candidate.expirationDate.timeIntervalSince(now)
guard remaining > 0 else {
finishExpiredTarget(target)
- return
+ return false
+ }
+
+ let retryWindow = startRetryWindowIfNeeded(
+ for: target,
+ startedAt: windowStartedAt
+ )
+ guard retryWindow.deadline > now else {
+ scheduleRetryWindowEnd(
+ at: now,
+ expectedTargetKey: target.key
+ )
+ return false
}
var delay = nextRetryDelay()
@@ -419,11 +492,20 @@ final class ResetCreditAutomationController {
delay = Self.finalNothingToResetDelay
}
delay = min(delay, remaining)
+ let retryDate = now.addingTimeInterval(delay)
+ guard retryDate < retryWindow.deadline else {
+ scheduleRetryWindowEnd(
+ at: retryWindow.deadline,
+ expectedTargetKey: target.key
+ )
+ return false
+ }
schedule(
- after: delay,
+ at: retryDate,
kind: .retry,
expectedTargetKey: target.key
)
+ return true
}
private func nextRetryDelay() -> TimeInterval {
@@ -442,25 +524,28 @@ final class ResetCreditAutomationController {
return
}
- let delay = target.candidate.expirationDate
- .addingTimeInterval(-settings.leadTime.duration)
- .timeIntervalSinceNow
+ let thresholdDate = thresholdDate(for: target)
+ if thresholdDate > Date() {
+ // 回到正常阈值等待后开始新的重试周期, 避免旧故障影响正式执行
+ resetRetryWindow()
+ }
schedule(
- after: delay,
+ at: thresholdDate,
kind: .threshold,
expectedTargetKey: target.key
)
}
private func schedule(
- after delay: TimeInterval,
+ at date: Date,
kind: ScheduledKind,
- expectedTargetKey: String?
+ expectedTargetKey: String
) {
- cancelScheduledTask()
+ cancelScheduledTask(clearsWakeSchedule: false)
+ keepAliveController.setAutoResetWakeDate(date)
scheduledTask = Task { @MainActor [weak self] in
do {
- try await Task.sleep(for: .seconds(max(0, delay)))
+ try await Task.sleep(for: .seconds(max(0, date.timeIntervalSinceNow)))
} catch {
return
}
@@ -476,10 +561,32 @@ final class ResetCreditAutomationController {
}
}
+ private func scheduleRetryWindowEnd(
+ at date: Date,
+ expectedTargetKey: String
+ ) {
+ cancelScheduledTask()
+ // 截止任务占住 scheduledTask, 防止当前评估返回后立即重排已经过去的阈值
+ // 系统唤醒已由 cancelScheduledTask 清除
+ scheduledTask = Task { @MainActor [weak self] in
+ do {
+ try await Task.sleep(for: .seconds(max(0, date.timeIntervalSinceNow)))
+ } catch {
+ return
+ }
+ guard let self, !Task.isCancelled else {
+ return
+ }
+
+ scheduledTask = nil
+ finishRetryWindow(ifMatching: expectedTargetKey)
+ }
+ }
+
private func reconcile(
accountIdentity: String,
availableCount: Int?,
- candidates: [ResetCreditAutomationCandidate]?,
+ candidates: [AutoResetCandidate]?,
now: Date
) {
if let target, target.accountIdentity != accountIdentity {
@@ -514,7 +621,7 @@ final class ResetCreditAutomationController {
let direction = matchingCandidate.expirationDate
< currentTarget.candidate.expirationDate ? "earlier" : "later"
AppLog.app.notice(
- "自动使用重置计划已更新: reason=expirationChanged direction=\(direction, privacy: .public)"
+ "自动重置计划已更新: reason=expirationChanged direction=\(direction, privacy: .public)"
)
}
if blockedTargets[currentTarget.key] == .authentication {
@@ -526,7 +633,7 @@ final class ResetCreditAutomationController {
}
} else {
// 凭证消失无法区分手动使用 其他设备使用或服务端过期
- // 因此只停止本机任务, 不发送自动使用通知
+ // 因此只停止本机任务, 不发送自动重置通知
clearTarget()
}
}
@@ -556,22 +663,22 @@ final class ResetCreditAutomationController {
candidate: nextCandidate
)
if expiredTargetDates.removeValue(forKey: nextTarget.key) != nil {
- AppLog.app.notice("自动使用重置计划已恢复: reason=expirationExtended")
+ AppLog.app.notice("自动重置计划已恢复: reason=expirationExtended")
}
if target?.key == nextTarget.key {
return
}
cancelScheduledTask()
+ resetRetryWindow()
target = nextTarget
- retryIndex = 0
if blockedTargets[nextTarget.key] == .authentication {
blockedTargets.removeValue(forKey: nextTarget.key)
}
}
private func reconcile(
- _ read: ResetCreditAutomationRead,
+ _ read: AutoResetRead,
now: Date = Date()
) {
reconcile(
@@ -583,7 +690,7 @@ final class ResetCreditAutomationController {
}
private func isCandidateEligible(
- _ candidate: ResetCreditAutomationCandidate,
+ _ candidate: AutoResetCandidate,
accountIdentity: String,
now: Date
) -> Bool {
@@ -591,7 +698,7 @@ final class ResetCreditAutomationController {
return false
}
- let key = ResetCreditAutomationIdentity.notificationToken(
+ let key = AutoResetIdentity.notificationToken(
accountIdentity: accountIdentity,
creditID: candidate.id
)
@@ -606,27 +713,72 @@ final class ResetCreditAutomationController {
private func makeTarget(
accountIdentity: String,
- candidate: ResetCreditAutomationCandidate
+ candidate: AutoResetCandidate
) -> Target {
Target(
accountIdentity: accountIdentity,
candidate: candidate,
- key: ResetCreditAutomationIdentity.notificationToken(
+ key: AutoResetIdentity.notificationToken(
accountIdentity: accountIdentity,
creditID: candidate.id
)
)
}
+ private func thresholdDate(for target: Target) -> Date {
+ target.candidate.expirationDate
+ .addingTimeInterval(-settings.leadTime.duration)
+ }
+
+ @discardableResult
+ private func startRetryWindowIfNeeded(
+ for target: Target,
+ startedAt: Date
+ ) -> RetryWindow {
+ if let retryWindow,
+ retryWindow.targetKey == target.key {
+ return retryWindow
+ }
+
+ let retryWindow = RetryWindow(
+ targetKey: target.key,
+ deadline: startedAt.addingTimeInterval(Self.retryWindowDuration)
+ )
+ self.retryWindow = retryWindow
+ retryIndex = 0
+ AppLog.app.notice("自动重置重试窗口已开始")
+ return retryWindow
+ }
+
+ private func finishRetryWindow(ifMatching targetKey: String) {
+ guard retryWindow?.targetKey == targetKey else {
+ return
+ }
+
+ retryWindow = nil
+ retryIndex = 0
+ AppLog.app.notice("自动重置重试窗口已结束: reason=deadline")
+ }
+
+ private func resetRetryWindow(ifMatching targetKey: String? = nil) {
+ if let targetKey,
+ retryWindow?.targetKey != targetKey {
+ return
+ }
+
+ retryWindow = nil
+ retryIndex = 0
+ }
+
private func finishExpiredTarget(_ expiredTarget: Target) {
expiredTargetDates[expiredTarget.key] = expiredTarget.candidate.expirationDate
clearTarget(ifMatching: expiredTarget.key)
- notificationService.notifyResetCreditAutoUseFailed(
+ notificationService.notifyAutoResetFailed(
reason: .expired,
dedupToken: expiredTarget.key
)
- AppLog.app.error("自动使用重置失败: reason=expired")
- statusViewModel.refreshAfterCurrent(trigger: .resetCreditAutoUse)
+ AppLog.app.error("自动重置失败: reason=expired")
+ statusViewModel.refreshAfterCurrent(trigger: .autoReset)
}
private func clearTarget(ifMatching key: String? = nil) {
@@ -635,16 +787,44 @@ final class ResetCreditAutomationController {
}
cancelScheduledTask()
target = nil
- retryIndex = 0
+ resetRetryWindow()
}
- private func cancelScheduledTask() {
+ private func cancelScheduledTask(clearsWakeSchedule: Bool = true) {
scheduledTask?.cancel()
scheduledTask = nil
+ if clearsWakeSchedule {
+ keepAliveController.setAutoResetWakeDate(nil)
+ }
+ }
+
+ private func beginWakeActivityIfNeeded(trigger: LogTrigger) -> Bool {
+ guard trigger == .auto || trigger == .retry || trigger == .wake else {
+ return false
+ }
+
+ let result = wakeActivity.beginPreventingIdleSleep()
+ guard result == kIOReturnSuccess else {
+ AppLog.app.error("自动重置短时防睡眠失败: code=\(result)")
+ return false
+ }
+ return true
+ }
+
+ private func endWakeActivityIfNeeded(_ isActive: Bool) {
+ guard isActive else {
+ return
+ }
+
+ let result = wakeActivity.endPreventingIdleSleep()
+ if result != kIOReturnSuccess {
+ AppLog.app.error("自动重置短时防睡眠释放失败: code=\(result)")
+ }
}
private func cancelWork() {
cancelScheduledTask()
+ resetRetryWindow()
settingsActivationTask?.cancel()
settingsActivationTask = nil
evaluationGeneration += 1
diff --git a/CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift b/CodexBar/Services/CodexStatus/AutoResetIdentity.swift
similarity index 91%
rename from CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift
rename to CodexBar/Services/CodexStatus/AutoResetIdentity.swift
index 2dc4fc4..e827e73 100644
--- a/CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift
+++ b/CodexBar/Services/CodexStatus/AutoResetIdentity.swift
@@ -1,10 +1,10 @@
import CryptoKit
import Foundation
-/// 自动使用重置的跨设备身份规则
+/// 自动重置的跨设备身份规则
/// namespace 和 UUIDv5 输入一旦发布就属于兼容性协议
-nonisolated enum ResetCreditAutomationIdentity {
- static let namespaceString = "8abd477b-2320-5e39-9518-2a2adfc542fa"
+nonisolated enum AutoResetIdentity {
+ static let namespaceString = "c2904ab3-0a87-5648-997d-bd8515edd401"
private static let namespace = UUID(uuidString: namespaceString)!
diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swift
index 09108d5..627e2cf 100644
--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift
+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift
@@ -199,10 +199,10 @@ actor CodexStatusService {
)
}
- /// 自动使用前必须绕过补充数据缓存读取一份新凭证明细
- func readResetCreditsForAutomation() throws -> ResetCreditAutomationRead {
- try withAutomationConnection { connection in
- try readResetCreditsForAutomation(using: connection)
+ /// 自动重置前必须绕过补充数据缓存读取一份新凭证明细
+ func readCreditsForAutoReset() throws -> AutoResetRead {
+ try withAutoResetConnection { connection in
+ try readCreditsForAutoReset(using: connection)
}
}
@@ -212,7 +212,7 @@ actor CodexStatusService {
idempotencyKey: String,
expectedAccountIdentity: String
) throws -> ResetCreditConsumeResult {
- let response: ResetCreditConsumeResponse = try withAutomationConnection { connection in
+ let response: ResetCreditConsumeResponse = try withAutoResetConnection { connection in
let accountResponse = try connection.session.request(
"account/read",
params: ["refreshToken": false],
@@ -221,8 +221,8 @@ actor CodexStatusService {
guard let account = accountResponse.account else {
throw CodexStatusError.notLoggedIn
}
- guard ResetCreditAutomationIdentity.accountIdentity(for: account) == expectedAccountIdentity else {
- throw ResetCreditAutomationServiceError.accountChanged
+ guard AutoResetIdentity.accountIdentity(for: account) == expectedAccountIdentity else {
+ throw AutoResetServiceError.accountChanged
}
connection.accountResponse = accountResponse
@@ -238,7 +238,7 @@ actor CodexStatusService {
// 消费结果已经确定时刷新失败不能覆盖结果
// 控制器仍会触发完整额度刷新, 这里先满足协议要求并尽快取得剩余次数
- let refreshedRead = try? readResetCreditsForAutomation()
+ let refreshedRead = try? readCreditsForAutoReset()
return ResetCreditConsumeResult(
outcome: response.outcome,
refreshedRead: refreshedRead
@@ -303,9 +303,9 @@ actor CodexStatusService {
}
}
- /// 自动使用链路在传输故障后重建一次连接
+ /// 自动重置链路在传输故障后重建一次连接
/// 每次逻辑操作最多刷新一次认证, 不在业务错误上创建新进程
- private func withAutomationConnection<Value>(
+ private func withAutoResetConnection<Value>(
_ operation: (AppServerConnection) throws -> Value
) throws -> Value {
var canRebuild = true
@@ -314,19 +314,19 @@ actor CodexStatusService {
let activeConnection = try readyConnection()
do {
- return try performAutomationOperation(
+ return try performAutoResetOperation(
using: activeConnection,
operation: operation
)
} catch let error as CodexStatusError where error.isTransportFailure && canRebuild {
canRebuild = false
teardownConnection()
- AppLog.app.notice("自动使用重置连接已重建: reason=transportError")
+ AppLog.app.notice("自动重置连接已重建: reason=transportError")
}
}
}
- private func performAutomationOperation<Value>(
+ private func performAutoResetOperation<Value>(
using connection: AppServerConnection,
operation: (AppServerConnection) throws -> Value
) throws -> Value {
@@ -411,9 +411,9 @@ actor CodexStatusService {
// MARK: - 数据抓取与缓存
- private func readResetCreditsForAutomation(
+ private func readCreditsForAutoReset(
using connection: AppServerConnection
- ) throws -> ResetCreditAutomationRead {
+ ) throws -> AutoResetRead {
let accountResponse = try connection.session.request(
"account/read",
params: ["refreshToken": false],
@@ -435,10 +435,10 @@ actor CodexStatusService {
supplementalDataCache.rateLimits = rateLimitsResponse
let summary = rateLimitsResponse.rateLimitResetCredits
- return ResetCreditAutomationRead(
- accountIdentity: ResetCreditAutomationIdentity.accountIdentity(for: account),
+ return AutoResetRead(
+ accountIdentity: AutoResetIdentity.accountIdentity(for: account),
availableCount: summary?.availableCount,
- candidates: summary?.automationCandidates
+ candidates: summary?.autoResetCandidates
)
}
diff --git a/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift
new file mode 100644
index 0000000..ffc8195
--- /dev/null
+++ b/CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift
@@ -0,0 +1,390 @@
+import Foundation
+import os
+
+/// 只负责同步自动重置的唤醒时间, 与防睡眠租约使用独立 XPC 连接
+@MainActor
+final class AutoResetWakeScheduler {
+ private enum AppliedSchedule: Equatable {
+ case unknown
+ case cleared
+ case scheduled(Date)
+
+ init(wakeDate: Date?) {
+ if let wakeDate {
+ self = .scheduled(wakeDate)
+ } else {
+ self = .cleared
+ }
+ }
+
+ var hasWakeDate: Bool {
+ if case .scheduled = self {
+ return true
+ }
+ return false
+ }
+ }
+
+ private enum PreparationState {
+ case none
+ case termination
+ case helperInterruption
+ }
+
+ var onErrorMessageChanged: ((String?) -> Void)?
+
+ private let runtimeStatusMonitor = HelperRuntimeStatusMonitor()
+ private var isRequested = false
+ private var isHelperReady = false
+ private var desiredWakeDate: Date?
+ private var appliedSchedule = AppliedSchedule.unknown
+ private var syncTask: Task<Void, Never>?
+ private var syncTaskID: UUID?
+ private var needsReconcile = false
+ private var preparationState = PreparationState.none
+ private var connection: NSXPCConnection?
+ private var errorMessage: String? {
+ didSet {
+ guard errorMessage != oldValue else {
+ return
+ }
+ onErrorMessageChanged?(errorMessage)
+ }
+ }
+
+ func setRequested(_ requested: Bool) {
+ guard requested != isRequested else {
+ reconcile()
+ return
+ }
+
+ isRequested = requested
+ errorMessage = nil
+ if !requested {
+ desiredWakeDate = nil
+ }
+ restartSyncForDesiredStateChange()
+ }
+
+ func setWakeDate(_ date: Date?) {
+ let normalizedDate = date.flatMap { value in
+ value.timeIntervalSinceNow > Self.minimumWakeLeadTime ? value : nil
+ }
+ guard normalizedDate != desiredWakeDate else {
+ return
+ }
+
+ desiredWakeDate = normalizedDate
+ errorMessage = nil
+ restartSyncForDesiredStateChange()
+ }
+
+ func setHelperReady(_ ready: Bool) {
+ guard ready != isHelperReady else {
+ if ready {
+ reconcile()
+ }
+ return
+ }
+
+ isHelperReady = ready
+ guard ready else {
+ errorMessage = nil
+ suspend()
+ return
+ }
+ reconcile()
+ }
+
+ func stop() {
+ isRequested = false
+ isHelperReady = false
+ preparationState = .none
+ desiredWakeDate = nil
+ errorMessage = nil
+ suspend()
+ }
+
+ func prepareForTermination(helperSupportsWakeScheduling: Bool) async -> Bool {
+ guard preparationState == .none else {
+ return false
+ }
+
+ preparationState = .termination
+ cancelSyncTask()
+ guard helperSupportsWakeScheduling || connection != nil else {
+ return !appliedSchedule.hasWakeDate
+ }
+ return await cancelOwnedSchedule(reason: "termination")
+ }
+
+ func resumeAfterTerminationCancellation() {
+ guard preparationState == .termination else {
+ return
+ }
+
+ preparationState = .none
+ reconcile()
+ }
+
+ func beginHelperInterruptionPreparation() -> Bool {
+ guard preparationState == .none else {
+ return false
+ }
+
+ preparationState = .helperInterruption
+ cancelSyncTask()
+ return true
+ }
+
+ func cancelBeforeHelperInterruption() async -> Bool {
+ guard preparationState == .helperInterruption else {
+ return false
+ }
+ guard connection != nil || appliedSchedule.hasWakeDate else {
+ return true
+ }
+ return await cancelOwnedSchedule(reason: "helperUpdate")
+ }
+
+ func resumeAfterHelperInterruption() {
+ guard preparationState == .helperInterruption else {
+ return
+ }
+
+ preparationState = .none
+ reconcile()
+ }
+
+ private func restartSyncForDesiredStateChange() {
+ cancelSyncTask()
+ reconcile()
+ }
+
+ private func suspend() {
+ cancelSyncTask()
+ invalidateConnection()
+ appliedSchedule = .unknown
+ }
+
+ private func cancelSyncTask() {
+ syncTask?.cancel()
+ runtimeStatusMonitor.cancelRequest()
+ syncTask = nil
+ syncTaskID = nil
+ needsReconcile = false
+ }
+
+ private func reconcile() {
+ guard preparationState == .none else {
+ return
+ }
+ guard isHelperReady else {
+ return
+ }
+ guard syncTask == nil else {
+ needsReconcile = true
+ return
+ }
+ guard appliedSchedule != AppliedSchedule(wakeDate: desiredWakeDate) else {
+ closeIdleConnectionIfNeeded()
+ return
+ }
+
+ let taskID = UUID()
+ syncTaskID = taskID
+ needsReconcile = false
+ syncTask = Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ await synchronizeSchedule()
+ finishSyncTask(taskID: taskID)
+ }
+ }
+
+ private func cancelOwnedSchedule(reason: String) async -> Bool {
+ for delay in KeepAliveHelperConfiguration.wakeCancellationRetryDelays {
+ if delay > .zero {
+ try? await Task.sleep(for: delay)
+ }
+ guard !Task.isCancelled else {
+ return false
+ }
+
+ let result = await runtimeStatusMonitor.setAutoResetWakeSchedule(
+ connection: connection ?? makeConnection(),
+ unixTimestamp: 0,
+ timeout: KeepAliveHelperConfiguration.requestTimeout
+ )
+ guard !Task.isCancelled else {
+ return false
+ }
+
+ switch result {
+ case .success:
+ appliedSchedule = .cleared
+ errorMessage = nil
+ invalidateConnection()
+ AppLog.keepAlive.notice(
+ "自动重置唤醒计划已确认取消: reason=\(reason, privacy: .public)"
+ )
+ return true
+
+ case let .helperFailure(code):
+ AppLog.keepAlive.error(
+ "自动重置唤醒计划取消失败: reason=\(reason, privacy: .public) code=\(code)"
+ )
+
+ case let .connectionFailure(error):
+ AppLog.keepAlive.error(
+ "自动重置唤醒计划取消连接失败: reason=\(reason, privacy: .public) detail=\(error.localizedDescription, privacy: .public)"
+ )
+ invalidateConnection()
+
+ case .timedOut:
+ AppLog.keepAlive.error(
+ "自动重置唤醒计划取消超时: reason=\(reason, privacy: .public)"
+ )
+ invalidateConnection()
+
+ case .cancelled:
+ break
+ }
+ }
+
+ appliedSchedule = .unknown
+ errorMessage = KeepAliveLocalizedMessage.autoResetWakeScheduleFailed
+ invalidateConnection()
+ return false
+ }
+
+ private func synchronizeSchedule() async {
+ var retryIndex = 0
+ while !Task.isCancelled, isHelperReady {
+ guard appliedSchedule != AppliedSchedule(wakeDate: desiredWakeDate) else {
+ return
+ }
+
+ let requestedDate = desiredWakeDate
+ let result = await runtimeStatusMonitor.setAutoResetWakeSchedule(
+ connection: connection ?? makeConnection(),
+ unixTimestamp: requestedDate?.timeIntervalSince1970 ?? 0,
+ timeout: KeepAliveHelperConfiguration.requestTimeout
+ )
+ guard !Task.isCancelled, isHelperReady else {
+ return
+ }
+
+ switch result {
+ case .success:
+ appliedSchedule = AppliedSchedule(wakeDate: requestedDate)
+ errorMessage = nil
+ let epoch = requestedDate.map { Int($0.timeIntervalSince1970) } ?? 0
+ AppLog.keepAlive.notice("自动重置唤醒计划已同步: epoch=\(epoch)")
+ retryIndex = 0
+ continue
+
+ case .cancelled:
+ continue
+
+ case let .helperFailure(code):
+ AppLog.keepAlive.error("自动重置唤醒计划同步失败: code=\(code)")
+
+ case let .connectionFailure(error):
+ AppLog.keepAlive.error(
+ "自动重置唤醒服务连接失败: detail=\(error.localizedDescription, privacy: .public)"
+ )
+ invalidateConnection()
+
+ case .timedOut:
+ AppLog.keepAlive.error("自动重置唤醒服务请求超时")
+ invalidateConnection()
+ }
+
+ appliedSchedule = .unknown
+ errorMessage = KeepAliveLocalizedMessage.autoResetWakeScheduleFailed
+ guard retryIndex < KeepAliveHelperConfiguration.wakeScheduleRetryDelays.count else {
+ return
+ }
+
+ let delay = KeepAliveHelperConfiguration.wakeScheduleRetryDelays[retryIndex]
+ retryIndex += 1
+ try? await Task.sleep(for: delay)
+ }
+ }
+
+ private func finishSyncTask(taskID: UUID) {
+ guard syncTaskID == taskID else {
+ return
+ }
+
+ syncTask = nil
+ syncTaskID = nil
+ if needsReconcile {
+ needsReconcile = false
+ reconcile()
+ } else {
+ closeIdleConnectionIfNeeded()
+ }
+ }
+
+ private func closeIdleConnectionIfNeeded() {
+ guard desiredWakeDate == nil,
+ appliedSchedule == .cleared,
+ connection != nil else {
+ return
+ }
+ invalidateConnection()
+ AppLog.keepAlive.notice("自动重置唤醒服务已断开: reason=idle")
+ }
+
+ private func makeConnection() -> NSXPCConnection {
+ let connection = NSXPCConnection(
+ machServiceName: CodexBarHelperIPC.machServiceName,
+ options: .privileged
+ )
+ connection.remoteObjectInterface = NSXPCInterface(with: CodexBarHelperProtocol.self)
+ connection.invalidationHandler = { [weak self, weak connection] in
+ Task { @MainActor in
+ self?.handleConnectionLoss(connection, reason: "invalidated")
+ }
+ }
+ connection.interruptionHandler = { [weak self, weak connection] in
+ Task { @MainActor in
+ self?.handleConnectionLoss(connection, reason: "interrupted")
+ }
+ }
+ connection.resume()
+ self.connection = connection
+ AppLog.keepAlive.notice("自动重置唤醒服务已连接")
+ return connection
+ }
+
+ private func handleConnectionLoss(_ connection: NSXPCConnection?, reason: String) {
+ guard let connection, self.connection === connection else {
+ return
+ }
+
+ connection.invalidationHandler = nil
+ connection.interruptionHandler = nil
+ connection.invalidate()
+ self.connection = nil
+ runtimeStatusMonitor.cancelRequest()
+ appliedSchedule = .unknown
+ AppLog.keepAlive.notice(
+ "自动重置唤醒服务已断开: reason=\(reason, privacy: .public)"
+ )
+ reconcile()
+ }
+
+ private func invalidateConnection() {
+ let connection = connection
+ self.connection = nil
+ connection?.invalidationHandler = nil
+ connection?.interruptionHandler = nil
+ connection?.invalidate()
+ }
+
+ private static let minimumWakeLeadTime: TimeInterval = 5
+}
diff --git a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift b/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift
index 02bc268..8823d39 100644
--- a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift
+++ b/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift
@@ -25,10 +25,18 @@ struct HelperRuntimeStatus {
@MainActor
final class HelperRuntimeStatusMonitor {
+ enum WakeScheduleResult {
+ case success
+ case helperFailure(Int32)
+ case connectionFailure(Error)
+ case timedOut
+ case cancelled
+ }
+
private(set) var isRequestInFlight = false
private var requestGeneration: UInt64 = 0
- private var requestContinuation: CheckedContinuation<RequestResult?, Never>?
+ private var requestContinuation: CheckedContinuation<RequestResult, Never>?
private var requestTimeoutTask: Task<Void, Never>?
private var observationTask: Task<Void, Never>?
private var observationToken: UUID?
@@ -64,9 +72,7 @@ final class HelperRuntimeStatusMonitor {
"Helper 状态请求超时: timeout=\(wait, privacy: .public)"
)
onTimeout()
- case .updateReset:
- break
- case nil:
+ case .updateReset, .wakeSchedule, .cancelled:
break
}
return nil
@@ -101,12 +107,34 @@ final class HelperRuntimeStatusMonitor {
"Helper 更新后的睡眠重置超时: timeout=\(wait, privacy: .public)"
)
onTimeout()
- case .status, .invalidResponse, nil:
+ case .status, .wakeSchedule, .invalidResponse, .cancelled:
break
}
return false
}
+ func setAutoResetWakeSchedule(
+ connection: NSXPCConnection,
+ unixTimestamp: TimeInterval,
+ timeout: Duration
+ ) async -> WakeScheduleResult {
+ let result = await performRequest(
+ connection: connection,
+ operation: .wakeSchedule(unixTimestamp),
+ timeout: timeout
+ )
+ switch result {
+ case let .wakeSchedule(exitCode):
+ return exitCode == 0 ? .success : .helperFailure(exitCode)
+ case let .connectionFailure(error):
+ return .connectionFailure(error)
+ case .timedOut:
+ return .timedOut
+ case .status, .updateReset, .invalidResponse, .cancelled:
+ return .cancelled
+ }
+ }
+
func startObservation(
interval: Duration,
action: @escaping @MainActor () async -> Void
@@ -144,16 +172,16 @@ final class HelperRuntimeStatusMonitor {
return
}
requestGeneration &+= 1
- finishRequest(nil, generation: requestGeneration)
+ finishRequest(.cancelled, generation: requestGeneration)
}
private func performRequest(
connection: NSXPCConnection,
operation: RequestOperation,
timeout: Duration
- ) async -> RequestResult? {
+ ) async -> RequestResult {
guard !isRequestInFlight else {
- return nil
+ return .cancelled
}
return await withCheckedContinuation { continuation in
@@ -184,53 +212,71 @@ final class HelperRuntimeStatusMonitor {
return
}
- switch operation {
- case .status:
- let reply: @Sendable (Int32, Int, Int, Bool) -> Void = { [weak self] exitCode, ownershipRawValue, activeClientCount, sleepDisabled in
- Task { @MainActor in
- guard exitCode == 0,
- let ownership = CodexBarSleepOwnershipState(
- rawValue: ownershipRawValue
- ),
- activeClientCount >= 0 else {
- self?.finishRequest(
- .invalidResponse(
- exitCode: exitCode,
- ownership: ownershipRawValue,
- activeClientCount: activeClientCount
- ),
- generation: generation
- )
- return
- }
+ send(operation, to: helper, generation: generation)
+ }
+ }
+
+ private func send(
+ _ operation: RequestOperation,
+ to helper: CodexBarHelperProtocol,
+ generation: UInt64
+ ) {
+ switch operation {
+ case .status:
+ let reply: @Sendable (Int32, Int, Int, Bool) -> Void = { [weak self] exitCode, ownershipRawValue, activeClientCount, sleepDisabled in
+ Task { @MainActor in
+ guard exitCode == 0,
+ let ownership = CodexBarSleepOwnershipState(
+ rawValue: ownershipRawValue
+ ),
+ activeClientCount >= 0 else {
self?.finishRequest(
- .status(
- HelperRuntimeStatus(
- ownership: ownership,
- activeClientCount: activeClientCount,
- sleepDisabled: sleepDisabled
- )
+ .invalidResponse(
+ exitCode: exitCode,
+ ownership: ownershipRawValue,
+ activeClientCount: activeClientCount
),
generation: generation
)
+ return
}
+ self?.finishRequest(
+ .status(
+ HelperRuntimeStatus(
+ ownership: ownership,
+ activeClientCount: activeClientCount,
+ sleepDisabled: sleepDisabled
+ )
+ ),
+ generation: generation
+ )
}
- helper.getSleepPreventionStatus(reply: reply)
- case let .updateReset(updateIdentifier):
- let reply: @Sendable (Int32) -> Void = { [weak self] exitCode in
- Task { @MainActor in
- self?.finishRequest(
- .updateReset(exitCode: exitCode),
- generation: generation
- )
- }
+ }
+ helper.getSleepPreventionStatus(reply: reply)
+ case let .updateReset(updateIdentifier):
+ let reply: @Sendable (Int32) -> Void = { [weak self] exitCode in
+ Task { @MainActor in
+ self?.finishRequest(
+ .updateReset(exitCode: exitCode),
+ generation: generation
+ )
+ }
+ }
+ helper.resetSleepAfterUpdate(updateIdentifier, reply: reply)
+ case let .wakeSchedule(unixTimestamp):
+ let reply: @Sendable (Int32) -> Void = { [weak self] exitCode in
+ Task { @MainActor in
+ self?.finishRequest(
+ .wakeSchedule(exitCode: exitCode),
+ generation: generation
+ )
}
- helper.resetSleepAfterUpdate(updateIdentifier, reply: reply)
}
+ helper.setAutoResetWakeSchedule(unixTimestamp, reply: reply)
}
}
- private func finishRequest(_ result: RequestResult?, generation: UInt64) {
+ private func finishRequest(_ result: RequestResult, generation: UInt64) {
guard generation == requestGeneration, isRequestInFlight else {
return
}
@@ -246,14 +292,17 @@ final class HelperRuntimeStatusMonitor {
private enum RequestResult {
case status(HelperRuntimeStatus)
case updateReset(exitCode: Int32)
+ case wakeSchedule(exitCode: Int32)
case connectionFailure(Error)
case invalidResponse(exitCode: Int32, ownership: Int, activeClientCount: Int)
case timedOut
+ case cancelled
}
private enum RequestOperation {
case status
case updateReset(String)
+ case wakeSchedule(TimeInterval)
}
private enum RequestError: LocalizedError {
diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swift
index 1cd33e2..af26c32 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift
@@ -35,6 +35,8 @@ final class KeepAliveController: ObservableObject {
/// 子面板入口该不该出现: 用户开关开着且依赖已就绪
/// 同样从 sleepBlockReason 派生, 于是新增阻断条件时必然要在那个 switch 里表态, 不会漏配
@Published private(set) var canShowOptions = false
+ /// 只供自动重置设置行展示, 不与防睡眠操作错误混在一起
+ @Published private(set) var autoResetWakeScheduleErrorMessage: String?
/// helper 安装与注册状态的错误, 注册恢复正常时才清除
@Published private var registrationErrorMessage: String?
@@ -44,7 +46,11 @@ final class KeepAliveController: ObservableObject {
/// 注册不成功时操作类错误只是下游噪音, 优先展示注册问题
var errorMessage: String? {
- registrationErrorMessage ?? operationErrorMessage
+ (isEnabled ? registrationErrorMessage : nil) ?? operationErrorMessage
+ }
+
+ var helperRegistrationErrorMessage: String? {
+ registrationErrorMessage
}
/// 时长上限的状态转发给 UI, 使调用方不必知道 limiter 的存在
@@ -65,9 +71,6 @@ final class KeepAliveController: ObservableObject {
/// 达到防睡眠时长上限且睡眠恢复成功之后回调一次
/// 时长上限本身是粘滞状态, 每个计时周期天然只会进入一次
- /// 所以返回值用不上, 也不像低电量那条需要锁存: hasReached 粘滞且此刻已不在防睡眠,
- /// 同一个周期里排不进第二次, 周期边界本身就是重置点
- /// 提交失败这一条就丢了, 重新 flush 需要再来一次睡眠恢复, 而睡眠已经恢复完了
var onKeepAliveLimitTriggered: ((MaximumDuration) async -> Bool)?
/// 用户开关仍开着, 且 helper 已经真的把睡眠关掉
@@ -107,6 +110,8 @@ final class KeepAliveController: ObservableObject {
private var helperRegistrationTask: Task<Void, Never>?
/// 与 hasRunningTasks 同理: 只经由派生状态影响 UI, 自己不发信号
private var isRefreshingHelper = false
+ private var isAutoResetRequested = false
+ private let autoResetWakeScheduler = AutoResetWakeScheduler()
/// 已排队但还没发出的低电量通知, 值是触及阈值时的电量
/// 恢复睡眠真的成功才发得出去: 恢复失败时机器仍不会睡, 那时说已恢复会把用户骗去合盖
private var pendingLowBatteryPercent: Int?
@@ -124,33 +129,6 @@ final class KeepAliveController: ObservableObject {
/// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值
private var isHookEnabled: Bool
- /// 防睡眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值
- private enum SleepBlockReason: String {
- case notStarted
- case userOff
- case hookDisabled
- case noTasks
- case helperUnavailable
- case helperRefreshing
- case terminating
- case lowBattery
- case limitReached
- }
-
- /// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志
- /// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"
- /// battery 只放布尔: 放电量百分比会让每掉 1% 都记一条
- private struct SleepConditions: Equatable {
- let blockReason: SleepBlockReason?
- let enabled: Bool
- let hook: Bool
- let tasks: Bool
- let helper: HelperStatus
- let refreshing: Bool
- let battery: Bool
- let limited: Bool
- }
-
// MARK: - 生命周期
init(
@@ -172,6 +150,9 @@ final class KeepAliveController: ObservableObject {
// 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做
keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)
activityMonitor.setActivityProtectionEnabled(isEnabled)
+ autoResetWakeScheduler.onErrorMessageChanged = { [weak self] message in
+ self?.autoResetWakeScheduleErrorMessage = message
+ }
}
func start() {
@@ -234,6 +215,7 @@ final class KeepAliveController: ObservableObject {
cancellables.removeAll()
cancelRetryTask()
cancelHelperRegistrationTask()
+ autoResetWakeScheduler.stop()
cancelExternalObservation()
startedRunningTaskIDs.removeAll()
waitingTaskIDs.removeAll()
@@ -246,8 +228,8 @@ final class KeepAliveController: ObservableObject {
invalidateConnection()
}
- /// App 退出时先等 root 侧把已取得的所有权恢复为 0
- /// 如果本轮只是外部来源, helper 会成功回复但不写 pmset
+ /// App 退出时先等 root 侧取消唤醒计划并把已取得的睡眠所有权恢复为 0
+ /// 如果本轮没有对应所有权, 两条清理请求都会收敛成无操作成功
func prepareForTermination() async -> Bool {
guard isStarted else {
return true
@@ -260,12 +242,17 @@ final class KeepAliveController: ObservableObject {
cancelRetryTask()
cancelHelperRegistrationTask()
cancelExternalObservation()
- let success = await releaseHelperLeaseIfNeeded(trigger: .termination)
+ let wakeScheduleReleased = await autoResetWakeScheduler.prepareForTermination(
+ helperSupportsWakeScheduling: isHelperReadyForAutoResetWake
+ )
+ let sleepLeaseReleased = await releaseHelperLeaseIfNeeded(trigger: .termination)
+ let success = wakeScheduleReleased && sleepLeaseReleased
guard !success else {
return true
}
// 退出被取消时恢复正常状态, 不能让一次失败把运行中的任务永久放开
+ autoResetWakeScheduler.resumeAfterTerminationCancellation()
isPreparingForTermination = false
reconcileSleepState(trigger: .termination, force: true)
return false
@@ -284,10 +271,13 @@ final class KeepAliveController: ObservableObject {
}
refreshHelperStatus()
- if isEnabled || helperStatus.isRegisteredOrAwaitingApproval {
+ if isEnabled
+ || isAutoResetRequested
+ || helperStatus.isRegisteredOrAwaitingApproval {
ensureHelperRegistration(opensSystemSettings: false)
}
reconcileSleepState(trigger: .statusRefresh)
+ reconcileAutoResetWakeSchedule()
}
// MARK: - 设置入口
@@ -558,6 +548,8 @@ final class KeepAliveController: ObservableObject {
completePendingHelperUpdate(updateIdentifier)
} else if helperStatus == .requiresApproval, opensSystemSettings {
openSystemSettings()
+ } else {
+ reconcileAutoResetWakeSchedule()
}
return
case .notRegistered, .notFound:
@@ -591,16 +583,23 @@ final class KeepAliveController: ObservableObject {
if helperStatus == .requiresApproval, opensSystemSettings {
openSystemSettings()
}
+ reconcileAutoResetWakeSchedule()
}
private func refreshRegisteredHelper(opensSystemSettings: Bool) {
let requiresSleepReset = helperStatus == .enabled
guard helperRegistrationTask == nil,
- KeepAliveHelperConfiguration.assetsArePresent,
- let updateIdentifier = KeepAliveHelperConfiguration.beginUpdate(
- defaults: defaults,
- requiresSleepReset: requiresSleepReset
- ) else {
+ KeepAliveHelperConfiguration.assetsArePresent else {
+ return
+ }
+ guard autoResetWakeScheduler.beginHelperInterruptionPreparation() else {
+ return
+ }
+ guard let updateIdentifier = KeepAliveHelperConfiguration.beginUpdate(
+ defaults: defaults,
+ requiresSleepReset: requiresSleepReset
+ ) else {
+ autoResetWakeScheduler.resumeAfterHelperInterruption()
return
}
@@ -617,29 +616,21 @@ final class KeepAliveController: ObservableObject {
guard let self else {
return
}
-
- var didUnregisterHelper = false
- var registrationError: Error?
- do {
- try Task.checkCancellation()
- try await service.unregister()
- didUnregisterHelper = true
- mayHaveHelperLease = false
- try Task.checkCancellation()
- try await registerRefreshedHelper(service)
- } catch is CancellationError {
- return
- } catch {
- registrationError = error
+ defer {
+ autoResetWakeScheduler.resumeAfterHelperInterruption()
}
+ let updateResult = await replaceRegisteredHelper(service)
- guard isStarted, !Task.isCancelled else {
+ guard !(updateResult.error is CancellationError),
+ isStarted,
+ !Task.isCancelled else {
return
}
refreshHelperStatus()
var helperWasUpdated = false
- if didUnregisterHelper, helperStatus.isRegisteredOrAwaitingApproval {
+ if updateResult.didUnregisterHelper,
+ helperStatus.isRegisteredOrAwaitingApproval {
KeepAliveHelperConfiguration.recordRegistration(
defaults: defaults,
status: helperStatus
@@ -655,7 +646,7 @@ final class KeepAliveController: ObservableObject {
}
if !helperWasUpdated {
- let detail = registrationError?.localizedDescription ?? "readinessFailed"
+ let detail = updateResult.error?.localizedDescription ?? "readinessFailed"
AppLog.keepAlive.error(
"Helper 注册更新失败: detail=\(detail, privacy: .public)"
)
@@ -668,6 +659,7 @@ final class KeepAliveController: ObservableObject {
openSystemSettings()
}
reconcileSleepState(trigger: .helperRegistered, force: true)
+ reconcileAutoResetWakeSchedule()
}
}
@@ -1409,6 +1401,8 @@ final class KeepAliveController: ObservableObject {
helperRegistrationTask?.cancel()
helperRegistrationTask = nil
assign(false, to: \.isRefreshingHelper)
+ reconcileAutoResetWakeSchedule()
+ autoResetWakeScheduler.resumeAfterHelperInterruption()
}
private func scheduleRetryIfNeeded(for requested: Bool) {
@@ -1511,6 +1505,66 @@ final class KeepAliveController: ObservableObject {
private static let lowBatteryHysteresis = 5
}
+extension KeepAliveController {
+ private func replaceRegisteredHelper(_ service: SMAppService) async -> (didUnregisterHelper: Bool, error: Error?) {
+ do {
+ try Task.checkCancellation()
+ guard await autoResetWakeScheduler.cancelBeforeHelperInterruption() else {
+ throw KeepAliveError.wakeScheduleCancellationFailed
+ }
+ reconcileAutoResetWakeSchedule()
+ try Task.checkCancellation()
+ try await service.unregister()
+ mayHaveHelperLease = false
+ try Task.checkCancellation()
+ try await registerRefreshedHelper(service)
+ return (true, nil)
+ } catch is CancellationError {
+ return (false, CancellationError())
+ } catch {
+ return (false, error)
+ }
+ }
+
+ func setAutoResetRequested(
+ _ requested: Bool,
+ opensSystemSettings: Bool
+ ) {
+ guard requested != isAutoResetRequested else {
+ if requested {
+ reconcileAutoResetWakeSchedule()
+ }
+ return
+ }
+
+ isAutoResetRequested = requested
+ autoResetWakeScheduler.setRequested(requested)
+ if requested, isStarted {
+ ensureHelperRegistration(opensSystemSettings: opensSystemSettings)
+ }
+ reconcileAutoResetWakeSchedule()
+ }
+
+ func setAutoResetWakeDate(_ date: Date?) {
+ autoResetWakeScheduler.setWakeDate(date)
+ }
+
+ private var isHelperReadyForAutoResetWake: Bool {
+ guard helperStatus == .enabled,
+ !isRefreshingHelper,
+ !KeepAliveHelperConfiguration.registrationNeedsRefresh(defaults: defaults) else {
+ return false
+ }
+ return KeepAliveHelperConfiguration.pendingUpdateIdentifier(defaults: defaults) == nil
+ }
+
+ private func reconcileAutoResetWakeSchedule() {
+ autoResetWakeScheduler.setHelperReady(
+ isStarted && isHelperReadyForAutoResetWake
+ )
+ }
+}
+
private extension KeepAliveController {
func completePendingHelperUpdate(_ updateIdentifier: String) {
guard helperRegistrationTask == nil else {
@@ -1518,6 +1572,7 @@ private extension KeepAliveController {
}
assign(true, to: \.isRefreshingHelper)
+ reconcileAutoResetWakeSchedule()
cancelRetryTask()
cancelExternalObservation()
registrationErrorMessage = nil
@@ -1539,6 +1594,7 @@ private extension KeepAliveController {
assign(!succeeded && helperStatus == .enabled, to: \.isRefreshingHelper)
helperRegistrationTask = nil
reconcileSleepState(trigger: .helperRegistered, force: true)
+ reconcileAutoResetWakeSchedule()
}
}
diff --git a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift b/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
index 44dd1d4..168c30b 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveHelperConfiguration.swift
@@ -32,6 +32,19 @@ enum KeepAliveHelperConfiguration {
.seconds(128),
.seconds(256)
]
+ static let wakeScheduleRetryDelays: [Duration] = [
+ .seconds(2),
+ .seconds(4),
+ .seconds(8),
+ .seconds(16),
+ .seconds(32),
+ .seconds(64)
+ ]
+ static let wakeCancellationRetryDelays: [Duration] = [
+ .zero,
+ .milliseconds(250),
+ .seconds(1)
+ ]
static var service: SMAppService {
SMAppService.daemon(plistName: CodexBarHelperIPC.daemonPlistName)
diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swift
index 264c411..b94b8b4 100644
--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift
+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift
@@ -91,6 +91,33 @@ extension KeepAliveController {
}
}
}
+
+ /// 防睡眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值
+ enum SleepBlockReason: String {
+ case notStarted
+ case userOff
+ case hookDisabled
+ case noTasks
+ case helperUnavailable
+ case helperRefreshing
+ case terminating
+ case lowBattery
+ case limitReached
+ }
+
+ /// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志
+ /// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"
+ /// battery 只放布尔: 放电量百分比会让每掉 1% 都记一条
+ struct SleepConditions: Equatable {
+ let blockReason: SleepBlockReason?
+ let enabled: Bool
+ let hook: Bool
+ let tasks: Bool
+ let helper: HelperStatus
+ let refreshing: Bool
+ let battery: Bool
+ let limited: Bool
+ }
}
nonisolated enum KeepAliveLocalizedMessage {
@@ -142,11 +169,16 @@ nonisolated enum KeepAliveLocalizedMessage {
localized: "keep-alive.error.connection-interrupted",
defaultValue: "服务连接中断"
)
+ static let autoResetWakeScheduleFailed = String(
+ localized: "keep-alive.error.auto-reset-wake-schedule-failed",
+ defaultValue: "设置自动重置唤醒计划失败"
+ )
}
nonisolated enum KeepAliveError: LocalizedError {
case invalidHelperProxy
case connectionInterrupted
+ case wakeScheduleCancellationFailed
var errorDescription: String? {
switch self {
@@ -154,6 +186,8 @@ nonisolated enum KeepAliveError: LocalizedError {
KeepAliveLocalizedMessage.invalidHelperInterface
case .connectionInterrupted:
KeepAliveLocalizedMessage.connectionInterrupted
+ case .wakeScheduleCancellationFailed:
+ KeepAliveLocalizedMessage.autoResetWakeScheduleFailed
}
}
}
diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swift
index 16e094b..fe46e7d 100644
--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift
+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift
@@ -61,10 +61,7 @@ final class SystemSleepService {
}
}
- private var sleepAssertion = Assertion(
- type: kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,
- name: "CodexBar - Codex activity" as CFString
- )
+ private var sleepAssertion: Assertion
private var displayAssertion = Assertion(
type: kIOPMAssertionTypeNoDisplaySleep as CFString,
name: "CodexBar - Codex activity display" as CFString
@@ -82,6 +79,13 @@ final class SystemSleepService {
userActivityTask != nil
}
+ init(sleepAssertionName: String = "CodexBar - Codex activity") {
+ sleepAssertion = Assertion(
+ type: kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,
+ name: sleepAssertionName as CFString
+ )
+ }
+
func beginPreventingIdleSleep() -> IOReturn {
sleepAssertion.begin()
}
diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swift
index c150bdd..426d328 100644
--- a/CodexBar/Services/Notifications/CodexNotificationService.swift
+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift
@@ -4,7 +4,7 @@ import Foundation
import os
import UserNotifications
-nonisolated enum ResetCreditAutomationFailureNotice: String, Sendable {
+nonisolated enum AutoResetFailureNotice: String, Sendable {
case expired
case authentication
case permanent
@@ -450,35 +450,35 @@ final class CodexNotificationService: NSObject {
}
}
- // MARK: - 自动使用重置
+ // MARK: - 自动重置
- func notifyResetCreditAutoUseSucceeded(
+ func notifyAutoResetSucceeded(
remainingCount: Int?,
dedupToken: String
) {
- guard settings.canDeliver, settings.isResetCreditAutoUseEnabled else {
+ guard settings.canDeliver, settings.isAutoResetEnabled else {
return
}
send(
- .resetCreditAutoUseSucceeded(remainingCount: remainingCount),
- sound: settings.resetCreditAutoUseSound,
- dedupKey: "autoResetSuccess|\(dedupToken)"
+ .autoResetSucceeded(remainingCount: remainingCount),
+ sound: settings.autoResetSound,
+ dedupKey: "autoResetSucceeded|\(dedupToken)"
)
}
- func notifyResetCreditAutoUseFailed(
- reason: ResetCreditAutomationFailureNotice,
+ func notifyAutoResetFailed(
+ reason: AutoResetFailureNotice,
dedupToken: String
) {
- guard settings.canDeliver, settings.isResetCreditAutoUseEnabled else {
+ guard settings.canDeliver, settings.isAutoResetEnabled else {
return
}
send(
- .resetCreditAutoUseFailed(reason: reason),
- sound: settings.resetCreditAutoUseSound,
- dedupKey: "autoResetFailure|\(dedupToken)|\(reason.rawValue)"
+ .autoResetFailed(reason: reason),
+ sound: settings.autoResetSound,
+ dedupKey: "autoResetFailed|\(dedupToken)|\(reason.rawValue)"
)
}
@@ -826,10 +826,10 @@ nonisolated struct CodexNotificationContent: Equatable {
)
}
- static func resetCreditAutoUseSucceeded(remainingCount: Int?) -> CodexNotificationContent {
+ static func autoResetSucceeded(remainingCount: Int?) -> CodexNotificationContent {
let body = if let remainingCount {
String(
- localized: "notification.reset-credit-auto-use.body.count",
+ localized: "notification.auto-reset.body.count",
defaultValue: "剩余重置次数: \(remainingCount)"
)
} else {
@@ -837,41 +837,41 @@ nonisolated struct CodexNotificationContent: Equatable {
}
return CodexNotificationContent(
- kind: "resetCreditAutoUse",
+ kind: "autoResetSucceeded",
title: String(
- localized: "notification.reset-credit-auto-use.title",
- defaultValue: "自动使用重置"
+ localized: "notification.auto-reset.title",
+ defaultValue: "自动重置"
),
body: body
)
}
- static func resetCreditAutoUseFailed(
- reason: ResetCreditAutomationFailureNotice
+ static func autoResetFailed(
+ reason: AutoResetFailureNotice
) -> CodexNotificationContent {
let body = switch reason {
case .expired:
String(
- localized: "notification.reset-credit-auto-use-failed.body.expired",
- defaultValue: "已过期, 未能自动使用"
+ localized: "notification.auto-reset-failed.body.expired",
+ defaultValue: "重置次数已过期, 自动重置未完成"
)
case .authentication:
String(
- localized: "notification.reset-credit-auto-use-failed.body.authentication",
+ localized: "notification.auto-reset-failed.body.authentication",
defaultValue: "Codex 登录状态已失效"
)
case .permanent:
String(
- localized: "notification.reset-credit-auto-use-failed.body.permanent",
+ localized: "notification.auto-reset-failed.body.permanent",
defaultValue: "请求无法完成"
)
}
return CodexNotificationContent(
- kind: "resetCreditAutoUseFailed",
+ kind: "autoResetFailed",
title: String(
- localized: "notification.reset-credit-auto-use-failed.title",
- defaultValue: "自动使用重置失败"
+ localized: "notification.auto-reset-failed.title",
+ defaultValue: "自动重置失败"
),
body: body
)
diff --git a/CodexBar/Services/Settings/ResetCreditAutomationSettings.swift b/CodexBar/Services/Settings/AutoResetSettings.swift
similarity index 61%
rename from CodexBar/Services/Settings/ResetCreditAutomationSettings.swift
rename to CodexBar/Services/Settings/AutoResetSettings.swift
index 4c39d9e..3cf16d0 100644
--- a/CodexBar/Services/Settings/ResetCreditAutomationSettings.swift
+++ b/CodexBar/Services/Settings/AutoResetSettings.swift
@@ -2,13 +2,13 @@ import Combine
import Foundation
import os
-nonisolated enum ResetCreditAutomationLeadTime: Int, CaseIterable, Hashable, Sendable {
+nonisolated enum AutoResetLeadTime: Int, CaseIterable, Hashable, Sendable {
+ case fifteenMinutes = 900
case thirtyMinutes = 1800
case oneHour = 3600
case twoHours = 7200
case fourHours = 14400
case sixHours = 21600
- case twelveHours = 43200
var duration: TimeInterval {
TimeInterval(rawValue)
@@ -16,6 +16,8 @@ nonisolated enum ResetCreditAutomationLeadTime: Int, CaseIterable, Hashable, Sen
var title: String {
switch self {
+ case .fifteenMinutes:
+ String(localized: "15 分钟")
case .thirtyMinutes:
String(localized: "30 分钟")
case .oneHour:
@@ -26,17 +28,15 @@ nonisolated enum ResetCreditAutomationLeadTime: Int, CaseIterable, Hashable, Sen
String(localized: "4 小时")
case .sixHours:
String(localized: "6 小时")
- case .twelveHours:
- String(localized: "12 小时")
}
}
}
-/// 自动使用临期重置的本机设置
+/// 自动重置的本机设置
@MainActor
-final class ResetCreditAutomationSettings: ObservableObject {
+final class AutoResetSettings: ObservableObject {
@Published private(set) var isEnabled: Bool
- @Published private(set) var leadTime: ResetCreditAutomationLeadTime
+ @Published private(set) var leadTime: AutoResetLeadTime
private let defaults: UserDefaults
@@ -63,30 +63,35 @@ final class ResetCreditAutomationSettings: ObservableObject {
return
}
- AppLog.settings.notice("自动使用重置变更: enabled=\(enabled ? 1 : 0)")
+ AppLog.settings.notice("自动重置变更: enabled=\(enabled ? 1 : 0)")
isEnabled = enabled
defaults.set(enabled, forKey: Self.enabledKey)
}
- func setLeadTime(_ leadTime: ResetCreditAutomationLeadTime) {
+ func setLeadTime(_ leadTime: AutoResetLeadTime) {
guard leadTime != self.leadTime else {
return
}
- AppLog.settings.notice("自动使用重置临期时间变更: seconds=\(leadTime.rawValue)")
+ 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
+ private static func loadLeadTime(from defaults: UserDefaults) -> AutoResetLeadTime {
+ guard let storedValue = defaults.object(forKey: leadTimeKey) else {
+ return defaultLeadTime
+ }
+ guard let rawValue = storedValue as? Int,
+ let leadTime = AutoResetLeadTime(rawValue: rawValue) else {
+ defaults.set(defaultLeadTime.rawValue, forKey: leadTimeKey)
+ return defaultLeadTime
}
return leadTime
}
- private static let enabledKey = "ResetCreditAutomation.enabled"
- private static let leadTimeKey = "ResetCreditAutomation.leadTimeSeconds"
+ private static let enabledKey = "AutoReset.enabled"
+ private static let leadTimeKey = "AutoReset.leadTimeSeconds"
+ private static let defaultLeadTime = AutoResetLeadTime.thirtyMinutes
}
diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swift
index b42466f..a789d70 100644
--- a/CodexBar/Services/Settings/NotificationSettings.swift
+++ b/CodexBar/Services/Settings/NotificationSettings.swift
@@ -15,7 +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 isAutoResetEnabled: Bool
@Published private(set) var isLowBatteryEnabled: Bool
@Published private(set) var isKeepAliveLimitEnabled: Bool
@Published private(set) var lowQuotaThresholdPercent: Int
@@ -25,7 +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 autoResetSound: NotificationSoundOption
@Published private(set) var lowBatterySound: NotificationSoundOption
@Published private(set) var keepAliveLimitSound: NotificationSoundOption
@Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined
@@ -80,9 +80,9 @@ 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(
+ isAutoResetEnabled = Self.bool(
from: defaults,
- key: Self.resetCreditAutoUseEnabledKey,
+ key: Self.autoResetEnabledKey,
defaultValue: true
)
isLowBatteryEnabled = Self.bool(from: defaults, key: Self.lowBatteryEnabledKey, defaultValue: true)
@@ -102,7 +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)
+ autoResetSound = Self.sound(from: defaults, key: Self.autoResetSoundKey)
lowBatterySound = Self.sound(from: defaults, key: Self.lowBatterySoundKey)
keepAliveLimitSound = Self.sound(from: defaults, key: Self.keepAliveLimitSoundKey)
}
@@ -148,8 +148,8 @@ final class NotificationSettings: ObservableObject {
setBool(enabled, current: &isCreditExpiryEnabled, key: Self.creditExpiryEnabledKey)
}
- func setResetCreditAutoUseEnabled(_ enabled: Bool) {
- setBool(enabled, current: &isResetCreditAutoUseEnabled, key: Self.resetCreditAutoUseEnabledKey)
+ func setAutoResetEnabled(_ enabled: Bool) {
+ setBool(enabled, current: &isAutoResetEnabled, key: Self.autoResetEnabledKey)
}
func setLowBatteryEnabled(_ enabled: Bool) {
@@ -200,8 +200,8 @@ final class NotificationSettings: ObservableObject {
setSound(sound, current: &creditExpirySound, key: Self.creditExpirySoundKey)
}
- func setResetCreditAutoUseSound(_ sound: NotificationSoundOption) {
- setSound(sound, current: &resetCreditAutoUseSound, key: Self.resetCreditAutoUseSoundKey)
+ func setAutoResetSound(_ sound: NotificationSoundOption) {
+ setSound(sound, current: &autoResetSound, key: Self.autoResetSoundKey)
}
func setLowBatterySound(_ sound: NotificationSoundOption) {
@@ -333,7 +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 autoResetEnabledKey = "Notification.autoResetEnabled"
private static let lowBatteryEnabledKey = "Notification.lowBatteryEnabled"
private static let keepAliveLimitEnabledKey = "Notification.keepAliveLimitEnabled"
private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"
@@ -343,7 +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 autoResetSoundKey = "Notification.autoResetSound"
private static let lowBatterySoundKey = "Notification.lowBatterySound"
private static let keepAliveLimitSoundKey = "Notification.keepAliveLimitSound"
}
diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swift
index 747cf37..d3c5bd2 100644
--- a/CodexBar/Services/Support/AppLog.swift
+++ b/CodexBar/Services/Support/AppLog.swift
@@ -56,7 +56,7 @@ nonisolated enum LogTrigger: String {
/// 电量或供电方式变化
case battery
case statusRefresh
- case resetCreditAutoUse
+ case autoReset
}
/// 日志里耗时字段的统一取值方式, 保留两位小数并带单位
diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swift
index 69c67a2..eadb7dd 100644
--- a/CodexBar/Views/Settings/AppSettingsView.swift
+++ b/CodexBar/Views/Settings/AppSettingsView.swift
@@ -13,7 +13,7 @@ struct AppSettingsView: View {
@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings
@ObservedObject var mainPanelSettings: MainPanelSettings
@ObservedObject var notificationSettings: NotificationSettings
- @ObservedObject var resetCreditAutomationSettings: ResetCreditAutomationSettings
+ @ObservedObject var autoResetSettings: AutoResetSettings
@ObservedObject var keepAliveController: KeepAliveController
let onSyncChanged: (Bool) -> Void
let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler
@@ -22,14 +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 autoResetAnchorProvider = 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 = false
+ @State private var isShowingAutoResetConfirmation = false
var body: some View {
VStack(spacing: 0) {
@@ -76,7 +76,7 @@ struct AppSettingsView: View {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
- resetCreditAutomationSettings.refresh()
+ autoResetSettings.refresh()
appUpdater.refreshAutomaticCheckSetting()
refreshStatusRows()
}
@@ -85,14 +85,14 @@ struct AppSettingsView: View {
syncSettings.refresh()
menuBarQuotaSettings.refresh()
mainPanelSettings.refresh()
- resetCreditAutomationSettings.refresh()
+ autoResetSettings.refresh()
codexHookSettings.verifyInstalledHooks()
refreshStatusRows()
}
.onReceive(NotificationCenter.default.publisher(for: .settingsWindowDidOpen)) { _ in
selectedRebuildRange = nil
isShowingRebuildConfirmation = false
- isShowingResetCreditAutomationConfirmation = false
+ isShowingAutoResetConfirmation = false
clearRebuildStatus()
}
.onChange(of: selectedTab) { _, _ in
@@ -131,15 +131,15 @@ struct AppSettingsView: View {
Text("将从本机原始 Hook 事件重新统计 \(selectedRebuildRange?.displayText ?? "")\n并在下次同步时替换当前设备对应日期的云端数据")
}
.alert(
- "开启自动使用重置?",
- isPresented: $isShowingResetCreditAutomationConfirmation
+ "开启自动重置?",
+ isPresented: $isShowingAutoResetConfirmation
) {
Button("取消", role: .cancel) {}
Button("开启", role: .destructive) {
- resetCreditAutomationSettings.setEnabled(true)
+ autoResetSettings.setEnabled(true)
}
} message: {
- Text("开启后, CodexBar 会在手动重置临近过期时, 按设置的临期时间自动使用该次数; 系统处在睡眠等状态可能导致使用失败; 手动重置使用后不可撤销")
+ Text("开启后, CodexBar 在手动重置临近过期时, 按设置的临期时间提前自动使用重置; 并可能短暂唤醒 Mac")
}
}
}
@@ -265,7 +265,7 @@ private extension AppSettingsView {
LiquidGlassDivider()
notificationRow
LiquidGlassDivider()
- resetCreditAutomationRow
+ autoResetRow
LiquidGlassDivider()
keepAliveRow
LiquidGlassDivider()
@@ -422,20 +422,21 @@ private extension AppSettingsView {
}
}
- var resetCreditAutomationRow: some View {
- let isEnabled = resetCreditAutomationSettings.isEnabled
+ var autoResetRow: some View {
+ let isEnabled = autoResetSettings.isEnabled
+ let caption = autoResetCaption
return VStack(alignment: .leading, spacing: 4) {
SettingsToggleRow(
icon: "arrow.counterclockwise.circle",
- title: "自动使用临期重置",
+ title: "自动重置",
isOn: Binding(
- get: { resetCreditAutomationSettings.isEnabled },
+ get: { autoResetSettings.isEnabled },
set: { enabled in
if enabled {
- isShowingResetCreditAutomationConfirmation = true
+ isShowingAutoResetConfirmation = true
} else {
- resetCreditAutomationSettings.setEnabled(enabled)
+ autoResetSettings.setEnabled(enabled)
}
}
)
@@ -443,23 +444,53 @@ private extension AppSettingsView {
optionsButton(isAvailable: isEnabled) {
onOptionsAction(
.toggle(
- panel: .resetCreditAutomation,
- anchorProvider: resetCreditAutomationAnchorProvider
+ panel: .autoReset,
+ anchorProvider: autoResetAnchorProvider
)
)
}
}
+
+ settingsStatusCaptionRow(caption)
}
.background {
- ScreenFrameReader(provider: resetCreditAutomationAnchorProvider)
+ ScreenFrameReader(provider: autoResetAnchorProvider)
}
+ .animation(Metrics.statusAnimation, value: caption)
.animation(Metrics.statusAnimation, value: isEnabled)
.onChange(of: isEnabled) { _, isEnabled in
guard !isEnabled else {
return
}
- onOptionsAction(.close(panel: .resetCreditAutomation))
+ onOptionsAction(.close(panel: .autoReset))
+ }
+ }
+
+ var autoResetCaption: SettingsStatusCaption? {
+ guard autoResetSettings.isEnabled else {
+ return nil
+ }
+ if let errorMessage = keepAliveController.helperRegistrationErrorMessage {
+ return SettingsStatusCaption(message: errorMessage, isError: true)
+ }
+
+ switch keepAliveController.helperStatus {
+ case .requiresApproval:
+ return SettingsStatusCaption(
+ message: String(localized: "需要授权允许 CodexBar 后台运行"),
+ showsSystemSettingsButton: true
+ )
+ case .notRegistered, .notFound:
+ return SettingsStatusCaption(
+ message: String(localized: "CodexBarHelper 尚未注册")
+ )
+ case .enabled:
+ guard let errorMessage = keepAliveController
+ .autoResetWakeScheduleErrorMessage else {
+ return nil
+ }
+ return SettingsStatusCaption(message: errorMessage, isError: true)
}
}
@@ -485,27 +516,7 @@ private extension AppSettingsView {
}
}
- if let caption {
- SettingsIndentedRow(alignment: .top) {
- Text(caption.message)
- .font(.caption)
- .foregroundStyle(caption.isError ? .red : .secondary)
- .fixedSize(horizontal: false, vertical: true)
- .contentTransition(.opacity)
-
- Spacer(minLength: 8)
-
- if caption.showsSystemSettingsButton {
- Button("打开系统设置") {
- keepAliveController.openSystemSettings()
- }
- .controlSize(.small)
- .fixedSize()
- .transition(.opacity.combined(with: .move(edge: .trailing)))
- }
- }
- .transition(.opacity)
- }
+ settingsStatusCaptionRow(caption)
}
.background {
ScreenFrameReader(provider: keepAliveAnchorProvider)
@@ -535,6 +546,31 @@ private extension AppSettingsView {
.animation(Metrics.statusAnimation, value: isAvailable)
}
+ @ViewBuilder
+ func settingsStatusCaptionRow(_ caption: SettingsStatusCaption?) -> some View {
+ if let caption {
+ SettingsIndentedRow(alignment: .top) {
+ Text(caption.message)
+ .font(.caption)
+ .foregroundStyle(caption.isError ? .red : .secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ .contentTransition(.opacity)
+
+ Spacer(minLength: 8)
+
+ if caption.showsSystemSettingsButton {
+ Button("打开系统设置") {
+ keepAliveController.openSystemSettings()
+ }
+ .controlSize(.small)
+ .fixedSize()
+ .transition(.opacity.combined(with: .move(edge: .trailing)))
+ }
+ }
+ .transition(.opacity)
+ }
+ }
+
/// 判定收在 KeepAliveController 里由 sleepBlockReason 派生, 这里只读结论
/// 在 View 里手抄那几个条件会漏掉后来新增的阻断项, 入口会亮着但点开不生效
var canShowKeepAliveOptions: Bool {
@@ -543,27 +579,27 @@ private extension AppSettingsView {
/// 返回 nil 表示这一行整个收起
/// 正常运行时不必占一行说"一切正常", 是否正在防睡眠由主面板的咖啡杯标记呈现
- var keepAliveCaption: KeepAliveCaption? {
+ var keepAliveCaption: SettingsStatusCaption? {
if let errorMessage = keepAliveController.errorMessage {
- return KeepAliveCaption(message: errorMessage, isError: true)
+ return SettingsStatusCaption(message: errorMessage, isError: true)
}
guard codexHookSettings.isEnabled else {
- return KeepAliveCaption(message: String(localized: "需要启用 CodexBar Hook"))
+ return SettingsStatusCaption(message: String(localized: "需要启用 CodexBar Hook"))
}
// 装着但校验不通过时不能说"需要启用", 那句会让用户去开一个已经开着的开关
// 具体是全局禁用还是不被信任, 由上面 Hook 那一行的说明给出, 这里只说结果
guard codexHookSettings.isVerified else {
- return KeepAliveCaption(message: String(localized: "CodexBar Hook 未生效"))
+ return SettingsStatusCaption(message: String(localized: "CodexBar Hook 未生效"))
}
guard keepAliveController.isEnabled else {
- return KeepAliveCaption(
+ return SettingsStatusCaption(
message: String(localized: "当有 Codex 任务运行时防止系统睡眠, 任务结束后自动恢复")
)
}
if keepAliveController.isActivelyPreventingSleep,
keepAliveController.sleepPreventionSource == .external {
- return KeepAliveCaption(
+ return SettingsStatusCaption(
message: String(localized: "系统睡眠已由其他来源关闭")
)
}
@@ -573,24 +609,24 @@ private extension AppSettingsView {
// 它成立即意味着 helper 已就绪, 所以排在下面那个 switch 之前不影响 helper 类问题的呈现
// 不写具体阈值: 滞回让保护一直持续到阈值加 5, 说死数字会与用户看到的电量对不上
if keepAliveController.isLowBatteryBlocking {
- return KeepAliveCaption(message: String(localized: "电量过低, 已恢复系统睡眠"))
+ return SettingsStatusCaption(message: String(localized: "电量过低, 已恢复系统睡眠"))
}
switch keepAliveController.helperStatus {
case .requiresApproval:
- return KeepAliveCaption(
+ return SettingsStatusCaption(
message: String(localized: "需要授权允许 CodexBar 后台运行"),
showsSystemSettingsButton: true
)
case .notRegistered, .notFound:
- return KeepAliveCaption(message: String(localized: "CodexBarHelper 尚未注册"))
+ return SettingsStatusCaption(message: String(localized: "CodexBarHelper 尚未注册"))
case .enabled:
// 上限之外的运行态都收起; 达到上限要留一句, 否则开关开着却没生效无从解释
guard keepAliveController.hasReachedMaximumDuration else {
return nil
}
let duration = keepAliveController.maximumDuration.title
- return KeepAliveCaption(
+ return SettingsStatusCaption(
message: String(localized: "已达到防睡眠时间上限 (\(duration))")
)
}
@@ -1385,7 +1421,7 @@ private struct RebuildStatus {
let isError: Bool
}
-private struct KeepAliveCaption: Equatable {
+private struct SettingsStatusCaption: Equatable {
let message: String
var isError = false
var showsSystemSettingsButton = false
diff --git a/CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swift b/CodexBar/Views/Settings/AutoResetOptionsView.swift
similarity index 85%
rename from CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swift
rename to CodexBar/Views/Settings/AutoResetOptionsView.swift
index 1f65dbd..46fa8c8 100644
--- a/CodexBar/Views/Settings/ResetCreditAutomationOptionsView.swift
+++ b/CodexBar/Views/Settings/AutoResetOptionsView.swift
@@ -1,8 +1,8 @@
import SwiftUI
-/// 自动使用重置子选项面板, 顶边对齐设置页的自动使用主开关行
-struct ResetCreditAutomationOptionsView: View {
- @ObservedObject var settings: ResetCreditAutomationSettings
+/// 自动重置子选项面板, 顶边对齐设置页的自动重置主开关行
+struct AutoResetOptionsView: View {
+ @ObservedObject var settings: AutoResetSettings
var body: some View {
HStack(spacing: Metrics.controlSpacing) {
@@ -18,7 +18,7 @@ struct ResetCreditAutomationOptionsView: View {
get: { settings.leadTime },
set: { settings.setLeadTime($0) }
),
- options: ResetCreditAutomationLeadTime.allCases,
+ options: AutoResetLeadTime.allCases,
label: { $0.title },
width: Metrics.pickerWidth,
alignment: .trailing
diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swift
index 5013ef7..29c3c47 100644
--- a/CodexBar/Views/Settings/NotificationOptionsView.swift
+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift
@@ -7,7 +7,7 @@ struct NotificationOptionsView: View {
@ObservedObject var notificationSettings: NotificationSettings
@ObservedObject var codexHookSettings: CodexHookSettings
@ObservedObject var codexCLINotificationSettings: CodexCLINotificationSettings
- @ObservedObject var resetCreditAutomationSettings: ResetCreditAutomationSettings
+ @ObservedObject var autoResetSettings: AutoResetSettings
@ObservedObject var keepAliveController: KeepAliveController
@State private var previewSound: NSSound?
@@ -18,7 +18,7 @@ struct NotificationOptionsView: View {
lowQuotaRow
quotaResetRow
creditExpiryRow
- resetCreditAutoUseRow
+ autoResetNotificationRow
lowBatteryRow
keepAliveLimitRow
taskHapticRow
@@ -159,21 +159,21 @@ struct NotificationOptionsView: View {
)
}
- /// 自动使用关着时显示为关闭并置灰, 不修改持久化的 isResetCreditAutoUseEnabled
- private var resetCreditAutoUseRow: some View {
- let isAutomationEnabled = resetCreditAutomationSettings.isEnabled
- let isDisplayedOn = isAutomationEnabled && notificationSettings.isResetCreditAutoUseEnabled
+ /// 自动重置关着时显示为关闭并置灰, 不修改持久化的 isAutoResetEnabled
+ private var autoResetNotificationRow: some View {
+ let isFeatureEnabled = autoResetSettings.isEnabled
+ let isDisplayedOn = isFeatureEnabled && notificationSettings.isAutoResetEnabled
return notificationOptionRow(
- title: "自动使用重置通知",
+ title: "自动重置通知",
isOn: Binding(
get: { isDisplayedOn },
- set: { notificationSettings.setResetCreditAutoUseEnabled($0) }
+ set: { notificationSettings.setAutoResetEnabled($0) }
),
- isEnabled: isAutomationEnabled,
+ isEnabled: isFeatureEnabled,
sound: Binding(
- get: { notificationSettings.resetCreditAutoUseSound },
- set: { notificationSettings.setResetCreditAutoUseSound($0) }
+ get: { notificationSettings.autoResetSound },
+ set: { notificationSettings.setAutoResetSound($0) }
)
)
}
diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swift
index 71e0a84..f6d4423 100644
--- a/CodexBarHelper/main.swift
+++ b/CodexBarHelper/main.swift
@@ -1,5 +1,7 @@
import Darwin
import Foundation
+import IOKit
+import IOKit.pwr_mgt
import os
import Security
@@ -89,6 +91,14 @@ private enum SleepRestoreTrigger: String {
case helperTermination
}
+private enum WakeScheduleCleanupTrigger: String {
+ case appRequest
+ case connectionClosed
+ case helperStartup
+ case ownershipCheck
+ case helperTermination
+}
+
// MARK: - pmset 调用
private enum PmsetRunner {
@@ -144,6 +154,83 @@ private enum PmsetRunner {
}
}
+private enum AutoResetWakeScheduler {
+ static let owner = CodexBarHelperIPC.machServiceName + ".auto-reset"
+
+ static func replaceSchedule(with date: Date?) -> IOReturn {
+ let cancelResult = cancelOwnedEvents()
+ guard cancelResult == kIOReturnSuccess else {
+ return cancelResult
+ }
+
+ guard let date else {
+ return kIOReturnSuccess
+ }
+ let scheduleResult = IOPMSchedulePowerEvent(
+ date as CFDate,
+ owner as CFString,
+ kIOPMAutoWake as CFString
+ )
+ guard scheduleResult == kIOReturnSuccess else {
+ return scheduleResult
+ }
+
+ let events = ownedEvents()
+ guard events.count == 1,
+ let scheduledDate = events[0][kIOPMPowerEventTimeKey] as? Date,
+ abs(scheduledDate.timeIntervalSince(date)) <= verificationTolerance else {
+ return kIOReturnError
+ }
+ return kIOReturnSuccess
+ }
+
+ static var ownedEventCount: Int {
+ ownedEvents().count
+ }
+
+ private static func cancelOwnedEvents() -> IOReturn {
+ var firstFailure: IOReturn?
+ for event in ownedEvents() {
+ guard let eventDate = event[kIOPMPowerEventTimeKey] as? Date else {
+ firstFailure = firstFailure ?? kIOReturnBadArgument
+ continue
+ }
+
+ let result = IOPMCancelScheduledPowerEvent(
+ eventDate as CFDate,
+ owner as CFString,
+ kIOPMAutoWake as CFString
+ )
+ if result != kIOReturnSuccess,
+ result != kIOReturnNotFound {
+ firstFailure = firstFailure ?? result
+ }
+ }
+
+ guard ownedEvents().isEmpty else {
+ return firstFailure ?? kIOReturnError
+ }
+ return kIOReturnSuccess
+ }
+
+ private static func ownedEvents() -> [NSDictionary] {
+ guard let events = IOPMCopyScheduledPowerEvents()?.takeRetainedValue() else {
+ return []
+ }
+
+ return (events as NSArray).compactMap { value in
+ guard let event = value as? NSDictionary,
+ event[kIOPMPowerEventAppNameKey] as? String == owner,
+ event[kIOPMPowerEventTypeKey] as? String == kIOPMAutoWake else {
+ return nil
+ }
+ return event
+ }
+ }
+
+ private static let verificationTolerance: TimeInterval = 1
+}
+
private final class CodexBarHelperConnectionSession: NSObject, CodexBarHelperProtocol,
@unchecked Sendable {
let identifier = UUID()
@@ -199,6 +286,21 @@ private final class CodexBarHelperConnectionSession: NSObject, CodexBarHelperPro
reply: reply
)
}
+
+ func setAutoResetWakeSchedule(
+ _ unixTimestamp: TimeInterval,
+ reply: @escaping @Sendable (Int32) -> Void
+ ) {
+ guard let runtime else {
+ reply(-1)
+ return
+ }
+ runtime.setAutoResetWakeSchedule(
+ unixTimestamp,
+ for: identifier,
+ reply: reply
+ )
+ }
}
private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unchecked Sendable {
@@ -214,6 +316,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
private var lastKnownSleepDisabled: Bool?
private var ownershipTimer: DispatchSourceTimer?
private var scheduledOwnershipCheckInterval: TimeInterval?
+ private var autoResetWakeConnectionIdentifier: UUID?
+ private var isAutoResetWakeCleanupPending = false
private var signalSources = [DispatchSourceSignal]()
private var listener: NSXPCListener?
@@ -237,6 +341,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
}
recoverOwnershipAtStartup()
+ recoverAutoResetWakeScheduleAtStartup()
installOwnershipTimer()
installSignalHandlers()
@@ -365,6 +470,67 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
}
}
+ fileprivate func setAutoResetWakeSchedule(
+ _ unixTimestamp: TimeInterval,
+ for identifier: UUID,
+ reply: @escaping @Sendable (Int32) -> Void
+ ) {
+ queue.async { [self] in
+ guard connections.contains(identifier),
+ unixTimestamp.isFinite,
+ unixTimestamp >= 0 else {
+ reply(kIOReturnBadArgument)
+ return
+ }
+
+ let date: Date?
+ if unixTimestamp == 0 {
+ date = nil
+ } else {
+ let requestedDate = Date(timeIntervalSince1970: unixTimestamp)
+ guard requestedDate > Date() else {
+ reply(kIOReturnBadArgument)
+ return
+ }
+ date = requestedDate
+ }
+
+ if date == nil {
+ autoResetWakeConnectionIdentifier = nil
+ } else {
+ autoResetWakeConnectionIdentifier = identifier
+ }
+
+ let result: IOReturn = if date == nil {
+ cancelAutoResetWakeSchedule(trigger: .appRequest)
+ } else {
+ AutoResetWakeScheduler.replaceSchedule(with: date)
+ }
+ guard result == kIOReturnSuccess else {
+ if date != nil {
+ scheduleOwnershipTimerIfNeeded()
+ }
+ let details = LogFields.joined(
+ "action=\(date == nil ? "cancel" : "schedule")",
+ "code=\(result)"
+ )
+ helperLog.error("自动重置唤醒计划更新失败: \(details, privacy: .public)")
+ reply(result)
+ return
+ }
+
+ if date != nil {
+ isAutoResetWakeCleanupPending = false
+ scheduleOwnershipTimerIfNeeded()
+ }
+ if let date {
+ let epoch = Int(date.timeIntervalSince1970)
+ helperLog.notice("自动重置唤醒计划已设置: epoch=\(epoch)")
+ }
+ reply(kIOReturnSuccess)
+ }
+ }
+
func listener(
_: NSXPCListener,
shouldAcceptNewConnection newConnection: NSXPCConnection
@@ -395,6 +561,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
return
}
+ cancelAutoResetWakeSchedule(ifOwnedBy: identifier)
let droppedClients = clients.compactMap { clientIdentifier, lease in
lease.connectionIdentifier == identifier ? clientIdentifier : nil
}
@@ -415,6 +582,39 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
}
}
+ private func cancelAutoResetWakeSchedule(ifOwnedBy identifier: UUID) {
+ guard autoResetWakeConnectionIdentifier == identifier else {
+ return
+ }
+
+ autoResetWakeConnectionIdentifier = nil
+ _ = cancelAutoResetWakeSchedule(trigger: .connectionClosed)
+ }
+
+ @discardableResult
+ private func cancelAutoResetWakeSchedule(
+ trigger: WakeScheduleCleanupTrigger
+ ) -> IOReturn {
+ defer { scheduleOwnershipTimerIfNeeded() }
+ let result = AutoResetWakeScheduler.replaceSchedule(with: nil)
+ guard result == kIOReturnSuccess else {
+ isAutoResetWakeCleanupPending = true
+ let details = LogFields.joined(
+ "reason=\(trigger.rawValue)",
+ "code=\(result)",
+ "remaining=\(AutoResetWakeScheduler.ownedEventCount)"
+ )
+ helperLog.error("自动重置唤醒计划取消失败: \(details, privacy: .public)")
+ return result
+ }
+
+ isAutoResetWakeCleanupPending = false
+ helperLog.notice(
+ "自动重置唤醒计划已取消: reason=\(trigger.rawValue, privacy: .public)"
+ )
+ return kIOReturnSuccess
+ }
+
private func scheduleWatchdog(for clientIdentifier: UUID, generation: UInt64) {
guard watchdogs[clientIdentifier] == nil else {
return
@@ -735,6 +935,35 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
}
}
+ private func recoverAutoResetWakeScheduleAtStartup() {
+ let initialEventCount = AutoResetWakeScheduler.ownedEventCount
+ guard initialEventCount > 0 else {
+ return
+ }
+
+ var lastResult = IOReturn(kIOReturnError)
+ for delay in Self.wakeCleanupStartupRetryDelays {
+ if delay > 0 {
+ Thread.sleep(forTimeInterval: delay)
+ }
+ lastResult = AutoResetWakeScheduler.replaceSchedule(with: nil)
+ if lastResult == kIOReturnSuccess {
+ helperLog.notice(
+ "自动重置遗留唤醒计划已清理: reason=helperStartup count=\(initialEventCount)"
+ )
+ return
+ }
+ }
+
+ isAutoResetWakeCleanupPending = true
+ let details = LogFields.joined(
+ "reason=\(WakeScheduleCleanupTrigger.helperStartup.rawValue)",
+ "code=\(lastResult)",
+ "remaining=\(AutoResetWakeScheduler.ownedEventCount)"
+ )
+ helperLog.error("自动重置遗留唤醒计划清理失败: \(details, privacy: .public)")
+ }
+
private func installOwnershipTimer() {
let timer = DispatchSource.makeTimerSource(queue: queue)
timer.setEventHandler { [weak self] in
@@ -746,6 +975,10 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
} else if ownership.needsRestore, watchdogs.isEmpty {
_ = restoreOwnedSleep(trigger: .ownershipCheck)
}
+ if isAutoResetWakeCleanupPending,
+ autoResetWakeConnectionIdentifier == nil {
+ _ = cancelAutoResetWakeSchedule(trigger: .ownershipCheck)
+ }
scheduleOwnershipTimerIfNeeded()
}
ownershipTimer = timer
@@ -758,7 +991,9 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
return
}
- let interval: TimeInterval = if activeClientCount == 0 {
+ let interval: TimeInterval = if isAutoResetWakeCleanupPending {
+ CodexBarHelperIPC.ownedCheckIntervalSeconds
+ } else if activeClientCount == 0 {
CodexBarHelperIPC.recoveryCheckIntervalSeconds
} else if ownership.needsRestore {
CodexBarHelperIPC.ownedCheckIntervalSeconds
@@ -788,6 +1023,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
if ownership.needsRestore {
_ = restoreOwnedSleep(trigger: .helperTermination)
}
+ autoResetWakeConnectionIdentifier = nil
+ _ = cancelAutoResetWakeSchedule(trigger: .helperTermination)
exit(EXIT_SUCCESS)
}
source.resume()
@@ -795,6 +1032,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc
}
}
+ private static let wakeCleanupStartupRetryDelays: [TimeInterval] = [0, 0.25, 1]
+
// MARK: - 所有权记录
private func ensureOwnershipDirectory() throws {
diff --git a/Config/Version.xcconfig b/Config/Version.xcconfig
index fd87172..fa25ef1 100644
--- a/Config/Version.xcconfig
+++ b/Config/Version.xcconfig
@@ -1,2 +1,2 @@
-MARKETING_VERSION = 3.6.2
-CURRENT_PROJECT_VERSION = 69
+MARKETING_VERSION = 3.6.3
+CURRENT_PROJECT_VERSION = 70
diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.md
index a33d6a7..91ae64e 100644
--- a/Docs/DeveloperGuide/README.md
+++ b/Docs/DeveloperGuide/README.md
@@ -49,10 +49,10 @@
| --- | --- |
| [整体架构](architecture.md) | 进程、模块、生命周期、actor 边界和 3 条数据链路 |
| [设计原则与关键决策](design-decisions.md) | 跨模块设计动机、系统不变量、失败优先级和实现小巧思 |
-| [app-server 数据链路](app-server.md) | CLI 定位、JSON-RPC 会话、账户、额度和用量刷新 |
+| [app-server 数据链路](app-server.md) | CLI 定位、JSON-RPC 会话、账户、额度、用量刷新和自动重置状态机 |
| [Hook 采集与历史聚合](hook-and-aggregation.md) | Hook 安装、事件落盘、聚合、保留期和 schema 演进 |
| [实时任务监控](activity-monitor.md) | 增量读取、rollout 对账、状态机和异常会话保护 |
-| [防睡眠系统](sleep-prevention.md) | IOKit assertion, CodexBarHelper, XPC 租约和恢复策略 |
+| [防睡眠系统](sleep-prevention.md) | IOKit assertion、CodexBarHelper、XPC 租约、自动重置唤醒计划和恢复策略 |
| [CloudKit 同步](sync.md) | 私有数据库、设备匿名化、上传、合并和重建 |
| [通知系统](notifications.md) | 通知触发、去重、声音、触觉和点击行为 |
| [UI 与应用生命周期](ui-and-lifecycle.md) | 菜单栏、面板、焦点、全局快捷键和服务装配 |
@@ -69,6 +69,7 @@
| 修改菜单、窗口或快捷键 | [UI 与应用生命周期](ui-and-lifecycle.md) | [开发与验证](development.md) |
| 修改通知触发或去重 | [通知系统](notifications.md) | 对应的数据来源专题 |
| 修改防睡眠策略或 helper | [防睡眠系统](sleep-prevention.md) | [数据与隐私边界](data-and-privacy.md) |
+| 修改自动重置调度或唤醒计划 | [app-server 数据链路](app-server.md) | [防睡眠系统](sleep-prevention.md)、[数据与隐私边界](data-and-privacy.md) |
| 修改同步字段或合并规则 | [CloudKit 同步](sync.md) | [Hook 采集与历史聚合](hook-and-aggregation.md) |
| 修改持久化结构或默认值 | [开发与验证](development.md) | [设计原则与关键决策](design-decisions.md) |
@@ -79,7 +80,7 @@
- `CodexActivityMonitor` 是任务状态的唯一来源
- UI, Controller, ViewModel 和 Settings 默认在 `MainActor` 上运行
- 阻塞 I/O 和共享可变状态必须离开主 actor
-- CodexBarHelper 只负责睡眠控制,不增加网络、任意命令执行或额外文件访问
+- CodexBarHelper 只负责固定的睡眠控制和自动重置唤醒计划,不增加网络、任意命令执行或额外文件访问
- Hook 配置修改必须保留用户和其他应用已有的 handler
- 聚合语义变化必须递增聚合 schema,并从原始事件完整重建
- 缺失的 Hook 计数字段表示历史来源不可用,不能解释为明确的 `0`
@@ -122,5 +123,7 @@ CodexActivityTask
- app-server 服务:[`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)
- Hook 子进程入口:[`WorkflowHookEventRecorder.swift`](../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)
- 实时任务状态机:[`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
+- 自动重置状态机:[`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift)
+- 自动重置唤醒同步:[`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
- 防睡眠编排:[`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
- CodexBarHelper:[`main.swift`](../../CodexBarHelper/main.swift)
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.md
index b616d14..827e49a 100644
--- a/Docs/DeveloperGuide/app-server.md
+++ b/Docs/DeveloperGuide/app-server.md
@@ -311,15 +311,15 @@ stale 是数据可信度的一部分,新增展示时不能只复制数值而
- 空数组表示服务端已获取明细,但没有返回可用凭证
- 明细列表可能被服务端截断,长度可以小于 `availableCount`
- 每条明细包含 opaque `id`、`status` 和可空的 Unix 秒级 `expiresAt`
-- 每条明细还包含 `resetType`,自动使用只接受 `codexRateLimits`
+- 每条明细还包含 `resetType`,自动重置只接受 `codexRateLimits`
模型层只保留 `status == available` 且晚于快照生成时间的过期日,并按时间排序。数量仍独立使用 `availableCount`,不能从过滤后的日期数量反推。
过期明细属于增强信息。`credits == nil` 时主面板仍展示可用数量,详情显示未知过期时间,不影响额度和用量。额度响应来自同账户缓存时,UI 可以继续展示旧明细,但通知服务不会用 stale 数据触发新的临期通知。
-### 自动使用临期重置
+### 自动重置
-用户主动开启自动使用后,[`ResetCreditAutomationController.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift) 只处理最新 `account/rateLimits/read` 明确返回的凭证明细:
+用户主动开启自动重置后,[`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift) 只处理最新 `account/rateLimits/read` 明确返回的凭证明细:
- 快照为 stale、`credits == nil`、缺少 `expiresAt`、状态不是 `available` 或 `resetType` 不是 `codexRateLimits` 时不调用消费接口
- 明细可能被截断,只处理实际返回的凭证,不从 `availableCount` 猜测未列出的 `creditId`
@@ -346,45 +346,53 @@ account/rateLimitResetCredit/consume
| `nothingToReset` | 当前没有可重置的额度窗口 | 凭证未消费,继续使用同一幂等键重试 |
| `noCredit` | 当前账户没有可用凭证 | 强制刷新;目标消失时静默停止,否则按暂时不一致重试 |
-`alreadyRedeemed` 不是失败,也不是再次消费。它是同一逻辑请求已经成功的确认,因此收到这个结果的设备会停止重试并发送本机的“自动使用重置”通知。
+`alreadyRedeemed` 不是失败,也不是再次消费。它是同一逻辑请求已经成功的确认,因此收到这个结果的设备会停止重试并发送本机的“自动重置”通知。
### 跨设备幂等契约
同一个 Codex 账户可能同时在多台 Mac 上运行 CodexBar。设备之间不依赖 CloudKit 协调,而是对相同 `creditId` 计算完全相同的 UUIDv5:
```text
-namespace = 8abd477b-2320-5e39-9518-2a2adfc542fa
+namespace = c2904ab3-0a87-5648-997d-bd8515edd401
name = creditId 的原始 UTF-8 字节
output = lowercase UUID string
```
-namespace 来自 URL namespace 对 `https://codexbar.zabrian.app/idempotency/reset-credit-auto-use/v1` 执行 UUIDv5。这个 URL 只用于确定 namespace,不代表运行时网络请求。
+namespace 来自 URL namespace 对 `https://codexbar.zabrian.app/idempotency/auto-reset/v1` 执行 UUIDv5。这个 URL 只用于确定 namespace,不代表运行时网络请求。
固定测试向量为:
```text
creditId = RateLimitResetCredit_123
-idempotencyKey = 9538d0a1-be12-587a-a1c0-d59f49029e3a
+idempotencyKey = 4035685d-9ca4-524f-8193-6e0ae2a7b3b9
```
namespace、UUID 版本、原始 UTF-8 输入和小写输出共同构成跨版本兼容协议,不能在普通重构中修改。最先成功的设备完成消费,其他设备用同一个 key 调用时会得到 `alreadyRedeemed`,或者在前置刷新时发现凭证已经消失。
-凭证消失无法区分手动使用、其他设备使用和服务端过期,因此只停止本机任务,不发送自动使用成功通知。只有明确收到 `reset` 或 `alreadyRedeemed` 的设备才发送成功通知。
+凭证消失无法区分手动使用、其他设备使用和服务端过期,因此只停止本机任务,不发送自动重置成功通知。只有明确收到 `reset` 或 `alreadyRedeemed` 的设备才发送成功通知。
### 调度与重试
-自动使用状态机完全位于普通 App 进程:
+自动重置状态机和网络请求仍位于普通 App 进程,CodexBarHelper 只负责受限的系统唤醒计划:
-- 不使用 helper,不申请防睡眠,也不会为 deadline 唤醒 Mac
+- 开启功能时复用现有 CodexBarHelper 注册与批准流程,不依赖“防止系统睡眠”主开关
+- App 只把最近一次阈值或重试时间交给 helper;helper 使用固定 owner 和固定 `wake` 类型替换 CodexBar 自己的事件,不接受任意事件类型
+- helper 设置或取消后必须回读系统事件;只有恰好存在一个目标时间事件或确认事件已经清零时才回复成功
+- 定时或唤醒触发后,App 仅在新鲜读取和消费请求期间持有 `PreventUserIdleSystemSleep` assertion,不保持显示器唤醒,也不修改 `SleepDisabled`
+- 任务变化、功能关闭、App 退出或对应 XPC 连接关闭时取消 CodexBar 自己的唤醒事件
+- helper 启动时先清除固定 owner 的遗留事件再接受连接;取消失败会放弃失效的连接所有者并在 helper 内重试
+- App 正常退出会等待取消回读;App 强制终止或 XPC 连接中断时由 helper 立即取消,突然断电留下的事件由 helper 下次启动收敛,之后 App 按新鲜明细重新调度
- App 启动、用户开启功能或系统唤醒时先做新鲜读取;已经进入临期窗口且尚未过期时立即补试,否则按临期时间重新调度
- App 退出后不持久化原始 `creditId`;下次启动通过新鲜明细重建任务和同一确定性幂等键
- 同一 `creditId` 的 `expiresAt` 变化时保留幂等身份,但取消当前阈值或重试任务并按新时间重排;新临期点已经过去时立即补检
-- 网络、超时、连接断开或暂时服务错误按 `15s, 30s, 1m, 2m, 5m` 退避,之后保持 `5m`
-- `nothingToReset` 在最后 10 分钟内最多每分钟重试一次
+- 只有已经掌握 `creditId + expiresAt` 的目标才能注册重试唤醒事件;只知道数量或读取失败时不为查询重试唤醒 Mac
+- 网络、超时、连接断开或暂时服务错误按 `15s, 30s, 1m, 2m, 5m` 序列计算退避,但不安排落在本轮 5 分钟截止点及之后的重试
+- 单轮超时后取消本地任务和系统唤醒事件,但不标记目标失败;后续普通额度刷新仍可为同一目标开启新一轮重试
+- `nothingToReset` 在距过期不足 10 分钟且本轮重试窗口尚未结束时固定等待 60 秒,其他时间沿用通用退避
- 认证失败先沿用 service 的单次 token refresh;仍失败时暂停当前凭证并按通知设置告知用户,后续可信快照证明认证恢复后再继续
- 参数、协议或方法错误停止当前凭证,不进行无意义重试
-自动使用触发完整额度刷新时,如果普通额度刷新正在执行,新刷新会排队到当前刷新结束后运行,不能被 `isRefreshing` guard 丢弃。
+自动重置触发完整额度刷新时,如果普通额度刷新正在执行,新刷新会排队到当前刷新结束后运行,不能被 `isRefreshing` guard 丢弃。
## Hook 版本与配置校验
@@ -454,13 +462,17 @@ Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原
- Reset Credits 明细为空或被截断时不从明细长度反推可用数量
- 过期、非 available 的 Reset Credits 不进入详情或通知
- stale rate limits 可以展示旧明细,但不触发临期通知
-- 自动使用关闭时不会调用消费接口,缺失设置默认关闭且临期时间默认 2 小时
-- 自动使用不会消费 stale、缺少明细、缺少过期时间或未列出的凭证
+- 自动重置关闭时不会调用消费接口,缺失设置默认关闭且提前量默认 30 分钟
+- 自动重置不会消费 stale、缺少明细、缺少过期时间或未列出的凭证
- 两台设备对固定 `creditId` 生成相同幂等键,并与固定测试向量一致
- 同一 `creditId` 的过期时间提前或推迟时都重新调度,幂等键保持不变
- `reset` 和 `alreadyRedeemed` 均停止重试并发送成功通知
- `nothingToReset` 保留凭证并按退避策略重试
-- 睡眠期间不会唤醒 Mac;唤醒后重新读取,已经进入临期窗口且尚未过期时补试,否则重新调度
+- 防睡眠关闭时仍可注册并批准 helper,未来阈值会写入固定 owner 的 `wake` 事件
+- 计划时间处于系统睡眠期间时唤醒 Mac,触发后重新读取;自然唤醒和 App 启动仍执行相同补检
+- 功能关闭、目标变化和 App 退出时取消已有唤醒事件,且不影响其他应用的计划事件
+- 只有数量或读取失败、没有具体目标时不注册查询重试唤醒事件
+- 已知目标的单轮连续重试在临期触发 5 分钟后停止,后续普通额度刷新仍可重新开启一轮
- 消费成功后的完整额度刷新不会被并发普通刷新丢弃
- 手动刷新后 60 秒倒计时重新对齐
@@ -471,5 +483,7 @@ Reset Credits 明细包含 opaque credit ID。系统日志不能记录 ID 或原
- [`AppServerPipeReaders.swift`](../../CodexBar/Services/CodexStatus/AppServerPipeReaders.swift)
- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift)
- [`CodexStatusViewModel.swift`](../../CodexBar/Services/CodexStatus/CodexStatusViewModel.swift)
-- [`ResetCreditAutomationController.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationController.swift)
-- [`ResetCreditAutomationIdentity.swift`](../../CodexBar/Services/CodexStatus/ResetCreditAutomationIdentity.swift)
+- [`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift)
+- [`AutoResetIdentity.swift`](../../CodexBar/Services/CodexStatus/AutoResetIdentity.swift)
+- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
+- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift)
diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.md
index 59c66d3..d67aa3b 100644
--- a/Docs/DeveloperGuide/architecture.md
+++ b/Docs/DeveloperGuide/architecture.md
@@ -25,8 +25,8 @@ CodexBar 是 macOS 15+ 菜单栏应用,使用 Swift 6, SwiftUI, AppKit 和 MVV
| Target | 职责 |
| --- | --- |
-| `CodexBar` | 菜单栏 UI、Codex 数据采集、通知、同步和防睡眠编排 |
-| `CodexBarHelper` | 以 root LaunchDaemon 运行,仅负责系统睡眠开关 |
+| `CodexBar` | 菜单栏 UI、Codex 数据采集、自动重置、通知、同步和系统电源编排 |
+| `CodexBarHelper` | 以 root LaunchDaemon 运行,负责固定的系统睡眠开关和自动重置唤醒计划 |
两个 target 通过 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 共享 XPC 协议。
@@ -46,13 +46,15 @@ CodexBar executable
|-- 本地只读 <-> Hook JSONL / rollout JSONL
|-- HTTPS <-> Sparkle
|-- CloudKit private database <-> 日级聚合
- `-- signed XPC lease <-> root CodexBarHelper <-> fixed pmset commands
+ `-- signed XPC lease / wake date <-> root CodexBarHelper
+ |-- fixed pmset commands
+ `-- fixed IOPM wake event
```
边界设计有两个关键点:
- 同一个可执行文件承载 Hook 模式可以让 handler 始终指向当前 App 版本,不需要额外部署采集工具
-- root helper 不知道 Codex 任务,只知道经过签名校验的租约,因而不会把业务输入直接带入特权边界
+- root helper 不知道 Codex 任务、账户或重置凭证,只接收经过签名校验的睡眠租约和自动重置唤醒时间
### 进程生命周期差异
@@ -61,7 +63,7 @@ CodexBar executable
| Hook 子进程 | 单个事件,最长几秒 | 读取 stdin、提取最小字段、追加本地 JSONL | 初始化 UI、建立网络连接、等待长期服务 |
| 主 App | 用户登录会话内长期运行 | 编排 UI、数据链路和副作用 | 直接以 root 修改系统设置 |
| app-server | 最长复用 1 小时 | 通过 JSON-RPC 提供账户和配置能力 | 成为 Hook 历史或实时任务的替代来源 |
-| CodexBarHelper | LaunchDaemon | 执行固定 `pmset` 操作并恢复所有权 | 访问账户、Hook、rollout、网络或任意命令 |
+| CodexBarHelper | LaunchDaemon | 执行固定 `pmset` 操作、管理固定 owner 的 `wake` 事件并恢复系统状态 | 访问账户、Hook、rollout、网络或任意命令 |
## 目录职责
@@ -91,7 +93,7 @@ Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本
-> 创建 CodexBarAppDelegate
-> AppDelegate 装配长期服务
-> 创建菜单栏和辅助窗口
- -> 启动刷新, 活动监控, 通知和防睡眠协调
+ -> 启动刷新、活动监控、自动重置、通知和系统电源协调
```
`--hook-event` 是 Codex 调用的短命子进程模式。它必须在任何 UI、CloudKit、通知或长期服务初始化之前完成。采集失败也不能阻断 Codex 主流程。
@@ -103,11 +105,12 @@ Scripts/ 构建, DMG, appcast 和 CodexBarHelper 清理脚本
- `CodexHookSettings`
- `CodexActivityMonitor`
- `KeepAliveController`
+- `AutoResetController`
- `WorkflowSyncSettings` 和同步调度器
- `CodexNotificationService`
- 菜单栏、快捷键、设置窗口和更新服务
-App 退出时需要先释放防睡眠状态。如果 CodexBarHelper 尚未确认恢复,终止流程会等待或取消退出,避免遗留系统级睡眠状态。
+App 退出时需要先取消自动重置唤醒计划并释放防睡眠状态。如果 CodexBarHelper 尚未回读确认两类系统状态都已恢复,终止流程会等待或取消退出。helper 启动时还会在接受新连接前清除固定 owner 的遗留唤醒事件,用于收敛突然断电或强制终止留下的状态。
### 为什么 Hook 判断必须放在 `App.init`
@@ -134,7 +137,7 @@ SwiftUI View 会因为布局、条件分支和窗口重建而重复创建。如
`applicationShouldTerminate` 先调用 `KeepAliveController.prepareForTermination()` 并返回 `.terminateLater`
-如果 helper 明确确认 release,App 再回复允许退出。如果释放失败,本次退出被取消,controller 回到正常协调状态并继续尝试维持正在运行的任务。
+如果 helper 明确确认自动重置唤醒事件已经取消且防睡眠 release 已完成,App 再回复允许退出。任一清理失败时,本次退出被取消,controller 回到正常协调状态并继续按当前设置运行。
直接在 `applicationWillTerminate` 中异步释放已经太晚,因为该回调不能可靠延长进程寿命。
@@ -144,7 +147,7 @@ CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、
| 链路 | 输入 | 输出 | 主要消费者 |
| --- | --- | --- | --- |
-| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Reset Credit 使用、Hook 配置能力 | 主面板、菜单栏额度、设置、自动使用状态机 |
+| app-server | `codex app-server` JSON-RPC | 账户、额度、token 用量、Reset Credit 使用、Hook 配置能力 | 主面板、菜单栏额度、设置、自动重置状态机 |
| Hook 历史 | Hook JSONL | 日级事件、session, turn, tool, model 聚合 | 活跃度热力图、历史统计、CloudKit |
| 实时任务 | Hook 增量事件加 rollout 生命周期 | 运行、等待批准、完成、中断 | 菜单栏状态、任务中心、通知、防睡眠 |
@@ -160,9 +163,10 @@ CodexBar 不使用一个聚合服务承载所有状态。3 条链路的输入、
```text
CodexStatusService ----------------> CodexStatusViewModel ----------------> UI
CodexStatusViewModel --------------> CodexNotificationService
-CodexStatusService ----------------> ResetCreditAutomationController
-CodexStatusViewModel --------------> ResetCreditAutomationController
-ResetCreditAutomationController ---> CodexNotificationService
+CodexStatusService ----------------> AutoResetController
+CodexStatusViewModel --------------> AutoResetController
+AutoResetController ---------------> CodexNotificationService
+AutoResetController ---------------> KeepAliveController ---> AutoResetWakeScheduler ---> helper
WorkflowService -------> WorkflowViewModel -----------> UI
@@ -197,7 +201,8 @@ Hook + rollout --------> CodexActivityMonitor --------> UI
- `CodexActivityMonitor`
- `KeepAliveController`
- `CodexNotificationService`
-- `ResetCreditAutomationController`
+- `AutoResetController`
+- `AutoResetWakeScheduler`
这些对象负责可观察状态和 UI 协调,不应直接执行阻塞 I/O。
@@ -293,13 +298,15 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护
| --- | --- | --- |
| app-server 连接与同账户缓存 | `CodexStatusService` | 请求只读结果 |
| 主面板账户加载状态 | `CodexStatusViewModel` | 观察发布值 |
-| 自动使用临期重置的目标、deadline 和重试 | `ResetCreditAutomationController` | 设置页只修改开关和临期时间 |
+| 自动重置的目标、deadline 和重试 | `AutoResetController` | 设置页只修改开关和提前量 |
+| 自动重置唤醒时间同步 | `AutoResetWakeScheduler` | `AutoResetController` 只提交下一次时间,`KeepAliveController` 只提交 helper 就绪状态 |
| Hook 安装与验证 | `CodexHookSettings` | 读取 `isOperable` |
| 历史聚合和维护游标 | `WorkflowService` | 请求快照或重建 |
| 实时任务 | `CodexActivityMonitor` | 读取 snapshot 或 transition |
| 同步游标与远端缓存 | `WorkflowSyncService` | 请求合并快照 |
| 防睡眠策略与 App assertion | `KeepAliveController` | 读取派生状态或调用设置入口 |
| root 睡眠所有权 | `CodexBarHelper` | 通过 XPC 请求和查询 |
+| root 自动重置唤醒事件 | `CodexBarHelper` | 通过 XPC 替换或取消固定 owner 的单个 `wake` 事件 |
| 通知去重 | `CodexNotificationService` | 上游只发布候选事件 |
新增消费者时,优先订阅已有快照。如果现有快照缺字段,应在状态所有者处扩展稳定值类型,不应让消费者重新读取原始文件。
@@ -322,7 +329,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护
| transport 失败 | 丢弃连接,最多重建一次 | 在不可信 pipe 上继续请求 |
| 数据源身份变化 | 新 generation,从原始来源重建 | 沿用旧 offset 继续追加 |
| 迟到异步结果 | generation 不匹配时丢弃 | 覆盖新设置或新 reader 状态 |
-| 特权状态不确定 | 保留可能租约并主动确认释放 | 假定 helper 没有执行 |
+| 特权状态不确定 | 保留可能租约或唤醒事件并主动确认清理 | 假定 helper 没有执行 |
| Hook recorder 失败 | 吞掉本次采集并退出成功 | 阻断 Codex 或弹 UI |
### 日志为什么记录阶段而不是用户数据
@@ -373,6 +380,7 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护
| 全局快捷键 | Carbon Hot Key API |
| App 防空闲睡眠 | IOKit power assertion |
| 系统睡眠控制 | CodexBarHelper 调用固定参数的 `/usr/bin/pmset` |
+| 自动重置系统唤醒 | CodexBarHelper 调用 `IOPMSchedulePowerEvent` 和 `IOPMCancelScheduledPowerEvent` |
| CodexBarHelper 安装和启动 | `SMAppService` |
| App 与 CodexBarHelper 通信 | XPC |
| 通知 | `UNUserNotificationCenter` |
@@ -387,5 +395,9 @@ Hook recorder 是另一个进程,所以 `WorkflowService` actor 无法保护
- [`CodexStatusService.swift`](../../CodexBar/Services/CodexStatus/CodexStatusService.swift) 管理 app-server
- [`WorkflowService.swift`](../../CodexBar/Services/Workflow/WorkflowService.swift) 管理 Hook 历史聚合
- [`CodexActivityMonitor.swift`](../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) 管理实时任务
-- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 管理防睡眠策略
+- [`AutoResetController.swift`](../../CodexBar/Services/CodexStatus/AutoResetController.swift) 管理自动重置目标和重试
+- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift) 同步下一次系统唤醒时间
+- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift) 管理 helper 注册、防睡眠策略和唤醒调度就绪状态
- [`WorkflowSyncService.swift`](../../CodexBar/Services/Workflow/WorkflowSyncService.swift) 管理 CloudKit 同步
+- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 定义受限特权接口
+- [`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift) 执行并验证系统睡眠与唤醒操作
diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.md
index 6225936..d70b091 100644
--- a/Docs/DeveloperGuide/data-and-privacy.md
+++ b/Docs/DeveloperGuide/data-and-privacy.md
@@ -2,7 +2,7 @@
## 原则
-CodexBar 只读取实现账户展示、Hook 统计、实时任务和防睡眠所需的数据:
+CodexBar 只读取实现账户展示、自动重置、Hook 统计、实时任务和防睡眠所需的数据:
- 原始数据能留在本机时不上传
- 可以保存聚合时不保存正文
@@ -63,12 +63,13 @@ CodexBar 的最小化顺序是:
| 来源 | CodexBar 使用方式 | 是否持久化 | 是否上传 CloudKit |
| --- | --- | --- | --- |
-| app-server 账户、额度和 Reset Credits | 主面板、通知判断和用户启用的自动使用 | 仅短期状态 | 否 |
+| app-server 账户、额度和 Reset Credits | 主面板、通知判断和用户启用的自动重置 | 仅短期状态 | 否 |
| Hook 结构化事件 | 历史聚合和实时任务 | 是,最长 210 天 | 只上传日聚合 |
| rollout 生命周期 | terminal 和进展对账 | 不单独持久化 | 否 |
| App 设置 | 功能开关和阈值 | UserDefaults | 否 |
| Activity Protection | 异常会话恢复 | 哈希身份,最长 24 小时 | 否 |
| CodexBarHelper ownership | 系统睡眠恢复 | root 状态文件 | 否 |
+| 自动重置唤醒计划 | 固定 owner、`wake` 类型和下一次时间 | 系统电源管理 | 否 |
### 为什么 3 条业务链路保持独立
@@ -85,7 +86,7 @@ app-server、Hook 历史和实时活动读取不同事实,具有不同的新
### Codex app-server
-App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、token 用量、Reset Credits 明细和 Codex 配置。用户主动开启自动使用后,App 还会通过同一 stdio 会话调用 Reset Credit 消费方法。
+App 通过本机 `codex app-server --listen stdio://` 获取账户、额度、token 用量、Reset Credits 明细和 Codex 配置。用户主动开启自动重置后,App 还会通过同一 stdio 会话调用 Reset Credit 消费方法。
CodexBar 不自行实现账户登录。app-server 是否访问 OpenAI 服务由 Codex CLI 的正常认证和协议行为决定。
@@ -124,11 +125,11 @@ rollout reader 从文件尾部按预算扫描,一方面减少 I/O,另一方
- 空明细数组表示服务端已读取明细,但没有返回可用凭证
- 明细列表可能被截断,不能用数组长度覆盖总数
- 菜单和临期通知只使用仍为 `available` 且尚未过期的 `expiresAt`
-- 自动使用只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 明细
-- opaque credit ID 和确定性幂等键只存在于当前进程内存,包括 app-server 响应与缓存、额度快照、自动使用状态机和内存请求日志,不持久化或上传
-- 自动使用通知写入 UserDefaults 的去重 key 只包含账户与 credit ID 的 SHA-256 组合,不保存原值
+- 自动重置只处理新鲜响应明确列出的 `available + codexRateLimits + expiresAt` 明细
+- opaque credit ID 和确定性幂等键只存在于当前进程内存,包括 app-server 响应与缓存、额度快照、自动重置状态机和内存请求日志,不持久化或上传
+- 自动重置通知写入 UserDefaults 的去重 key 只包含账户与 credit ID 的 SHA-256 组合,不保存原值
-额度响应来自旧缓存时可以继续展示,但不能触发新的临期通知或消费操作。自动使用设置和调度状态不进入 CloudKit,Mac 之间只通过服务端消费接口的确定性幂等键收敛。
+额度响应来自旧缓存时可以继续展示,但不能触发新的临期通知或消费操作。自动重置设置和调度状态不进入 CloudKit,Mac 之间只通过服务端消费接口的确定性幂等键收敛。
## 本地持久化
@@ -174,7 +175,7 @@ UserDefaults 保存:
- 通知阈值和声音名称
- 全局快捷键
- 菜单栏显示选择
-- 自动使用重置开关和临期时间
+- 自动重置开关和提前量
- 有界的通知去重 key
- CodexBarHelper fingerprint 等运行配置
@@ -190,6 +191,8 @@ UserDefaults 不是无 schema 存储。对已有 key 改名、枚举 raw value
文件只保存 CodexBarHelper 是否拥有 `SleepDisabled` 的恢复事务,不包含 Codex 任务、账户或 Hook 数据。
+自动重置唤醒计划由系统电源管理保存,只包含 CodexBar 固定 owner、`wake` 类型和下一次时间。helper 不接收或保存账户、`creditId`、幂等键或网络数据。
+
目录和文件由 root 管理。详细权限和恢复策略见 [防睡眠系统](sleep-prevention.md)
## 内存日志和系统日志
@@ -224,7 +227,7 @@ ring buffer 的 500 条上限既控制内存,也限制打开日志窗口时的
| CloudKit private database | 同步日级 Hook 聚合 | 用户主动开启同步 |
| Sparkle appcast 和更新资源 | 检查或安装更新 | 自动检查或用户手动检查 |
-账户、额度、token 用量、Reset Credits 明细和用户明确开启的 Reset Credit 消费通过本机 app-server stdio 完成。CodexBar 不为自动使用增加独立 HTTP 客户端。
+账户、额度、token 用量、Reset Credits 明细和用户明确开启的 Reset Credit 消费通过本机 app-server stdio 完成。CodexBar 不为自动重置增加独立 HTTP 客户端。
CodexBarHelper 不进行任何网络访问。
@@ -247,7 +250,7 @@ CloudKit 不上传:
- 完整工作目录
- prompt, response, tool 参数或输出
- Codex 账户、额度和 token 用量
-- Reset Credits 明细、自动使用设置和消费状态
+- Reset Credits 明细、自动重置设置和消费状态
- access token
- App 请求日志
- Activity Protection 状态
@@ -258,13 +261,14 @@ HMAC 设备 pseudonym 只降低硬件身份关联,不会自动匿名化 projec
## root helper 的数据隔离
-CodexBarHelper 只需要知道 3 类状态:
+CodexBarHelper 只需要知道 4 类状态:
- 哪个已验证客户端持有哪一代 lease
- `SleepDisabled` 当前实测值
- CodexBar 是否拥有恢复责任
+- 自动重置唤醒计划的有限 Unix 时间戳和当前连接所有者
-它不需要 task ID、project 名、Hook 路径、账户状态或用户设置全文。XPC 只传布尔请求、client session ID, generation 和 update identifier。
+它不需要 task ID、project 名、Hook 路径、账户状态、`creditId` 或用户设置全文。XPC 只传布尔请求、client session ID、generation、update identifier 和有限 Unix 时间戳。
这种能力最小化意味着即使普通 App 层以后新增网络或数据功能,root 进程也不会自动获得这些能力。不应为了复用文件读取或网络代码把业务 service 链接进 helper。
diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.md
index 2d1b18c..2432760 100644
--- a/Docs/DeveloperGuide/design-decisions.md
+++ b/Docs/DeveloperGuide/design-decisions.md
@@ -11,7 +11,7 @@ CodexBar 看起来只是一个菜单栏 App,但它同时横跨 4 个性质完
- Codex 自己的本机协议和配置
- 持续变化的 Hook 与 rollout 文件
- macOS 窗口、通知和电源管理
-- 带 root 权限的系统级睡眠控制
+- 带 root 权限的系统级睡眠与定时唤醒控制
这些边界不能用同一种失败策略处理。
@@ -33,7 +33,7 @@ CodexBar 看起来只是一个菜单栏 App,但它同时横跨 4 个性质完
这个顺序解释了很多看起来不对称的处理:
- Hook recorder 获取锁超时后丢弃本次统计,而不是继续等待
-- App 退出时可以被延后,直到 helper 确认释放由 CodexBar 拥有的睡眠状态
+- App 退出时可以被延后,直到 helper 确认释放由 CodexBar 拥有的睡眠状态并取消自动重置唤醒计划
- app-server 补充接口失败时可以展示带陈旧标记的缓存,但 method unsupported 必须展示来源缺失
- 唤醒恢复如果没有通过新的 Hook 读取屏障,异常会话保护继续暂停
@@ -195,14 +195,14 @@ monitor 先用 Hook 建立活动状态,再用 rollout 补齐生命周期。`St
这不是简单的“双源合并”。冲突时需要按语义决定谁更权威,还要防止迟到事件复活已经完成的任务。
-## 为什么特权 helper 只接受睡眠租约
+## 为什么特权 helper 只接受受限电源操作
-App 需要 root 权限修改 `pmset disablesleep`,但任务识别、网络和文件解析不需要 root。
+App 需要 root 权限修改 `pmset disablesleep` 和登记系统 `wake` 事件,但任务识别、自动重置判断、网络和文件解析不需要 root。
把策略放进 helper 会显著扩大攻击面和故障恢复范围。当前边界把 helper 限制为一个小型执行器:
-- 输入只有租约、generation、状态查询和更新恢复标识
-- 命令固定为 `/usr/bin/pmset` 的固定参数组合
+- 输入只有睡眠租约、generation、状态查询、更新恢复标识和有限的 Unix 唤醒时间戳
+- 睡眠命令固定为 `/usr/bin/pmset` 的固定参数组合,唤醒计划固定为 CodexBar owner 和 `wake` 类型
- 客户端通过 code-signing requirement 校验
- helper 不读取 Codex 文件、不访问网络、不接受任意路径或命令
@@ -309,6 +309,7 @@ helper 定期读取实际值。一旦 external 消失而租约仍有效,CodexB
- 聚合语义变化递增 schema 并完整重建
- root helper 不获得网络、任意命令或额外文件读取能力
- 只有 CodexBar 自己取得的睡眠所有权可以由 CodexBar 恢复
+- 自动重置只替换或取消 CodexBar 固定 owner 的 `wake` 事件,不修改其他计划事件
- 通知描述系统效果时,必须在效果已经确认后发送
- 匿名任务不进入通知、防睡眠和异常会话保护
- 兼容性变化必须先确定迁移与降级策略
diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.md
index da4aa2b..f039085 100644
--- a/Docs/DeveloperGuide/development.md
+++ b/Docs/DeveloperGuide/development.md
@@ -185,6 +185,7 @@ trigger=wake want=0 reason=lowBattery elapsed=0.183s
| 同步缺数据 | sync stage、local 和 confirmed 数量、replacement dates |
| 通知不出现 | authorization, kind, duplicate 或 obsolete |
| 防睡眠不生效 | block reason, helper registration, XPC generation, source |
+| 自动重置未执行 | target、threshold、retry window、helper registration、wake schedule |
## Debug 与 Release
@@ -308,16 +309,19 @@ schema 递增的判断标准是语义输出是否会因同一份 raw event 得
完整重建优于字段级迁移,因为 raw JSONL 才是事实来源。字段级迁移必须猜测旧算法中丢失的信息,长期会堆积不可组合的历史分支。
-### 防睡眠
+### 系统电源控制
-- CodexBarHelper 只控制睡眠
+- CodexBarHelper 只控制固定的睡眠状态和自动重置 `wake` 事件
- CodexBarHelper 不增加网络或任意命令能力
- 外部 `SleepDisabled=1` 不能被 CodexBar 声明或恢复
- 租约、watchdog 和 owned 持久化必须共同成立
-- App 退出前确认系统状态恢复
+- 自动重置唤醒接口只接受有限时间戳,owner 和事件类型由 helper 固定
+- App 退出前确认睡眠状态恢复并取消自动重置唤醒计划
修改防睡眠时先写出 acquire, release, timeout, crash 和 external-owner 5 条时序。只验证正常开关无法证明全局系统状态可恢复。
+修改自动重置唤醒时先写出 schedule、replace、cancel、connection-loss、helper-startup 和 unregister 6 条时序。系统回读必须证明固定 owner 最终只有一个匹配事件或已经清零。
+
任何新增 helper 方法都要先证明必须由 root 执行。能在普通 App 完成的读取、网络或文件操作不得因为“方便复用”放进 helper。
### 兼容性
@@ -328,6 +332,7 @@ schema 递增的判断标准是语义输出是否会因同一份 raw event 得
- 本地 schema 变化
- CloudKit record 或字段变化
- CodexBarHelper ownership 格式变化
+- 自动重置唤醒事件的 owner 或类型变化
- Debug 与 Release 共享身份计算变化
- 最低系统版本或 API 可用性变化
@@ -424,7 +429,7 @@ schema 递增的判断标准是语义输出是否会因同一份 raw event 得
- 自定义声音缺失回退
- TUI 通知与 App 通知互不影响
-### 防睡眠
+### 系统电源与 helper
- App 包内 CodexBarHelper 和 plist 位置
- App 与 CodexBarHelper 签名
@@ -433,6 +438,10 @@ schema 递增的判断标准是语义输出是否会因同一份 raw event 得
- 低电量和最长时长停止
- 外部 `SleepDisabled` 共存
- 正常退出和异常退出恢复
+- 自动重置开启时的 helper 注册与系统批准
+- 自动重置阈值和重试时间只保留最近一个固定 owner 的 `wake` 事件
+- 自动重置关闭、目标变化、正常退出、连接中断和 helper 重启时清理唤醒事件
+- helper 注销前确认固定 owner 的唤醒事件已经清零
- Debug 与 Release 分离
## 手动验证如何留下可复查证据
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index 38e3555..38f2f65 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -8,7 +8,7 @@
- app-server 账户、额度和 Reset Credits 快照
- `CodexActivityMonitor` 任务转场和防睡眠恢复事件
-- `ResetCreditAutomationController` 已确认的消费结果或需要告知用户的失败状态
+- `AutoResetController` 已确认的消费结果或需要告知用户的失败状态
View 和其他服务不直接创建系统通知。它们发布状态变化,通知服务负责资格判断、去重、声音和点击行为。
@@ -39,7 +39,7 @@ View 和其他服务不直接创建系统通知。它们发布状态变化,通
| 低额度 | 连续可信快照 | 需要比较阈值上下两帧 |
| 额度重置 | 连续可信快照 | 需要先观察消费再观察归零 |
| Reset Credits 到期 | 当前快照加时间调度 | 到期提醒由未来 deadline 触发 |
-| 自动使用重置 | app-server mutation 结果 | 只有明确结果才能说明本机自动操作发生过 |
+| 自动重置 | app-server mutation 结果 | 只有明确结果才能说明本机自动操作发生过 |
| 任务完成 | monitor 转场 | 历史 terminal 快照不能补发 |
| 等待批准 | monitor 转场加当前快照 | 先通知新等待,再撤回过时等待 |
| 异常会话保护 | 已提交保护结果 | 必须描述已经隐藏的任务 |
@@ -65,7 +65,7 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings
## 通知开关
-通知总开关默认关闭。7 个可配置分类的子开关默认开启,触觉反馈默认关闭。
+通知总开关默认关闭。8 个可配置分类的子开关默认开启,触觉反馈默认关闭。
总开关关闭时不会申请系统通知权限,也不会发送任何分类通知。子开关用于在总开关开启后选择具体类型:
@@ -74,7 +74,7 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings
| 额度重置 | app-server 额度窗口 | 独立子开关 |
| 低额度 | app-server 剩余额度 | 独立子开关和阈值 |
| Reset Credits 到期 | app-server 重置凭证明细 | 独立子开关 |
-| 自动使用重置 | 已确认消费结果或需要告知用户的失败状态 | 自动使用开关、独立通知子开关和通知总开关 |
+| 自动重置 | 已确认消费结果或需要告知用户的失败状态 | 自动重置开关、独立通知子开关和通知总开关 |
| 任务完成 | 实时任务 terminal 转场 | 独立子开关和最短时长 |
| 等待批准 | 实时任务 waiting 转场 | 独立子开关 |
| 异常会话保护 | Activity Protection | 防睡眠主开关和通知总开关 |
@@ -97,20 +97,20 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings
重置状态不持久化。App 启动时必须重新观察到消费后才通知重置,这是主动接受漏掉离线期间重置,以换取绝不在启动时对 0% 用量误报。
-## 自动使用重置
+## 自动重置
-自动使用和额度重置是两个独立事件,因此保留两条通知:
+自动重置操作和额度窗口重置是两个独立事件,因此保留两条通知:
-- “自动使用重置”说明 CodexBar 的自动操作收到 `reset` 或 `alreadyRedeemed`
+- “自动重置”说明 CodexBar 的自动操作收到 `reset` 或 `alreadyRedeemed`
- “额度已重置”说明普通额度快照先观察到消耗,随后观察到归零
-一次自动使用可能同时满足两者,所以同一台设备可以先后收到两条通知。不能因为内容接近就合并:前者证明自动化动作,后者是额度生命周期通知,来源和开关都不同。
+一次自动重置可能同时满足两者,所以同一台设备可以先后收到两条通知。不能因为内容接近就合并:前者证明自动化动作,后者是额度生命周期通知,来源和开关都不同。
成功通知正文优先带上消费后新鲜读取的剩余重置次数,包括明确的 `0`。后置读取失败时仍保留已经明确的成功结果,并发送只有标题、没有正文的通知。
`alreadyRedeemed` 表示相同幂等键此前已经成功,不应继续重试。多台设备同时调用时,每台明确收到 `reset` 或 `alreadyRedeemed` 的设备都可以发送本机成功通知。某台设备只在刷新中看到凭证消失时无法区分手动使用、其他设备使用或过期,因此静默停止,不发送成功通知。
-失败通知使用“自动使用重置失败”,当前包括:
+失败通知使用“自动重置失败”,当前包括:
- 单次认证刷新后仍未登录,当前凭证暂停到可信快照证明认证恢复
- 参数、协议或方法错误,当前凭证停止重试
@@ -118,7 +118,7 @@ App 激活时会重新读取系统状态,因为用户可能在 System Settings
短暂网络和服务错误只进入退避重试,不在每次失败时打扰用户。同一凭证的同一失败原因最多通知一次;认证、永久错误和本机明确观察到的过期使用不同去重键,因此同一凭证可能先后出现不同失败通知。目标从服务端明细消失时无法判断原因,状态机会静默停止,不补发过期通知。
-成功和失败通知共用“自动使用重置通知”子开关及声音,默认开启并使用系统默认声音。自动使用功能关闭时设置行置灰,但不覆盖已经保存的通知和声音选择;重新开启后恢复原值。
+成功和失败通知共用“自动重置通知”子开关及声音,默认开启并使用系统默认声音。自动重置功能关闭时设置行置灰,但不覆盖已经保存的通知和声音选择;重新开启后恢复原值。
## 低额度
@@ -338,12 +338,12 @@ App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继
- 系统拒绝权限时设置页展示可理解状态
- 低额度只在向下跨越阈值时通知
- 初次加载 100% 额度不误报重置
-- 自动使用明确返回 `reset` 时发送“自动使用重置”,后续额度归零时仍可独立发送“额度已重置”
-- 自动使用明确返回 `alreadyRedeemed` 时按成功通知并停止重试
-- 只看到目标凭证消失时不发送自动使用通知
+- 自动重置明确返回 `reset` 时发送“自动重置”,后续额度归零时仍可独立发送“额度已重置”
+- 自动重置明确返回 `alreadyRedeemed` 时按成功通知并停止重试
+- 只看到目标凭证消失时不发送自动重置通知
- 网络重试期间不发送失败通知,同一凭证的同一失败原因最多通知一次
-- 自动使用关闭时通知子项置灰,重新开启后恢复原来的开关和音效
-- 成功和失败通知使用“自动使用重置通知”所选音效,选择静音时两者都无声
+- 自动重置关闭时通知子项置灰,重新开启后恢复原来的开关和音效
+- 成功和失败通知使用“自动重置通知”所选音效,选择静音时两者都无声
- 完成时长低于和高于阈值时行为正确
- `Stop` 与 rollout terminal 同时出现时只通知一次
- 自动审批不发送等待批准通知
diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.md
index e48c3dd..5514e1c 100644
--- a/Docs/DeveloperGuide/sleep-prevention.md
+++ b/Docs/DeveloperGuide/sleep-prevention.md
@@ -8,7 +8,7 @@
- App 退出、崩溃或失联后可靠恢复系统设置
- 不覆盖用户或其他应用已经设置的系统级防睡眠状态
-普通 App 进程负责策略和用户界面,CodexBarHelper 只执行受限的系统睡眠操作:
+普通 App 进程负责策略和用户界面,CodexBarHelper 只执行受限的系统睡眠与唤醒操作:
```text
CodexActivityMonitor
@@ -17,6 +17,12 @@ CodexActivityMonitor
-> XPC lease
-> CodexBarHelper
-> /usr/bin/pmset
+
+AutoResetController
+ -> AutoResetWakeScheduler
+ -> XPC wake date
+ -> CodexBarHelper
+ -> IOPMSchedulePowerEvent
```
## 为什么这不是一个 assertion 开关
@@ -151,11 +157,22 @@ App 侧 assertion 只覆盖当前进程生命周期。系统级 `SleepDisabled`
CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHelper 使用 [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift) 定义的 XPC 接口。
-接口只提供 3 类能力:
+接口只提供 4 类能力:
- 设置或撤销 App 租约
- 查询 CodexBarHelper 运行和拥有状态
- App 更新后重置 CodexBarHelper 状态
+- 设置或取消 CodexBar 固定 owner 的下一次自动重置 `wake` 事件
+
+自动重置与防睡眠共用 helper 注册和系统批准状态,但使用独立 XPC 连接。开启自动重置时,即使防睡眠主开关关闭,也会尝试注册 helper;尚未批准时,自动重置设置行会提供相同的状态和“打开系统设置”入口。
+
+唤醒计划采用系统状态收敛而不是只依赖正常退出清理:
+
+- helper 每次启动都在开放 XPC listener 前清除固定 owner 的遗留事件,App 重连后再按最新目标重新安排
+- 设置成功必须回读到恰好一个时间匹配的事件,取消成功必须回读到零个事件
+- 对应 XPC 连接断开时立即放弃内存所有者;取消失败会进入待清理状态,并由 helper 短周期重试
+- App 退出会等待唤醒计划和防睡眠租约分别确认释放;helper 更新会先冻结唤醒同步,并在当前进程存在唤醒连接或已应用时间时显式取消计划
+- `Scripts/cleanup.swift` 注销 helper 前会检查固定 owner;事件无法取消并回读清零时停止注销,避免同时失去最后一个具备清理权限的进程;注销成功后同时关闭防睡眠和自动重置,避免 App 下次启动时重新注册 helper
每个 App 进程生成稳定的 `clientSessionID`,XPC 重连期间保持不变。每次租约变更带单调递增 generation,CodexBarHelper 只接受更新的请求,避免迟到消息覆盖新状态:
@@ -168,8 +185,10 @@ CodexBarHelper 通过 `SMAppService` 注册为 LaunchDaemon。App 和 CodexBarHe
[`CodexBarHelper/main.swift`](../../CodexBarHelper/main.swift) 以 root 运行,但能力被刻意限制:
-- 只执行固定路径 `/usr/bin/pmset`
+- 系统睡眠切换只执行固定路径 `/usr/bin/pmset`
- 只使用固定参数读取或切换 `disablesleep`
+- 只使用固定 owner 和固定 `wake` 类型设置或取消一个系统唤醒事件
+- 唤醒接口只接受有限时间戳,不接受任意 owner、事件类型或命令
- 不接受任意命令或参数
- 不访问 Hook、rollout、账户或日志数据
- 不进行网络访问
@@ -248,6 +267,8 @@ CodexBarHelper 把系统所有权记录保存在:
该文件记录 CodexBar 对系统睡眠设置的所有权。
+自动重置唤醒事件不写入该文件。它由 macOS 电源管理保存,身份固定为当前 Debug 或 Release helper 的 mach service 名加 `.auto-reset`,类型固定为 `wake`。
+
## 租约与故障恢复
App 持有有效任务时保持带身份的 XPC lease。CodexBarHelper 不把一次请求解释为脱离连接的永久授权:
@@ -261,11 +282,11 @@ App 持有有效任务时保持带身份的 XPC lease。CodexBarHelper 不把一
异常退出后,CodexBarHelper 依靠连接失效、watchdog 和持久化所有权共同恢复系统设置。
-App 正常退出时先撤销租约和 IOKit assertion。如果 CodexBarHelper 尚未确认恢复,App 终止流程会等待,避免在不确定状态下直接离开。
+App 正常退出时先取消自动重置唤醒计划,再撤销租约和 IOKit assertion。如果 CodexBarHelper 尚未确认两类 root 状态都已清理,App 终止流程会等待,避免在不确定状态下直接离开。
### 正常退出为什么可以被取消
-`applicationShouldTerminate` 不能在未确认释放时直接返回允许。`prepareForTermination()` 会先停止新重试、请求释放可能存在的租约,然后等待 helper 回读结果:
+`applicationShouldTerminate` 不能在未确认释放时直接返回允许。`prepareForTermination()` 会先停止新重试,取消可能存在的自动重置唤醒计划,再请求释放可能存在的租约,然后等待 helper 回读结果:
- 释放成功时继续终止
- 释放失败时取消本次终止,恢复正常条件求值和重试
@@ -280,6 +301,7 @@ helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`
- owned 且已无租约时恢复 `0`
- external 时只观察,不把外部状态写成自己的 ownership
- 持久化记录不可信时采取 fail-safe 恢复,不把损坏记录当成继续持有权限的依据
+- 自动重置唤醒事件取消失败且已经没有连接所有者时,每 5 秒继续回读并清理固定 owner
这里的周期检查不是替代事件驱动 XPC,而是修复系统设置被其他进程改写、回调丢失或进程重启造成的事实漂移。
@@ -379,6 +401,13 @@ CodexBar 在确认自己拥有的系统设置已恢复后读取 clamshell 状态
诊断时应区分 registration error 和 operation error。前者表示 helper 未安装、待批准或更新失败,后者表示已安装 helper 的某次切换没有得到可信结果。
+自动重置唤醒计划使用独立的有界同步策略:
+
+- 设置或替换失败后按 `2s, 4s, 8s, 16s, 32s, 64s` 重试,耗尽后在自动重置设置行保留错误
+- 正常退出或 helper 更新前按立即、`250ms`、`1s` 三次尝试取消并回读
+- 目标时间距现在不超过 5 秒时不再登记系统事件,App 内任务直接进入到点执行路径
+- XPC 连接丢失后清除 App 侧已应用状态并重新协调;helper 同时取消该连接拥有的固定事件
+
## CodexBarHelper 更新
App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 CodexBarHelper fingerprint,检测变化后通过 `SMAppService` 和重置接口刷新安装状态。
@@ -390,6 +419,7 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C
- App 和 CodexBarHelper 签名匹配预期
- 首次系统授权流程可完成
- 更新后旧 owned 状态能够安全恢复
+- 更新前自动重置唤醒计划已取消,新 helper 就绪后按当前目标重新登记
## 手动验证矩阵
@@ -398,6 +428,11 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C
- 外部先设置 `disablesleep 1` 时,CodexBar 不声明所有权也不恢复为 `0`
- App 正常退出时恢复 owned 状态
- App 强制退出或 XPC 断开后,watchdog 恢复 owned 状态
+- 自动重置开启且防睡眠关闭时仍能完成 helper 注册与批准
+- 未来阈值和重试只保留一个固定 owner 的 `wake` 事件,替换时不影响其他 owner
+- 自动重置关闭、目标变化和正常退出时回读确认计划清零
+- 自动重置 XPC 连接断开或 helper 重启时清理遗留计划
+- `Scripts/cleanup.swift` 只在固定 owner 的计划确认清零后注销 helper
- 达到时长上限后先恢复睡眠再通知
- 低电量触发和 5% 滞回恢复正确
- 异常会话保护隐藏任务后释放防睡眠
@@ -408,6 +443,7 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C
- [`KeepAliveController.swift`](../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
- [`SystemSleepService.swift`](../../CodexBar/Services/KeepAlive/SystemSleepService.swift)
- [`HelperRuntimeStatusMonitor.swift`](../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)
+- [`AutoResetWakeScheduler.swift`](../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
- [`KeepAliveDurationLimiter.swift`](../../CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift)
- [`PowerSourceMonitor.swift`](../../CodexBar/Services/KeepAlive/PowerSourceMonitor.swift)
- [`CodexBarHelperXPC.swift`](../../Shared/CodexBarHelperXPC.swift)
diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.md
index 6d16e3a..9abe985 100644
--- a/Docs/DeveloperGuide/sync.md
+++ b/Docs/DeveloperGuide/sync.md
@@ -14,7 +14,7 @@ CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统
-> 按日期合并展示
```
-账户、额度、token 总量、Reset Credits、自动使用设置与状态、实时任务和防睡眠状态不参与同步。
+账户、额度、token 总量、Reset Credits、自动重置设置与状态、实时任务和防睡眠状态不参与同步。
## 设计目标和非目标
@@ -32,7 +32,7 @@ CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统
- 实时任务状态,因为它变化快且需要本机低延迟判断
- 账户额度,因为它属于 Codex 账户而不是设备工作历史
-- 自动使用临期重置,因为多设备收敛依赖相同 `creditId` 的确定性幂等键,不依赖 CloudKit 锁或任务记录
+- 自动重置,因为多设备收敛依赖相同 `creditId` 的确定性幂等键,不依赖 CloudKit 锁或任务记录
- 防睡眠状态,因为它是当前 Mac 的系统副作用
- 原始事件,因为跨设备统计只需要可合并的日级事实
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index 9fa3988..daa2c6a 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -40,12 +40,12 @@ SwiftUI 负责声明内容,AppKit 负责窗口和事件生命周期:
AppDelegate 负责:
- 创建长期 service, ViewModel 和 settings
-- 建立 monitor 与通知、防睡眠的观察关系
+- 建立 monitor 与通知、防睡眠的观察关系,并装配自动重置状态机
- 启动状态刷新和 Hook 活动读取
- 创建状态栏控制器
- 安装全局快捷键
- 配置 Sparkle 更新
-- 在 App 终止时协调防睡眠释放
+- 在 App 终止时协调自动重置唤醒计划取消和防睡眠释放
对象由 composition root 显式持有,避免 SwiftUI View 生命周期意外销毁长期服务。
@@ -56,15 +56,15 @@ AppDelegate 负责:
```text
创建 settings 和数据服务
-> 建立 ViewModel
- -> 启动 activity monitor
- -> 连接 notification 与 keep-alive 副作用
-> 创建 status item 和窗口 controller
+ -> 启动通知与自动重置副作用
+ -> 启动 activity monitor 与 keep-alive 协调
-> 启动周期刷新与更新服务
```
通知和防睡眠只消费 monitor 已发布的快照或转场,不反向控制 reader。Controller 通过闭包连接这些服务,从而避免服务层依赖 AppKit 容器。
-终止时顺序反转,但防睡眠是例外。AppDelegate 先异步确认 helper lease 已释放,成功后才允许进程终止。详细事务见 [防睡眠系统](sleep-prevention.md)
+终止时顺序反转,但 helper 系统状态是例外。AppDelegate 先异步确认自动重置唤醒计划已经取消,并确认防睡眠 lease 已释放,全部成功后才允许进程终止。详细事务见 [防睡眠系统](sleep-prevention.md)
## 状态栏图标
@@ -214,7 +214,7 @@ hover 类型的热力图面板在打开其他面板前可以渐隐,点击类
设置窗口的高度随当前 tab 内容变化,但固定上边缘并限制到屏幕 visible frame。固定上边缘可以减少切换 tab 时整窗上下漂移,让标题栏保持稳定视觉锚点。
-通知和防睡眠的二级设置面板按需创建。控制器一旦创建就会长期订阅内容高度变化,如果 App 启动时预建所有面板,从未使用的 UI 也会一直参与更新。
+通知、自动重置和防睡眠的二级设置面板按需创建。控制器一旦创建就会长期订阅内容高度变化,如果 App 启动时预建所有面板,从未使用的 UI 也会一直参与更新。
### 120 ms 焦点恢复不是业务延迟
@@ -296,6 +296,7 @@ app-server 状态默认每 60 秒刷新。面板打开时会安排约 160 ms 的
- 全局快捷键在状态栏锚点有效和无效场景都能打开面板
- 从通知点击激活 App 并打开面板
- 设置窗口首次打开、关闭和再次打开时焦点正确
+- 通知、自动重置和防睡眠子面板互斥,顶边对齐对应设置行,内容变化后高度正确
- 上下文菜单打开设置或日志时没有焦点丢失
- 多显示器和不同菜单栏位置下 fallback panel 位于鼠标屏幕
- 快捷键冲突后原快捷键仍可用
diff --git a/Docs/README.md b/Docs/README.md
index 3aaebae..446d6f0 100644
--- a/Docs/README.md
+++ b/Docs/README.md
@@ -14,7 +14,7 @@ CodexBar 文档按读者和职责分成两套,使用说明与实现细节保
1. 阅读 [安装与快速开始](UserGuide/getting-started.md)
2. 了解 [主面板与菜单栏](UserGuide/main-panel.md)
3. 按需开启 [实时任务与 CodexBar Hook](UserGuide/activity-and-hook.md)
-4. 在 [设置参考](UserGuide/settings.md) 中确认各选项的作用
+4. 在 [设置参考](UserGuide/settings.md) 中确认自动重置、防睡眠和其他选项的作用
### 排查使用问题
@@ -46,6 +46,7 @@ Docs
└── DeveloperGuide
├── README.md
├── architecture.md
+ ├── design-decisions.md
├── app-server.md
├── hook-and-aggregation.md
├── activity-monitor.md
diff --git a/Docs/UserGuide/README.md b/Docs/UserGuide/README.md
index d577069..a9adcf5 100644
--- a/Docs/UserGuide/README.md
+++ b/Docs/UserGuide/README.md
@@ -10,13 +10,14 @@
| [通知与提醒](notifications.md) | 每类通知的触发条件、默认值、音效和触觉反馈 |
| [防止系统睡眠](sleep-prevention.md) | 生效条件、全部保护选项、CodexBarHelper 授权和外部来源共存 |
| [数据、同步与隐私](sync-data-privacy.md) | 本机数据、iCloud 同步、重建数据和网络边界 |
-| [设置参考](settings.md) | 通用、高级和关于页面中每一个设置的作用 |
-| [常见问题与排查](troubleshooting.md) | 登录、Hook、通知、防睡眠、同步和日志问题 |
+| [设置参考](settings.md) | 通用、高级和关于页面中每一个设置的作用,包括自动重置 |
+| [常见问题与排查](troubleshooting.md) | 登录、Hook、通知、自动重置、防睡眠、同步和日志问题 |
## 按目标快速查找
- 只想查看账户和额度,从 [安装与快速开始](getting-started.md) 开始
- 想看正在运行或等待批准的任务,阅读 [实时任务与 CodexBar Hook](activity-and-hook.md)
+- 想在重置次数到期前自动重置额度,阅读 [设置参考](settings.md#自动重置)
- 想在长任务期间阻止 Mac 睡眠,阅读 [防止系统睡眠](sleep-prevention.md)
- 想知道某个开关是否会上传数据,阅读 [数据、同步与隐私](sync-data-privacy.md)
- 已经遇到错误提示,直接进入 [常见问题与排查](troubleshooting.md)
@@ -30,6 +31,6 @@
| CodexBar Hook | CodexBar 安装到 Codex 配置中的事件处理器 |
| 实时任务 | CodexBar 根据 Hook 事件和本机会话状态判断出的运行中或等待批准任务 |
| Hook 聚合 | 从本机 Hook 原始事件计算出的每日会话、轮次和工具等统计 |
-| CodexBarHelper | 只负责系统级睡眠状态切换的 CodexBar 后台服务 |
+| CodexBarHelper | 负责系统级睡眠状态切换和固定自动重置唤醒计划的 CodexBar 后台服务 |
返回 [CodexBar README](../../README.md)
diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.md
index c92f8e6..1107d42 100644
--- a/Docs/UserGuide/getting-started.md
+++ b/Docs/UserGuide/getting-started.md
@@ -32,7 +32,7 @@ CodexBar 是菜单栏 App,启动后不会在 Dock 中显示图标:
2. 左键点击图标打开主面板
3. 等待首次账户和用量刷新完成
4. 如果显示未登录,先在当前 Codex 中完成登录
-5. 如果需要实时任务、通知或防睡眠,在 `设置 > 高级` 中开启 CodexBar Hook
+5. 如果需要实时任务、任务类通知、防睡眠或 Hook 统计,在 `设置 > 高级` 中开启 CodexBar Hook
CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主面板中的账户图标可以立即刷新。
@@ -50,7 +50,7 @@ CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主
| 悬停热力图方块 | 查看当天 Token 和 Hook 统计 |
| 点击活动卡片 | 打开并发任务中心 |
| 点击手动重置次数 | 查看各批次过期时间 |
-| `设置 > 高级 > 自动使用临期重置` | 配置是否自动使用临期重置以及过期前多久使用 |
+| `设置 > 高级 > 自动重置` | 配置是否自动重置以及提前量 |
全局快捷键优先在鼠标所在屏幕打开主面板,菜单栏锚点不可用时会使用独立浮动面板。
@@ -63,7 +63,7 @@ CodexBar 每 60 秒自动刷新一次账户、额度和 Token 用量,双击主
| 实时任务和任务中心 | 需要 | Hook 已通过校验 |
| 每日 Hook 统计 | 需要 | 本机存在 Hook 原始事件 |
| 额度类通知 | 不需要 | 系统通知总开关和权限已开启 |
-| 自动使用临期重置 | 不需要 | 用户主动开启;默认提前 2 小时,本机睡眠时不会主动唤醒 |
+| 自动重置 | 不需要 | 用户主动开启;系统睡眠期间按计划唤醒需要 CodexBarHelper 获得批准;可选提前 15 分钟至 6 小时,默认提前 30 分钟 |
| 任务类通知 | 需要 | Hook 已通过校验且通知已开启 |
| 防止系统睡眠 | 需要 | CodexBarHelper 已注册并获得系统批准 |
| 跨设备同步 | 需要 | iCloud 可用且用户主动开启同步 |
diff --git a/Docs/UserGuide/notifications.md b/Docs/UserGuide/notifications.md
index ddccf00..88faa93 100644
--- a/Docs/UserGuide/notifications.md
+++ b/Docs/UserGuide/notifications.md
@@ -20,8 +20,8 @@
| 额度预警 | 可信额度首次跌到阈值或以下 | 开启,10% | 无 |
| 额度重置 | 已观察到消耗的额度窗口回到未消耗状态 | 开启 | 无 |
| 重置临期 | 手动重置次数进入过期前 7 天窗口 | 开启 | 存在可用重置次数 |
-| 自动使用重置 | 自动使用明确返回成功或此前已成功 | 开启 | 自动使用开关、通知子开关和通知总开关 |
-| 自动使用重置失败 | 认证失败导致暂停、协议错误导致停止,或本机明确观察到过期 | 与成功通知共用设置 | 自动使用开关、通知子开关和通知总开关 |
+| 自动重置 | 自动重置明确返回成功或此前已成功 | 开启 | 自动重置开关、通知子开关和通知总开关 |
+| 自动重置失败 | 认证失败导致暂停、协议错误导致停止,或本机明确观察到过期 | 与成功通知共用设置 | 自动重置开关、通知子开关和通知总开关 |
| 低电量保护 | 低电量保护成功恢复系统睡眠 | 开启 | 防睡眠和低电量保护 |
| 防睡眠上限 | 达到时长上限并成功恢复系统睡眠 | 开启 | 防睡眠和有限时长上限 |
| 异常会话保护 | 运行中任务超过静默阈值且候选仍有效 | 固定行为 | CodexBar Hook 和防睡眠主开关 |
@@ -45,20 +45,20 @@
手动重置次数会在过期前 7, 6, 5, 4, 3, 2 和 1 天分别判断是否需要提醒。
-## 自动使用通知
+## 自动重置通知
-“自动使用重置”和“额度已重置”来自两个独立事实:
+“自动重置”和“额度已重置”来自两个独立事实:
-- “自动使用重置”说明本机自动调用收到 `reset` 或 `alreadyRedeemed`
+- “自动重置”说明本机自动调用收到 `reset` 或 `alreadyRedeemed`
- “额度已重置”说明额度窗口从已消费状态回到未消费状态
-因此一次自动使用可能产生两条通知。它们不互相替代,也分别遵守各自的触发条件。
+因此一次自动重置可能产生两条通知。它们不互相替代,也分别遵守各自的触发条件。
多台设备同时尝试时,明确收到成功结果的设备会发送自己的成功通知;只在刷新中看到凭证消失的设备不会通知,因为无法判断是手动使用、其他设备使用还是过期。
网络、超时和暂时服务错误只会在后台重试,不会每次通知。认证仍失败时当前任务暂停,后续可信快照确认认证恢复后继续;确定的协议错误会停止当前任务;本机明确观察到凭证过期时停止并通知。如果凭证直接从服务端明细消失,因为无法判断是手动使用、其他设备使用还是过期,本机会静默停止。
-同一凭证的同一失败原因最多通知一次,不同失败原因可能分别通知。成功和失败通知共用“自动使用重置通知”子开关及音效。自动使用功能关闭时该选项不可用,重新开启后恢复此前的通知和音效选择。
+同一凭证的同一失败原因最多通知一次,不同失败原因可能分别通知。成功和失败通知共用“自动重置通知”子开关及音效。自动重置功能关闭时该选项不可用,重新开启后恢复此前的通知和音效选择。
## 通知音效
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index 5a610fa..56bb93c 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -35,7 +35,7 @@
| CodexBar Hook | 安装并校验 Codex 事件 handler | 未安装时关闭 |
| 主面板任务中心 | 控制活动卡片和任务中心是否显示 | 开启,Hook 关闭时不可用 |
| 系统通知 | 控制 CodexBar 本地通知和任务触觉反馈 | 关闭 |
-| 自动使用临期重置 | 按所选时间在过期前自动使用尚未消费的重置次数 | 关闭,提前 2 小时 |
+| 自动重置 | 按所选提前量在过期前使用尚未消费的重置次数重置 Codex 额度 | 关闭,提前 30 分钟 |
| 防止系统睡眠 | 根据实时 Codex 任务自动切换系统睡眠 | 关闭 |
| 跨设备同步 | 通过 iCloud 同步每日 Hook 聚合 | 关闭 |
| 重建数据 | 从所选日期的本机原始事件重新生成聚合 | 手动操作 |
@@ -65,7 +65,7 @@ Hook 关闭时该选项会显示为关闭并置灰,保存的选择不会被覆
| 额度预警通知 | 开启,10% | 阈值可选 5%, 10%, 25% |
| 额度重置通知 | 开启 | 只在观察到消耗后识别重置 |
| 重置临期通知 | 开启 | 提醒 7 天内到期的手动重置次数 |
-| 自动使用重置通知 | 开启 | 只有自动使用临期重置开启时可用,成功和失败共用音效 |
+| 自动重置通知 | 开启 | 只有自动重置开启时可用,成功和失败共用音效 |
| 低电量保护通知 | 开启 | 只有低电量保护实际可用时生效 |
| 防睡眠上限通知 | 开启 | 只有最长时间不是无限制时生效 |
| 任务触觉反馈 | 关闭 | 任务完成或等待批准时触发触摸板震动 |
@@ -75,25 +75,28 @@ Hook 关闭时该选项会显示为关闭并置灰,保存的选择不会被覆
完整说明见 [通知与提醒](notifications.md)
-### 自动使用临期重置
+### 自动重置
-每次开启都会显示操作确认。开启后点击主开关行右侧的选项按钮,在侧边面板选择到期前 `30 分钟`、`1 小时`、`2 小时`、`4 小时`、`6 小时` 或 `12 小时` 开始尝试,默认是 `2 小时`。
+每次开启都会显示操作确认。开启后点击主开关行右侧的选项按钮,在侧边面板的“临期时间”中选择到期前 `15 分钟`、`30 分钟`、`1 小时`、`2 小时`、`4 小时` 或 `6 小时` 开始尝试,默认是 `30 分钟`。
- 只处理 app-server 最新响应明确列出的可用重置次数
- 每次使用前重新确认账号、凭证状态和过期时间
- 同一时间只处理最早到期的一次
-- 电脑睡眠时不会主动唤醒,也不会为了这个功能阻止睡眠
-- 系统唤醒或 App 下次启动时会立即补检;已经进入临期窗口且尚未过期时补试,否则按临期时间重新安排
-- 网络或暂时服务错误会逐步退避重试,最长间隔 5 分钟
-- 当前没有可重置额度时不会消费次数,并会继续使用同一幂等键重试
+- 开启功能时会注册现有 CodexBarHelper;即使“防止系统睡眠”关闭,也可能需要在“登录项与扩展”中批准 CodexBar 后台运行
+- 自动重置设置行会显示 CodexBarHelper 待批准、未注册、注册失败或唤醒计划同步失败状态
+- 有未来任务时,CodexBarHelper 只为最近一次阈值或重试注册一个系统唤醒事件;任务变化、功能关闭或 App 退出时会取消,异常中断遗留的事件会在 helper 下次启动时清理
+- 定时触发后仅在重新读取和使用期间短暂阻止空闲睡眠,不唤醒显示器,也不会开启“防止系统睡眠”
+- 系统自然唤醒或 App 下次启动时仍会立即补检;已经进入临期窗口且尚未过期时补试,否则按临期时间重新安排
+- 只有已经读到具体凭证和过期时间时才会安排重试唤醒;每轮连续重试最多持续 5 分钟,后续普通额度刷新仍可重新尝试
+- 当前没有可重置额度时不会消费次数,并会在本轮 5 分钟窗口内继续使用同一幂等键重试
- 服务端更新同一重置次数的过期时间后,会保留其幂等身份并按新时间重新安排
- 认证失效或确定的协议错误会暂停或停止当前任务,并在通知设置允许时通过系统通知说明
多台 Mac 同时开启时,每台设备独立调度,但会为相同 `creditId` 生成相同幂等键。最先成功的设备完成消费;其他设备收到已成功结果后停止,或者在刷新时发现凭证已经消失并静默停止。
-成功后会发送“自动使用重置”通知。普通“额度已重置”通知来自额度窗口变化,因此两条通知可能同时出现。自动使用本身不依赖系统通知开关;通知关闭时仍会执行,只是不展示结果通知。
+成功后会发送“自动重置”通知。普通“额度已重置”通知来自额度窗口变化,因此两条通知可能同时出现。自动重置本身不依赖系统通知开关;通知关闭时仍会执行,只是不展示结果通知。
-通知侧面板中的“自动使用重置通知”同时控制成功和失败通知,并为两者配置同一个音效。自动使用功能关闭时该项显示为关闭并置灰,保存的通知和音效选择不会被覆盖。
+通知侧面板中的“自动重置通知”同时控制成功和失败通知,并为两者配置同一个音效。自动重置功能关闭时该项显示为关闭并置灰,保存的通知和音效选择不会被覆盖。
该设置只保存在当前 Mac,不通过 CloudKit 同步。
diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.md
index 48abf6d..16dc601 100644
--- a/Docs/UserGuide/sleep-prevention.md
+++ b/Docs/UserGuide/sleep-prevention.md
@@ -99,14 +99,15 @@ CodexBar 会同时阻止显示器睡眠,并定期声明用户活动以压住
## CodexBarHelper 授权
-防睡眠需要随 App 安装的 CodexBarHelper 修改系统级睡眠状态:
+防睡眠需要随 App 安装的 CodexBarHelper 修改系统级睡眠状态。自动重置也复用同一个后台服务注册和批准状态,用于设置固定的系统唤醒计划:
- 首次开启时由 macOS 注册后台服务
- 系统要求批准后台项目时,设置页会显示 `打开系统设置`
- CodexBarHelper 缺失或注册失败时不会执行防睡眠
- App 更新导致 CodexBarHelper 变化时会刷新注册并校验睡眠状态
-- App 正常退出前会先释放 CodexBarHelper 租约并恢复由 CodexBar 修改的状态
+- App 正常退出前会先取消自动重置唤醒计划、释放 CodexBarHelper 租约并恢复由 CodexBar 修改的状态
- CodexBarHelper 连接意外中断后会在宽限期结束时释放失联客户端租约
+- 自动重置使用独立连接;连接中断时会立即取消该连接拥有的唤醒计划
## 与其他防睡眠来源共存
diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.md
index aacb81e..458f201 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,13 +60,16 @@
| 同步缓存 | 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 |
+| 自动重置唤醒计划 | CodexBar 固定 owner、`wake` 类型和下一次时间 | macOS 系统电源管理,触发或取消后移除 |
+| App 偏好 | 开关、阈值、快捷键、自动重置提前量和通知去重状态 | macOS UserDefaults |
| app-server 交互日志 | 最近 500 条请求和响应 | 只存在当前 App 进程内存 |
每日聚合只在最近 3 天保留 session 和 turn ID 列表,更早日期转换为计数并删除列表。
CodexBarHelper 所有权文件由 root 持有,用于 App 或 CodexBarHelper 异常退出后的睡眠状态恢复。
+自动重置唤醒计划不包含账户、重置次数、`creditId` 或幂等键。CodexBarHelper 启动时会清理同一构建身份遗留的计划,App 也会在任务变化、功能关闭和正常退出时取消计划。
+
匿名任务不参与异常会话保护,因此不会生成哈希任务标识或写入保护状态文件。
## CloudKit 上传字段
@@ -91,7 +94,7 @@ CodexBarHelper 所有权文件由 root 持有,用于 App 或 CodexBarHelper
- 完整工作目录路径
- prompt、Codex 回复、工具参数或工具输出
- Codex 账户、额度和 Token 用量
-- 重置次数明细、自动使用设置和消费状态
+- 重置次数明细、自动重置设置和消费状态
- app-server 交互日志
- 异常会话保护记录
- Codex 认证 token
@@ -108,7 +111,7 @@ CodexBar 会读取以下本机数据:
rollout 读取只提取生命周期、时间和推理强度等字段,不展示或保存会话正文和工具内容。
-用户主动开启自动使用后,CodexBar 通过同一个本机 app-server 使用明确列出的临期重置次数。原始 `creditId` 和幂等键不写入磁盘或 CloudKit;`UserDefaults` 只保存功能开关、临期时间、自动使用通知开关、音效选择和哈希后的通知去重键。
+用户主动开启自动重置后,CodexBar 通过同一个本机 app-server 使用明确列出的临期重置次数。原始 `creditId` 和幂等键不写入磁盘或 CloudKit;`UserDefaults` 只保存功能开关、提前量、自动重置通知开关、音效选择和哈希后的通知去重键。
CodexBar 不复制或持久化 Codex 认证 token。
@@ -119,7 +122,7 @@ CodexBar 不复制或持久化 Codex 认证 token。
| Sparkle 更新源 | 检查并安装 CodexBar 更新 | 自动检查开启或用户手动检查时 |
| CloudKit private database | 同步多设备每日 Hook 聚合 | 用户开启跨设备同步时 |
-账户、额度、Token 用量、手动重置次数明细和用户开启的自动使用操作通过本机 app-server 的 stdio 通信完成。自动使用不会增加 CloudKit 请求,也不会使用 CodexBarHelper。
+账户、额度、Token 用量、手动重置次数明细和用户开启的自动重置操作通过本机 app-server 的 stdio 通信完成。自动重置不会增加 CloudKit 请求;自动重置只向 CodexBarHelper 提交固定系统唤醒计划的时间,不提交账户或重置次数数据。
## 日志隐私
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index c8aae22..c9cf60a 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -96,6 +96,24 @@ Hook 配置位于 `$CODEX_HOME/hooks.json`,未设置 `CODEX_HOME` 时位于 `~
- 如果提示服务异常或 CodexBarHelper 文件缺失,重新安装完整 CodexBar App
- 更新后持续失败时退出 CodexBar,重新打开并再次检查授权
+## 自动重置没有按时执行
+
+按以下顺序检查:
+
+1. `自动重置` 是否开启,提前量是否符合预期
+2. 自动重置设置行是否提示 CodexBarHelper 待批准、未注册或唤醒计划失败
+3. 当前 app-server 是否返回了具体的可用重置次数和过期时间
+4. 计划时间到达后,网络与 Codex 登录状态是否可用
+5. “自动重置通知”是否开启;通知关闭不会阻止自动重置本身执行
+
+自动重置只处理 app-server 最新响应明确列出的凭证。单轮网络或暂时服务故障最多连续重试 5 分钟,后续普通额度刷新仍会为仍然有效的凭证重新安排。
+
+关闭自动重置或退出 CodexBar 会取消当前唤醒计划。需要核对系统计划时,可在 Terminal 中执行:
+
+```bash
+pmset -g sched
+```
+
## 跨设备同步不可用
- 确认 Mac 已登录 iCloud
diff --git a/README.md b/README.md
index 83ce06d..b2cedc7 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@ CodexBar 是面向 macOS 15 及更高版本的菜单栏 App, 用于集中展示
- 展示当前 Codex 账户和套餐
- 展示全部额度窗口, 剩余比例和重置时间
- 展示可用积分和手动重置次数
-- 可设置在过期前 30 分钟到 12 小时自动使用临期重置, 默认提前 2 小时
+- 支持自动重置,可设置在手动重置次数过期前 15 分钟到 6 小时执行,默认提前 30 分钟;计划到点时可唤醒 Mac,并在执行前重新确认可用状态
- 可在菜单栏图标旁直接显示所选额度窗口
### 看见自己的 Codex 使用节奏
@@ -86,7 +86,7 @@ brew install --cask bob-zebedy/tap/codexbar
1. 启动 CodexBar, 在菜单栏找到 CodexBar 图标
2. 左键点击图标查看账户, 额度和 Token 用量
3. 右键或按住 Control 点击图标打开设置, 日志或退出菜单
-4. 在 `设置 > 高级` 中启用 CodexBar Hook, 解锁实时任务, 通知, 防睡眠和 Hook 统计
+4. 在 `设置 > 高级` 中启用 CodexBar Hook, 解锁实时任务, 任务类通知, 防睡眠和 Hook 统计
默认全局快捷键为 `⌘⇧W`, 可在设置中重新录制或关闭
diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swift
index f8e9f4b..3e5fbc0 100755
--- a/Scripts/cleanup.swift
+++ b/Scripts/cleanup.swift
@@ -3,8 +3,41 @@
import AppKit
import Darwin
import Foundation
+import IOKit
+import IOKit.pwr_mgt
import ServiceManagement
+@objc private protocol CleanupHelperProtocol: AnyObject {
+ func setAutoResetWakeSchedule(
+ _ unixTimestamp: TimeInterval,
+ reply: @escaping @Sendable (Int32) -> Void
+ )
+}
+
+private final class WakeScheduleCancellationState: @unchecked Sendable {
+ private let lock = NSLock()
+ private var isCompleted = false
+ private var errorMessage: String?
+
+ func complete(errorMessage: String?) -> Bool {
+ lock.lock()
+ defer { lock.unlock() }
+ guard !isCompleted else {
+ return false
+ }
+
+ isCompleted = true
+ self.errorMessage = errorMessage
+ return true
+ }
+
+ func completedErrorMessage() -> String? {
+ lock.lock()
+ defer { lock.unlock() }
+ return errorMessage
+ }
+}
+
private enum CleanupBuildConfiguration: String, CaseIterable {
case release = "Release"
case debug = "Debug"
@@ -357,10 +390,12 @@ private final class KeepAliveCleanupCommand {
}
try runChecked(destinationExecutableURL.path, ["--unregister-child", target.plistName])
- try runChecked(
- "/usr/bin/defaults",
- ["write", target.bundleIdentifier, "KeepAlive.isEnabled", "-bool", "false"]
- )
+ for key in ["KeepAlive.isEnabled", "AutoReset.enabled"] {
+ try runChecked(
+ "/usr/bin/defaults",
+ ["write", target.bundleIdentifier, key, "-bool", "false"]
+ )
+ }
_ = try run(
"/usr/bin/defaults",
["delete", target.bundleIdentifier, "KeepAlive.helperRegistrationFingerprint"],
@@ -500,6 +535,10 @@ private func runUnregisterChild(plistName: String) -> Never {
let service = SMAppService.daemon(plistName: plistName)
switch service.status {
case .enabled, .requiresApproval:
+ let serviceLabel = String(plistName.dropLast(".plist".count))
+ guard cancelAutoResetWakeScheduleBeforeUnregister(serviceLabel: serviceLabel) else {
+ Darwin.exit(EXIT_FAILURE)
+ }
service.unregister { error in
if let error {
FileHandle.standardError.write(
@@ -525,6 +564,84 @@ private func runUnregisterChild(plistName: String) -> Never {
}
}
+private func cancelAutoResetWakeScheduleBeforeUnregister(serviceLabel: String) -> Bool {
+ let owner = serviceLabel + ".auto-reset"
+ guard hasScheduledWakeEvent(owner: owner) else {
+ return true
+ }
+
+ let state = WakeScheduleCancellationState()
+ let semaphore = DispatchSemaphore(value: 0)
+ let connection = NSXPCConnection(machServiceName: serviceLabel, options: .privileged)
+ connection.remoteObjectInterface = NSXPCInterface(with: CleanupHelperProtocol.self)
+ let finish: @Sendable (String?) -> Void = { errorMessage in
+ if state.complete(errorMessage: errorMessage) {
+ semaphore.signal()
+ }
+ }
+ connection.interruptionHandler = {
+ finish("连接中断")
+ }
+ connection.invalidationHandler = {
+ finish("连接失效")
+ }
+ connection.resume()
+
+ let errorHandler: @Sendable (Error) -> Void = { error in
+ finish(error.localizedDescription)
+ }
+ guard let helper = connection.remoteObjectProxyWithErrorHandler(errorHandler)
+ as? CleanupHelperProtocol else {
+ connection.invalidate()
+ reportWakeScheduleCancellationFailure(owner: owner, detail: "服务接口无效")
+ return false
+ }
+
+ helper.setAutoResetWakeSchedule(0) { exitCode in
+ finish(exitCode == 0 ? nil : "code=\(exitCode)")
+ }
+ let waitResult = semaphore.wait(timeout: .now() + 10)
+ connection.invalidationHandler = nil
+ connection.interruptionHandler = nil
+ connection.invalidate()
+
+ let errorMessage = waitResult == .timedOut
+ ? "请求超时"
+ : state.completedErrorMessage()
+ guard !hasScheduledWakeEvent(owner: owner) else {
+ reportWakeScheduleCancellationFailure(
+ owner: owner,
+ detail: errorMessage ?? "系统回读仍存在事件"
+ )
+ return false
+ }
+
+ print("自动重置唤醒计划已取消: owner=\(owner)")
+ return true
+}
+
+private func hasScheduledWakeEvent(owner: String) -> Bool {
+ guard let events = IOPMCopyScheduledPowerEvents()?.takeRetainedValue() else {
+ return false
+ }
+
+ return (events as NSArray).contains { value in
+ guard let event = value as? NSDictionary else {
+ return false
+ }
+ return event[kIOPMPowerEventAppNameKey] as? String == owner
+ && event[kIOPMPowerEventTypeKey] as? String == kIOPMAutoWake
+ }
+}
+
+private func reportWakeScheduleCancellationFailure(owner: String, detail: String) {
+ FileHandle.standardError.write(
+ Data(
+ "自动重置唤醒计划取消失败, 已停止注销: owner=\(owner), detail=\(detail)\n".utf8
+ )
+ )
+}
+
let arguments = Array(CommandLine.arguments.dropFirst())
if arguments.first == "--unregister-child" {
guard arguments.count == 2 else {
diff --git a/Shared/CodexBarHelperXPC.swift b/Shared/CodexBarHelperXPC.swift
index 015bb46..909c3ad 100644
--- a/Shared/CodexBarHelperXPC.swift
+++ b/Shared/CodexBarHelperXPC.swift
@@ -54,4 +54,10 @@ nonisolated enum CodexBarSleepOwnershipState: Int, Sendable {
_ updateIdentifier: String,
reply: @escaping @Sendable (Int32) -> Void
)
+
+ /// 时间戳为 0 时取消 CodexBar 自己的重置次数唤醒计划
+ func setAutoResetWakeSchedule(
+ _ unixTimestamp: TimeInterval,
+ reply: @escaping @Sendable (Int32) -> Void
+ )
}
diff --git a/appcast.xml b/appcast.xml
index 15ef197..accde21 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.3</title>
+ <sparkle:version>70</sparkle:version>
+ <sparkle:shortVersionString>3.6.3</sparkle:shortVersionString>
+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>
+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.6.3</sparkle:releaseNotesLink>
+ <pubDate>Thu, 13 Aug 2026 10:22:03 +0800</pubDate>
+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.6.3.dmg" sparkle:edSignature="l73u49ZGsCqVuQqa8s1B6McU7mniIxdsEjWaZmcF3tKk/FWnhxAAYORc6MjbUT9cygVMSkoCvYj61nIiWbRVDg==" length="7115983" type="application/octet-stream"/>
+ </item>
<item>
<title>CodexBar.app 3.6.2</title>
<sparkle:version>69</sparkle:version>