CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 新增等待批准保持与屏幕常亮选项
Bob5d0c86b3dbfa
diff --git a/AGENTS.md b/AGENTS.mdindex abe3ab4..e74aa56 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -33,11 +33,11 @@ CodexBar 是面向 macOS 15+ 的 `LSUIElement` 菜单栏应用, 使用 Swift 6,工程默认采用 `MainActor` 隔离. UI, Controller, ViewModel 和 Settings 依赖默认隔离, 共享可变状态放入 actor, DTO 和跨 actor 值类型按需添加 `nonisolated` 标记, 禁止在主 actor 执行阻塞 I/O. 类型命名使用 `UpperCamelCase` 风格, 成员命名使用 `lowerCamelCase` 风格. 注释只解释非显然的生命周期, 焦点, actor 或系统 API 约束-保持三条数据链路独立: app-server 额度与用量, Hook 历史聚合, `CodexActivityMonitor` 实时任务; helper 只能控制休眠, 不得增加网络, 任意命令执行或额外文件访问; 修改 Hook 配置时必须保留用户和其他应用已有的 handler; 新增网络访问, 日志数据或 CloudKit 字段前先核对隐私边界+保持三条数据链路独立: app-server 额度与用量, Hook 历史聚合, `CodexActivityMonitor` 实时任务; helper 只能控制睡眠, 不得增加网络, 任意命令执行或额外文件访问; 修改 Hook 配置时必须保留用户和其他应用已有的 handler; 新增网络访问, 日志数据或 CloudKit 字段前先核对隐私边界## 测试规范-仓库没有 XCTest target 或覆盖率门槛. 每次改动至少应完成构建, 运行 `swiftformat` 和 `swiftlint` 两项检查, 并手动验证受影响流程. 菜单, 窗口焦点, Hook, 同步, 通知和防休眠改动必须说明手动验证场景. Debug 与 Release 使用不同 App 和 helper bundle ID, 排查时不要混用+仓库没有 XCTest target 或覆盖率门槛. 每次改动至少应完成构建, 运行 `swiftformat` 和 `swiftlint` 两项检查, 并手动验证受影响流程. 菜单, 窗口焦点, Hook, 同步, 通知和防睡眠改动必须说明手动验证场景. Debug 与 Release 使用不同 App 和 helper bundle ID, 排查时不要混用## Commit 与 Pull Request 规范diff --git a/CLAUDE.md b/CLAUDE.mdindex 80d3960..a7cb6a6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -53,7 +53,7 @@ Scripts/appcast.sh # sign_update 签名并写入 appcast.xmlScripts/cleanup.swift --help```-日常调试直接 `open CodexBar.xcodeproj` 用 Xcode 跑 Debug scheme; 注意 Debug 产物用的是 `app.zabrian.codexbar.debug` 这个 bundle ID, 与 Release 安装版可以共存, 排查防休眠问题时要确认自己看的是哪一套 helper+日常调试直接 `open CodexBar.xcodeproj` 用 Xcode 跑 Debug scheme; 注意 Debug 产物用的是 `app.zabrian.codexbar.debug` 这个 bundle ID, 与 Release 安装版可以共存, 排查防睡眠问题时要确认自己看的是哪一套 helper`Scripts/build.sh` 会先清空 `build/` 目录, 成功后只留最终产物 `.app` 文件; 凭据推荐用 keychain profile, 先跑一次 `xcrun notarytool store-credentials "codexbar-notary" --apple-id "<Apple ID>" --team-id "<Team ID>"` 存好, 之后构建加上 `--notary-profile codexbar-notary`@@ -111,19 +111,19 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev**链路三: 实时任务, 由 `CodexActivityMonitor` 驱动**-`CodexActivityMonitor` 是菜单栏图标, 活动卡片, 通知, 触觉反馈和防休眠的**唯一任务状态来源**, 由两个 reader 供料+`CodexActivityMonitor` 是菜单栏图标, 活动卡片, 通知, 触觉反馈和防睡眠的**唯一任务状态来源**, 由两个 reader 供料- `HookEventTailReader` (actor) 的 bootstrap 覆盖滚动 24 小时并作为单次事务发送, 之后按当日文件 offset 增量 tail- `CodexSessionLifecycleReader` (actor) 增量读取 `~/.codex/sessions` 与 `archived_sessions` 下的 rollout JSONL, 只提取 turn 生命周期字段, 不解码会话或工具内容系统唤醒时 `NSWorkspace.didWakeNotification` 会触发立即 drain 并重置生命周期解析回退-### 防休眠 (KeepAlive) 与 root helper+### 防睡眠 (KeepAlive) 与 root helper两套机制叠加, 职责不同-- `SystemSleepService` 用进程内 `IOPMAssertion` 建立 `PreventUserIdleSystemSleep` 断言, 只挡空闲休眠, 不需要提权; 断言名必须是 ASCII, 否则 `pmset -g assertions` 显示不出标识-- `CodexBarHelper` 是 root LaunchDaemon, 通过 XPC 接受 `setSleepDisabled` 请求, 执行 `/usr/bin/pmset -a disablesleep` 覆盖合盖休眠+- `SystemSleepService` 用进程内 `IOPMAssertion` 建立 `PreventUserIdleSystemSleep` 断言, 只挡空闲睡眠, 不需要提权; 断言名必须是 ASCII, 否则 `pmset -g assertions` 显示不出标识+- `CodexBarHelper` 是 root LaunchDaemon, 通过 XPC 接受 `setSleepDisabled` 请求, 执行 `/usr/bin/pmset -a disablesleep` 覆盖合盖睡眠链路: `KeepAliveController` (MainActor) 订阅 `activityMonitor.$snapshot` 与 `codexHookSettings.$isEnabled` -> `SMAppService.daemon(plistName:)` 注册 -> `NSXPCConnection` -> helper@@ -137,21 +137,24 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- helper 只做一件事; 不要给 root helper 增加网络, 任意命令执行或其他文件访问能力- 调用方校验由 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/<machService>.state` 这个路径, **必须保持 `absent` `present` `unreadable` 三态**, 把读取失败折叠成 nil 会让恢复流程以为无需恢复, 使 `SleepDisabled=1` 永久残留; watchdog 宽限 15 秒, 哨兵自检 60 秒一次-- 切换失败按 2/4/8...256 秒重试, 列表耗尽 (约 8.5 分钟) 即放弃, 瞬时抖动能自愈, 权限类故障不该无限重试+- 切换失败按 2/4/8...256 秒重试, 列表耗尽即放弃 (延时累计约 8.5 分钟, 每轮再等一次超时约 10 分钟), 瞬时抖动能自愈, 权限类故障不该无限重试+- XPC 请求带超时并汇进同一条重试路径; launchd 拉不起 helper 时 `setSleepDisabled` 既不回复也不触发 errorHandler, 没有它界面会显示防睡眠开着而实际没生效, 日志里只剩没有配对回复的 `Helper XPC 请求已发送`+- 超时取值放在 `CodexBarHelperIPC.requestTimeoutSeconds` 而不是控制器里, 它与 `watchdogGraceSeconds` 是一对: 必须更小, App 先放手 helper 才能靠 watchdog 兜底, 分处两个 module 会让人改了一边不知道另一边+- 开发期间用 `xcodebuild` 覆盖正在运行的 App bundle 会让 launchd 记的 daemon 与磁盘上的 helper 对不上, helper 从此拉不起来; 重启 App 会由 `helperRegistrationNeedsRefresh` 的指纹比对自愈, 排查时先看这一条- helper 回传的 `restoredSleepDisabled` 只有 `.present` 分支是实测值, `.absent` (本轮没接管过) 与 pmset 失败时都是占位的 `true`; App 侧靠 `canTrustRestoreResult` (接管到恢复之间连接未断) 判断可不可信, 这是从未接管的一轮里不误发 `IOPMSleepSystem` 的唯一屏障, 不要把 `.absent` 改成回实测值- 低电量保护由 `PowerSourceMonitor` 供数, 它只报事实 (有没有内置电池, 电量, 是否靠电池供电), 不知道阈值; 读数保持 `unavailable` `unreadable` `present` 三态, 把读取失败折叠成"没有电池"会让设置项凭空消失且保护静默失效- 见过一次内置电池就记住 `hasSeenBattery`, 之后读到空列表只能返回 `unreadable`; 硬件不会中途消失, 空列表只是 IOKit 重新枚举时的缺口, 当成台式机会当场撤掉保护- `hasSeenBattery` 只活在进程内不持久化, 每次启动重新判定; 笔记本启动时撞上枚举缺口会短暂显示成没有电池, 由下一次电源通知自愈, 而持久化会让从笔记本备份恢复的台式机永远多出低电量设置项-- `IOPSNotificationCreateRunLoopSource` 注册失败时降级成 60 秒轮询并记 `action=poll`; 只靠 `didWakeNotification` 补读不够, 防休眠生效的机器按定义就不会睡, 那条通知永远不来+- `IOPSNotificationCreateRunLoopSource` 注册失败时降级成 60 秒轮询并记 `action=poll`; 只靠 `didWakeNotification` 补读不够, 防睡眠生效的机器按定义就不会睡, 那条通知永远不来- 首次读取在 `start()` 里单独判一次并记 `stage=start` 这条, 不能改走 `refresh()` 那条路: 后者按变化过滤, 而读数初始值就是 `unreadable` 本身, 首读失败会被静默吞掉, 之后只留下一条没有配对失败行的恢复日志-- 防休眠上限累计的是**真正挡住休眠**的那段时间, `begin` 起表 `pause` 收表, 收表之后机器睡着或被低电量拦下都不占用户的上限+- 防睡眠上限累计的是**真正挡住睡眠**的那段时间, `begin` 起表 `pause` 收表, 收表之后机器睡着或被低电量拦下都不占用户的上限- 上限计时用 `SuspendingClock` 而不是 `Date`, 后者受系统时间调整影响且系统睡眠期间照走; 排计时器的 `Task.sleep` 同样要传 `SuspendingClock`, 否则睡一夜醒来会当场判定到期-- 低电量是**纯条件**判定, 不设"低过电"的粘滞标志: 电量会回升, 充上电就该自动恢复防休眠; `hasReachedMaximumDuration` 之所以是粘滞标志只因为累计只增不减, 两者不要照抄+- 低电量是**纯条件**判定, 不设"低过电"的粘滞标志: 电量会回升, 充上电就该自动恢复防睡眠; `hasReachedMaximumDuration` 之所以是粘滞标志只因为累计只增不减, 两者不要照抄- 低电量必须同时满足在用电池与电量低于阈值, 只看百分比会让"剩 5% 插上电再跑任务"当场被判低电量; 判定用 `Power Source State`, 不能用 `Is Charging` (接电停充时它也是 false)-- 电量读不到时维持上一次的判定, 从没读到过就是不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制休眠兜底-- 已经在低电量保护中时读数失败不清零, 否则一次瞬时失败会绕过滞回, 让防休眠反复开关并重发通知-- 低电量通知只在 `isActivelyPreventingSleep` 为真时排队, 没挡过就不说"已恢复系统休眠"; 日志无条件记并用 `action=release|none` 区分, 百分比只有那一条能看到-- 排队的通知要等 helper 恢复休眠的 XPC 回复确认成功才发得出去, 恢复失败走重试直至放弃, 提前说"已恢复系统休眠"会把用户骗去合盖然后把电耗干+- 电量读不到时维持上一次的判定, 从没读到过就是不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制睡眠兜底+- 已经在低电量保护中时读数失败不清零, 否则一次瞬时失败会绕过滞回, 让防睡眠反复开关并重发通知+- 低电量通知只在 `isActivelyPreventingSleep` 为真时排队, 没挡过就不说"已恢复系统睡眠"; 日志无条件记并用 `action=release|none` 区分, 百分比只有那一条能看到+- 排队的通知要等 helper 恢复睡眠的 XPC 回复确认成功才发得出去, 恢复失败走重试直至放弃, 提前说"已恢复系统睡眠"会把用户骗去合盖然后把电耗干- 补发 `IOPMSleepSystem` 之前还要 `await` 到通知真的提交完成, 只把提交排进下一个 MainActor job 的话同一个 job 里的补发会抢在它前面- 那次 `await` 之后要重认一次 `generation` 再走 `finishSleepRestore` 这一步, 挂起期间可能已有新的禁用请求接管, 否则会释放掉刚建立的空闲断言- 设置页那句低电量说明看 `isLowBatteryBlocking` 而不是 `isLowBatteryActive`, 后者在没有任务时也成立, 那时无话可说@@ -162,8 +165,12 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- `SleepConditions` 里只放 `battery` 布尔, 放电量百分比会让每掉 1% 刷一条变化日志; 真实电量只在触发那一条单独记- 状态只呈现在主面板活动卡片右侧的咖啡杯标记 (带 tooltip), 由 `KeepAliveController.isActivelyPreventingSleep` 驱动, 卡片折叠成"暂无数据"时标记要跟着一起收- 设置页那一行说明只在异常, 低电量生效或达到上限时出现, 正常运行时整行收起, `keepAliveCaption` 返回 nil 即代表收起-- 最长防休眠时间与低电量阈值都在防休眠子面板里, 台式机读不到电池时低电量那一行整行隐藏而不是置灰-- **菜单栏图标不承载防休眠状态**, 它要保持模板渲染让系统按菜单栏外观着色, 自行着色在深浅和带染色的菜单栏下都会失控+- 最长防睡眠时间与低电量阈值都在防睡眠子面板里, 台式机读不到电池时低电量那一行整行隐藏而不是置灰+- 保持屏幕常亮跟 `isActivelyPreventingSleep` 走, 由 `reconcileDisplayAwake` 单点切换, 于是低电量拦下, 达到上限, 任务结束时屏幕都跟着放开+- 显示断言只保证屏幕不睡, 屏保与闲置锁屏跟的是系统 idle 计时, 要靠 30 秒一次的 `IOPMAssertionDeclareUserActivity` 压住, 两者缺一不可+- 声明用户活动复用同一个 assertion ID, 每次传 null 会新建一条, `pmset -g assertions` 里会堆成一串同名断言+- 逐次声明不记日志, 建立与释放各一条就够还原状态; 两条断言都是进程级的, App 退出或崩溃时系统自动收回, 不经过 helper+- **菜单栏图标不承载防睡眠状态**, 它要保持模板渲染让系统按菜单栏外观着色, 自行着色在深浅和带染色的菜单栏下都会失控### 通知@@ -171,10 +178,10 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- `send` 是唯一的提交入口, 返回一个 `Task<Bool, Never>?` 值, 需要等通知真的发出去再做下一步的调用方 `await` 它的 `value` 即可; 不要另开一条 async 通道, 那会悄悄少掉去重 时效判定与提交失败回调三项能力- 去重判定留在 `send` 的同步段而不是挪进 `Task` 内部, 这样连续两次调用的第二次一定被挡下, 不依赖任务调度顺序- `NotificationSettings` 管 CodexBar 自身通知; `CodexCLINotificationSettings` 是另一回事, 它通过 app-server `config/read` 与 `config/batchWrite` 读写 Codex 自己的用户级 `config.toml`-- 通知面板里带依赖的行一律显示为关闭并置灰而不是隐藏, 任务类看 `codexHookSettings.isOperable`, 低电量保护通知看 `KeepAliveController.isLowBatteryProtectionEnabled` (防休眠可用, 阈值开着, 且这台机器确实有电池), 防休眠上限通知看 `KeepAliveController.isMaximumDurationEnabled` (防休眠可用且不是无限制); 都不回写用户保存的开关-- 两条防休眠通知的依赖里都含"防休眠可用"这一层, 即防休眠开关与 Hook 都开着, 判定收在 `publishNotificationDependencies` 一处; 只判各自的子设置会让防休眠关着时这两行还亮着+- 通知面板里带依赖的行一律显示为关闭并置灰而不是隐藏, 任务类看 `codexHookSettings.isOperable`, 低电量保护通知看 `KeepAliveController.isLowBatteryProtectionEnabled` (防睡眠可用, 阈值开着, 且这台机器确实有电池), 防睡眠上限通知看 `KeepAliveController.isMaximumDurationEnabled` (防睡眠可用且不是无限制); 都不回写用户保存的开关+- 两条防睡眠通知的依赖里都含"防睡眠可用"这一层, 即防睡眠开关与 Hook 都开着, 判定收在 `publishNotificationDependencies` 一处; 只判各自的子设置会让防睡眠关着时这两行还亮着- 带依赖的行由 `KeepAliveController` 判定并派生成一个值, 视图只读结论, 不在各视图各写一遍 `!= .unlimited` 这类规则-- 防休眠上限通知与低电量通知共用同一个发送时机; 达到上限是粘滞状态, 一个计时周期只发一次, 不需要低电量那种本轮已通知的锁存+- 防睡眠上限通知与低电量通知共用同一个发送时机; 达到上限是粘滞状态, 一个计时周期只发一次, 不需要低电量那种本轮已通知的锁存### 并发与隔离@@ -200,8 +207,8 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 文案骨架是 `<主体><动作>: 字段=值; 字段=值`, 标题只说发生了什么, 理由进 `reason=`, 处置进 `action=`; 起止用 `开始` `完成` `失败`, 中间状态用 `已<动作>`- 字段顺序固定为 标识 (`trigger` `generation` `date`) 输入 结果 `elapsed` `reason`/`detail`; 公共字段有 `trigger` `result` `reason` `action` `detail` `code` (系统返回码) `exit` (进程退出码) `elapsed`, 其中 `code` 与 `exit` 必须分开, 不要用一个 `error=` 同时装 OSStatus IOReturn 和退出码- 文案只描述事实, 不写"用户做了什么"这类主语, 也不写推论; 字段值要可 grep, 用枚举 rawValue 而不是中文句子, App 与 helper 两侧保持同一套格式-- 词根固定, 一个词能 grep 出整条链路: 额度, 统计刷新 (调度层), 事件汇总 (计算层), 同步, KeepAlive (防休眠决策层), 空闲断言 (进程内 `IOPMAssertion`), Helper 注册 (`SMAppService`), Helper XPC (`NSXPCConnection`), 系统休眠 (helper 的 pmset 效果), 电源监听 (`PowerSourceMonitor`), 任务, Hook, codex, 通知-- 防休眠日志按两套机制分组: `KeepAlive` 是两套共用的决策层, `空闲断言` 是机制一, `Helper 注册` `Helper XPC` `系统休眠` 是机制二的授权 传输 效果三层, 故障定位就是在这几层里找+- 词根固定, 一个词能 grep 出整条链路: 额度, 统计刷新 (调度层), 事件汇总 (计算层), 同步, KeepAlive (防睡眠决策层), 空闲断言 (进程内 `IOPMAssertion`), 显示断言 (屏幕常亮那条 `IOPMAssertion`), Helper 注册 (`SMAppService`), Helper XPC (`NSXPCConnection`), 系统睡眠 (helper 的 pmset 效果), 电源监听 (`PowerSourceMonitor`), 任务, Hook, codex, 通知+- 防睡眠日志按两套机制分组: `KeepAlive` 是两套共用的决策层, `空闲断言` 与 `显示断言` 是机制一, `Helper 注册` `Helper XPC` `系统睡眠` 是机制二的授权 传输 效果三层, 故障定位就是在这几层里找- `trigger=` 由 `LogTrigger` 提供, 从 UI 入口透传到服务层, 用来区分同一条链路是被用户动作 定时轮询还是系统事件踢起来的; 统计维护挂在额度刷新完成事件上, 它的 trigger 继承那一次刷新- 变化检测类日志只在值真的变了才记, 例如 `KeepAlive 条件已变化` 与 `Hook 配置已变化` 各自存一份上次的值, 否则每次开面板都会刷一条- 设置项的变更日志照抄设置页那一行的标题, 例如 `菜单栏额度指示变更` `开机自动启动变更`, 用户说"我改了那个开关"时能直接对上; 只有本身带完整链路的才用链路词根, 例如 Hook 同步 通知 KeepAlive 快捷键@@ -217,21 +224,24 @@ 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` 再加 `KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled` 两条, 防休眠面板只订 `$hasBattery` 一条; 订整个防休眠控制器会让任务每起停一次都白排一轮 resize+- 两个子面板的高度都会变, 通知面板随音效行增删, 防睡眠面板随 `hasBattery` 增删低电量那一行; resize 时要固定顶边向下生长, 直接改 size 会保持底边不动而把顶边顶离主开关行+- 高度重算只订阅真正会改变行数的那几项, 通知面板订 `notificationSettings` 与 `codexHookSettings` 的 `objectWillChange` 再加 `KeepAliveController.$isLowBatteryProtectionEnabled` 与 `$isMaximumDurationEnabled` 两条, 防睡眠面板只订 `$hasBattery` 一条; 订整个防睡眠控制器会让任务每起停一次都白排一轮 resize- 置灰也会改高度: 带音效的行置灰时音效子行跟着收起, 所以每个置灰依赖都要有一个对应的订阅源- 增删行或改行的显示条件时要同步补上对应的订阅源, 漏一项会让面板裁掉底部或留下空白- resize 的竖向夹紧走 `SidePanelSupport.clampedVertically`, 与初次展开的 `position` 同一条规则, 否则放不下时两边会把面板推向相反的边-- 子面板入口只在开关开着且依赖就绪时出现, 通知看 `NotificationSettings.canShowOptions` 那个值, 防休眠看 `KeepAliveController.canShowOptions` 这个值; 两者都只控制入口显隐, 不回写用户保存的开关+- 子面板入口只在开关开着且依赖就绪时出现, 通知看 `NotificationSettings.canShowOptions` 那个值, 防睡眠看 `KeepAliveController.canShowOptions` 这个值; 两者都只控制入口显隐, 不回写用户保存的开关- 两个子面板都只由滑杆按钮展开, 动作只有 toggle 与 close 两种, 开启主开关不自动弹出- 侧边面板公共能力集中在 `Controllers/SidePanelSupport.swift` 里, 含 `SidePanelDrawerPresenter` `SidePanelContentHost` `SidePanelDrawerAnimator` panel 工厂和定位夹紧; 挂在主面板上的那三个面板优先复用 `SidePanelDrawerPresenter` 这一层, 不要另起一套- 设置窗口的子面板直接复用 `Controllers/SettingsOptionsPanelController.swift`, 它在 presenter 之上补齐了装配, 两套关闭观察者, 顶边对齐定位和高度重算; 新增设置子面板只要给它内容工厂与内容变化来源, 不要再写一层壳- 两个设置子面板的行高与间距从 `SettingsOptionsPanelMetrics` 取, 下拉控件共用 `SettingsOptionsPicker` 这一个, 只有面板宽度和 picker 宽度各自定义, 这样两个面板看起来才是同一套控件+- 设置子面板的内容工厂必须走 `SettingsOptionsPanelController.makeContentController(_:rebuiltBy:)`, 否则首次展开时原生 Switch 只剩一条空轨道; 重建信号由它接在内容外面, 内容视图不必知道 `SidePanelEntryCue`+- 原因是 thumb 由 `WindowPortal` 投射而不是画在开关上, 面板首次布局那一轮 portal 建不起来, 而且不会自愈, 只有一次内容重建才补得上; 第二次展开正常是因为 hosting controller 常驻, 复用了已经建好的那份+- 不要再用 `@_optimize(none)` 规避这个漏绘: 它当年在通知子面板管用只是因为逼着 body 重算时判定那些行变过, 与优化等级无关, 换个写法就失效; `SidePanelSupport` 里剩下那一处标注规避的是编译器崩溃, 与此无关- 主面板任务中心的显隐由 `MainPanelSettings.showsTaskCenter` 与 `codexHookSettings.isEnabled` 共同决定, Hook 未开启时设置页那一行显示为关闭并置灰, 不回写用户保存的开关值- 设置窗口 (通用/高级/关于三页) 和日志窗口复用 `HostingWindowController` 的行为, 可以成为 key window, 但不应成为 main window- 视觉风格统一走 `Views/Shared/LiquidGlassStyle.swift` 这一套, 避免引入与系统菜单栏工具不一致的重装饰 UI@@ -246,7 +256,7 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- `isEnabled` 只表示 `hooks.json` 里装着, `isVerified` 是最近一次校验的明确结论, 两者与出来的 `isOperable` 才是"事件真的送得过来"; 依赖 Hook 的下游一律看 `isOperable`- `isVerified` 乐观默认为 true 且只由明确结论写入两个方向: 校验只在设置窗口打开与 App 激活时跑, 而 RPC 失败属于"验不了"不是"确认不通", 那时置灰会把好用的功能关掉- 全局禁用要排在 `hooks/list` 之前判: 它一关列表里必然找不到我们的 handler, 那时报"已不完整"会把用户引去翻本来就完好的 `hooks.json`-- 校验不通过时防休眠那一行的说明写"CodexBar Hook 未生效"而不是"需要启用 CodexBar Hook", 后者会让用户去开一个已经开着的开关; 具体病因由 Hook 那一行自己的说明给出+- 校验不通过时防睡眠那一行的说明写"CodexBar Hook 未生效"而不是"需要启用 CodexBar Hook", 后者会让用户去开一个已经开着的开关; 具体病因由 Hook 那一行自己的说明给出## 隐私与数据边界@@ -266,5 +276,5 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- **任何兼容性问题都必须主动询问用户, 不要自行决定**; 只要改动会影响新旧共存就适用, 不限于旧数据迁移或丢弃, 持久化 key 改名或改结构, 老版本升上来的降级路径, 最低系统版本与 API 可用性取舍, 云端记录格式变更; 先说清影响面和几种做法的代价, 等用户选定再动手- 处理窗口, 菜单, 快捷键, App 激活或事件监听时, 特别注意 `LSUIElement` 应用特有的焦点行为- 注释保持克制, 只解释非显然的生命周期, 焦点, actor 或系统 API 约束; 现有注释多为解释为什么的类型, 沿用同样风格-- 改动涉及菜单面板, 窗口焦点, Hook, 同步, 通知或防休眠时, 构建通过之外还要说明应手动覆盖的交互场景; 防休眠额外要验证 App 包内 helper 与 plist 位置, 签名, 首次系统授权, 运行/等待切换和异常退出后的恢复+- 改动涉及菜单面板, 窗口焦点, Hook, 同步, 通知或防睡眠时, 构建通过之外还要说明应手动覆盖的交互场景; 防睡眠额外要验证 App 包内 helper 与 plist 位置, 签名, 首次系统授权, 运行/等待切换和异常退出后的恢复- 不要把发布产物, DerivedData, 临时 DMG, 签名文件或个人凭据提交进仓库diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 97ab887..949c824 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -424,7 +424,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 63;+ CURRENT_PROJECT_VERSION = 64;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -441,7 +441,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.9;+ MARKETING_VERSION = 3.5.10;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;@@ -464,7 +464,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 63;+ CURRENT_PROJECT_VERSION = 64;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -481,7 +481,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.5.9;+ MARKETING_VERSION = 3.5.10;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Controllers/SettingsOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swiftindex 96b8b35..1562a5c 100644--- a/CodexBar/Controllers/SettingsOptionsPanelController.swift+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift@@ -17,8 +17,30 @@ enum SettingsOptionsPanelAction {case closeAll}+/// 子面板入场时的内容重建信号, 由 makeContentController 接进内容视图, 面板自己不必知道+/// 原生 Switch 的 thumb 由 WindowPortal 投射, 面板首次布局那一轮建不起来也不会自愈, 只有重建补得上+/// bump 排在 present 之后, 那时入场动画已经把内容 translation 到可视区外, 重建才看不见+@MainActor+final class SidePanelEntryCue: ObservableObject {+ @Published private(set) var pass = 0++ func bump() {+ pass += 1+ }+}++/// 把重建信号接到内容外面, 于是内容视图不必为这个宿主层的问题多带一个属性+private struct SidePanelEntryRebuildHost<Content: View>: View {+ @ObservedObject var cue: SidePanelEntryCue+ let content: Content++ var body: some View {+ content.id(cue.pass)+ }+}+/// 设置窗口右侧子选项面板的公共装配-/// 通知与防休眠两个子面板只差内容视图和高度变化的来源, 定位 关闭 高度重算这套脚手架全在这里+/// 通知与防睡眠两个子面板只差内容视图和高度变化的来源, 定位 关闭 高度重算这套脚手架全在这里/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView@MainActorfinal class SettingsOptionsPanelController {@@ -26,7 +48,8 @@ final class SettingsOptionsPanelController {private let initialPanelSize: CGSize/// 展开前的准备动作, 例如刷新只在这个面板里露面的设置项private let willShow: (() -> Void)?- private let contentControllerProvider: () -> NSViewController+ private let contentControllerProvider: (SidePanelEntryCue) -> NSViewController+ private let entryCue = SidePanelEntryCue()private var panel: NSPanel?private var hostingController: NSViewController?@@ -49,7 +72,7 @@ final class SettingsOptionsPanelController {animationKey: String,initialPanelSize: CGSize,willShow: (() -> Void)? = nil,- contentControllerProvider: @escaping () -> NSViewController,+ contentControllerProvider: @escaping (SidePanelEntryCue) -> NSViewController,contentChanges: AnyPublisher<Void, Never>) {self.animationKey = animationKey@@ -67,8 +90,14 @@ final class SettingsOptionsPanelController {}/// sizingOptions 必须是 preferredContentSize: 面板的高度重算靠的就是它提交的 fitting size- static func makeContentController(_ content: some View) -> NSViewController {- let controller = NSHostingController(rootView: content)+ /// 入场重建也在这里接上, 新增子面板照抄这一句即可, 内容视图不必知道 cue 的存在+ static func makeContentController(+ _ content: some View,+ rebuiltBy cue: SidePanelEntryCue+ ) -> NSViewController {+ let controller = NSHostingController(+ rootView: SidePanelEntryRebuildHost(cue: cue, content: content)+ )controller.sizingOptions = [.preferredContentSize]return controller}@@ -135,6 +164,8 @@ final class SettingsOptionsPanelController {}willShow?()+ // 只有刚构造出来的那一次需要重建, hosting controller 之后常驻, portal 已经建好+ let needsEntryRebuild = panel == nillet panel = ensurePanel()// 这里不必先布局: 下面 measuredPanelSize 走的 validFittingSize 第一句就是 layoutSubtreeIfNeeded,// 而中间两句只碰设置窗口那棵树, 不会把面板弄脏@@ -169,6 +200,10 @@ final class SettingsOptionsPanelController {isEntryAnimationRunning = falsescheduleResize()}+ // 排在 present 之后: 入场动画先把内容 translation 到可视区外, 这一次重建落在那段里, 看不见+ if needsEntryRebuild {+ entryCue.bump()+ }}private func ensurePanel() -> NSPanel {@@ -181,7 +216,7 @@ final class SettingsOptionsPanelController {ignoresMouseEvents: false,keyable: true)- let hostingController = contentControllerProvider()+ let hostingController = contentControllerProvider(entryCue)panel.contentViewController = hostingControllerSidePanelSupport.configureLayers(hostingView: hostingController.view,diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex bd8751e..c8c1dc6 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -153,19 +153,20 @@ final class SettingsWindowController: HostingWindowController {willShow: { [codexCLINotificationSettings] incodexCLINotificationSettings.refresh()},- contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, keepAliveController] in+ contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, keepAliveController] entryCue inSettingsOptionsPanelController.makeContentController(NotificationOptionsView(notificationSettings: notificationSettings,codexHookSettings: codexHookSettings,codexCLINotificationSettings: codexCLINotificationSettings,keepAliveController: keepAliveController- )+ ),+ rebuiltBy: entryCue)},// 音效子行随各开关增删, 低电量与上限那两行还跟着各自的依赖置灰// 置灰会连带收起音效子行, 所以两个依赖的派生值都要订上- // 防休眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度+ // 防睡眠只订这两个派生值: 订整个控制器会让任务每起停一次都白重算一次高度contentChanges: Publishers.MergeMany([notificationSettings.objectWillChange.eraseToAnyPublisher(),codexHookSettings.objectWillChange.eraseToAnyPublisher(),@@ -181,12 +182,13 @@ final class SettingsWindowController: HostingWindowController {SettingsOptionsPanelController(animationKey: "CodexBar.keepAliveOptionsDrawerTransform",initialPanelSize: KeepAliveOptionsView.initialPanelSize,- contentControllerProvider: { [keepAliveController] in+ contentControllerProvider: { [keepAliveController] entryCue inSettingsOptionsPanelController.makeContentController(- KeepAliveOptionsView(keepAliveController: keepAliveController)+ KeepAliveOptionsView(keepAliveController: keepAliveController),+ rebuiltBy: entryCue)},- // 面板里只有 hasBattery 会增删行, 两个 picker 的取值不改高度+ // 面板里只有 hasBattery 会增删行, 其余各行的取值不改高度contentChanges: keepAliveController.$hasBattery.map { _ in () }.eraseToAnyPublisher()diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 26bd88e..58e5e66 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -89,13 +89,15 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let keepAlive = keepAliveController.isEnabled ? 1 : 0let keepAliveLimit = keepAliveController.maximumDuration.loggedHourslet keepAliveBattery = keepAliveController.lowBatteryThreshold.rawValue+ let keepAliveWaiting = keepAliveController.keepsAwakeWhileWaiting ? 1 : 0+ let keepAliveDisplay = keepAliveController.keepsDisplayAwake ? 1 : 0let sync = syncSettings.isEnabled ? 1 : 0let notification = notificationSettings.isEnabled ? 1 : 0let menuBarQuota = menuBarQuotaSettings.selection.rawValuelet taskCenter = mainPanelSettings.showsTaskCenter ? 1 : 0let hotKey = globalHotKeySettings.shortcut == nil ? 0 : 1AppLog.app.notice(- "App 已启动: version=\(version, privacy: .public); build=\(build, privacy: .public); hook=\(hook); keepAlive=\(keepAlive); keepAliveLimit=\(keepAliveLimit); keepAliveBattery=\(keepAliveBattery); sync=\(sync); notification=\(notification); menuBarQuota=\(menuBarQuota, privacy: .public); taskCenter=\(taskCenter); hotKey=\(hotKey)"+ "App 已启动: version=\(version, privacy: .public); build=\(build, privacy: .public); hook=\(hook); keepAlive=\(keepAlive); keepAliveLimit=\(keepAliveLimit); keepAliveBattery=\(keepAliveBattery); keepAliveWaiting=\(keepAliveWaiting); keepAliveDisplay=\(keepAliveDisplay); sync=\(sync); notification=\(notification); menuBarQuota=\(menuBarQuota, privacy: .public); taskCenter=\(taskCenter); hotKey=\(hotKey)")}diff --git a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swiftindex 51a802c..13f1fec 100644--- a/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusViewModel.swift@@ -64,7 +64,7 @@ final class CodexStatusViewModel: ObservableObject {autoRefreshTask = Task { [weak self] inself?.refreshIfNeeded(trigger: .launch)- // 每轮按剩余时间休眠, 手动刷新后倒计时会自然重新对齐+ // 每轮按剩余时间等待, 手动刷新后倒计时会自然重新对齐while !Task.isCancelled {let delay = self?.autoRefreshDelay ?? Self.refreshIntervalif await (try? Task.sleep(for: .seconds(delay))) == nil {diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 97fc734..7ca9fdb 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -12,20 +12,24 @@ final class KeepAliveController: ObservableObject {@Published private(set) var helperStatus = HelperStatus.notRegistered@Published private(set) var isPreventingSleep = false@Published private(set) var lowBatteryThreshold: LowBatteryThreshold+ /// 等待批准的任务算不算"有任务", 决定审批期间要不要继续挡住睡眠+ @Published private(set) var keepsAwakeWhileWaiting: Bool+ /// 防睡眠生效期间是否连屏幕一起留住, 顺带压住屏保与闲置锁屏+ @Published private(set) var keepsDisplayAwake: Bool/// 确认没有内置电池时为 false, 设置页据此隐藏低电量那一行@Published private(set) var hasBattery = true- /// 当前是否因低电量而停止防休眠, 带滞回所以不等于"电量低于阈值"+ /// 当前是否因低电量而停止防睡眠, 带滞回所以不等于"电量低于阈值"/// 会随电量自己翻转, 不需要外部清除, 与 hasReachedMaximumDuration 那种粘滞标志不是一回事@Published private(set) var isLowBatteryActive = false- /// 低电量保护是不是真的在起作用: 防休眠本身可用, 阈值开着, 且这台机器确实有电池- /// 规则收在这里而不是各视图各写一遍: 通知面板要据此置灰那一行, 防休眠面板据此决定显不显示阈值+ /// 低电量保护是不是真的在起作用: 防睡眠本身可用, 阈值开着, 且这台机器确实有电池+ /// 规则收在这里而不是各视图各写一遍: 通知面板要据此置灰那一行, 防睡眠面板据此决定显不显示阈值@Published private(set) var isLowBatteryProtectionEnabled = false- /// 时长上限是不是真的会到点: 防休眠本身可用, 且没选无限制+ /// 时长上限是不是真的会到点: 防睡眠本身可用, 且没选无限制/// 与 isLowBatteryProtectionEnabled 同一个用法, 视图只读结论, 不各自再判一次 unlimited/// 只在跨越边界时发信号, 1 小时改 2 小时不必让通知面板白排一轮高度重算@Published private(set) var isMaximumDurationEnabled = false- /// 低电量是不是当下唯一拦住防休眠的那一项+ /// 低电量是不是当下唯一拦住防睡眠的那一项/// 由 reconcileSleepState 从 sleepBlockReason 派生, 见那里的说明@Published private(set) var isLowBatteryBlocking = false/// 子面板入口该不该出现: 用户开关开着且依赖已就绪@@ -34,7 +38,7 @@ final class KeepAliveController: ObservableObject {/// helper 安装与注册状态的错误, 注册恢复正常时才清除@Published private var registrationErrorMessage: String?- /// 切换休眠状态过程中的错误, 只能由下一次操作结果或用户动作覆盖+ /// 切换睡眠状态过程中的错误, 只能由下一次操作结果或用户动作覆盖/// 与注册类错误分开存储: refreshHelperStatus 每次 App 激活都会跑, 不能抹掉操作结果@Published private var operationErrorMessage: String?@@ -52,21 +56,21 @@ final class KeepAliveController: ObservableObject {durationLimiter.hasReached}- /// 低电量导致休眠恢复之后回调一次, 参数是触及阈值时的电量; 由 AppDelegate 接到通知服务+ /// 低电量导致睡眠恢复之后回调一次, 参数是触及阈值时的电量; 由 AppDelegate 接到通知服务/// 用事件回调而不是 @Published: 触发是一次性动作, 电量回升到解除门槛以上后再次跌破要能重新发一次- /// async 是为了让补发休眠等到通知真的提交完: 同步回调只把提交排进下一个 MainActor job,+ /// async 是为了让补发睡眠等到通知真的提交完: 同步回调只把提交排进下一个 MainActor job,/// 而 IOPMSleepSystem 就在当前这个 job 里, 机器会先睡下去/// 返回值是通知有没有真的发出去, 决定这一轮算不算已通知var onLowBatteryTriggered: ((Int) async -> Bool)?- /// 达到防休眠时长上限且休眠恢复成功之后回调一次+ /// 达到防睡眠时长上限且睡眠恢复成功之后回调一次/// 时长上限本身是粘滞状态, 每个计时周期天然只会进入一次- /// 所以返回值用不上, 也不像低电量那条需要锁存: hasReached 粘滞且此刻已不在防休眠,+ /// 所以返回值用不上, 也不像低电量那条需要锁存: hasReached 粘滞且此刻已不在防睡眠,/// 同一个周期里排不进第二次, 周期边界本身就是重置点- /// 提交失败这一条就丢了, 重新 flush 需要再来一次休眠恢复, 而休眠已经恢复完了+ /// 提交失败这一条就丢了, 重新 flush 需要再来一次睡眠恢复, 而睡眠已经恢复完了var onKeepAliveLimitTriggered: ((MaximumDuration) async -> Bool)?- /// 用户开关仍开着, 且 helper 已经真的把休眠关掉+ /// 用户开关仍开着, 且 helper 已经真的把睡眠关掉/// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它)/// 叠这一层是为了关开关到 helper 回调之间的异步空窗: 用户意图先落地var isActivelyPreventingSleep: Bool {@@ -84,7 +88,8 @@ final class KeepAliveController: ObservableObject {private var hasRunningTasks = false/// 保留仍活跃且已经进入过运行态的任务, 避免普通快照刷新被误判成新任务private var startedRunningTaskIDs = Set<UUID>()- /// 记录上一份快照中的等待任务, 用于识别等待批准后恢复运行的状态转换+ /// 最近一份快照中的等待任务, 用于识别等待批准后恢复运行的状态转换+ /// 开着 keepsAwakeWhileWaiting 时它同时是"有没有任务撑着防睡眠"的另一半输入private var waitingTaskIDs = Set<UUID>()private var connection: NSXPCConnection?/// 本轮接管以来连接没有断过, helper 那边的哨兵必然还在@@ -95,18 +100,19 @@ final class KeepAliveController: ObservableObject {private var requestInFlight = falseprivate var requestGeneration: UInt64 = 0private var retryTask: Task<Void, Never>?+ private var requestTimeoutTask: Task<Void, Never>?private var retryAttempt = 0private var helperRegistrationTask: Task<Void, Never>?/// 与 hasRunningTasks 同理: 只经由派生状态影响 UI, 自己不发信号private var isRefreshingHelper = false/// 已排队但还没发出的低电量通知, 值是触及阈值时的电量- /// 恢复休眠真的成功才发得出去: 恢复失败时机器仍不会睡, 那时说已恢复会把用户骗去合盖+ /// 恢复睡眠真的成功才发得出去: 恢复失败时机器仍不会睡, 那时说已恢复会把用户骗去合盖private var pendingLowBatteryPercent: Int?/// 本轮低电量已经通知过/// 只看是否接电不足以收口: 适配器接触不良时供电状态会反复翻转, 每翻一次都会重发一条/// 由电量回到解除门槛以上清除, 也就是电量真的回来了才算下一轮private var hasNotifiedLowBattery = false- /// 达到时长上限后等待休眠恢复成功再发送, 恢复失败时保留给重试路径+ /// 达到时长上限后等待睡眠恢复成功再发送, 恢复失败时保留给重试路径private var pendingKeepAliveLimit: MaximumDuration?private var cancellables = Set<AnyCancellable>()private var isStarted = false@@ -115,7 +121,7 @@ final class KeepAliveController: ObservableObject {/// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值private var isHookEnabled: Bool- /// 防休眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+ /// 防睡眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值private enum SleepBlockReason: String {case notStartedcase userOff@@ -157,6 +163,10 @@ final class KeepAliveController: ObservableObject {// 默认关闭: 老版本升上来的用户不该多出一条中断任务的路径lowBatteryThreshold = (defaults.object(forKey: Self.lowBatteryThresholdKey) as? Int).flatMap(LowBatteryThreshold.init(rawValue:)) ?? .off+ // 同样默认关闭: 等待批准没有终点, 开着它意味着无人值守时机器可能整夜不睡+ keepsAwakeWhileWaiting = defaults.bool(forKey: Self.keepsAwakeWhileWaitingKey)+ // 默认关闭: 它会让人离开后机器一直停在解锁状态, 这个取舍只能由用户自己做+ keepsDisplayAwake = defaults.bool(forKey: Self.keepsDisplayAwakeKey)}func start() {@@ -166,9 +176,9 @@ final class KeepAliveController: ObservableObject {isStarted = true// Hook 是本功能的依赖, 不是用户意图- // 只重新求值当前该不该防止系统休眠, 绝不改写用户保存的开关+ // 只重新求值当前该不该防止系统睡眠, 绝不改写用户保存的开关// 看 isOperable 那两个输入而不是只看 isEnabled: Codex 那边全局关掉 hooks- // 或者不信任我们的 handler 时事件送不过来, 任务恒为空, 防休眠也就不该显示成可用+ // 或者不信任我们的 handler 时事件送不过来, 任务恒为空, 防睡眠也就不该显示成可用// @Published 在 willSet 就发信号, 此刻回读 codexHookSettings.isOperable 会拿到// 正在变的那一项的旧值; CombineLatest 的两个参数都是各自的新值, 所以只认闭包参数Publishers.CombineLatest(codexHookSettings.$isEnabled, codexHookSettings.$isVerified)@@ -278,6 +288,32 @@ final class KeepAliveController: ObservableObject {publishNotificationDependencies()}+ /// 只改"哪些任务算数", 不参与拦截判定+ /// 所以它不进 sleepBlockReason: 关着它时审批中的任务报的仍然是 noTasks, 与没有任务同一回事+ func setKeepsAwakeWhileWaiting(_ enabled: Bool) {+ guard enabled != keepsAwakeWhileWaiting else {+ return+ }++ AppLog.keepAlive.notice("KeepAlive 等待批准时保持变更: enabled=\(enabled ? 1 : 0)")+ keepsAwakeWhileWaiting = enabled+ defaults.set(enabled, forKey: Self.keepsAwakeWhileWaitingKey)+ // 快照不会因为改设置重发一次, 正等着批准的那些任务只能在这里重新求值+ reconcileSleepState(trigger: .settings)+ }++ /// 与防睡眠的实际效果绑在一起: 只在真的挡住睡眠时留住屏幕, 低电量或达到上限解除时一并放开+ func setKeepsDisplayAwake(_ enabled: Bool) {+ guard enabled != keepsDisplayAwake else {+ return+ }++ AppLog.keepAlive.notice("KeepAlive 保持屏幕常亮变更: enabled=\(enabled ? 1 : 0)")+ keepsDisplayAwake = enabled+ defaults.set(enabled, forKey: Self.keepsDisplayAwakeKey)+ reconcileDisplayAwake()+ }+func setLowBatteryThreshold(_ threshold: LowBatteryThreshold) {guard threshold != lowBatteryThreshold else {return@@ -308,10 +344,10 @@ final class KeepAliveController: ObservableObject {}/// 纯条件判定: 只看当下, 不记"低过电"这笔账, 所以充上电会自动恢复- /// 滞回让解除门槛比触发门槛高一截, 否则电量在阈值附近抖动会反复切换休眠状态+ /// 滞回让解除门槛比触发门槛高一截, 否则电量在阈值附近抖动会反复切换睡眠状态/// 读不到电量时维持上一次的判定, 两种情形各有各的理由- /// 从没读到过时保持不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制休眠兜底- /// 已经在保护中时不清零: 一次瞬时失败不该让防休眠反复开关, 那还会绕过滞回并重发通知+ /// 从没读到过时保持不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制睡眠兜底+ /// 已经在保护中时不清零: 一次瞬时失败不该让防睡眠反复开关, 那还会绕过滞回并重发通知private func updateBatteryState() {let reading = powerSourceMonitor.reading// 读失败时维持上一次的判定, 与下面 isLowBatteryActive 同一条规则@@ -364,23 +400,23 @@ final class KeepAliveController: ObservableObject {}// 百分比只在这里记一次; 放进 SleepConditions 会让每掉 1% 刷一条- // 本来就没在挡休眠时这一跌不改变任何事, 但仍要记: 这是排查"为什么在这个电量断的"的唯一依据+ // 本来就没在挡睡眠时这一跌不改变任何事, 但仍要记: 这是排查"为什么在这个电量断的"的唯一依据let wasPreventingSleep = isActivelyPreventingSleepAppLog.keepAlive.notice("KeepAlive 电量已触及阈值: percent=\(status.percent); threshold=\(threshold); action=\(wasPreventingSleep ? "release" : "none", privacy: .public)")- // 没挡过就不通知: "已恢复系统休眠"会变成一句空话, 启动时电量本就偏低的机器首当其冲+ // 没挡过就不通知: "已恢复系统睡眠"会变成一句空话, 启动时电量本就偏低的机器首当其冲guard wasPreventingSleep, !hasNotifiedLowBattery else {return}- // 这里只排队不发: 休眠还没真的恢复, 恢复请求可能失败并耗尽重试+ // 这里只排队不发: 睡眠还没真的恢复, 恢复请求可能失败并耗尽重试pendingLowBatteryPercent = status.percent}- /// 排队的低电量通知在休眠真的恢复之后才发- /// 途中接上电源时拦下防休眠的已经不是低电量, 那条通知随即作废+ /// 排队的低电量通知在睡眠真的恢复之后才发+ /// 途中接上电源时拦下防睡眠的已经不是低电量, 那条通知随即作废private func flushPendingLowBatteryNotification() async {guard let percent = pendingLowBatteryPercent else {return@@ -396,7 +432,7 @@ final class KeepAliveController: ObservableObject {hasNotifiedLowBattery = await onLowBatteryTriggered?(percent) ?? false}- /// 恢复休眠成功之后按当下的拦截原因发对应的那一条, 顺带把另一条作废+ /// 恢复睡眠成功之后按当下的拦截原因发对应的那一条, 顺带把另一条作废/// 作废低电量只写 pendingLowBatteryPercent, 不能改走 clearPendingLowBatteryNotification:/// 那个方法会连 hasNotifiedLowBattery 一起清, 而这一轮低电量还没结束 (电量没回到解除门槛),/// 清了会让下一次跌破阈值重发第二条, 也就是供电状态反复翻转时每翻一次一条@@ -437,7 +473,7 @@ final class KeepAliveController: ObservableObject {startedRunningTaskIDs.formUnion(runningTaskIDs)waitingTaskIDs = currentWaitingTaskIDs- assign(!runningTaskIDs.isEmpty, to: \.hasRunningTasks)+ hasRunningTasks = !runningTaskIDs.isEmptyif activeTaskIDs.isEmpty {durationLimiter.reset()} else if !newRunningTaskIDs.isEmpty || !resumedRunningTaskIDs.isEmpty {@@ -446,7 +482,7 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .taskChanged)}- /// 还没真正挡住休眠时只清零不起表, 等禁用成功后由 begin 补上+ /// 还没真正挡住睡眠时只清零不起表, 等禁用成功后由 begin 补上private func restartMaximumDurationPeriod() {guard isEnabled else {return@@ -620,6 +656,8 @@ final class KeepAliveController: ObservableObject {let wantsSleepDisabled = blockReason == nilupdatePendingKeepAliveLimitNotification(for: blockReason)publishDerivedState(blockReason: blockReason)+ // 挂在这条所有输入都会经过的路上, 否则关掉防睡眠开关要等 XPC 回复绕回来才放开屏幕+ reconcileDisplayAwake()logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)guard wantsSleepDisabled else {@@ -638,8 +676,8 @@ final class KeepAliveController: ObservableObject {applySleepDisabled(true)}- /// 只有实际防休眠正在生效时达到上限才排队- /// 其他原因先解除防休眠时即使累计时长足够, 也不能把恢复动作归因给时长上限+ /// 只有实际防睡眠正在生效时达到上限才排队+ /// 其他原因先解除防睡眠时即使累计时长足够, 也不能把恢复动作归因给时长上限private func updatePendingKeepAliveLimitNotification(for blockReason: SleepBlockReason?) {guard blockReason == .limitReached else {pendingKeepAliveLimit = nil@@ -678,7 +716,7 @@ final class KeepAliveController: ObservableObject {)}- /// 缺依赖时收起入口, 只是没在防休眠 (没任务, 低电量, 已达上限) 时仍然要能改设置+ /// 缺依赖时收起入口, 只是没在防睡眠 (没任务, 低电量, 已达上限) 时仍然要能改设置private static func allowsOptions(_ blockReason: SleepBlockReason?) -> Bool {switch blockReason {case .notStarted, .userOff, .hookDisabled, .helperUnavailable:@@ -698,7 +736,7 @@ final class KeepAliveController: ObservableObject {blockReason: blockReason,enabled: isEnabled,hook: isHookEnabled,- tasks: hasRunningTasks,+ tasks: hasKeepAliveTasks,helper: helperStatus,refreshing: isRefreshingHelper,battery: isLowBatteryActive,@@ -724,7 +762,7 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.notice("KeepAlive 已解除: reason=\(blockReason.rawValue, privacy: .public)")}- // MARK: - 休眠切换与恢复+ // MARK: - 睡眠切换与恢复private func applySleepDisabled(_ disabled: Bool) {guard appliedSleepDisabled != disabled else {@@ -735,7 +773,7 @@ final class KeepAliveController: ObservableObject {let result = systemSleepService.beginPreventingIdleSleep()guard result == kIOReturnSuccess else {AppLog.keepAlive.error("空闲断言建立失败: code=\(result)")- operationErrorMessage = "防止空闲休眠失败"+ operationErrorMessage = "防止空闲睡眠失败"scheduleRetryIfNeeded(for: true)return}@@ -750,6 +788,7 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.notice("Helper XPC 请求已发送: op=\(disabled ? "disable" : "restore", privacy: .public); generation=\(generation)")+ scheduleRequestTimeout(for: disabled, generation: generation)let errorHandler: (Error) -> Void = { [weak self] error inTask { @MainActor in@@ -771,6 +810,7 @@ final class KeepAliveController: ObservableObject {return}self.requestInFlight = false+ self.cancelRequestTimeout()let replyResult = exitCode == 0 ? "ok" : "failed"AppLog.keepAlive.notice("Helper XPC 回复已收到: generation=\(generation); result=\(replyResult, privacy: .public); exit=\(exitCode)"@@ -778,8 +818,8 @@ final class KeepAliveController: ObservableObject {guard exitCode == 0 else {// invalidateConnection 会连同 assertion 一起收self.invalidateConnection()- AppLog.keepAlive.error("系统休眠切换失败: generation=\(generation); exit=\(exitCode)")- self.operationErrorMessage = "切换休眠状态失败"+ AppLog.keepAlive.error("系统睡眠切换失败: generation=\(generation); exit=\(exitCode)")+ self.operationErrorMessage = "切换睡眠状态失败"self.scheduleRetryIfNeeded(for: disabled)return}@@ -787,6 +827,8 @@ final class KeepAliveController: ObservableObject {self.cancelRetryTask()self.isPreventingSleep = disabledself.operationErrorMessage = nil+ // 屏幕跟着实际效果走, 这里是它唯一的建立时机+ self.reconcileDisplayAwake()if disabled {// lidCausesSleep=0 说明这一轮 pmset 是空转的, 真正在挡的只有空闲断言// 排查「开了却还是睡了」时先看这个字段@@ -794,15 +836,15 @@ final class KeepAliveController: ObservableObject {let lidCausesSleep = lidStatus.map { $0.lidClosureCausesSleep ? "1" : "0" } ?? "unknown"AppLog.keepAlive.notice(- "系统休眠已关闭: generation=\(generation); lidCausesSleep=\(lidCausesSleep, privacy: .public)"+ "系统睡眠已关闭: generation=\(generation); lidCausesSleep=\(lidCausesSleep, privacy: .public)")self.canTrustRestoreResult = trueself.durationLimiter.begin()} else {// 先收表再走恢复: finishSleepRestore 可能直接把机器送去睡self.durationLimiter.pause()- // 通知同样要赶在补发休眠之前发出去, 理由与收表相同- // 走到这里 pmset 已经恢复成功, 那句"已恢复系统休眠"才站得住+ // 通知同样要赶在补发睡眠之前发出去, 理由与收表相同+ // 走到这里 pmset 已经恢复成功, 那句"已恢复系统睡眠"才站得住await self.flushPendingSleepRestoreNotification()// 上面这一步会挂起, 期间可能已经有新的禁用请求接管// 那时再走恢复会释放掉刚建立的空闲断言, 所以重新认一次代@@ -822,19 +864,19 @@ final class KeepAliveController: ObservableObject {let idleSleepResult = systemSleepService.endPreventingIdleSleep()if idleSleepResult != kIOReturnSuccess {AppLog.keepAlive.error("空闲断言释放失败: code=\(idleSleepResult)")- operationErrorMessage = "恢复空闲休眠策略失败"+ operationErrorMessage = "恢复空闲睡眠策略失败"}let sleepDisabled = sleepDisabledAfterOperation ? 1 : 0// 连接断过时 helper 可能已自行恢复并清掉哨兵, 这份回复不带实测状态- // 不能据此补发合盖休眠: 本轮可能压根不是我们禁用的休眠+ // 不能据此补发合盖睡眠: 本轮可能压根不是我们禁用的睡眠guard canTrustRestoreResult else {- // 这条判断是防止误发强制休眠的唯一屏障, 生效时必须留痕, 否则误判无从追查- AppLog.keepAlive.notice("系统休眠恢复结果不可信: reason=connectionLost")+ // 这条判断是防止误发强制睡眠的唯一屏障, 生效时必须留痕, 否则误判无从追查+ AppLog.keepAlive.notice("系统睡眠恢复结果不可信: reason=connectionLost")return}- AppLog.keepAlive.notice("系统休眠已恢复: sleepDisabled=\(sleepDisabled)")+ AppLog.keepAlive.notice("系统睡眠已恢复: sleepDisabled=\(sleepDisabled)")let lidStatus = SystemSleepService.currentStatus()let shouldRequestSystemSleep = !sleepDisabledAfterOperation@@ -851,16 +893,16 @@ final class KeepAliveController: ObservableObject {"unknown"}AppLog.keepAlive.notice(- "休眠补发已跳过: reason=\(reason, privacy: .public)"+ "睡眠补发已跳过: reason=\(reason, privacy: .public)")return}- AppLog.keepAlive.notice("休眠补发已请求")+ AppLog.keepAlive.notice("睡眠补发已请求")let result = SystemSleepService.requestSystemSleep()if result != kIOReturnSuccess {- AppLog.keepAlive.error("休眠补发失败: code=\(result)")- operationErrorMessage = "请求系统休眠失败"+ AppLog.keepAlive.error("睡眠补发失败: code=\(result)")+ operationErrorMessage = "请求系统睡眠失败"}}@@ -881,7 +923,7 @@ final class KeepAliveController: ObservableObject {}let shouldRetry = self.requestInFlight || self.isPreventingSleeplet desiredSleepDisabled = self.shouldDisableSleep- // 复用统一清理: 连接失效同样要释放 assertion, 否则空闲休眠会被永久阻止+ // 复用统一清理: 连接失效同样要释放 assertion, 否则空闲睡眠会被永久阻止self.invalidateConnection()if shouldRetry {self.scheduleRetryIfNeeded(for: desiredSleepDisabled)@@ -912,7 +954,36 @@ final class KeepAliveController: ObservableObject {}}+ /// helper 起不来时 setSleepDisabled 既不回复也不触发 errorHandler, 请求就那么挂着+ /// 没有这道超时, 界面会显示防睡眠开着而实际没生效, 日志里只剩一条没有配对回复的请求已发送+ private func scheduleRequestTimeout(for disabled: Bool, generation: UInt64) {+ requestTimeoutTask?.cancel()+ requestTimeoutTask = Task { @MainActor [weak self] in+ try? await Task.sleep(for: Self.helperRequestTimeout)+ // 认状态而不是认取消位: 每条取消路径都同时推进了 generation 或清了 in-flight,+ // 认状态就不必依赖将来每个新路径都记得 cancel+ guard let self, generation == requestGeneration, requestInFlight else {+ return+ }++ let timeout = LogDuration.seconds(Self.helperRequestTimeout)+ AppLog.keepAlive.error(+ "Helper XPC 请求超时: op=\(disabled ? "disable" : "restore", privacy: .public); generation=\(generation); timeout=\(timeout, privacy: .public)"+ )+ // 连接已经不可信, 收掉它再走既有的重试阶梯, 与切换失败同一条路径+ invalidateConnection()+ operationErrorMessage = "服务无响应"+ scheduleRetryIfNeeded(for: disabled)+ }+ }++ private func cancelRequestTimeout() {+ requestTimeoutTask?.cancel()+ requestTimeoutTask = nil+ }+private func invalidateConnection() {+ cancelRequestTimeout()requestGeneration &+= 1let connection = connectionself.connection = nil@@ -922,7 +993,7 @@ final class KeepAliveController: ObservableObject {// 无连接时也会走到这里, 只记真的断掉了一条, 避免空转刷屏if connection != nil {// trusted 记的是断开这一刻的可信度: 它一断, 后面那轮恢复回复就不再可信- // 也就不会补发休眠, 这是追查「任务结束了机器却没睡」的唯一线索+ // 也就不会补发睡眠, 这是追查「任务结束了机器却没睡」的唯一线索let trusted = canTrustRestoreResult ? 1 : 0AppLog.keepAlive.notice("Helper XPC 已断开: trusted=\(trusted)")}@@ -934,15 +1005,49 @@ final class KeepAliveController: ObservableObject {}/// assertion 与 isPreventingSleep 同进同退的唯一出口- /// 两者必须一起收: 只清标志会让菜单栏图标显示成未防休眠, 而这条 assertion 仍在防止空闲休眠,- /// 且没有任何后续路径会释放它; 仍需要防休眠时由重试经 applySleepDisabled(true) 重建+ /// 两者必须一起收: 只清标志会让菜单栏图标显示成未防睡眠, 而这条 assertion 仍在防止空闲睡眠,+ /// 且没有任何后续路径会释放它; 仍需要防睡眠时由重试经 applySleepDisabled(true) 重建private func releaseSleepPrevention() {_ = systemSleepService.endPreventingIdleSleep()assign(false, to: \.isPreventingSleep)- // 收表跟着实际效果走: 这里之后休眠不再被挡, 那段时间不该占用户的上限+ // 空闲断言与屏幕成对: 这里之后睡眠不再被挡, 屏幕也没有留住的理由+ reconcileDisplayAwake()+ // 收表跟着实际效果走: 这里之后睡眠不再被挡, 那段时间不该占用户的上限durationLimiter.pause()}+ // MARK: - 屏幕常亮++ /// 用户开关与防睡眠实际效果的汇合点, 两边任意一个变了都要过这里+ /// 跟 isActivelyPreventingSleep 走, 于是低电量拦下, 达到上限, 任务结束时屏幕都会跟着放开+ /// 失败只记日志不占 operationErrorMessage: 那个字段是睡眠切换的结论, 会顶到设置页最前面,+ /// 让一个附加效果的失败显示成防睡眠本身出错+ private func reconcileDisplayAwake() {+ let shouldKeepAwake = keepsDisplayAwake && isActivelyPreventingSleep+ guard shouldKeepAwake != systemSleepService.isPreventingDisplaySleep else {+ return+ }++ guard shouldKeepAwake else {+ let result = systemSleepService.endPreventingDisplaySleep()+ if result != kIOReturnSuccess {+ AppLog.keepAlive.error("显示断言释放失败: code=\(result)")+ return+ }++ AppLog.keepAlive.notice("显示断言已释放")+ return+ }++ let result = systemSleepService.beginPreventingDisplaySleep()+ guard result == kIOReturnSuccess else {+ AppLog.keepAlive.error("显示断言建立失败: code=\(result)")+ return+ }++ AppLog.keepAlive.notice("显示断言已建立")+ }+private func cancelRetryTask() {retryTask?.cancel()retryTask = nil@@ -970,7 +1075,7 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.error("KeepAlive 切换重试已放弃: attempts=\(Self.sleepToggleRetryDelays.count)")- operationErrorMessage = "防休眠多次失败, 已停止重试"+ operationErrorMessage = "防睡眠多次失败, 已停止重试"return}@@ -979,7 +1084,7 @@ final class KeepAliveController: ObservableObject {let attempt = retryAttemptlet wait = LogDuration.seconds(delay)AppLog.keepAlive.notice(- "休眠切换重试: attempt=\(attempt); delay=\(wait, privacy: .public); disabled=\(disabled ? 1 : 0)"+ "睡眠切换重试: attempt=\(attempt); delay=\(wait, privacy: .public); disabled=\(disabled ? 1 : 0)")retryTask = Task { @MainActor [weak self] in@@ -997,7 +1102,7 @@ final class KeepAliveController: ObservableObject {}}- // MARK: - 防休眠条件判定+ // MARK: - 防睡眠条件判定/// 用户意图 (isEnabled) 与依赖可用性在这里汇合/// 依赖不满足只让效果失效, 不回写 isEnabled@@ -1005,6 +1110,11 @@ final class KeepAliveController: ObservableObject {sleepBlockReason == nil}+ /// 等待批准算不算"有任务"由用户开关决定, 快照与设置两条路径共用这一份规则+ private var hasKeepAliveTasks: Bool {+ hasRunningTasks || (keepsAwakeWhileWaiting && !waitingTaskIDs.isEmpty)+ }+/// 按顺序返回第一个不满足的条件, 全部满足时为 nil/// 判定与日志共用这一份顺序, 新增条件不会漏进日志private var sleepBlockReason: SleepBlockReason? {@@ -1017,7 +1127,7 @@ final class KeepAliveController: ObservableObject {if !isHookEnabled {return .hookDisabled}- if !hasRunningTasks {+ if !hasKeepAliveTasks {return .noTasks}if helperStatus != .enabled {@@ -1039,10 +1149,11 @@ final class KeepAliveController: ObservableObject {private static let enabledKey = "KeepAlive.isEnabled"private static let lowBatteryThresholdKey = "KeepAlive.lowBatteryThresholdPercent"+ private static let keepsAwakeWhileWaitingKey = "KeepAlive.keepsAwakeWhileWaiting"+ private static let keepsDisplayAwakeKey = "KeepAlive.keepsDisplayAwake"/// 解除门槛比触发门槛高这么多个百分点, 避免电量在阈值附近抖动导致反复切换private static let lowBatteryHysteresis = 5- private static let helperRegistrationFingerprintKey =- "KeepAlive.helperRegistrationFingerprint"+ private static let helperRegistrationFingerprintKey = "KeepAlive.helperRegistrationFingerprint"private static let helperRegistrationRetryDelays: [Duration] = [.milliseconds(500),.seconds(1),@@ -1050,8 +1161,13 @@ final class KeepAliveController: ObservableObject {]private static let operationNotPermittedErrorCode = 1- /// 切换休眠状态失败后的重试节奏, 逐次翻倍- /// 列表耗尽 (累计约 8.5 分钟) 即放弃: 瞬时抖动能自愈, 权限类故障不会无限重试+ /// 与 helper 的 watchdog 宽限是一对, 取值和理由都在 CodexBarHelperIPC 那边+ private static let helperRequestTimeout = Duration.seconds(+ CodexBarHelperIPC.requestTimeoutSeconds+ )++ /// 切换睡眠状态失败后的重试节奏, 逐次翻倍+ /// 列表耗尽即放弃 (延时累计约 8.5 分钟, 每轮再等一次超时约 10 分钟): 瞬时抖动能自愈, 权限类故障不会无限重试private static let sleepToggleRetryDelays: [Duration] = [.seconds(2),.seconds(4),diff --git a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swiftindex 6d835b7..7b851d6 100644--- a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift@@ -2,8 +2,8 @@ import Combineimport Foundationimport os-/// 防休眠的时长上限计时-/// 累计的是真正挡住休眠的那段时间: begin 起表, pause 收表, 收表之后机器睡着或被低电量拦下都不算+/// 防睡眠的时长上限计时+/// 累计的是真正挡住睡眠的那段时间: begin 起表, pause 收表, 收表之后机器睡着或被低电量拦下都不算/// 时钟用 SuspendingClock 而不是 Date: 后者受系统时间调整影响, 且系统睡眠期间照走/// hasReached 是粘滞标志: 累计只增不减, 到期之后每一秒都还成立/// 只有重新开始计时的入口能清除它, 这些清除全部收在 clearReached 里@@ -15,7 +15,7 @@ final class KeepAliveDurationLimiter: ObservableObject {@Published private(set) var duration: Duration@Published private(set) var hasReached = false- /// 状态变化后需要重新求值一次防休眠条件, 参数是这次变化的来源+ /// 状态变化后需要重新求值一次防睡眠条件, 参数是这次变化的来源/// begin pause restart reset 不走这里: 它们的调用方本来就会紧接着求值var onStateChanged: ((LogTrigger) -> Void)?@@ -48,7 +48,7 @@ final class KeepAliveDurationLimiter: ObservableObject {return}- AppLog.keepAlive.notice("KeepAlive 防休眠时间上限变更: threshold=\(duration.loggedHours)")+ AppLog.keepAlive.notice("KeepAlive 防睡眠时间上限变更: threshold=\(duration.loggedHours)")self.duration = durationdefaults.set(duration.rawValue, forKey: Self.durationKey)@@ -69,7 +69,7 @@ final class KeepAliveDurationLimiter: ObservableObject {onStateChanged?(.settings)}- /// 防休眠真正生效后起表; 已经在走就保持这一段不变+ /// 防睡眠真正生效后起表; 已经在走就保持这一段不变func begin() {if runningSince == nil {runningSince = .now@@ -78,7 +78,7 @@ final class KeepAliveDurationLimiter: ObservableObject {schedule()}- /// 防休眠解除时收表, 把这一段并进累计值+ /// 防睡眠解除时收表, 把这一段并进累计值/// 收表之后的时间一律不算: 机器睡着, 低电量拦着, helper 断开都不该占用户的上限func pause() {guard let runningSince else {@@ -91,7 +91,7 @@ final class KeepAliveDurationLimiter: ObservableObject {}/// 有新任务或等待任务恢复运行时重新计时- /// isPreventingSleep 由调用方给出: 还没真正挡住休眠时只清零, 等 begin 起表+ /// isPreventingSleep 由调用方给出: 还没真正挡住睡眠时只清零, 等 begin 起表func restart(isPreventingSleep: Bool) {cancelTask()accumulated = 0@@ -121,7 +121,7 @@ final class KeepAliveDurationLimiter: ObservableObject {hasReached = false}- /// 这一轮已经挡住休眠的总时长, 含当前还没收表的这一段+ /// 这一轮已经挡住睡眠的总时长, 含当前还没收表的这一段private var elapsed: TimeInterval {guard let runningSince else {return accumulateddiff --git a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swiftindex 03c8829..b146b3e 100644--- a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift+++ b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift@@ -40,7 +40,7 @@ nonisolated struct BatteryStatus: Equatable {let isOnBattery: Bool}-/// 只读系统电源状态并在变化时通知外部, 不知道阈值也不知道防休眠+/// 只读系统电源状态并在变化时通知外部, 不知道阈值也不知道防睡眠/// IOKit 的 C 接口和内存管理约定全部收在这里, 不漏到调用方@MainActorfinal class PowerSourceMonitor {@@ -89,7 +89,7 @@ final class PowerSourceMonitor {reading = initialReading// 装在 source 之前: 注册失败时它已经就位, 与那条路的轮询兜底叠着用- // 休眠期间电量可能变化很大, 而系统不一定为此补发电源通知+ // 睡眠期间电量可能变化很大, 而系统不一定为此补发电源通知wakeObserver = NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification,object: nil,@@ -142,7 +142,7 @@ final class PowerSourceMonitor {}/// 注册失败后的兜底轮询- /// 只靠唤醒补读不够: 防休眠正在生效的机器按定义就不会睡, 那条通知永远不来+ /// 只靠唤醒补读不够: 防睡眠正在生效的机器按定义就不会睡, 那条通知永远不来private func startPolling() {pollTask?.cancel()pollTask = Task { @MainActor [weak self] indiff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftindex 62a28e2..16e094b 100644--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -1,6 +1,7 @@import Foundationimport IOKitimport IOKit.pwr_mgt+import os@MainActorfinal class SystemSleepService {@@ -13,39 +14,140 @@ final class SystemSleepService {}}- private static let assertionName = "CodexBar - Codex activity"+ /// 两条断言只差类型与名字, 持有和释放的规则完全一样+ /// 名称必须是 ASCII: 含中文时 pmset -g assertions 的 named 会显示成空串, 断言就失去了标识+ private struct Assertion {+ let type: CFString+ let name: CFString+ private var id = IOPMAssertionID(kIOPMNullAssertionID)- private var assertionID = IOPMAssertionID(kIOPMNullAssertionID)+ init(type: CFString, name: CFString) {+ self.type = type+ self.name = name+ }- func beginPreventingIdleSleep() -> IOReturn {- guard assertionID == IOPMAssertionID(kIOPMNullAssertionID) else {- return kIOReturnSuccess+ var isActive: Bool {+ id != IOPMAssertionID(kIOPMNullAssertionID)}- var createdAssertionID = IOPMAssertionID(kIOPMNullAssertionID)- // 名称必须是 ASCII: 含中文时 pmset -g assertions 的 named 会显示成空串, 这条断言就失去了标识- let result = IOPMAssertionCreateWithName(- kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,- IOPMAssertionLevel(kIOPMAssertionLevelOn),- Self.assertionName as CFString,- &createdAssertionID- )- if result == kIOReturnSuccess {- assertionID = createdAssertionID+ mutating func begin() -> IOReturn {+ guard !isActive else {+ return kIOReturnSuccess+ }++ var createdAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ let result = IOPMAssertionCreateWithName(+ type,+ IOPMAssertionLevel(kIOPMAssertionLevelOn),+ name,+ &createdAssertionID+ )+ if result == kIOReturnSuccess {+ id = createdAssertionID+ }+ return result+ }++ mutating func end() -> IOReturn {+ guard isActive else {+ return kIOReturnSuccess+ }++ let result = IOPMAssertionRelease(id)+ if result == kIOReturnSuccess || result == kIOReturnNotFound {+ id = IOPMAssertionID(kIOPMNullAssertionID)+ }+ return result == kIOReturnNotFound ? kIOReturnSuccess : result}- return result+ }++ private var sleepAssertion = Assertion(+ type: kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,+ name: "CodexBar - Codex activity" as CFString+ )+ private var displayAssertion = Assertion(+ type: kIOPMAssertionTypeNoDisplaySleep as CFString,+ name: "CodexBar - Codex activity display" as CFString+ )+ /// 复用同一个 ID 重新触发, 每次传 null 会新建一条, pmset -g assertions 里会堆成一串同名断言+ private var userActivityAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ private var userActivityTask: Task<Void, Never>?+ /// 上一拍声明成功没有, 用来只在成败翻转时记日志; 每轮起表时归位成"成功"+ private var didDeclareUserActivity = true++ /// 认节拍而不是认断言: 释放失败的那一轮会留下"断言还在但节拍已停", 认断言会把它当成还留着屏幕,+ /// 之后再要留住时被判定成无事可做, 于是屏幕不睡而屏保照常启动+ /// 反过来"节拍在而断言不在"不可达, 节拍只在断言建立成功之后才起+ var isPreventingDisplaySleep: Bool {+ userActivityTask != nil+ }++ func beginPreventingIdleSleep() -> IOReturn {+ sleepAssertion.begin()}func endPreventingIdleSleep() -> IOReturn {- guard assertionID != IOPMAssertionID(kIOPMNullAssertionID) else {- return kIOReturnSuccess+ sleepAssertion.end()+ }++ /// 屏幕不睡与不进屏保是两件事, 后者要靠节拍声明用户活动, 所以两者收在同一对方法里+ func beginPreventingDisplaySleep() -> IOReturn {+ let result = displayAssertion.begin()+ guard result == kIOReturnSuccess else {+ return result}- let result = IOPMAssertionRelease(assertionID)- if result == kIOReturnSuccess || result == kIOReturnNotFound {- assertionID = IOPMAssertionID(kIOPMNullAssertionID)+ startUserActivityTicks()+ return result+ }++ func endPreventingDisplaySleep() -> IOReturn {+ userActivityTask?.cancel()+ userActivityTask = nil+ didDeclareUserActivity = true+ if userActivityAssertionID != IOPMAssertionID(kIOPMNullAssertionID) {+ IOPMAssertionRelease(userActivityAssertionID)+ userActivityAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ }+ return displayAssertion.end()+ }++ /// 屏保与闲置锁屏跟的是系统 idle 计时, 显示断言只保证屏幕不睡, 挡不住它们+ private func startUserActivityTicks() {+ // 断言已在而节拍断了的那一轮会重新走到这里, 不先收掉旧的会留下一个空转的 Task+ userActivityTask?.cancel()+ userActivityTask = Task { @MainActor [weak self] in+ while !Task.isCancelled {+ guard let self else {+ return+ }++ declareUserActivity()+ try? await Task.sleep(for: Self.userActivityInterval)+ }+ }+ }++ /// 逐次声明不记日志, 只在成败翻转时记一条: 这是 30 秒一拍的高频路径, 持续失败会把日志刷满+ private func declareUserActivity() {+ let result = IOPMAssertionDeclareUserActivity(+ displayAssertion.name,+ kIOPMUserActiveLocal,+ &userActivityAssertionID+ )+ let didSucceed = result == kIOReturnSuccess+ defer {+ didDeclareUserActivity = didSucceed+ }+ guard didSucceed != didDeclareUserActivity else {+ return+ }++ if didSucceed {+ AppLog.keepAlive.notice("显示断言声明用户活动已恢复")+ } else {+ AppLog.keepAlive.error("显示断言声明用户活动失败: code=\(result)")}- return result == kIOReturnNotFound ? kIOReturnSuccess : result}static func currentStatus() -> Status? {@@ -84,6 +186,9 @@ final class SystemSleepService {return IOPMSleepSystem(connection)}+ /// 节拍取得比系统能设的最短屏保等待时间 (1 分钟) 小+ private static let userActivityInterval = Duration.seconds(30)+private static func booleanProperty(_ key: String,of rootDomain: io_service_tdiff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex e18ee00..71c28fa 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -88,7 +88,7 @@ final class CodexNotificationService: NSObject {}.store(in: &cancellables)- // 休眠可能错过重置次数的临期检查, 唤醒时补检+ // 睡眠可能错过重置次数的临期检查, 唤醒时补检NSWorkspace.shared.notificationCenter.publisher(for: NSWorkspace.didWakeNotification).receive(on: DispatchQueue.main)@@ -389,9 +389,9 @@ final class CodexNotificationService: NSObject {// MARK: - 低电量保护- /// 由 KeepAliveController 在低电量导致休眠恢复成功之后调用, 恢复失败不会走到这里+ /// 由 KeepAliveController 在低电量导致睡眠恢复成功之后调用, 恢复失败不会走到这里/// 不做去重: 调用方自己保证同一轮低电量只发一次, 电量回到解除门槛以上才算下一轮- /// async 是为了让调用方能等提交完再补发休眠, 否则合着盖的机器会先睡下去+ /// async 是为了让调用方能等提交完再补发睡眠, 否则合着盖的机器会先睡下去/// 返回是否真的发出去了: 调用方据此决定这一轮算不算已通知, 提交失败就不该占掉这一轮func notifyLowBatteryProtection(percent: Int) async -> Bool {guard settings.canDeliver, settings.isLowBatteryEnabled else {@@ -404,10 +404,10 @@ final class CodexNotificationService: NSObject {)?.value ?? false}- // MARK: - 防休眠时长上限+ // MARK: - 防睡眠时长上限- /// 由 KeepAliveController 在达到时长上限且休眠恢复成功之后调用- /// 调用时机与低电量通知相同, 必须赶在可能补发合盖休眠之前完成提交+ /// 由 KeepAliveController 在达到时长上限且睡眠恢复成功之后调用+ /// 调用时机与低电量通知相同, 必须赶在可能补发合盖睡眠之前完成提交func notifyKeepAliveLimitReached(durationText: String) async -> Bool {guard settings.canDeliver, settings.isKeepAliveLimitEnabled else {return false@@ -703,16 +703,16 @@ nonisolated struct CodexNotificationContent: Equatable {static func lowBattery(percent: Int) -> CodexNotificationContent {CodexNotificationContent(kind: "lowBattery",- title: "已恢复系统休眠",- body: "电量剩余 \(percent)%, 已停止防休眠"+ title: "已恢复系统睡眠",+ body: "电量剩余 \(percent)%, 已停止防睡眠")}static func keepAliveLimit(durationText: String) -> CodexNotificationContent {CodexNotificationContent(kind: "keepAliveLimit",- title: "已恢复系统休眠",- body: "已达防休眠上限 \(durationText), 已停止防休眠"+ title: "已恢复系统睡眠",+ body: "已达防睡眠上限 \(durationText), 已停止防睡眠")}}diff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex 10df1b2..bd491c5 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -14,7 +14,7 @@ final class CodexHookSettings: ObservableObject {@Published private(set) var isVerified = true/// Hook 链路真的通不通: hooks.json 里装着, 且最近一次校验没有明确失败- /// 依赖 Hook 的下游 (防休眠, 任务类通知) 一律看这个+ /// 依赖 Hook 的下游 (防睡眠, 任务类通知) 一律看这个/// isEnabled 只说明装了, Codex 那边全局关掉 hooks 或者不信任我们的 handler 时它照样是 truevar isOperable: Bool {isEnabled && isVerified@@ -168,7 +168,7 @@ final class CodexHookSettings: ObservableObject {/// @Published 在 willSet 无条件发信号, 而每次 App 激活都会跑一次校验/// 同值赋值会让设置页与两个子面板反复空转, 所以走这里- /// reason 是排查依据: 用户只会说"防休眠灰了", 那时得能从日志看出是全局禁用还是校验没过+ /// reason 是排查依据: 用户只会说"防睡眠灰了", 那时得能从日志看出是全局禁用还是校验没过/// "验不了"那一支不调这里, 结论保持不变也就不该记一条变化private func assignVerified(_ verified: Bool, reason: HookVerificationReason) {guard isVerified != verified else {diff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swiftindex 63c0867..383d4e8 100644--- a/CodexBar/Views/Menu/CodexActivityCard.swift+++ b/CodexBar/Views/Menu/CodexActivityCard.swift@@ -25,7 +25,7 @@ struct CodexActivityCard: View {}/// 额度数据不可用时卡片整体退到"暂无数据", 徽标属于活动信息, 必须跟着一起收- /// 否则会出现"暂无数据"配上防休眠徽标的自相矛盾画面+ /// 否则会出现"暂无数据"配上防睡眠徽标的自相矛盾画面private var showsKeepAliveBadge: Bool {keepAliveController.isActivelyPreventingSleep && !showsUnavailableState}@@ -77,12 +77,12 @@ struct CodexActivityCard: View {Spacer(minLength: 0)if showsKeepAliveBadge {- // 防休眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行+ // 防睡眠只在任务运行期间生效, 所以状态挂在活动卡片上而不是单独占一行Image(systemName: "cup.and.saucer.fill").font(.system(size: 11, weight: .semibold)).foregroundStyle(Color.teal).transition(.opacity)- .help("已防止系统休眠")+ .help("已防止系统睡眠")}if content.otherTaskCount > 0 {diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 3805042..beabfbb 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -399,7 +399,7 @@ private extension AppSettingsView {}}- // MARK: - 防休眠+ // MARK: - 防睡眠var keepAliveRow: some View {let caption = keepAliveCaption@@ -407,7 +407,7 @@ private extension AppSettingsView {return VStack(alignment: .leading, spacing: 4) {SettingsToggleRow(icon: "moon.zzz",- title: "防止系统休眠",+ title: "防止系统睡眠",isOn: Binding(get: { keepAliveController.isEnabled },set: { keepAliveController.setEnabled($0) }@@ -478,7 +478,7 @@ private extension AppSettingsView {}/// 返回 nil 表示这一行整个收起- /// 正常运行时不必占一行说"一切正常", 是否正在防休眠由主面板的咖啡杯标记呈现+ /// 正常运行时不必占一行说"一切正常", 是否正在防睡眠由主面板的咖啡杯标记呈现var keepAliveCaption: KeepAliveCaption? {if let errorMessage = keepAliveController.errorMessage {return KeepAliveCaption(message: errorMessage, isError: true)@@ -492,15 +492,15 @@ private extension AppSettingsView {return KeepAliveCaption(message: "CodexBar Hook 未生效")}guard keepAliveController.isEnabled else {- return KeepAliveCaption(message: "当有 Codex 任务运行时防止系统休眠, 任务结束后自动恢复")+ return KeepAliveCaption(message: "当有 Codex 任务运行时防止系统睡眠, 任务结束后自动恢复")}- // 低电量拦下时开关开着却不防休眠, 不留一句无从解释+ // 低电量拦下时开关开着却不防睡眠, 不留一句无从解释// 判定用 isLowBatteryBlocking 而不是 isLowBatteryActive: 后者在没有任务时也成立, 那时无话可说// 它成立即意味着 helper 已就绪, 所以排在下面那个 switch 之前不影响 helper 类问题的呈现// 不写具体阈值: 滞回让保护一直持续到阈值加 5, 说死数字会与用户看到的电量对不上if keepAliveController.isLowBatteryBlocking {- return KeepAliveCaption(message: "电量过低, 已恢复系统休眠")+ return KeepAliveCaption(message: "电量过低, 已恢复系统睡眠")}switch keepAliveController.helperStatus {@@ -517,7 +517,7 @@ private extension AppSettingsView {return nil}return KeepAliveCaption(- message: "已达到防休眠时间上限 (\(keepAliveController.maximumDuration.title))"+ message: "已达到防睡眠时间上限 (\(keepAliveController.maximumDuration.title))")}}@@ -675,7 +675,7 @@ private extension AppSettingsView {rebuildableDates = WorkflowStorage.rebuildableEventDateKeys()}- /// 防休眠不在这里刷: 控制器自己订阅了 didBecomeActive, 窗口打开也走 refreshSettingsState+ /// 防睡眠不在这里刷: 控制器自己订阅了 didBecomeActive, 窗口打开也走 refreshSettingsState/// 再调一次会让每次激活都多跑一遍电源读取 helper 状态查询和 helper 二进制哈希func refreshStatusRows() {refreshCodexVersionSection()diff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftindex 8ea68ef..4005477 100644--- a/CodexBar/Views/Settings/KeepAliveOptionsView.swift+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -1,12 +1,14 @@import SwiftUI-/// 防休眠子选项面板, 挂在设置窗口右侧, 顶边对齐设置页的防休眠主开关行+/// 防睡眠子选项面板, 挂在设置窗口右侧, 顶边对齐设置页的防睡眠主开关行/// 行样式与度量沿用通知子面板, 只有面板宽度按内容收窄struct KeepAliveOptionsView: View {@ObservedObject var keepAliveController: KeepAliveControllervar body: some View {VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ waitingApprovalRow+ displayAwakeRowmaximumDurationRow// 台式机读不到电池, 这一行整个收起而不是置灰@@ -25,15 +27,15 @@ struct KeepAliveOptionsView: View {CGSize(width: Metrics.panelWidth,height: Metrics.verticalPadding * 2- + (Metrics.rowHeight + Metrics.captionRowHeight) * 2- + Metrics.rowSpacing+ + (Metrics.rowHeight + Metrics.captionRowHeight) * CGFloat(Metrics.maximumRowCount)+ + Metrics.rowSpacing * CGFloat(Metrics.maximumRowCount - 1))}private var maximumDurationRow: some View {pickerRow(- title: "最长防休眠时间",- caption: "防休眠时长超过阈值后自动恢复系统休眠",+ title: "最长防睡眠时间",+ caption: "防睡眠时长超过阈值后自动恢复系统睡眠",selection: Binding(get: { keepAliveController.maximumDuration },set: { keepAliveController.setMaximumDuration($0) }@@ -43,6 +45,30 @@ struct KeepAliveOptionsView: View {)}+ /// 只改"哪些任务算数", 没有额外依赖, 所以不置灰也不隐藏+ private var waitingApprovalRow: some View {+ toggleRow(+ title: "等待批准时保持",+ caption: "任务等待批准期间继续防止系统睡眠",+ isOn: Binding(+ get: { keepAliveController.keepsAwakeWhileWaiting },+ set: { keepAliveController.setKeepsAwakeWhileWaiting($0) }+ )+ )+ }++ /// 只在防睡眠真的生效时留住屏幕, 所以和上面那一行一样没有额外依赖+ private var displayAwakeRow: some View {+ toggleRow(+ title: "保持屏幕常亮",+ caption: "同时阻止屏幕保护与自动锁屏",+ isOn: Binding(+ get: { keepAliveController.keepsDisplayAwake },+ set: { keepAliveController.setKeepsDisplayAwake($0) }+ )+ )+ }+private var lowBatteryRow: some View {pickerRow(title: "低电量保护",@@ -56,13 +82,44 @@ struct KeepAliveOptionsView: View {)}- /// 第二行的固定说明与通知子面板的音效子行同一套字号和层级private func pickerRow<Option: Hashable>(title: String,caption: String,selection: Binding<Option>,options: [Option],label: KeyPath<Option, String>+ ) -> some View {+ row(title: title, caption: caption) {+ SettingsOptionsPicker(+ title: title,+ selection: selection,+ options: options,+ label: { $0[keyPath: label] },+ width: Metrics.pickerWidth,+ alignment: .trailing+ )+ }+ }++ /// 开关的修饰链与通知子面板的 optionRow 保持一致, 两个面板才是同一套控件+ private func toggleRow(+ title: String,+ caption: String,+ isOn: Binding<Bool>+ ) -> some View {+ row(title: title, caption: caption) {+ Toggle(title, isOn: isOn)+ .labelsHidden()+ .toggleStyle(.switch)+ .controlSize(.mini)+ }+ }++ /// 面板里每一行都是控件行加一句固定说明, 说明那行与通知子面板的音效子行同一套字号和层级+ private func row(+ title: String,+ caption: String,+ @ViewBuilder control: () -> some View) -> some View {VStack(spacing: 0) {HStack(spacing: Metrics.controlSpacing) {@@ -72,14 +129,7 @@ struct KeepAliveOptionsView: View {Spacer(minLength: 8)- SettingsOptionsPicker(- title: title,- selection: selection,- options: options,- label: { $0[keyPath: label] },- width: Metrics.pickerWidth,- alignment: .trailing- )+ control()}.frame(height: Metrics.rowHeight)@@ -96,6 +146,8 @@ struct KeepAliveOptionsView: View {private enum Metrics {static let panelWidth: CGFloat = 250+ /// 有内置电池的设备时行数, 无内置电池设备少一行低电量保护+ static let maximumRowCount = 4static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingdiff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex 4715514..ad496c5 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -34,7 +34,7 @@ struct NotificationOptionsView: View {width: Metrics.panelWidth,height: Metrics.verticalPadding * 2+ Metrics.notificationRowHeight * CGFloat(Metrics.notificationRowCount)- + Metrics.rowHeight * CGFloat(Metrics.standardRowCount)+ + Metrics.captionedRowHeight * CGFloat(Metrics.captionedRowCount)+ Metrics.rowSpacing * CGFloat(Metrics.totalRowCount - 1))}@@ -129,14 +129,18 @@ struct NotificationOptionsView: View {private var taskHapticRow: some View {let isDisplayedOn = codexHookSettings.isOperable && notificationSettings.isTaskHapticEnabled- return optionRow(- title: "任务触觉反馈",- isOn: Binding(- get: { isDisplayedOn },- set: { notificationSettings.setTaskHapticEnabled($0) }- ),- isEnabled: codexHookSettings.isOperable- )+ return VStack(spacing: 0) {+ optionRow(+ title: "任务触觉反馈",+ isOn: Binding(+ get: { isDisplayedOn },+ set: { notificationSettings.setTaskHapticEnabled($0) }+ ),+ isEnabled: codexHookSettings.isOperable+ )++ captionRow("任务完成或等待批准时触发触摸板震动")+ }}private var creditExpiryRow: some View {@@ -153,10 +157,10 @@ struct NotificationOptionsView: View {)}- /// 防休眠关着或低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled+ /// 防睡眠关着或低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled/// 保护默认就是关的, 不置灰会让这一行在任何默认安装上都亮着, 而对应通知永远发不出来/// "保护是不是真的在起作用"由 KeepAliveController 判定, 这里只读结论- /// 它同时覆盖了台式机: 那时防休眠面板整行隐藏低电量保护, 而阈值可能是从笔记本迁移过来的非 off 值+ /// 它同时覆盖了台式机: 那时防睡眠面板整行隐藏低电量保护, 而阈值可能是从笔记本迁移过来的非 off 值private var lowBatteryRow: some View {let isProtectionOn = keepAliveController.isLowBatteryProtectionEnabledlet isDisplayedOn = isProtectionOn && notificationSettings.isLowBatteryEnabled@@ -175,14 +179,14 @@ struct NotificationOptionsView: View {)}- /// 防休眠关着或选了无限制时显示为关闭并置灰, 不修改持久化的 isKeepAliveLimitEnabled+ /// 防睡眠关着或选了无限制时显示为关闭并置灰, 不修改持久化的 isKeepAliveLimitEnabled/// 与低电量那一行同一个做法, "上限会不会到点"由 KeepAliveController 判定, 这里只读结论private var keepAliveLimitRow: some View {let hasLimit = keepAliveController.isMaximumDurationEnabledlet isDisplayedOn = hasLimit && notificationSettings.isKeepAliveLimitEnabledreturn notificationOptionRow(- title: "防休眠上限通知",+ title: "防睡眠上限通知",isOn: Binding(get: { isDisplayedOn },set: { notificationSettings.setKeepAliveLimitEnabled($0) }@@ -196,24 +200,28 @@ struct NotificationOptionsView: View {}private var codexCLINotificationRow: some View {- optionRow(- title: "Codex TUI 通知",- isOn: Binding(- get: { codexCLINotificationSettings.isEnabled },- set: { codexCLINotificationSettings.setEnabled($0) }- ),- isEnabled: !codexCLINotificationSettings.isUpdating- ) {- if codexCLINotificationSettings.isUpdating {- ProgressView()- .controlSize(.mini)- .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)- } else if let errorMessage = codexCLINotificationSettings.errorMessage {- Image(systemName: "exclamationmark.circle")- .foregroundStyle(.orange)- .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)- .help(errorMessage)+ VStack(spacing: 0) {+ optionRow(+ title: "Codex TUI 通知",+ isOn: Binding(+ get: { codexCLINotificationSettings.isEnabled },+ set: { codexCLINotificationSettings.setEnabled($0) }+ ),+ isEnabled: !codexCLINotificationSettings.isUpdating+ ) {+ if codexCLINotificationSettings.isUpdating {+ ProgressView()+ .controlSize(.mini)+ .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)+ } else if let errorMessage = codexCLINotificationSettings.errorMessage {+ Image(systemName: "exclamationmark.circle")+ .foregroundStyle(.orange)+ .frame(width: Metrics.statusIconSize, height: Metrics.statusIconSize)+ .help(errorMessage)+ }}++ captionRow("Codex TUI 通知, 独立于 CodexBar 通知")}}@@ -229,8 +237,6 @@ struct NotificationOptionsView: View {}}- /// Swift 6.3.3 在 -O 下会让这两个行构建器中的原生 mini Switch 漏绘 thumb- @_optimize(none)private func optionRow(title: String,isOn: Binding<Bool>,@@ -255,6 +261,17 @@ struct NotificationOptionsView: View {.frame(height: Metrics.rowHeight)}+ private func captionRow(_ caption: String) -> some View {+ HStack(spacing: 0) {+ Text(caption)+ .font(.caption2)+ .foregroundStyle(.tertiary)++ Spacer(minLength: 0)+ }+ .frame(height: Metrics.secondaryRowHeight)+ }+private func notificationOptionRow(title: String,isOn: Binding<Bool>,@@ -271,7 +288,6 @@ struct NotificationOptionsView: View {}}- @_optimize(none)private func notificationOptionRow(title: String,isOn: Binding<Bool>,@@ -417,12 +433,14 @@ struct NotificationOptionsView: View {static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPaddingstatic let verticalPadding = SettingsOptionsPanelMetrics.verticalPaddingstatic let notificationRowCount = 7- static let standardRowCount = 2- static let totalRowCount = notificationRowCount + standardRowCount+ static let captionedRowCount = 2+ static let totalRowCount = notificationRowCount + captionedRowCountstatic let rowSpacing = SettingsOptionsPanelMetrics.rowSpacingstatic let rowHeight = SettingsOptionsPanelMetrics.rowHeight- static let soundRowHeight = SettingsOptionsPanelMetrics.secondaryRowHeight+ static let secondaryRowHeight = SettingsOptionsPanelMetrics.secondaryRowHeight+ static let soundRowHeight = secondaryRowHeightstatic let notificationRowHeight = rowHeight + soundRowHeight+ static let captionedRowHeight = rowHeight + secondaryRowHeightstatic let notificationControlSpacing = SettingsOptionsPanelMetrics.controlSpacingstatic let pickerWidth: CGFloat = 68static let soundMenuWidth: CGFloat = 160diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex 5327691..14e576b 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -13,7 +13,7 @@ enum SettingsOptionsPanelMetrics {static let verticalPadding: CGFloat = 10static let rowSpacing: CGFloat = 5static let rowHeight: CGFloat = 22- /// 第二行的高度, 通知面板用于音效子行, 防休眠面板用于固定说明+ /// 第二行的高度, 通知面板用于音效子行, 防睡眠面板用于固定说明static let secondaryRowHeight: CGFloat = 18static let controlSpacing: CGFloat = 6static let cornerRadius: CGFloat = 12diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex 376ef65..be0f245 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -41,7 +41,7 @@ private enum SentinelState {case present(previouslyDisabled: Bool)case unreadable(Error)- /// 读取失败也必须进入恢复流程: 记录损坏时无法排除「休眠正被我们禁用着」+ /// 读取失败也必须进入恢复流程: 记录损坏时无法排除「睡眠正被我们禁用着」var needsRestore: Bool {switch self {case .absent:@@ -151,7 +151,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code}helperLog.notice("Helper 已启动: sentinel=\(sentinelName, privacy: .public)")- // 读取失败也必须进入恢复流程: 记录损坏时无法排除「休眠正被我们禁用着」+ // 读取失败也必须进入恢复流程: 记录损坏时无法排除「睡眠正被我们禁用着」if startupSentinel.needsRestore {_ = restoreSleep(trigger: .helperStartup)}@@ -244,7 +244,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code}}- // MARK: - 休眠切换与恢复+ // MARK: - 睡眠切换与恢复private func disableSleep() -> Int32 {var didCreateSentinel = false@@ -255,10 +255,10 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, CodesentinelValue = previouslyDisabled ? "1" : "0"case let .unreadable(error):// 不能用当前的 SleepDisabled 覆写损坏的记录: 当前值可能正是我们自己禁用的结果- // 那会把「原本允许休眠」错记成「原本已禁用」让后续恢复永久跳过+ // 那会把「原本允许睡眠」错记成「原本已禁用」让后续恢复永久跳过let sentinelPath = sentinelURL.pathhelperLog.error(- "休眠哨兵损坏: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "睡眠哨兵损坏: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")return -1case .absent:@@ -277,7 +277,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code} catch {let sentinelPath = sentinelURL.pathhelperLog.error(- "休眠哨兵写入失败: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)"+ "睡眠哨兵写入失败: path=\(sentinelPath, privacy: .public); detail=\(error.localizedDescription, privacy: .public)")return -1}@@ -289,12 +289,12 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codetry? FileManager.default.removeItem(at: sentinelURL)}helperLog.error(- "系统休眠关闭失败: exit=\(result.exitCode); detail=\(result.output, privacy: .public)"+ "系统睡眠关闭失败: exit=\(result.exitCode); detail=\(result.output, privacy: .public)")return result.exitCode}- helperLog.notice("系统休眠已关闭: sentinel=\(sentinelValue, privacy: .public)")+ helperLog.notice("系统睡眠已关闭: sentinel=\(sentinelValue, privacy: .public)")return 0}@@ -304,15 +304,15 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codeswitch sentinelState() {case .absent:// 没接管过就没有要恢复的东西, 这个值只是占位, 不代表系统真实状态- // 必须保持 true: App 用它抑制补发合盖休眠, 换成实测值会让从未接管的这一轮把机器按睡+ // 必须保持 true: App 用它抑制补发合盖睡眠, 换成实测值会让从未接管的这一轮把机器按睡return SleepRestoreResult(exitCode: 0, restoredSleepDisabled: true)case let .present(value):previouslyDisabled = valuecase let .unreadable(error):- // 读不出原值时按系统默认的「允许休眠」恢复+ // 读不出原值时按系统默认的「允许睡眠」恢复// 宁可多恢复一次(pmset 幂等), 也不能把 SleepDisabled=1 永久留给用户helperLog.error(- "休眠哨兵读取失败: trigger=\(trigger.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public); action=forceRestore"+ "睡眠哨兵读取失败: trigger=\(trigger.rawValue, privacy: .public); detail=\(error.localizedDescription, privacy: .public); action=forceRestore")previouslyDisabled = false}@@ -321,7 +321,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codelet result = PmsetRunner.setSleepDisabled(previouslyDisabled)guard result.exitCode == 0 else {helperLog.error(- "系统休眠恢复失败: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue); exit=\(result.exitCode); detail=\(result.output, privacy: .public)"+ "系统睡眠恢复失败: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue); exit=\(result.exitCode); detail=\(result.output, privacy: .public)")return SleepRestoreResult(exitCode: result.exitCode,@@ -331,7 +331,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codetry? FileManager.default.removeItem(at: sentinelURL)helperLog.notice(- "系统休眠已恢复: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue)"+ "系统睡眠已恢复: trigger=\(trigger.rawValue, privacy: .public); sleepDisabled=\(previousValue)")return SleepRestoreResult(exitCode: 0,@@ -597,9 +597,9 @@ private enum CodexBarHelperError: LocalizedError {var errorDescription: String? {switch self {case let .insecureSentinelDirectory(detail):- "休眠设置目录无效: \(detail)"+ "睡眠设置目录无效: \(detail)"case let .invalidSentinel(detail):- "休眠设置记录无效: \(detail)"+ "睡眠设置记录无效: \(detail)"case let .codeSigningValidationFailed(reason):"签名校验失败: \(reason)"}diff --git a/README.md b/README.mdindex 8f5af52..f8cfca1 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@ CodexBar 把 Codex 的运行状态收进菜单栏: 账户信息, 剩余额度,## 特性-其中实时任务, 热力图面板中的详细统计数据与防休眠功能依赖 CodexBar Hook, 开启方式见[关于 Hook](#关于-hook)+其中实时任务, 热力图面板中的详细统计数据与防睡眠功能依赖 CodexBar Hook, 开启方式见[关于 Hook](#关于-hook)### 账户信息@@ -50,18 +50,20 @@ CodexBar 把 Codex 的运行状态收进菜单栏: 账户信息, 剩余额度,- 开启 CodexBar Hook 后的会话还可统计对话轮次, 工具调用, 权限请求, 上下文压缩, 子 Agent 等指标- 可选开启 iCloud 同步, 在多台 Mac 之间同步数据-### 防止系统休眠+### 防止系统睡眠-需要长时间运行 Codex 任务但是怕系统自动休眠?+需要长时间运行 Codex 任务但是怕系统自动睡眠?-- 仅在任务运行期间防止系统休眠, 任务结束恢复系统休眠设置-- 可设置最长防休眠时间 1, 2, 4, 8, 12, 24 小时或无限制-- 可开启低电量保护, 使用电池且电量跌破阈值时恢复系统休眠, 接通电源后自动恢复防休眠-- 防休眠状态可在主面板的任务卡片右侧显示一个咖啡杯标记+- 仅在任务运行期间防止系统睡眠, 任务结束恢复系统睡眠设置+- 可开启等待批准时保持, 任务等待批准期间继续防止系统睡眠+- 可开启保持屏幕常亮, 防睡眠期间同时阻止屏幕保护与自动锁屏+- 可设置最长防睡眠时间 1, 2, 4, 8, 12, 24 小时或无限制+- 可开启低电量保护, 使用电池且电量跌破阈值时恢复系统睡眠, 接通电源后自动恢复防睡眠+- 防睡眠状态可在主面板的任务卡片右侧显示一个咖啡杯标记### 通知与提醒-- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期, 低电量保护生效, 防休眠阈值+- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期, 低电量保护生效, 防睡眠阈值- 通知音效独立设置- 任务状态变化可设置触摸板震动反馈通知@@ -102,17 +104,17 @@ brew install --cask bob-zebedy/tap/codexbar### 关于 Hook-实时任务展示, 热力图统计数据与防休眠都依赖 CodexBar Hook+实时任务展示, 热力图统计数据与防睡眠都依赖 CodexBar Hook> [!NOTE]> 不会影响任何原本的 Codex Hook-### 关于防休眠+### 关于防睡眠开启后需要一个 Helper 进行守护, 因此首次开启时 macOS 会要求授权后台项目; 该功能同样依赖 CodexBar Hook> [!WARNING]-> 为了避免异常任务导致系统长时间处于禁止休眠状态, 建议设置最长防休眠时间+> 为了避免异常任务导致系统长时间处于禁止睡眠状态, 建议设置最长防睡眠时间## 隐私@@ -152,7 +154,7 @@ flowchart LRB2 --> UIC3 --> UIC3 --> N["通知事件"]- C3 --> K["防休眠"]+ C3 --> K["防睡眠"]```<details>diff --git a/Shared/CodexBarHelperXPC.swift b/Shared/CodexBarHelperXPC.swiftindex cd5d6bc..8058c7f 100644--- a/Shared/CodexBarHelperXPC.swift+++ b/Shared/CodexBarHelperXPC.swift@@ -8,6 +8,9 @@ nonisolated enum CodexBarHelperIPC {static let daemonPlistName = machServiceName + ".plist"static let watchdogGraceSeconds: TimeInterval = 15static let sentinelCheckIntervalSeconds: TimeInterval = 60+ /// App 侧等回复的上限, 与 watchdog 宽限是一对: 必须更小, 这样 App 先放手 helper 再自行兜底+ /// helper 冷启动加一次 pmset 通常一秒内完成, 留这么宽只为排除偶发的调度抖动+ static let requestTimeoutSeconds: TimeInterval = 10private static let bundleIdentifier: String = {guard let identifier = Bundle.main.bundleIdentifier, !identifier.isEmpty else {@@ -19,7 +22,7 @@ nonisolated enum CodexBarHelperIPC {@objc nonisolated protocol CodexBarHelperProtocol: AnyObject {/// reply 的两个参数是 pmset 退出码, 与恢复写回的 SleepDisabled 值- /// 写回的是接管前的原值, 所以第二个参数不等于请求值: 系统原本就禁用休眠时恢复后仍是禁用+ /// 写回的是接管前的原值, 所以第二个参数不等于请求值: 系统原本就禁用睡眠时恢复后仍是禁用/// 但 helper 本轮没接管过或 pmset 操作失败时它只是占位的 true, 并非实测状态/// 调用方要先确认退出码为 0, 且自己的接管过程没有被连接中断打断, 才能把它当成实测值func setSleepDisabled(diff --git a/appcast.xml b/appcast.xmlindex ae2ac88..558b811 100644--- a/appcast.xml+++ b/appcast.xml@@ -7,6 +7,15 @@<link>https://codexbar.zabrian.app/appcast.xml</link><description>CodexBar appcast feed</description><language>zh-CN</language>+ <item>+ <title>CodexBar.app 3.5.10</title>+ <sparkle:version>64</sparkle:version>+ <sparkle:shortVersionString>3.5.10</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.10</sparkle:releaseNotesLink>+ <pubDate>Sat, 01 Aug 2026 23:53:34 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.10.dmg" sparkle:edSignature="hODeMRnBs1RYwWDv4I8mre1z1cTw+vUzsaXQJHL5dVXw6kOGdz+62i+XNXY974m4LyDXFLhOug2MJHo1v5nODw==" length="6625904" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.5.9</title><sparkle:version>63</sparkle:version>