CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 增强防休眠保护与设置面板
Bob1c9c4336f67e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 20fd9d1..9866d17 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -47,8 +47,9 @@ Scripts/dmg.sh # 打包 DMGScripts/appcast.sh # sign_update 签名并写入 appcast.xml# 注销 KeepAlive LaunchDaemon; 清理前需先退出所有 CodexBar 实例-# 常用: --dry-run 只显示目标, --check 只验证临时清理 App,-# --release-only / --debug-only 限定范围, --sign-identity 指定签名身份+# 不带参数时同时处理 Release 与 Debug 两套+# 常用: --release / --debug 限定范围, --check 只验证目标不真的注销+# 签名身份取环境变量 CODEXBAR_CLEANUP_SIGN_IDENTITY, 默认 Apple DevelopmentScripts/cleanup.swift --help```@@ -128,20 +129,49 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev关键约束-- `shouldDisableSleep` 是用户意图与依赖可用性的唯一汇合点, 要求 `isEnabled && codexHookSettings.isEnabled && hasRunningTasks && helperStatus == .enabled && !hasReachedMaximumDuration` 同时成立; **依赖不满足只让效果失效, 绝不回写用户保存的 `isEnabled`**+- `shouldDisableSleep` 是用户意图与依赖可用性的唯一汇合点, 要求 `isStarted && isEnabled && isHookEnabled && hasRunningTasks && helperStatus == .enabled && !isRefreshingHelper && !isLowBatteryActive && !hasReachedMaximumDuration` 同时成立; **依赖不满足只让效果失效, 绝不回写用户保存的 `isEnabled`**+- Hook 状态在类内只认 `isHookEnabled` 这份镜像, 不要回读 `codexHookSettings.isEnabled` 那个属性: 订阅回调跑在 `willSet`, 那一刻它还是改动前的值+- 新增拦截条件一律加进 `sleepBlockReason` 的顺序判断里, 它和 `shouldDisableSleep` 同源, 顺带保证日志的 `reason=` 不会漏项+- UI 用的 `isLowBatteryBlocking` 与 `canShowOptions` 由 `reconcileSleepState` 从 `sleepBlockReason` 单点派生, 新增拦截条件时 `allowsOptions` 那个穷举 `switch` 会强制表态, 于是不会出现入口亮着却点不动+- `hasRunningTasks` 与 `isRefreshingHelper` 都不带 `@Published` 标注, 它们变得比结论频繁, 各自发信号会把整个设置页拖着一起重算- 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 分钟) 即放弃, 瞬时抖动能自愈, 权限类故障不该无限重试- helper 回传的 `restoredSleepDisabled` 只有 `.present` 分支是实测值, `.absent` (本轮没接管过) 与 pmset 失败时都是占位的 `true`; App 侧靠 `canTrustRestoreResult` (接管到恢复之间连接未断) 判断可不可信, 这是从未接管的一轮里不误发 `IOPMSleepSystem` 的唯一屏障, 不要把 `.absent` 改成回实测值+- 低电量保护由 `PowerSourceMonitor` 供数, 它只报事实 (有没有内置电池, 电量, 是否靠电池供电), 不知道阈值; 读数保持 `unavailable` `unreadable` `present` 三态, 把读取失败折叠成"没有电池"会让设置项凭空消失且保护静默失效+- 见过一次内置电池就记住 `hasSeenBattery`, 之后读到空列表只能返回 `unreadable`; 硬件不会中途消失, 空列表只是 IOKit 重新枚举时的缺口, 当成台式机会当场撤掉保护+- `hasSeenBattery` 只活在进程内不持久化, 每次启动重新判定; 笔记本启动时撞上枚举缺口会短暂显示成没有电池, 由下一次电源通知自愈, 而持久化会让从笔记本备份恢复的台式机永远多出低电量设置项+- `IOPSNotificationCreateRunLoopSource` 注册失败时降级成 60 秒轮询并记 `action=poll`; 只靠 `didWakeNotification` 补读不够, 防休眠生效的机器按定义就不会睡, 那条通知永远不来+- 首次读取在 `start()` 里单独判一次并记 `stage=start` 这条, 不能改走 `refresh()` 那条路: 后者按变化过滤, 而读数初始值就是 `unreadable` 本身, 首读失败会被静默吞掉, 之后只留下一条没有配对失败行的恢复日志+- 防休眠上限累计的是**真正挡住休眠**的那段时间, `begin` 起表 `pause` 收表, 收表之后机器睡着或被低电量拦下都不占用户的上限+- 上限计时用 `SuspendingClock` 而不是 `Date`, 后者受系统时间调整影响且系统睡眠期间照走; 排计时器的 `Task.sleep` 同样要传 `SuspendingClock`, 否则睡一夜醒来会当场判定到期+- 低电量是**纯条件**判定, 不设"低过电"的粘滞标志: 电量会回升, 充上电就该自动恢复防休眠; `hasReachedMaximumDuration` 之所以是粘滞标志只因为累计只增不减, 两者不要照抄+- 低电量必须同时满足在用电池与电量低于阈值, 只看百分比会让"剩 5% 插上电再跑任务"当场被判低电量; 判定用 `Power Source State`, 不能用 `Is Charging` (接电停充时它也是 false)+- 电量读不到时维持上一次的判定, 从没读到过就是不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制休眠兜底+- 已经在低电量保护中时读数失败不清零, 否则一次瞬时失败会绕过滞回, 让防休眠反复开关并重发通知+- 低电量通知只在 `isActivelyPreventingSleep` 为真时排队, 没挡过就不说"已恢复系统休眠"; 日志无条件记并用 `action=release|none` 区分, 百分比只有那一条能看到+- 排队的通知要等 helper 恢复休眠的 XPC 回复确认成功才发得出去, 恢复失败走重试直至放弃, 提前说"已恢复系统休眠"会把用户骗去合盖然后把电耗干+- 补发 `IOPMSleepSystem` 之前还要 `await` 到通知真的提交完成, 只把提交排进下一个 MainActor job 的话同一个 job 里的补发会抢在它前面+- 那次 `await` 之后要重认一次 `generation` 再走 `finishSleepRestore` 这一步, 挂起期间可能已有新的禁用请求接管, 否则会释放掉刚建立的空闲断言+- 设置页那句低电量说明看 `isLowBatteryBlocking` 而不是 `isLowBatteryActive`, 后者在没有任务时也成立, 那时无话可说+- 触发与解除用 `阈值` 与 `阈值 + 5%` 两道门槛, 否则电量在阈值附近抖动会反复切 pmset, 合盖时还会反复补发 `IOPMSleepSystem`+- 一轮低电量通知的终点是电量回到 `阈值 + 5%` 或者用户改了阈值, 由 `hasNotifiedLowBattery` 记住; 只看是否接电会让适配器接触不良时每翻一次供电状态就重发一条+- `hasNotifiedLowBattery` 只在通知真的提交成功之后才置位, 打在入队处或提交前都会让没送达的那一条吃掉整轮配额, 使这一轮之后真正触发的低电量再也提醒不了+- `hasNotifiedLowBattery` 只管通知不管判定, 与上面"纯条件"不冲突: 电量回到解除门槛以下再跌破仍算同一轮, 不会重复提醒+- `SleepConditions` 里只放 `battery` 布尔, 放电量百分比会让每掉 1% 刷一条变化日志; 真实电量只在触发那一条单独记- 状态只呈现在主面板活动卡片右侧的咖啡杯标记 (带 tooltip), 由 `KeepAliveController.isActivelyPreventingSleep` 驱动, 卡片折叠成"暂无数据"时标记要跟着一起收-- 设置页那一行说明只在异常或达到上限时出现, 正常运行时整行收起, `keepAliveCaption` 返回 nil 即代表收起+- 设置页那一行说明只在异常, 低电量生效或达到上限时出现, 正常运行时整行收起, `keepAliveCaption` 返回 nil 即代表收起+- 最长防休眠时间与低电量阈值都在防休眠子面板里, 台式机读不到电池时低电量那一行整行隐藏而不是置灰- **菜单栏图标不承载防休眠状态**, 它要保持模板渲染让系统按菜单栏外观着色, 自行着色在深浅和带染色的菜单栏下都会失控### 通知- `CodexNotificationService` 是集中式的 MainActor 服务, 订阅额度快照与实时活动, 负责阈值穿越判定, 去重, 额度重置识别, 触觉反馈和本地通知; dedup key 落 UserDefaults+- `send` 是唯一的提交入口, 返回一个 `Task<Bool, Never>?` 值, 需要等通知真的发出去再做下一步的调用方 `await` 它的 `value` 即可; 不要另开一条 async 通道, 那会悄悄少掉去重 时效判定与提交失败回调三项能力+- 去重判定留在 `send` 的同步段而不是挪进 `Task` 内部, 这样连续两次调用的第二次一定被挡下, 不依赖任务调度顺序- `NotificationSettings` 管 CodexBar 自身通知; `CodexCLINotificationSettings` 是另一回事, 它通过 app-server `config/read` 与 `config/batchWrite` 读写 Codex 自己的用户级 `config.toml`+- 通知面板里带依赖的行一律显示为关闭并置灰而不是隐藏, 任务类看 `codexHookSettings.isEnabled`, 低电量保护通知看 `KeepAliveController.isLowBatteryProtectionEnabled` (阈值开着且这台机器确实有电池); 都不回写用户保存的开关### 并发与隔离@@ -167,7 +197,7 @@ 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 效果), 任务, Hook, codex, 通知+- 词根固定, 一个词能 grep 出整条链路: 额度, 统计刷新 (调度层), 事件汇总 (计算层), 同步, KeepAlive (防休眠决策层), 空闲断言 (进程内 `IOPMAssertion`), Helper 注册 (`SMAppService`), Helper XPC (`NSXPCConnection`), 系统休眠 (helper 的 pmset 效果), 电源监听 (`PowerSourceMonitor`), 任务, Hook, codex, 通知- 防休眠日志按两套机制分组: `KeepAlive` 是两套共用的决策层, `空闲断言` 是机制一, `Helper 注册` `Helper XPC` `系统休眠` 是机制二的授权 传输 效果三层, 故障定位就是在这几层里找- `trigger=` 由 `LogTrigger` 提供, 从 UI 入口透传到服务层, 用来区分同一条链路是被用户动作 定时轮询还是系统事件踢起来的; 统计维护挂在额度刷新完成事件上, 它的 trigger 继承那一次刷新- 变化检测类日志只在值真的变了才记, 例如 `KeepAlive 条件已变化` 与 `Hook 配置已变化` 各自存一份上次的值, 否则每次开面板都会刷一条@@ -184,8 +214,20 @@ Hook 子进程按天写入 `~/Library/Application Support/CodexBar/HookEvents/ev- 菜单栏按钮左键切换主面板; 右键或 Control+点击打开上下文菜单; `⌘,` 打开自定义设置窗口, 菜单面板打开时 `⌘L` 打开日志窗口; 默认全局快捷键 `⌘⇧W` 由 `GlobalHotKeySettings` 与 `GlobalHotKeyController` 管理- 主面板是锚定 status item 的 `NSPopover` 弹窗, 锚点不可信时回退到 `FallbackPanelController` 提供的屏幕顶部居中 `NSPanel` 面板, 处理快捷键, 屏幕选择和焦点时要保留这两个分支- 关闭逻辑统一由 `MenuSurfaceDismissMonitor` 管理, 淡出由 `MenuSurfaceFadeCoordinator` 负责-- 侧边面板都是 borderless nonactivating child panel, 热力图详情, 重置次数和任务中心挂在主面板上, 通知选项挂在设置窗口上-- 侧边面板公共能力集中在 `Controllers/SidePanelSupport.swift` 里, 含 `SidePanelDrawerPresenter` `SidePanelContentHost` `SidePanelDrawerAnimator` panel 工厂和定位夹紧; 新增面板优先复用 `SidePanelDrawerPresenter` 这一层, 不要另起一套+- 侧边面板都是 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` 一条, 防休眠面板只订 `$hasBattery` 一条; 订整个防休眠控制器会让任务每起停一次都白排一轮 resize+- 增删行或改行的显示条件时要同步补上对应的订阅源, 漏一项会让面板裁掉底部或留下空白+- resize 的竖向夹紧走 `SidePanelSupport.clampedVertically`, 与初次展开的 `position` 同一条规则, 否则放不下时两边会把面板推向相反的边+- 子面板入口只在开关开着且依赖就绪时出现, 通知看 `NotificationSettings.canShowOptions` 那个值, 防休眠看 `KeepAliveController.canShowOptions` 这个值; 两者都只控制入口显隐, 不回写用户保存的开关+- 两个子面板都只由滑杆按钮展开, 动作只有 toggle 与 close 两种, 开启主开关不自动弹出+- 侧边面板公共能力集中在 `Controllers/SidePanelSupport.swift` 里, 含 `SidePanelDrawerPresenter` `SidePanelContentHost` `SidePanelDrawerAnimator` panel 工厂和定位夹紧; 挂在主面板上的那三个面板优先复用 `SidePanelDrawerPresenter` 这一层, 不要另起一套+- 设置窗口的子面板直接复用 `Controllers/SettingsOptionsPanelController.swift`, 它在 presenter 之上补齐了装配, 两套关闭观察者, 顶边对齐定位和高度重算; 新增设置子面板只要给它内容工厂与内容变化来源, 不要再写一层壳+- 两个设置子面板的行高与间距从 `SettingsOptionsPanelMetrics` 取, 下拉控件共用 `SettingsOptionsPicker` 这一个, 只有面板宽度和 picker 宽度各自定义, 这样两个面板看起来才是同一套控件- 主面板任务中心的显隐由 `MainPanelSettings.showsTaskCenter` 与 `codexHookSettings.isEnabled` 共同决定, Hook 未开启时设置页那一行显示为关闭并置灰, 不回写用户保存的开关值- 设置窗口 (通用/高级/关于三页) 和日志窗口复用 `HostingWindowController` 的行为, 可以成为 key window, 但不应成为 main window- 视觉风格统一走 `Views/Shared/LiquidGlassStyle.swift` 这一套, 避免引入与系统菜单栏工具不一致的重装饰 UIdiff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex acf9e33..1250025 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 = 60;+ CURRENT_PROJECT_VERSION = 61;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.6;+ MARKETING_VERSION = 3.5.7;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 = 60;+ CURRENT_PROJECT_VERSION = 61;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.6;+ MARKETING_VERSION = 3.5.7;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";diff --git a/CodexBar/Controllers/ActivityCenterPanelController.swift b/CodexBar/Controllers/ActivityCenterPanelController.swiftindex fc40c66..967e0ab 100644--- a/CodexBar/Controllers/ActivityCenterPanelController.swift+++ b/CodexBar/Controllers/ActivityCenterPanelController.swift@@ -179,21 +179,13 @@ final class ActivityCenterPanelController {maximumHeight: min(screenMaximumHeight, menuMaximumHeight),snapshot: snapshot)- let positioningFrame = SidePanelSupport.anchorAwareVisibleFrame(- visibleFrame: visibleFrame,- screenFrame: screen?.frame,- alignmentScreenFrame: alignmentScreenFrame- )- let position = SidePanelSupport.position(+ let position = SidePanelSupport.anchoredPosition(panelSize: panelSize,menuSurfaceFrame: menuSurfaceFrame,- visibleFrame: positioningFrame,- preferredSide: context.preferredSide,- proposedY: SidePanelSupport.alignedProposedY(- panelSize: panelSize,- menuSurfaceFrame: menuSurfaceFrame,- alignmentScreenFrame: alignmentScreenFrame- )+ visibleFrame: visibleFrame,+ screenFrame: screen?.frame,+ alignmentScreenFrame: alignmentScreenFrame,+ preferredSide: context.preferredSide)return (panelSize, position)diff --git a/CodexBar/Controllers/NotificationOptionsPanelController.swift b/CodexBar/Controllers/SettingsOptionsPanelController.swiftsimilarity index 56%rename from CodexBar/Controllers/NotificationOptionsPanelController.swiftrename to CodexBar/Controllers/SettingsOptionsPanelController.swiftindex c1dc888..96b8b35 100644--- a/CodexBar/Controllers/NotificationOptionsPanelController.swift+++ b/CodexBar/Controllers/SettingsOptionsPanelController.swift@@ -2,24 +2,37 @@ import AppKitimport Combineimport SwiftUI-/// 通知子选项面板动作, 由 AppSettingsView 发出并在 SettingsWindowController 中路由-nonisolated enum NotificationOptionsPanelAction {- case toggle- case open- case close+/// 设置窗口右侧的子选项面板, 同一时刻只展开一个+enum SettingsOptionsPanel: CaseIterable {+ case notification+ case keepAlive}-/// 通知子选项面板控制器, 挂在设置窗口右侧并保持底边对齐, 复用侧边抽屉动效+/// 子选项面板动作, 由 AppSettingsView 发出并在 SettingsWindowController 中路由+/// 展开时带上主开关行的 anchor, 面板顶边要对齐那一行而不是设置窗口底边+enum SettingsOptionsPanelAction {+ case toggle(panel: SettingsOptionsPanel, anchorProvider: ScreenFrameProvider)+ case close(panel: SettingsOptionsPanel)+ /// 切换分页时一次收掉全部; 视图不必知道一共有几个面板+ case closeAll+}++/// 设置窗口右侧子选项面板的公共装配+/// 通知与防休眠两个子面板只差内容视图和高度变化的来源, 定位 关闭 高度重算这套脚手架全在这里/// 与重置次数面板不同: 内容是交互控件, 用常驻 hosting controller + ObservableObject 驱动更新, 不替换 rootView@MainActor-final class NotificationOptionsPanelController {- private let notificationSettings: NotificationSettings- private let codexHookSettings: CodexHookSettings- private let codexCLINotificationSettings: CodexCLINotificationSettings+final class SettingsOptionsPanelController {+ private let animationKey: String+ private let initialPanelSize: CGSize+ /// 展开前的准备动作, 例如刷新只在这个面板里露面的设置项+ private let willShow: (() -> Void)?+ private let contentControllerProvider: () -> NSViewController+private var panel: NSPanel?- private var hostingController: NSHostingController<NotificationOptionsView>?+ private var hostingController: NSViewController?+ private var cancellables = Set<AnyCancellable>()private lazy var presenter = SidePanelDrawerPresenter(- animationKey: Metrics.drawerTransformAnimationKey,+ animationKey: animationKey,makesKey: true,usesUntranslatedInitialLayout: true,contentViewProvider: { [weak self] in@@ -29,61 +42,119 @@ final class NotificationOptionsPanelController {private weak var settingsWindow: NSWindow?private var panelDismissObserver: NSObjectProtocol?private var settingsWindowDismissObservers: [NSObjectProtocol] = []- private var cancellables = Set<AnyCancellable>()private var panelResizeTask: Task<Void, Never>?private var isEntryAnimationRunning = falseinit(- notificationSettings: NotificationSettings,- codexHookSettings: CodexHookSettings,- codexCLINotificationSettings: CodexCLINotificationSettings+ animationKey: String,+ initialPanelSize: CGSize,+ willShow: (() -> Void)? = nil,+ contentControllerProvider: @escaping () -> NSViewController,+ contentChanges: AnyPublisher<Void, Never>) {- self.notificationSettings = notificationSettings- self.codexHookSettings = codexHookSettings- self.codexCLINotificationSettings = codexCLINotificationSettings- observeContentHeightChanges()+ self.animationKey = animationKey+ self.initialPanelSize = initialPanelSize+ self.willShow = willShow+ self.contentControllerProvider = contentControllerProvider+ // 内容行数随开关增删, 高度得跟着重算+ // 订阅整个 ObservableObject 而不是逐个 @Published: 那种列表漏一项就会让面板裁掉底部或留下空白,+ // 而多余的触发在面板收着时被 scheduleResize 的守卫挡掉, 展开时也只是一次尺寸相同的空转+ contentChanges+ .sink { [weak self] in+ self?.scheduleResize()+ }+ .store(in: &cancellables)}- private var isVisible: Bool {- presenter.isVisible+ /// sizingOptions 必须是 preferredContentSize: 面板的高度重算靠的就是它提交的 fitting size+ static func makeContentController(_ content: some View) -> NSViewController {+ let controller = NSHostingController(rootView: content)+ controller.sizingOptions = [.preferredContentSize]+ return controller}- private func owns(_ window: NSWindow?) -> Bool {- window === panel+ var isVisible: Bool {+ presenter.isVisible}func toggle(relativeTo window: NSWindow?,- contentView: NSView?+ contentView: NSView?,+ anchorProvider: ScreenFrameProvider) {if isVisible {hide()return}- show(relativeTo: window, contentView: contentView)+ show(relativeTo: window, contentView: contentView, anchorProvider: anchorProvider)+ }++ func hide(immediate: Bool = false) {+ panelResizeTask?.cancel()+ panelResizeTask = nil+ isEntryAnimationRunning = false+ presenter.hide(immediate: immediate)+ }++ private func scheduleResize() {+ // isVisible 也在同步守卫里: 收着的面板不必为每次内容变化排一个 Task 再让出两轮 runloop+ guard panel?.isVisible == true, !isEntryAnimationRunning else {+ return+ }++ panelResizeTask?.cancel()+ panelResizeTask = Task { @MainActor [weak self] in+ // @Published 先于 SwiftUI 布局发出变更, 等待视图提交新的 fitting size+ await Task.yield()+ await Task.yield()+ guard let self,+ !Task.isCancelled,+ let panel,+ panel.isVisible,+ let size = hostingController?.view.validFittingSize else {+ return+ }++ resizePanel(panel, to: size)+ }+ }++ private func owns(_ window: NSWindow?) -> Bool {+ window === panel}- func show(+ private func show(relativeTo window: NSWindow?,- contentView: NSView?+ contentView: NSView?,+ anchorProvider: ScreenFrameProvider) {guard let window else {hide(immediate: true)return}- codexCLINotificationSettings.refresh()+ willShow?()let panel = ensurePanel()- panel.contentView?.layoutSubtreeIfNeeded()+ // 这里不必先布局: 下面 measuredPanelSize 走的 validFittingSize 第一句就是 layoutSubtreeIfNeeded,+ // 而中间两句只碰设置窗口那棵树, 不会把面板弄脏let windowSurfaceFrame = SidePanelSupport.contentScreenFrame(for: contentView, in: window) ?? window.frame+ let screen = window.screen ?? NSScreen.main+ let visibleFrame = screen?.visibleFrame ?? windowSurfaceFrame+ let alignmentScreenFrame = SidePanelSupport.validatedAlignmentScreenFrame(+ anchorProvider.currentScreenFrame(in: window),+ menuSurfaceFrame: windowSurfaceFrame+ )let panelSize = measuredPanelSize()- let position = SidePanelSupport.position(+ // clampsToSurfaceBottom 传 false: 顶边要对齐主开关行, 放不下时底边探出窗口也不能把整个面板上推+ let position = SidePanelSupport.anchoredPosition(panelSize: panelSize,menuSurfaceFrame: windowSurfaceFrame,- visibleFrame: (window.screen ?? NSScreen.main)?.visibleFrame ?? windowSurfaceFrame,+ visibleFrame: visibleFrame,+ screenFrame: screen?.frame,+ alignmentScreenFrame: alignmentScreenFrame,preferredSide: .right,- proposedY: windowSurfaceFrame.minY+ clampsToSurfaceBottom: false)panel.level = window.level@@ -96,40 +167,26 @@ final class NotificationOptionsPanelController {}isEntryAnimationRunning = false- schedulePanelResize()+ scheduleResize()}}- func hide(immediate: Bool = false) {- panelResizeTask?.cancel()- panelResizeTask = nil- isEntryAnimationRunning = false- presenter.hide(immediate: immediate)- }-private func ensurePanel() -> NSPanel {if let panel {return panel}let panel = SidePanelSupport.makePanel(- initialSize: NotificationOptionsView.initialPanelSize,+ initialSize: initialPanelSize,ignoresMouseEvents: false,keyable: true)- let hostingController = NSHostingController(- rootView: NotificationOptionsView(- notificationSettings: notificationSettings,- codexHookSettings: codexHookSettings,- codexCLINotificationSettings: codexCLINotificationSettings- )- )- hostingController.sizingOptions = [.preferredContentSize]+ let hostingController = contentControllerProvider()panel.contentViewController = hostingControllerSidePanelSupport.configureLayers(hostingView: hostingController.view,contentView: panel.contentView,- cornerRadius: NotificationOptionsView.panelCornerRadius+ cornerRadius: SettingsOptionsPanelMetrics.cornerRadius)panelDismissObserver = makeResignKeyDismissObserver(observing: panel) { [weak self] keyWindow inself?.owns(keyWindow) != true@@ -192,44 +249,7 @@ final class NotificationOptionsPanelController {}private func measuredPanelSize() -> CGSize {- hostingController?.view.validFittingSize ?? NotificationOptionsView.initialPanelSize- }-- private func observeContentHeightChanges() {- Publishers.MergeMany([- notificationSettings.$isLowQuotaEnabled.map { _ in () },- notificationSettings.$isQuotaResetEnabled.map { _ in () },- notificationSettings.$isLongTaskEnabled.map { _ in () },- notificationSettings.$isTaskWaitingEnabled.map { _ in () },- notificationSettings.$isCreditExpiryEnabled.map { _ in () },- codexHookSettings.$isEnabled.map { _ in () }- ])- .sink { [weak self] in- self?.schedulePanelResize()- }- .store(in: &cancellables)- }-- private func schedulePanelResize() {- guard panel != nil, !isEntryAnimationRunning else {- return- }-- panelResizeTask?.cancel()- panelResizeTask = Task { @MainActor [weak self] in- // @Published 先于 SwiftUI 布局发出变更, 等待视图提交新的 fitting size- await Task.yield()- await Task.yield()- guard let self,- !Task.isCancelled,- let panel,- panel.isVisible,- let size = hostingController?.view.validFittingSize else {- return- }-- resizePanel(panel, to: size)- }+ hostingController?.view.validFittingSize ?? initialPanelSize}private func resizePanel(_ panel: NSPanel, to size: CGSize) {@@ -237,13 +257,15 @@ final class NotificationOptionsPanelController {return}+ // 面板顶边对齐主开关行, 所以增删内容行时要向下生长+ // 直接改 size 会保持底边不动而把顶边顶上去, 那样就跟主开关行错开了var targetFrame = panel.frame+ let topEdge = targetFrame.maxYtargetFrame.size = size+ targetFrame.origin.y = topEdge - targetFrame.heightif let visibleFrame = panel.screen?.visibleFrame {- let maximumY = visibleFrame.maxY - SidePanelSupport.Metrics.screenPadding- if targetFrame.maxY > maximumY {- targetFrame.origin.y = maximumY - targetFrame.height- }+ // 与初次展开走同一条夹紧规则, 否则放不下时重算的位置会和 position 给的位置对不上+ targetFrame = SidePanelSupport.clampedVertically(targetFrame, in: visibleFrame)}NSAnimationContext.runAnimationGroup { context in@@ -254,7 +276,6 @@ final class NotificationOptionsPanelController {}private enum Metrics {- static let drawerTransformAnimationKey = "CodexBar.notificationOptionsDrawerTransform"static let resizeDuration: TimeInterval = 0.16}}diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex 13864ea..ddca083 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -1,4 +1,5 @@import AppKit+import Combineimport SwiftUI/// 设置窗口控制器, 打开前刷新设置状态并按内容自适应高度@@ -16,11 +17,10 @@ final class SettingsWindowController: HostingWindowController {private let keepAliveController: KeepAliveControllerprivate let onSyncChanged: (Bool) -> Voidprivate let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler- private lazy var notificationOptionsPanelController = NotificationOptionsPanelController(- notificationSettings: notificationSettings,- codexHookSettings: codexHookSettings,- codexCLINotificationSettings: codexCLINotificationSettings- )+ /// 只在真的要展开时构造: 控制器一建就挂上内容变化订阅并常驻到 App 结束,+ /// 而用户可能一次子面板都没开过+ private var notificationOptionsPanelController: SettingsOptionsPanelController?+ private var keepAliveOptionsPanelController: SettingsOptionsPanelController?init(viewModel: CodexStatusViewModel,@@ -70,8 +70,8 @@ final class SettingsWindowController: HostingWindowController {keepAliveController: keepAliveController,onSyncChanged: onSyncChanged,onRebuildWorkflowData: onRebuildWorkflowData,- onNotificationOptionsAction: { [weak self] action in- self?.handleNotificationOptionsAction(action)+ onOptionsAction: { [weak self] action in+ self?.handleOptionsAction(action)},onContentHeightChanged: { [weak self] height inself?.resizeContentHeight(height)@@ -113,20 +113,103 @@ final class SettingsWindowController: HostingWindowController {keepAliveController.refresh()}- private func handleNotificationOptionsAction(_ action: NotificationOptionsPanelAction) {- switch action {- case .toggle:- notificationOptionsPanelController.toggle(- relativeTo: window,- contentView: window?.contentViewController?.view+ private func optionsPanelController(+ _ panel: SettingsOptionsPanel+ ) -> SettingsOptionsPanelController {+ if let existing = existingOptionsPanelController(panel) {+ return existing+ }++ let controller = makeOptionsPanelController(panel)+ switch panel {+ case .notification:+ notificationOptionsPanelController = controller+ case .keepAlive:+ keepAliveOptionsPanelController = controller+ }+ return controller+ }++ /// 没建过就说明它不可能开着, 收起动作不必为此把它构造出来+ private func existingOptionsPanelController(+ _ panel: SettingsOptionsPanel+ ) -> SettingsOptionsPanelController? {+ switch panel {+ case .notification:+ notificationOptionsPanelController+ case .keepAlive:+ keepAliveOptionsPanelController+ }+ }++ private func makeOptionsPanelController(+ _ panel: SettingsOptionsPanel+ ) -> SettingsOptionsPanelController {+ switch panel {+ case .notification:+ SettingsOptionsPanelController(+ animationKey: "CodexBar.notificationOptionsDrawerTransform",+ initialPanelSize: NotificationOptionsView.initialPanelSize,+ willShow: { [codexCLINotificationSettings] in+ codexCLINotificationSettings.refresh()+ },+ contentControllerProvider: { [notificationSettings, codexHookSettings, codexCLINotificationSettings, keepAliveController] in+ SettingsOptionsPanelController.makeContentController(+ NotificationOptionsView(+ notificationSettings: notificationSettings,+ codexHookSettings: codexHookSettings,+ codexCLINotificationSettings: codexCLINotificationSettings,+ keepAliveController: keepAliveController+ )+ )+ },+ // 音效子行随各开关增删, 低电量那一行还跟着防休眠的保护状态置灰+ // 防休眠只订这一个派生值: 订整个控制器会让任务每起停一次都白重算一次高度+ contentChanges: Publishers.MergeMany([+ notificationSettings.objectWillChange.eraseToAnyPublisher(),+ codexHookSettings.objectWillChange.eraseToAnyPublisher(),+ keepAliveController.$isLowBatteryProtectionEnabled+ .map { _ in () }+ .eraseToAnyPublisher()+ ]).eraseToAnyPublisher()+ )+ case .keepAlive:+ SettingsOptionsPanelController(+ animationKey: "CodexBar.keepAliveOptionsDrawerTransform",+ initialPanelSize: KeepAliveOptionsView.initialPanelSize,+ contentControllerProvider: { [keepAliveController] in+ SettingsOptionsPanelController.makeContentController(+ KeepAliveOptionsView(keepAliveController: keepAliveController)+ )+ },+ // 面板里只有 hasBattery 会增删行, 两个 picker 的取值不改高度+ contentChanges: keepAliveController.$hasBattery+ .map { _ in () }+ .eraseToAnyPublisher())- case .open:- notificationOptionsPanelController.show(+ }+ }++ /// 子面板占设置窗口右侧同一位置, 展开一个必须先收掉其余的+ /// 收旧面板用 immediate, 否则滑回与滑出在同一处交叠+ /// 互斥规则只写在这里, 再加一个面板也不会漏掉某一对+ private func handleOptionsAction(_ action: SettingsOptionsPanelAction) {+ switch action {+ case let .toggle(panel, anchorProvider):+ for other in SettingsOptionsPanel.allCases where other != panel {+ existingOptionsPanelController(other)?.hide(immediate: true)+ }+ optionsPanelController(panel).toggle(relativeTo: window,- contentView: window?.contentViewController?.view+ contentView: window?.contentViewController?.view,+ anchorProvider: anchorProvider)- case .close:- notificationOptionsPanelController.hide()+ case let .close(panel):+ existingOptionsPanelController(panel)?.hide()+ case .closeAll:+ for panel in SettingsOptionsPanel.allCases {+ existingOptionsPanelController(panel)?.hide()+ }}}diff --git a/CodexBar/Controllers/SidePanelSupport.swift b/CodexBar/Controllers/SidePanelSupport.swiftindex 05e4576..d8eca2d 100644--- a/CodexBar/Controllers/SidePanelSupport.swift+++ b/CodexBar/Controllers/SidePanelSupport.swift@@ -26,6 +26,8 @@ final class KeyableBorderlessPanel: NSPanel {}}+// MARK: - 抽屉动效+@MainActorfinal class SidePanelDrawerAnimator {private let contentViewProvider: @MainActor () -> NSView?@@ -142,6 +144,8 @@ final class SidePanelDrawerAnimator {}}+// MARK: - 展开与收起+/// 重置次数; 通知子选项和并发任务中心三类"一次性展开"抽屉面板共用的显隐状态机/// 负责 generation 竞态防护; 入退场动画和 child window 挂载/卸载/// (热力图详情面板因带切边与延迟隐藏, 状态机不同, 不走这里)@@ -261,6 +265,8 @@ final class SidePanelDrawerPresenter {}}+// MARK: - 内容宿主+/// 侧边面板的内容宿主: 懒建 panel + hostingController, 统一"替换 rootView →/// configureLayers → setContentSize"的更新序列/// ⚠️ 每次更新都整树替换 rootView 是刻意行为 (见 CLAUDE.md 热力图详情面板的说明), 不要改成常驻状态推送@@ -333,6 +339,8 @@ final class SidePanelContentHost<Root: View> {}}+// MARK: - 面板工厂与定位+@MainActorenum SidePanelSupport {/// 侧边面板共用的几何与抽屉动画常量@@ -379,12 +387,15 @@ enum SidePanelSupport {/// 水平方向优先贴在请求侧, 空间不足时换边, 最后夹紧到屏幕可见区域/// 纵向由调用方给出期望位置, 这里统一夹紧+ /// clampsToSurfaceBottom 为 true 时面板底边不低于宿主内容区底边, 适合锚点行随内容滚动的菜单面板+ /// 设置窗口的子面板要严格贴住主开关行, 放不下时宁可让底边探出窗口, 所以传 falsestatic func position(panelSize: CGSize,menuSurfaceFrame: CGRect,visibleFrame: CGRect,preferredSide: UsageHeatmapDetailSide,- proposedY: CGFloat+ proposedY: CGFloat,+ clampsToSurfaceBottom: Bool = true) -> SidePanelPosition {let leftX = menuSurfaceFrame.minX - Metrics.panelGap - panelSize.widthlet rightX = menuSurfaceFrame.maxX + Metrics.panelGap@@ -407,9 +418,10 @@ enum SidePanelSupport {lower: visibleFrame.minX + Metrics.screenPadding,upper: visibleFrame.maxX - panelSize.width - Metrics.screenPadding)+ let screenBottom = visibleFrame.minY + Metrics.screenPaddinglet y = clamped(proposedY,- lower: max(visibleFrame.minY + Metrics.screenPadding, menuSurfaceFrame.minY),+ lower: clampsToSurfaceBottom ? max(screenBottom, menuSurfaceFrame.minY) : screenBottom,upper: visibleFrame.maxY - panelSize.height - Metrics.screenPadding)@@ -424,6 +436,35 @@ enum SidePanelSupport {)}+ /// 锚点对齐的完整定位: 先按锚点收窄可见区域, 再算出对齐锚点顶边的 y, 最后交给 position 夹紧+ /// 三步顺序固定且必须一致, 拆开写过一次就会出现第二份, 加参数时也只会改到其中一份+ static func anchoredPosition(+ panelSize: CGSize,+ menuSurfaceFrame: CGRect,+ visibleFrame: CGRect,+ screenFrame: CGRect?,+ alignmentScreenFrame: CGRect?,+ preferredSide: UsageHeatmapDetailSide,+ clampsToSurfaceBottom: Bool = true+ ) -> SidePanelPosition {+ position(+ panelSize: panelSize,+ menuSurfaceFrame: menuSurfaceFrame,+ visibleFrame: anchorAwareVisibleFrame(+ visibleFrame: visibleFrame,+ screenFrame: screenFrame,+ alignmentScreenFrame: alignmentScreenFrame+ ),+ preferredSide: preferredSide,+ proposedY: alignedProposedY(+ panelSize: panelSize,+ menuSurfaceFrame: menuSurfaceFrame,+ alignmentScreenFrame: alignmentScreenFrame+ ),+ clampsToSurfaceBottom: clampsToSurfaceBottom+ )+ }+static func attach(_ panel: NSPanel, to parentWindow: NSWindow) {guard panel.parent !== parentWindow else {return@@ -542,6 +583,18 @@ enum SidePanelSupport {return screenFrame}+ /// 面板竖向夹回可见区域, 与 position 用同一条内边距和越界规则+ /// 高度变化后重新定位要走这里, 否则重算出的位置会和初次展开的位置对不上+ static func clampedVertically(_ frame: CGRect, in visibleFrame: CGRect) -> CGRect {+ var frame = frame+ frame.origin.y = clamped(+ frame.origin.y,+ lower: visibleFrame.minY + Metrics.screenPadding,+ upper: visibleFrame.maxY - frame.height - Metrics.screenPadding+ )+ return frame+ }+private static func clamped(_ value: CGFloat, lower: CGFloat, upper: CGFloat) -> CGFloat {guard lower <= upper else {return lowerdiff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex e5f813c..dda10ee 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -28,6 +28,8 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {private var statusItemController: StatusItemController?private var notificationService: CodexNotificationService?+ // MARK: - App 生命周期+func applicationDidFinishLaunching(_: Notification) {// Hook 子进程模式绝不会走到这里, 干净退出标志因此不会被它改写AppProcessDiagnostics.install()@@ -57,6 +59,10 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {}notificationService.start()self.notificationService = notificationService+ // 低电量触发会中断正在跑的任务, 得让用户知道是谁干的+ keepAliveController.onLowBatteryTriggered = { [weak notificationService] percent in+ await notificationService?.notifyLowBatteryProtection(percent: percent) ?? false+ }activityMonitor.start()keepAliveController.start()logLaunchState()@@ -78,14 +84,15 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "-"let hook = codexHookSettings.isEnabled ? 1 : 0let keepAlive = keepAliveController.isEnabled ? 1 : 0- let keepAliveLimit = keepAliveController.maximumDuration.title+ let keepAliveLimit = keepAliveController.maximumDuration.loggedHours+ let keepAliveBattery = keepAliveController.lowBatteryThreshold.rawValuelet 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, privacy: .public); 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); sync=\(sync); notification=\(notification); menuBarQuota=\(menuBarQuota, privacy: .public); taskCenter=\(taskCenter); hotKey=\(hotKey)")}@@ -518,6 +525,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}}+ // MARK: - 装配与对外入口+func install() {configureStatusButton()configurePopover()@@ -606,6 +615,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {return hostingController}+ // MARK: - 订阅与全局快捷键+private func observeViewModel() {let hasQuotaSnapshot = viewModel.$snapshot.map { $0 != nil }@@ -759,6 +770,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {return "快捷键已被占用"}+ // MARK: - 菜单栏图标+private func updateStatusImage(_ state: StatusIconState) {statusItem.button?.toolTip = state.toolTip(at: Date())@@ -901,6 +914,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}}+ // MARK: - 菜单面板开合+private func toggleMenuSurface(relativeTo button: NSStatusBarButton) {toggleMenuSurface {openPopover(relativeTo: button)@@ -1026,6 +1041,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {scheduleDelayedStatusRefresh()}+ // MARK: - 右键菜单+private func showContextMenu(relativeTo button: NSStatusBarButton) {closeMenuSurface(animated: false)presentStatusItemMenu(makeContextMenu(), relativeTo: button)@@ -1101,6 +1118,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {}}+ // MARK: - 辅助窗口与焦点+private func openLogFromShortcut() {closeMenuSurface(animated: false)openLog()@@ -1150,6 +1169,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {NSApplication.shared.terminate(nil)}+ // MARK: - 关闭流程+private func closeMenuSurface(animated: Bool = true) {if menuSurfaceState == .closing, animated {return@@ -1245,6 +1266,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {logWindowController.setAllowsKeyFocus(allowsKeyFocus)}+ // MARK: - 刷新与同步+private func scheduleDelayedStatusRefresh() {delayedStatusRefreshTask?.cancel()delayedStatusRefreshTask = Task { @MainActor [weak self] in@@ -1293,6 +1316,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {syncSettings.activation(isHookEnabled: codexHookSettings.isEnabled)}+ // MARK: - 侧边面板+private func updateHeatmapDetailPanel(_ context: UsageHeatmapHoverContext?) {guard isActiveMenuSurfaceVisible,let menuSurfaceContentView = activeMenuSurfaceContentView,diff --git a/CodexBar/Models/CodexWorkflowModels.swift b/CodexBar/Models/CodexWorkflowModels.swiftindex a648523..c7c2451 100644--- a/CodexBar/Models/CodexWorkflowModels.swift+++ b/CodexBar/Models/CodexWorkflowModels.swift@@ -56,6 +56,8 @@ private nonisolated enum WorkflowCountResolution {}}+// MARK: - Hook 原始事件+/// hooks 进程落盘的最小事件模型, 对历史字段缺失保持宽容nonisolated struct WorkflowHookEvent: Decodable, Equatable {let timestamp: Date@@ -189,6 +191,8 @@ nonisolated struct WorkflowHookEvent: Decodable, Equatable {}}+// MARK: - 每日聚合指标+/// 热力图详情面板直接消费的每日统计nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {let startDate: String@@ -291,6 +295,8 @@ nonisolated struct WorkflowDailyMetrics: Equatable, Identifiable {}}+// MARK: - 面板快照+/// WorkflowService 发布给 UI 的近端快照nonisolated struct WorkflowSnapshot: Equatable {let dailyMetrics: [WorkflowDailyMetrics]@@ -398,6 +404,8 @@ nonisolated struct WorkflowSnapshot: Equatable {}}+// MARK: - 会话与轮次标识缓存+/// 聚合时保留 Set 缓存, 避免同一会话或轮次重复计数nonisolated struct WorkflowDailyIdentifierCache {var sessionIds: Set<String>diff --git a/CodexBar/Services/CodexStatus/CodexStatusService.swift b/CodexBar/Services/CodexStatus/CodexStatusService.swiftindex 5889ada..310be90 100644--- a/CodexBar/Services/CodexStatus/CodexStatusService.swift+++ b/CodexBar/Services/CodexStatus/CodexStatusService.swift@@ -145,6 +145,8 @@ actor CodexStatusService {_ = Self.ignoreBrokenPipeSignal}+ // MARK: - 对外入口+func fetchOutcome() async -> CodexFetchResult {var trace = CodexFetchTrace()let outcome = await resolveOutcome(allowRebuild: true, trace: &trace)@@ -230,6 +232,8 @@ actor CodexStatusService {}}+ // MARK: - 连接复用与重建+private func readyConnection() throws -> AppServerConnection {switch ensureConnection() {case let .ready(connection, _):@@ -297,6 +301,8 @@ actor CodexStatusService {connection = nil}+ // MARK: - 数据抓取与缓存+/// 额度与用量独立读取/// 认证失败全程只刷新一次 token/// 传输故障交给外层重建连接diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 819789f..9398fe1 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -9,10 +9,24 @@ import ServiceManagement@MainActorfinal class KeepAliveController: ObservableObject {@Published private(set) var isEnabled: Bool- @Published private(set) var maximumDuration: MaximumDuration@Published private(set) var helperStatus = HelperStatus.notRegistered@Published private(set) var isPreventingSleep = false- @Published private(set) var hasReachedMaximumDuration = false+ @Published private(set) var lowBatteryThreshold: LowBatteryThreshold+ /// 确认没有内置电池时为 false, 设置页据此隐藏低电量那一行+ @Published private(set) var hasBattery = true+ /// 当前是否因低电量而停止防休眠, 带滞回所以不等于"电量低于阈值"+ /// 会随电量自己翻转, 不需要外部清除, 与 hasReachedMaximumDuration 那种粘滞标志不是一回事+ @Published private(set) var isLowBatteryActive = false+ /// 低电量保护是不是真的在起作用: 阈值开着且这台机器确实有电池+ /// 规则收在这里而不是各视图各写一遍: 通知面板要据此置灰那一行, 防休眠面板据此决定显不显示阈值+ @Published private(set) var isLowBatteryProtectionEnabled = false++ /// 低电量是不是当下唯一拦住防休眠的那一项+ /// 由 reconcileSleepState 从 sleepBlockReason 派生, 见那里的说明+ @Published private(set) var isLowBatteryBlocking = false+ /// 子面板入口该不该出现: 用户开关开着且依赖已就绪+ /// 同样从 sleepBlockReason 派生, 于是新增阻断条件时必然要在那个 switch 里表态, 不会漏配+ @Published private(set) var canShowOptions = false/// helper 安装与注册状态的错误, 注册恢复正常时才清除@Published private var registrationErrorMessage: String?@@ -25,6 +39,22 @@ final class KeepAliveController: ObservableObject {registrationErrorMessage ?? operationErrorMessage}+ /// 时长上限的状态转发给 UI, 使调用方不必知道 limiter 的存在+ var maximumDuration: MaximumDuration {+ durationLimiter.duration+ }++ var hasReachedMaximumDuration: Bool {+ durationLimiter.hasReached+ }++ /// 低电量导致休眠恢复之后回调一次, 参数是触及阈值时的电量; 由 AppDelegate 接到通知服务+ /// 用事件回调而不是 @Published: 触发是一次性动作, 电量回升到解除门槛以上后再次跌破要能重新发一次+ /// async 是为了让补发休眠等到通知真的提交完: 同步回调只把提交排进下一个 MainActor job,+ /// 而 IOPMSleepSystem 就在当前这个 job 里, 机器会先睡下去+ /// 返回值是通知有没有真的发出去, 决定这一轮算不算已通知+ var onLowBatteryTriggered: ((Int) async -> Bool)?+/// 用户开关仍开着, 且 helper 已经真的把休眠关掉/// isPreventingSleep 在稳态下已隐含 isEnabled (shouldDisableSleep 要求它)/// 叠这一层是为了关开关到 helper 回调之间的异步空窗: 用户意图先落地@@ -36,6 +66,10 @@ final class KeepAliveController: ObservableObject {private let codexHookSettings: CodexHookSettingsprivate let defaults: UserDefaultsprivate let systemSleepService = SystemSleepService()+ private let powerSourceMonitor = PowerSourceMonitor()+ private let durationLimiter: KeepAliveDurationLimiter+ /// 不加 @Published: 设置页在根上观察整个控制器, 任务每起停一次都会重算整页 body+ /// 需要跟着它刷新的只有派生出去的 isLowBatteryBlocking 与 canShowOptionsprivate var hasRunningTasks = false/// 保留仍活跃且已经进入过运行态的任务, 避免普通快照刷新被误判成新任务private var startedRunningTaskIDs = Set<UUID>()@@ -51,10 +85,16 @@ final class KeepAliveController: ObservableObject {private var requestGeneration: UInt64 = 0private var retryTask: Task<Void, Never>?private var retryAttempt = 0- private var maximumDurationTask: Task<Void, Never>?- private var maximumDurationStartedAt: Date?private var helperRegistrationTask: Task<Void, Never>?+ /// 与 hasRunningTasks 同理: 只经由派生状态影响 UI, 自己不发信号private var isRefreshingHelper = false+ /// 已排队但还没发出的低电量通知, 值是触及阈值时的电量+ /// 恢复休眠真的成功才发得出去: 恢复失败时机器仍不会睡, 那时说已恢复会把用户骗去合盖+ private var pendingLowBatteryPercent: Int?+ /// 本轮低电量已经通知过+ /// 只看是否接电不足以收口: 适配器接触不良时供电状态会反复翻转, 每翻一次都会重发一条+ /// 由电量回到解除门槛以上清除, 也就是电量真的回来了才算下一轮+ private var hasNotifiedLowBattery = falseprivate var cancellables = Set<AnyCancellable>()private var isStarted = falseprivate var lastLoggedSleepConditions: SleepConditions?@@ -62,7 +102,7 @@ final class KeepAliveController: ObservableObject {/// 不直接读那个属性: 订阅回调跑在 willSet, 那时它还是改动前的值private var isHookEnabled: Bool- /// 阻止休眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值+ /// 防休眠没生效时缺的是哪一项, 同时充当日志里的 reason= 取值private enum SleepBlockReason: String {case notStartedcase userOff@@ -70,11 +110,13 @@ final class KeepAliveController: ObservableObject {case noTaskscase helperUnavailablecase helperRefreshing+ case lowBatterycase limitReached}/// shouldDisableSleep 的求值结果与它依赖的各项, 只用于变化检测与日志/// blockReason 与 shouldDisableSleep 同源, 不会出现"字段都满足却报某项缺失"+ /// battery 只放布尔: 放电量百分比会让每掉 1% 都记一条private struct SleepConditions: Equatable {let blockReason: SleepBlockReason?let enabled: Bool@@ -82,9 +124,12 @@ final class KeepAliveController: ObservableObject {let tasks: Boollet helper: HelperStatuslet refreshing: Bool+ let battery: Boollet limited: Bool}+ // MARK: - 生命周期+init(activityMonitor: CodexActivityMonitor,codexHookSettings: CodexHookSettings,@@ -93,10 +138,12 @@ final class KeepAliveController: ObservableObject {self.activityMonitor = activityMonitorself.codexHookSettings = codexHookSettingsself.defaults = defaults+ durationLimiter = KeepAliveDurationLimiter(defaults: defaults)isHookEnabled = codexHookSettings.isEnabledisEnabled = defaults.bool(forKey: Self.enabledKey)- maximumDuration = (defaults.object(forKey: Self.maximumDurationKey) as? Int)- .flatMap(MaximumDuration.init(rawValue:)) ?? .twelveHours+ // 默认关闭: 老版本升上来的用户不该多出一条中断任务的路径+ lowBatteryThreshold = (defaults.object(forKey: Self.lowBatteryThresholdKey) as? Int)+ .flatMap(LowBatteryThreshold.init(rawValue:)) ?? .off}func start() {@@ -106,7 +153,7 @@ final class KeepAliveController: ObservableObject {isStarted = true// Hook 是本功能的依赖, 不是用户意图- // 只重新求值当前该不该阻止休眠, 绝不改写用户保存的开关+ // 只重新求值当前该不该防止系统休眠, 绝不改写用户保存的开关// @Published 在 willSet 就发信号, 此刻回读 codexHookSettings.isEnabled 拿到的还是旧值// 因此把新值先存进 isHookEnabled, 判定与日志都只认它codexHookSettings.$isEnabled@@ -123,6 +170,22 @@ final class KeepAliveController: ObservableObject {}.store(in: &cancellables)+ powerSourceMonitor.start { [weak self] in+ self?.handlePowerSourceChange()+ }+ updateBatteryState()++ durationLimiter.start()+ durationLimiter.onStateChanged = { [weak self] trigger in+ self?.reconcileSleepState(trigger: trigger)+ }+ // duration 与 hasReached 由计算属性转发, 变化要接力发出去才能刷新 UI+ durationLimiter.objectWillChange+ .sink { [weak self] in+ self?.objectWillChange.send()+ }+ .store(in: &cancellables)+NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification).sink { [weak self] _ inself?.refresh()@@ -142,7 +205,10 @@ final class KeepAliveController: ObservableObject {cancelHelperRegistrationTask()startedRunningTaskIDs.removeAll()waitingTaskIDs.removeAll()- resetMaximumDurationState()+ durationLimiter.stop()+ powerSourceMonitor.stop()+ assign(false, to: \.isLowBatteryActive)+ clearPendingLowBatteryNotification()if connection != nil {applySleepDisabled(false)@@ -151,6 +217,8 @@ final class KeepAliveController: ObservableObject {}func refresh() {+ // 电源监听注册失败并降级成轮询时, 这是唯一还会即时重读电量的路径+ powerSourceMonitor.refresh()refreshRegistrationAndSleepState()}@@ -162,6 +230,8 @@ final class KeepAliveController: ObservableObject {reconcileSleepState(trigger: .statusRefresh)}+ // MARK: - 设置入口+func setEnabled(_ enabled: Bool) {// 与 sleepBlockReason 读同一份镜像, 类内只保留一个 Hook 状态的真相来源guard !enabled || isHookEnabled else {@@ -180,33 +250,137 @@ final class KeepAliveController: ObservableObject {if enabled {ensureHelperRegistration(opensSystemSettings: true)} else {- resetMaximumDurationState()+ durationLimiter.reset()}reconcileSleepState(trigger: .settings)}func setMaximumDuration(_ duration: MaximumDuration) {- guard duration != maximumDuration else {+ durationLimiter.setDuration(duration)+ }++ func setLowBatteryThreshold(_ threshold: LowBatteryThreshold) {+ guard threshold != lowBatteryThreshold else {+ return+ }++ AppLog.keepAlive.notice(+ "KeepAlive 低电量阈值变更: threshold=\(threshold.rawValue)"+ )+ lowBatteryThreshold = threshold+ defaults.set(threshold.rawValue, forKey: Self.lowBatteryThresholdKey)+ // 换了阈值就是新的一轮: 旧阈值下打的锁存对新阈值不成立+ // 留着它会让提高阈值后第一次真正触发的低电量不提醒+ clearPendingLowBatteryNotification()+ updateBatteryState()+ reconcileSleepState(trigger: .settings)+ }++ // MARK: - 电量与任务变化++ private func handlePowerSourceChange() {+ let wasBatteryLow = isLowBatteryActive+ updateBatteryState()+ guard isLowBatteryActive != wasBatteryLow else {return}- AppLog.keepAlive.notice("KeepAlive 上限变更: duration=\(duration.title, privacy: .public)")- maximumDuration = duration- defaults.set(duration.rawValue, forKey: Self.maximumDurationKey)+ reconcileSleepState(trigger: .battery)+ }- guard let maximumDurationStartedAt else {+ /// 纯条件判定: 只看当下, 不记"低过电"这笔账, 所以充上电会自动恢复+ /// 滞回让解除门槛比触发门槛高一截, 否则电量在阈值附近抖动会反复切换休眠状态+ /// 读不到电量时维持上一次的判定, 两种情形各有各的理由+ /// 从没读到过时保持不触发: 误触发会当场断掉用户任务, 漏触发最坏也有系统强制休眠兜底+ /// 已经在保护中时不清零: 一次瞬时失败不该让防休眠反复开关, 那还会绕过滞回并重发通知+ private func updateBatteryState() {+ let reading = powerSourceMonitor.reading+ // 读失败时维持上一次的判定, 与下面 isLowBatteryActive 同一条规则+ // unreadable.hasBattery 是 true (从没读到过时按"可能有"处理), 无条件赋值会让一次+ // IOKit 缺口把已确认没有电池的台式机翻回有电池, 低电量那一行跟着闪进闪出+ if reading != .unreadable {+ assign(reading.hasBattery, to: \.hasBattery)+ }+ // 阈值与 hasBattery 都只在这条路径上变, 派生值跟着一起收在这里+ assign(+ hasBattery && lowBatteryThreshold != .off,+ to: \.isLowBatteryProtectionEnabled+ )++ // 保护关掉了就没有可维持的状态, 这一条要排在读数判断之前+ guard let threshold = lowBatteryThreshold.percent else {+ assign(false, to: \.isLowBatteryActive)+ clearPendingLowBatteryNotification()return}- if let deadline = maximumDurationDeadline(from: maximumDurationStartedAt),- Date() >= deadline {- reachMaximumDuration()+ // 读失败与确认没有电池必须分开: 后者该清零, 前者维持现状+ guard reading != .unreadable else {return}- hasReachedMaximumDuration = false- scheduleMaximumDurationTask()- reconcileSleepState(trigger: .settings)+ guard let status = reading.status else {+ assign(false, to: \.isLowBatteryActive)+ clearPendingLowBatteryNotification()+ return+ }++ // 这一轮结束的标志是电量真的回来了, 不是接上了电源+ // 排在供电状态之前: 充电期间也要能收口, 否则下一次拔线还算同一轮+ if status.percent >= threshold + Self.lowBatteryHysteresis {+ clearPendingLowBatteryNotification()+ }++ guard status.isOnBattery else {+ assign(false, to: \.isLowBatteryActive)+ return+ }++ let wasBatteryLow = isLowBatteryActive+ let isLow = wasBatteryLow+ ? status.percent < threshold + Self.lowBatteryHysteresis+ : status.percent <= threshold+ assign(isLow, to: \.isLowBatteryActive)+ guard isLow, !wasBatteryLow else {+ return+ }++ // 百分比只在这里记一次; 放进 SleepConditions 会让每掉 1% 刷一条+ // 本来就没在挡休眠时这一跌不改变任何事, 但仍要记: 这是排查"为什么在这个电量断的"的唯一依据+ let wasPreventingSleep = isActivelyPreventingSleep+ AppLog.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+ }++ pendingLowBatteryPercent = nil+ guard isLowBatteryBlocking else {+ return+ }++ // 锁存要等通知真的发出去才打: 打在入队处或提交前, 都会让没送达的那一条吃掉整轮配额+ // 使这一轮之后真正触发的低电量再也提醒不了+ hasNotifiedLowBattery = await onLowBatteryTriggered?(percent) ?? false+ }++ private func clearPendingLowBatteryNotification() {+ pendingLowBatteryPercent = nil+ hasNotifiedLowBattery = false}private func handleActivitySnapshot(_ snapshot: CodexActivitySnapshot) {@@ -222,27 +396,26 @@ final class KeepAliveController: ObservableObject {startedRunningTaskIDs.formUnion(runningTaskIDs)waitingTaskIDs = currentWaitingTaskIDs- hasRunningTasks = !runningTaskIDs.isEmpty+ assign(!runningTaskIDs.isEmpty, to: \.hasRunningTasks)if activeTaskIDs.isEmpty {- resetMaximumDurationState()+ durationLimiter.reset()} else if !newRunningTaskIDs.isEmpty || !resumedRunningTaskIDs.isEmpty {restartMaximumDurationPeriod()}reconcileSleepState(trigger: .taskChanged)}+ /// 还没真正挡住休眠时只清零不起表, 等禁用成功后由 begin 补上private func restartMaximumDurationPeriod() {guard isEnabled else {return}- maximumDurationStartedAt = Date()- hasReachedMaximumDuration = false- if helperStatus == .enabled, !isRefreshingHelper {- scheduleMaximumDurationTask()- }+ durationLimiter.restart(isPreventingSleep: isPreventingSleep)}+ // MARK: - helper 注册+func openSystemSettings() {SMAppService.openSystemSettingsLoginItems()}@@ -292,7 +465,7 @@ final class KeepAliveController: ObservableObject {return}- isRefreshingHelper = true+ assign(true, to: \.isRefreshingHelper)cancelRetryTask()invalidateConnection()// 连接已失效, 重试也取消了, 之前的操作类错误已经过期@@ -331,7 +504,7 @@ final class KeepAliveController: ObservableObject {registrationErrorMessage = "更新服务失败"}- isRefreshingHelper = false+ assign(false, to: \.isRefreshingHelper)helperRegistrationTask = nilif helperStatus == .requiresApproval, opensSystemSettings {openSystemSettings()@@ -360,7 +533,8 @@ final class KeepAliveController: ObservableObject {/// @Published 在 willSet 无条件发信号, 不比较新旧值/// refreshHelperStatus 每次 App 激活跑, releaseSleepPrevention 每条活动快照都会经过- /// 同值赋值会让菜单面板和设置页反复空转, 所有 @Published 的写入都走这里+ /// 同值赋值会让菜单面板和设置页反复空转, 所以反复求值路径上的写入都走这里+ /// 用户动作与一次性的操作结果本来就不会重复, 直接赋值即可private func assign<Value: Equatable>(_ value: Value,to keyPath: ReferenceWritableKeyPath<KeepAliveController, Value>@@ -394,13 +568,16 @@ final class KeepAliveController: ObservableObject {assign(nil, to: \.registrationErrorMessage)} else if helperStatus != .requiresApproval {releaseSleepPrevention()- resetMaximumDurationState()+ durationLimiter.reset()}}+ // MARK: - 决策与条件日志+private func reconcileSleepState(trigger: LogTrigger, force: Bool = false) {let blockReason = sleepBlockReasonlet wantsSleepDisabled = blockReason == nil+ publishDerivedState(blockReason: blockReason)logSleepConditionsIfChanged(blockReason: blockReason, trigger: trigger)guard wantsSleepDisabled else {@@ -419,6 +596,25 @@ final class KeepAliveController: ObservableObject {applySleepDisabled(true)}+ /// UI 关心的两个布尔都从 blockReason 派生, 且只在这里写+ /// 这么做是因为 sleepBlockReason 里的输入 (任务, helper 刷新中) 变化远比结论频繁,+ /// 让它们各自 @Published 会把整个设置页拖着一起重算+ /// 新增阻断条件时 allowsOptions 那个 switch 必须表态, 于是不会出现"入口亮着却点不动"+ private func publishDerivedState(blockReason: SleepBlockReason?) {+ assign(blockReason == .lowBattery, to: \.isLowBatteryBlocking)+ assign(Self.allowsOptions(blockReason), to: \.canShowOptions)+ }++ /// 缺依赖时收起入口, 只是没在防休眠 (没任务, 低电量, 已达上限) 时仍然要能改设置+ private static func allowsOptions(_ blockReason: SleepBlockReason?) -> Bool {+ switch blockReason {+ case .notStarted, .userOff, .hookDisabled, .helperUnavailable:+ false+ case nil, .noTasks, .helperRefreshing, .lowBattery, .limitReached:+ true+ }+ }+/// 任何一项变了才记一条, 逐次求值不记/// want 为 0 时这条是唯一能看出「是哪一项把它拉下来」的依据private func logSleepConditionsIfChanged(@@ -432,6 +628,7 @@ final class KeepAliveController: ObservableObject {tasks: hasRunningTasks,helper: helperStatus,refreshing: isRefreshingHelper,+ battery: isLowBatteryActive,limited: hasReachedMaximumDuration)guard conditions != lastLoggedSleepConditions else {@@ -444,7 +641,7 @@ final class KeepAliveController: ObservableObject {let triggerName = trigger.rawValuelet helperName = String(describing: conditions.helper)AppLog.keepAlive.notice(- "KeepAlive 条件变化: trigger=\(triggerName, privacy: .public); want=\(blockReason == nil ? 1 : 0); enabled=\(conditions.enabled ? 1 : 0); hook=\(conditions.hook ? 1 : 0); tasks=\(conditions.tasks ? 1 : 0); helper=\(helperName, privacy: .public); refreshing=\(conditions.refreshing ? 1 : 0); limited=\(conditions.limited ? 1 : 0)"+ "KeepAlive 条件变化: trigger=\(triggerName, privacy: .public); want=\(blockReason == nil ? 1 : 0); enabled=\(conditions.enabled ? 1 : 0); hook=\(conditions.hook ? 1 : 0); tasks=\(conditions.tasks ? 1 : 0); helper=\(helperName, privacy: .public); refreshing=\(conditions.refreshing ? 1 : 0); battery=\(conditions.battery ? 1 : 0); limited=\(conditions.limited ? 1 : 0)")guard let previous, previous.blockReason == nil, let blockReason else {@@ -454,6 +651,8 @@ final class KeepAliveController: ObservableObject {AppLog.keepAlive.notice("KeepAlive 已解除: reason=\(blockReason.rawValue, privacy: .public)")}+ // MARK: - 休眠切换与恢复+private func applySleepDisabled(_ disabled: Bool) {guard appliedSleepDisabled != disabled else {return@@ -463,7 +662,7 @@ final class KeepAliveController: ObservableObject {let result = systemSleepService.beginPreventingIdleSleep()guard result == kIOReturnSuccess else {AppLog.keepAlive.error("空闲断言建立失败: code=\(result)")- operationErrorMessage = "阻止空闲休眠失败"+ operationErrorMessage = "防止空闲休眠失败"scheduleRetryIfNeeded(for: true)return}@@ -525,8 +724,18 @@ final class KeepAliveController: ObservableObject {"系统休眠已关闭: generation=\(generation); lidCausesSleep=\(lidCausesSleep, privacy: .public)")self.canTrustRestoreResult = true- self.beginMaximumDurationCountdownIfNeeded()+ self.durationLimiter.begin()} else {+ // 先收表再走恢复: finishSleepRestore 可能直接把机器送去睡+ self.durationLimiter.pause()+ // 通知同样要赶在补发休眠之前发出去, 理由与收表相同+ // 走到这里 pmset 已经恢复成功, 那句"已恢复系统休眠"才站得住+ await self.flushPendingLowBatteryNotification()+ // 上面这一步会挂起, 期间可能已经有新的禁用请求接管+ // 那时再走恢复会释放掉刚建立的空闲断言, 所以重新认一次代+ guard generation == self.requestGeneration else {+ return+ }self.finishSleepRestore(sleepDisabledAfterOperation: sleepDisabledAfterOperation)@@ -535,56 +744,6 @@ final class KeepAliveController: ObservableObject {}}- private func beginMaximumDurationCountdownIfNeeded() {- if maximumDurationStartedAt == nil {- maximumDurationStartedAt = Date()- hasReachedMaximumDuration = false- }- scheduleMaximumDurationTask()- }-- private func scheduleMaximumDurationTask() {- cancelMaximumDurationTask()-- guard isStarted,- let maximumDurationStartedAt,- !hasReachedMaximumDuration else {- return- }-- guard let deadline = maximumDurationDeadline(from: maximumDurationStartedAt) else {- return- }-- let remaining = deadline.timeIntervalSinceNow- guard remaining > 0 else {- reachMaximumDuration()- return- }-- maximumDurationTask = Task { @MainActor [weak self] in- try? await Task.sleep(for: .seconds(remaining))- guard !Task.isCancelled, let self else {- return- }- maximumDurationTask = nil- reachMaximumDuration()- }- }-- private func reachMaximumDuration() {- guard maximumDurationStartedAt != nil,- !hasReachedMaximumDuration else {- return- }-- cancelMaximumDurationTask()- hasReachedMaximumDuration = true- let durationTitle = maximumDuration.title- AppLog.keepAlive.notice("KeepAlive 已达上限: duration=\(durationTitle, privacy: .public)")- reconcileSleepState(trigger: .limitReached)- }-private func finishSleepRestore(sleepDisabledAfterOperation: Bool) {// assertion 无论回复可不可信都要释放, 与下面的判断无关let idleSleepResult = systemSleepService.endPreventingIdleSleep()@@ -632,20 +791,7 @@ final class KeepAliveController: ObservableObject {}}- private func resetMaximumDurationState() {- cancelMaximumDurationTask()- maximumDurationStartedAt = nil- assign(false, to: \.hasReachedMaximumDuration)- }-- private func cancelMaximumDurationTask() {- maximumDurationTask?.cancel()- maximumDurationTask = nil- }-- private func maximumDurationDeadline(from startedAt: Date) -> Date? {- maximumDuration.timeInterval.map(startedAt.addingTimeInterval)- }+ // MARK: - XPC 连接与重试private func makeConnection() -> NSXPCConnection {let connection = NSXPCConnection(@@ -715,11 +861,13 @@ final class KeepAliveController: ObservableObject {}/// assertion 与 isPreventingSleep 同进同退的唯一出口- /// 两者必须一起收: 只清标志会让菜单栏图标显示成未防休眠, 而这条 assertion 仍在阻止空闲休眠,+ /// 两者必须一起收: 只清标志会让菜单栏图标显示成未防休眠, 而这条 assertion 仍在防止空闲休眠,/// 且没有任何后续路径会释放它; 仍需要防休眠时由重试经 applySleepDisabled(true) 重建private func releaseSleepPrevention() {_ = systemSleepService.endPreventingIdleSleep()assign(false, to: \.isPreventingSleep)+ // 收表跟着实际效果走: 这里之后休眠不再被挡, 那段时间不该占用户的上限+ durationLimiter.pause()}private func cancelRetryTask() {@@ -732,7 +880,7 @@ final class KeepAliveController: ObservableObject {private func cancelHelperRegistrationTask() {helperRegistrationTask?.cancel()helperRegistrationTask = nil- isRefreshingHelper = false+ assign(false, to: \.isRefreshingHelper)}private func scheduleRetryIfNeeded(for disabled: Bool) {@@ -747,9 +895,9 @@ final class KeepAliveController: ObservableObject {// 固定 2 秒无上限重试会让持续失败的 helper 变成无限循环guard retryAttempt < Self.sleepToggleRetryDelays.count else {AppLog.keepAlive.error(- "阻止休眠多次失败: attempts=\(Self.sleepToggleRetryDelays.count)"+ "KeepAlive 切换重试已放弃: attempts=\(Self.sleepToggleRetryDelays.count)")- operationErrorMessage = "阻止休眠多次失败, 已停止重试"+ operationErrorMessage = "防休眠多次失败, 已停止重试"return}@@ -776,6 +924,8 @@ final class KeepAliveController: ObservableObject {}}+ // MARK: - 防休眠条件判定+/// 用户意图 (isEnabled) 与依赖可用性在这里汇合/// 依赖不满足只让效果失效, 不回写 isEnabledprivate var shouldDisableSleep: Bool {@@ -803,14 +953,21 @@ final class KeepAliveController: ObservableObject {if isRefreshingHelper {return .helperRefreshing}+ if isLowBatteryActive {+ return .lowBattery+ }if hasReachedMaximumDuration {return .limitReached}return nil}+ // MARK: - 常量+private static let enabledKey = "KeepAlive.isEnabled"- private static let maximumDurationKey = "KeepAlive.maximumContinuousDurationSeconds"+ private static let lowBatteryThresholdKey = "KeepAlive.lowBatteryThresholdPercent"+ /// 解除门槛比触发门槛高这么多个百分点, 避免电量在阈值附近抖动导致反复切换+ private static let lowBatteryHysteresis = 5private static let helperRegistrationFingerprintKey ="KeepAlive.helperRegistrationFingerprint"private static let helperRegistrationRetryDelays: [Duration] = [@@ -833,6 +990,8 @@ final class KeepAliveController: ObservableObject {.seconds(256)]+ // MARK: - helper 资源与指纹+private static var helperService: SMAppService {SMAppService.daemon(plistName: CodexBarHelperIPC.daemonPlistName)}@@ -891,71 +1050,6 @@ final class KeepAliveController: ObservableObject {}}-extension KeepAliveController {- enum MaximumDuration: Int, CaseIterable, Identifiable {- case oneHour = 3600- case twoHours = 7200- case fourHours = 14400- case eightHours = 28800- case twelveHours = 43200- case twentyFourHours = 86400- case unlimited = -1-- var id: Int {- rawValue- }-- var title: String {- switch self {- case .oneHour:- "1 小时"- case .twoHours:- "2 小时"- case .fourHours:- "4 小时"- case .eightHours:- "8 小时"- case .twelveHours:- "12 小时"- case .twentyFourHours:- "24 小时"- case .unlimited:- "无限制"- }- }-- var timeInterval: TimeInterval? {- self == .unlimited ? nil : TimeInterval(rawValue)- }- }-- enum HelperStatus: Equatable {- case notRegistered- case enabled- case requiresApproval- case notFound-- var isRegisteredOrAwaitingApproval: Bool {- self == .enabled || self == .requiresApproval- }-- init(_ status: SMAppService.Status) {- switch status {- case .notRegistered:- self = .notRegistered- case .enabled:- self = .enabled- case .requiresApproval:- self = .requiresApproval- case .notFound:- self = .notFound- @unknown default:- self = .notFound- }- }- }-}-private enum KeepAliveError: LocalizedError {case invalidHelperProxycase connectionInterrupteddiff --git a/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swiftnew file mode 100644index 0000000..6d835b7--- /dev/null+++ b/CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift@@ -0,0 +1,188 @@+import Combine+import Foundation+import os++/// 防休眠的时长上限计时+/// 累计的是真正挡住休眠的那段时间: begin 起表, pause 收表, 收表之后机器睡着或被低电量拦下都不算+/// 时钟用 SuspendingClock 而不是 Date: 后者受系统时间调整影响, 且系统睡眠期间照走+/// hasReached 是粘滞标志: 累计只增不减, 到期之后每一秒都还成立+/// 只有重新开始计时的入口能清除它, 这些清除全部收在 clearReached 里+/// 低电量那条是纯条件判定, 不要照抄这里的粘滞写法+@MainActor+final class KeepAliveDurationLimiter: ObservableObject {+ typealias Duration = KeepAliveController.MaximumDuration++ @Published private(set) var duration: Duration+ @Published private(set) var hasReached = false++ /// 状态变化后需要重新求值一次防休眠条件, 参数是这次变化的来源+ /// begin pause restart reset 不走这里: 它们的调用方本来就会紧接着求值+ var onStateChanged: ((LogTrigger) -> Void)?++ private let defaults: UserDefaults+ private var task: Task<Void, Never>?+ /// 已经收表的累计时长+ private var accumulated: TimeInterval = 0+ /// 当前这一段的起点, nil 表示没在累加+ private var runningSince: SuspendingClock.Instant?+ /// 避免 stop 之后在途回调又把计时器支起来+ private var isRunning = false++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ duration = (defaults.object(forKey: Self.durationKey) as? Int)+ .flatMap(Duration.init(rawValue:)) ?? .twelveHours+ }++ func start() {+ isRunning = true+ }++ func stop() {+ isRunning = false+ reset()+ }++ func setDuration(_ duration: Duration) {+ guard duration != self.duration else {+ return+ }++ AppLog.keepAlive.notice("KeepAlive 防休眠时间上限变更: threshold=\(duration.loggedHours)")+ self.duration = duration+ defaults.set(duration.rawValue, forKey: Self.durationKey)++ // 这一轮没累计过就没有可解除的状态, 条件没变也就不必让外面重新求值+ guard hasAccumulated else {+ return+ }++ // 走 fireReached 而不是直接 markReached: 这一轮可能已经达过上限+ // 把上限调大但仍然不够时不该再记一条已达上限, 也不该重复通知外面+ if let limit = duration.timeInterval, elapsed >= limit {+ fireReached()+ return+ }++ clearReached()+ schedule()+ onStateChanged?(.settings)+ }++ /// 防休眠真正生效后起表; 已经在走就保持这一段不变+ func begin() {+ if runningSince == nil {+ runningSince = .now+ clearReached()+ }+ schedule()+ }++ /// 防休眠解除时收表, 把这一段并进累计值+ /// 收表之后的时间一律不算: 机器睡着, 低电量拦着, helper 断开都不该占用户的上限+ func pause() {+ guard let runningSince else {+ return+ }++ accumulated += TimeInterval(runningSince.duration(to: .now))+ self.runningSince = nil+ cancelTask()+ }++ /// 有新任务或等待任务恢复运行时重新计时+ /// isPreventingSleep 由调用方给出: 还没真正挡住休眠时只清零, 等 begin 起表+ func restart(isPreventingSleep: Bool) {+ cancelTask()+ accumulated = 0+ clearReached()+ runningSince = isPreventingSleep ? .now : nil+ guard isPreventingSleep else {+ return+ }++ schedule()+ }++ func reset() {+ cancelTask()+ runningSince = nil+ accumulated = 0+ clearReached()+ }++ /// @Published 在 willSet 无条件发信号, 而这里的 objectWillChange 被转发进 KeepAliveController+ /// 同值赋值会让整个高级设置页和活动卡片跟着空转, 所以 hasReached 的清零都走这里+ private func clearReached() {+ guard hasReached else {+ return+ }++ hasReached = false+ }++ /// 这一轮已经挡住休眠的总时长, 含当前还没收表的这一段+ private var elapsed: TimeInterval {+ guard let runningSince else {+ return accumulated+ }++ return accumulated + TimeInterval(runningSince.duration(to: .now))+ }++ /// 这一轮有没有真的累计过, 没累计过就没有可解除的上限状态+ private var hasAccumulated: Bool {+ runningSince != nil || accumulated > 0+ }++ private func schedule() {+ cancelTask()++ guard isRunning,+ runningSince != nil,+ !hasReached,+ let limit = duration.timeInterval else {+ return+ }++ let remaining = limit - elapsed+ guard remaining > 0 else {+ fireReached()+ return+ }++ // 计时器同样走 SuspendingClock, 否则机器睡一夜醒来会当场判定到期+ let deadline = SuspendingClock.Instant.now.advanced(by: .seconds(remaining))+ task = Task { @MainActor [weak self] in+ try? await Task.sleep(until: deadline, clock: SuspendingClock())+ guard !Task.isCancelled, let self else {+ return+ }+ task = nil+ fireReached()+ }+ }++ private func fireReached() {+ guard hasAccumulated, !hasReached else {+ return+ }++ markReached()+ onStateChanged?(.limitReached)+ }++ private func markReached() {+ cancelTask()+ hasReached = true+ let thresholdHours = duration.loggedHours+ AppLog.keepAlive.notice("KeepAlive 已达上限: threshold=\(thresholdHours)")+ }++ private func cancelTask() {+ task?.cancel()+ task = nil+ }++ private static let durationKey = "KeepAlive.maximumContinuousDurationSeconds"+}diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swiftnew file mode 100644index 0000000..7f661de--- /dev/null+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift@@ -0,0 +1,96 @@+import Foundation+import ServiceManagement++extension KeepAliveController {+ /// 低电量保护阈值, rawValue 就是百分比; off 用 -1 与合法百分比区分+ enum LowBatteryThreshold: Int, CaseIterable, Identifiable {+ case off = -1+ case fivePercent = 5+ case tenPercent = 10+ case fifteenPercent = 15+ case twentyPercent = 20+ case twentyFivePercent = 25++ var id: Int {+ rawValue+ }++ var title: String {+ self == .off ? "关闭" : "\(rawValue)%"+ }++ /// nil 表示不启用保护+ var percent: Int? {+ self == .off ? nil : rawValue+ }+ }++ enum MaximumDuration: Int, CaseIterable, Identifiable {+ case oneHour = 3600+ case twoHours = 7200+ case fourHours = 14400+ case eightHours = 28800+ case twelveHours = 43200+ case twentyFourHours = 86400+ case unlimited = -1++ var id: Int {+ rawValue+ }++ var title: String {+ switch self {+ case .oneHour:+ "1 小时"+ case .twoHours:+ "2 小时"+ case .fourHours:+ "4 小时"+ case .eightHours:+ "8 小时"+ case .twelveHours:+ "12 小时"+ case .twentyFourHours:+ "24 小时"+ case .unlimited:+ "无限制"+ }+ }++ /// 日志用的小时数, 与 LowBatteryThreshold 的百分比同一种可读形式, 无限制同样记 -1+ /// rawValue 是秒数, 直接记会得到 14400 这种不好读的值+ var loggedHours: Int {+ self == .unlimited ? -1 : rawValue / 3600+ }++ var timeInterval: TimeInterval? {+ self == .unlimited ? nil : TimeInterval(rawValue)+ }+ }++ enum HelperStatus: Equatable {+ case notRegistered+ case enabled+ case requiresApproval+ case notFound++ var isRegisteredOrAwaitingApproval: Bool {+ self == .enabled || self == .requiresApproval+ }++ init(_ status: SMAppService.Status) {+ switch status {+ case .notRegistered:+ self = .notRegistered+ case .enabled:+ self = .enabled+ case .requiresApproval:+ self = .requiresApproval+ case .notFound:+ self = .notFound+ @unknown default:+ self = .notFound+ }+ }+ }+}diff --git a/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swiftnew file mode 100644index 0000000..03c8829--- /dev/null+++ b/CodexBar/Services/KeepAlive/PowerSourceMonitor.swift@@ -0,0 +1,203 @@+import AppKit+import Foundation+import IOKit.ps+import os++/// 一次电源读取的结果+/// 三态而不是可选值: 把读取失败折叠进"没有电池"会让设置项凭空消失, 保护也静默失效+nonisolated enum BatteryReading: Equatable {+ /// 确认这台机器没有内置电池 (台式机)+ case unavailable+ /// 读取失败, 有没有电池以及电量都未知+ case unreadable+ case present(BatteryStatus)++ var status: BatteryStatus? {+ guard case let .present(status) = self else {+ return nil+ }+ return status+ }++ /// 只有确认没有电池才隐藏设置项; 读不出来时按"可能有"处理, 避免设置项闪烁+ var hasBattery: Bool {+ self != .unavailable+ }++ /// 日志用的状态标识; 不带电量, 那个只在触及阈值那一条里记+ var loggedState: String {+ switch self {+ case .unavailable: "unavailable"+ case .unreadable: "unreadable"+ case .present: "present"+ }+ }+}++nonisolated struct BatteryStatus: Equatable {+ let percent: Int+ /// 正在靠电池供电; 接着电源时为 false, 此时电量不会被耗干+ let isOnBattery: Bool+}++/// 只读系统电源状态并在变化时通知外部, 不知道阈值也不知道防休眠+/// IOKit 的 C 接口和内存管理约定全部收在这里, 不漏到调用方+@MainActor+final class PowerSourceMonitor {+ private(set) var reading = BatteryReading.unreadable++ private var onChange: (() -> Void)?+ private var runLoopSource: CFRunLoopSource?+ private var wakeObserver: NSObjectProtocol?+ private var pollTask: Task<Void, Never>?+ /// 重入守卫; 不能拿 runLoopSource 顶替: 注册失败时它是 nil, 而唤醒观察者已经装上了+ private var isMonitoring = false+ /// 这台机器确认装着内置电池+ /// 硬件不会中途消失, 所以见过之后再读到空列表只能是枚举缺口, 不能当成台式机+ private var hasSeenBattery = false++ /// 回调里持有的是 unretained 指针, 停止监听必须显式做, 由持有者在 stop 时调用+ /// 不放 deinit: Swift 6 的 nonisolated deinit 碰不了这两个非 Sendable 属性+ func stop() {+ isMonitoring = false+ pollTask?.cancel()+ pollTask = nil+ if let runLoopSource {+ CFRunLoopRemoveSource(CFRunLoopGetMain(), runLoopSource, .defaultMode)+ self.runLoopSource = nil+ }+ if let wakeObserver {+ NSWorkspace.shared.notificationCenter.removeObserver(wakeObserver)+ self.wakeObserver = nil+ }+ onChange = nil+ }++ /// onChange 只在读数真的变化时回调+ func start(onChange: @escaping () -> Void) {+ guard !isMonitoring else {+ return+ }+ isMonitoring = true+ self.onChange = onChange+ // 不走 refresh: 它按变化过滤, 而初始值就是 unreadable, 首读失败会被静默吞掉+ // 那之后低电量判定一直冻着, 却只在恢复时留下一条没有配对失败行的日志+ let initialReading = currentReading()+ if initialReading == .unreadable {+ AppLog.keepAlive.error("电源监听读取失败: stage=start")+ }+ reading = initialReading++ // 装在 source 之前: 注册失败时它已经就位, 与那条路的轮询兜底叠着用+ // 休眠期间电量可能变化很大, 而系统不一定为此补发电源通知+ wakeObserver = NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.didWakeNotification,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ MainActor.assumeIsolated {+ self?.refresh()+ }+ }++ let context = Unmanaged.passUnretained(self).toOpaque()+ guard let source = IOPSNotificationCreateRunLoopSource({ context in+ guard let context else {+ return+ }+ // 回调跑在注册它的 runloop 上, 这里就是主线程+ MainActor.assumeIsolated {+ Unmanaged<PowerSourceMonitor>.fromOpaque(context)+ .takeUnretainedValue()+ .refresh()+ }+ }, context)?.takeRetainedValue() else {+ // action= 记的是降级后还剩什么, 否则只知道注册失败, 不知道保护是不是全没了+ AppLog.keepAlive.error(+ "电源监听注册失败: stage=createRunLoopSource; action=poll"+ )+ startPolling()+ return+ }++ CFRunLoopAddSource(CFRunLoopGetMain(), source, .defaultMode)+ runLoopSource = source+ }++ func refresh() {+ let newReading = currentReading()+ guard newReading != reading else {+ return+ }++ // 降级与恢复成对记: 判定在整个 unreadable 窗口里被冻结, 只记进不记出就看不出冻了多久+ if case .unreadable = newReading {+ AppLog.keepAlive.error("电源监听读取失败: stage=refresh")+ } else if case .unreadable = reading {+ let state = newReading.loggedState+ AppLog.keepAlive.notice("电源监听读取已恢复: state=\(state, privacy: .public)")+ }+ reading = newReading+ onChange?()+ }++ /// 注册失败后的兜底轮询+ /// 只靠唤醒补读不够: 防休眠正在生效的机器按定义就不会睡, 那条通知永远不来+ private func startPolling() {+ pollTask?.cancel()+ pollTask = Task { @MainActor [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(Self.pollIntervalSeconds))+ guard !Task.isCancelled, let self else {+ return+ }++ refresh()+ }+ }+ }++ /// 电量取 Current/Max 的比例而不是直接用 Current+ /// 实测两者都是百分比 (Max=100), 但历史上某些路径下是 mAh, 按比例算两种情况都对+ private func currentReading() -> BatteryReading {+ guard let blob = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),+ let sources = IOPSCopyPowerSourcesList(blob)?.takeRetainedValue() as? [CFTypeRef] else {+ return .unreadable+ }++ for source in sources {+ // Get 语义, 不能 takeRetainedValue+ guard let description = IOPSGetPowerSourceDescription(blob, source)?+ .takeUnretainedValue() as? [String: Any],+ description[kIOPSTypeKey] as? String == kIOPSInternalBatteryType,+ description[kIOPSIsPresentKey] as? Bool == true else {+ continue+ }++ hasSeenBattery = true+ guard let current = description[kIOPSCurrentCapacityKey] as? Int,+ let maximum = description[kIOPSMaxCapacityKey] as? Int,+ maximum > 0 else {+ return .unreadable+ }++ let percent = Int((Double(current) / Double(maximum) * 100).rounded())+ // 只有 Battery Power 才是真的在耗电池+ // 不能用 Is Charging: 接电但停充时它也是 false, 而那时电量并没有在掉+ let isOnBattery = description[kIOPSPowerSourceStateKey] as? String+ == kIOPSBatteryPowerValue+ return .present(+ BatteryStatus(+ percent: min(max(percent, 0), 100),+ isOnBattery: isOnBattery+ )+ )+ }++ // 走到这里既可能是台式机, 也可能是 IOKit 正在重新枚举而列表暂时为空+ // 见过电池就只能算这一次读不到, 交给调用方维持上一次判定, 否则一次缺口会当场撤掉保护+ return hasSeenBattery ? .unreadable : .unavailable+ }++ private static let pollIntervalSeconds = 60+}diff --git a/CodexBar/Services/Notifications/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex 5946538..3f7b2cc 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -387,6 +387,23 @@ final class CodexNotificationService: NSObject {}}+ // MARK: - 低电量保护++ /// 由 KeepAliveController 在低电量导致休眠恢复成功之后调用, 恢复失败不会走到这里+ /// 不做去重: 调用方自己保证同一轮低电量只发一次, 电量回到解除门槛以上才算下一轮+ /// async 是为了让调用方能等提交完再补发休眠, 否则合着盖的机器会先睡下去+ /// 返回是否真的发出去了: 调用方据此决定这一轮算不算已通知, 提交失败就不该占掉这一轮+ func notifyLowBatteryProtection(percent: Int) async -> Bool {+ guard settings.canDeliver, settings.isLowBatteryEnabled else {+ return false+ }++ return await send(+ .lowBattery(percent: percent),+ sound: settings.lowBatterySound+ )?.value ?? false+ }+// MARK: - 重置次数临期提醒private func processCreditExpirations(_ snapshot: CodexQuotaSnapshot) {@@ -454,6 +471,10 @@ final class CodexNotificationService: NSObject {// MARK: - 发送与文案/// 通知的 title 与 body 含项目名和任务信息, 一律不进日志, 只记 kind+ /// 返回提交任务, 需要等通知真的发出去再做下一步的调用方 await 它的 value+ /// 只有这一个入口: 另开一条 async 通道会让它悄悄少掉去重 时效判定和失败回调三项能力+ /// 去重判定留在同步段, 这样连续两次 send 的第二次一定被挡下, 不依赖 Task 的调度顺序+ @discardableResultprivate func send(_ notification: CodexNotificationContent,sound: NotificationSoundOption,@@ -461,13 +482,13 @@ final class CodexNotificationService: NSObject {dedupKey: String? = nil,isStillRelevant: (() -> Bool)? = nil,onSubmissionFailure: (() -> Void)? = nil- ) {+ ) -> Task<Bool, Never>? {let kind = notification.kindif let dedupKey {guard !sentDedupKeys.contains(dedupKey),submittingDedupKeys.insert(dedupKey).inserted else {AppLog.notification.notice("通知已跳过: kind=\(kind, privacy: .public); reason=duplicate")- return+ return nil}}@@ -481,50 +502,64 @@ final class CodexNotificationService: NSObject {content: content,trigger: nil)- Task { @MainActor [weak self] in- guard let self else {- return+ return Task { @MainActor [weak self] in+ await self?.deliver(+ request,+ kind: kind,+ dedupKey: dedupKey,+ isStillRelevant: isStillRelevant,+ onSubmissionFailure: onSubmissionFailure+ ) ?? false+ }+ }++ /// 返回值是"这条通知真的提交出去了", 调用方据此决定要不要记下已通知+ private func deliver(+ _ request: UNNotificationRequest,+ kind: String,+ dedupKey: String?,+ isStillRelevant: (() -> Bool)?,+ onSubmissionFailure: (() -> Void)?+ ) async -> Bool {+ defer {+ if let dedupKey {+ submittingDedupKeys.remove(dedupKey)}+ }- defer {- if let dedupKey {- submittingDedupKeys.remove(dedupKey)- }+ for _ in 0 ... Self.notificationSubmissionRetryCount {+ guard isStillRelevant?() != false else {+ AppLog.notification.notice(+ "通知已跳过: kind=\(kind, privacy: .public); reason=obsolete"+ )+ return false}-- for _ in 0 ... Self.notificationSubmissionRetryCount {+ do {+ try await UNUserNotificationCenter.current().add(request)guard isStillRelevant?() != false else {+ // 投递后任务状态又变了, 撤回避免用户看到过期提醒AppLog.notification.notice(- "通知已跳过: kind=\(kind, privacy: .public); reason=obsolete"+ "通知已撤回: kind=\(kind, privacy: .public); reason=obsolete")- return+ removeNotifications(withIdentifiers: [request.identifier])+ return false}- do {- try await UNUserNotificationCenter.current().add(request)- guard isStillRelevant?() != false else {- // 投递后任务状态又变了, 撤回避免用户看到过期提醒- AppLog.notification.notice(- "通知已撤回: kind=\(kind, privacy: .public); reason=obsolete"- )- removeNotifications(withIdentifiers: [identifier])- return- }- if let dedupKey {- rememberSentDedupKey(dedupKey)- }- AppLog.notification.notice("通知已发送: kind=\(kind, privacy: .public)")- return- } catch {- continue+ if let dedupKey {+ rememberSentDedupKey(dedupKey)}+ AppLog.notification.notice("通知已发送: kind=\(kind, privacy: .public)")+ return true+ } catch {+ continue}-- // 重试全部用尽才记, 循环内的单次失败会重试- AppLog.notification.error(- "通知发送失败: kind=\(kind, privacy: .public); reason=retryExhausted"- )- onSubmissionFailure?()}++ // 重试全部用尽才记, 循环内的单次失败会重试+ AppLog.notification.error(+ "通知发送失败: kind=\(kind, privacy: .public); reason=retryExhausted"+ )+ onSubmissionFailure?()+ return false}private func removeNotifications(withIdentifiers identifiers: [String]) {@@ -649,6 +684,14 @@ nonisolated struct CodexNotificationContent: Equatable {body: "有 \(count) 个重置次数将于 \(CodexDateFormat.localDisplayString(from: expirationDate)) 过期")}++ static func lowBattery(percent: Int) -> CodexNotificationContent {+ CodexNotificationContent(+ kind: "lowBattery",+ title: "已恢复系统休眠",+ body: "电量剩余 \(percent)%, 已停止防休眠"+ )+ }}// MARK: - UNUserNotificationCenterDelegatediff --git a/CodexBar/Services/Settings/CodexHookSettings.swift b/CodexBar/Services/Settings/CodexHookSettings.swiftindex a2a3389..8a8d9a8 100644--- a/CodexBar/Services/Settings/CodexHookSettings.swift+++ b/CodexBar/Services/Settings/CodexHookSettings.swift@@ -41,6 +41,8 @@ final class CodexHookSettings: ObservableObject {updateTask?.cancel()}+ // MARK: - 对外入口+func refresh() {do {let config = try readConfigIfPresent()@@ -85,6 +87,8 @@ final class CodexHookSettings: ObservableObject {}}+ // MARK: - 更新流程与并发控制+private func applyEnabled(_ enabled: Bool, generation: Int) async {do {if enabled {@@ -317,6 +321,8 @@ private extension CodexHookSettings {}}+ // MARK: - hooks.json 读写+func writeCodexBarHookConfig(enabled: Bool) throws {var config = try readConfigIfPresent()try Self.removeCodexBarHooks(@@ -345,6 +351,8 @@ private extension CodexHookSettings {)}+ // MARK: - Hook 信任状态+func cleanupCodexHookTrust(removing keys: Set<String>,discoveryError: Error?,diff --git a/CodexBar/Services/Settings/NotificationSettings.swift b/CodexBar/Services/Settings/NotificationSettings.swiftindex af3eb4a..a855c4c 100644--- a/CodexBar/Services/Settings/NotificationSettings.swift+++ b/CodexBar/Services/Settings/NotificationSettings.swift@@ -15,6 +15,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var isTaskWaitingEnabled: Bool@Published private(set) var isTaskHapticEnabled: Bool@Published private(set) var isCreditExpiryEnabled: Bool+ @Published private(set) var isLowBatteryEnabled: Bool@Published private(set) var lowQuotaThresholdPercent: Int@Published private(set) var longTaskThresholdSeconds: Int@Published private(set) var lowQuotaSound: NotificationSoundOption@@ -22,6 +23,7 @@ final class NotificationSettings: ObservableObject {@Published private(set) var longTaskSound: NotificationSoundOption@Published private(set) var taskWaitingSound: NotificationSoundOption@Published private(set) var creditExpirySound: NotificationSoundOption+ @Published private(set) var lowBatterySound: NotificationSoundOption@Published private(set) var authorizationStatus: UNAuthorizationStatus = .notDetermined/// 系统授权被拒时设置页展示引导, 通知服务停发@@ -70,6 +72,7 @@ final class NotificationSettings: ObservableObject {isTaskWaitingEnabled = Self.bool(from: defaults, key: Self.taskWaitingEnabledKey, defaultValue: true)isTaskHapticEnabled = Self.bool(from: defaults, key: Self.taskHapticEnabledKey, defaultValue: true)isCreditExpiryEnabled = Self.bool(from: defaults, key: Self.creditExpiryEnabledKey, defaultValue: true)+ isLowBatteryEnabled = Self.bool(from: defaults, key: Self.lowBatteryEnabledKey, defaultValue: true)lowQuotaThresholdPercent = Self.option(defaults.object(forKey: Self.lowQuotaThresholdKey) as? Int,in: Self.lowQuotaThresholdOptions,@@ -85,6 +88,7 @@ final class NotificationSettings: ObservableObject {longTaskSound = Self.sound(from: defaults, key: Self.longTaskSoundKey)taskWaitingSound = Self.sound(from: defaults, key: Self.taskWaitingSoundKey)creditExpirySound = Self.sound(from: defaults, key: Self.creditExpirySoundKey)+ lowBatterySound = Self.sound(from: defaults, key: Self.lowBatterySoundKey)}deinit {@@ -128,6 +132,10 @@ final class NotificationSettings: ObservableObject {setBool(enabled, current: &isCreditExpiryEnabled, key: Self.creditExpiryEnabledKey)}+ func setLowBatteryEnabled(_ enabled: Bool) {+ setBool(enabled, current: &isLowBatteryEnabled, key: Self.lowBatteryEnabledKey)+ }+func setLowQuotaThresholdPercent(_ percent: Int) {guard Self.lowQuotaThresholdOptions.contains(percent),percent != lowQuotaThresholdPercent else {@@ -168,6 +176,10 @@ final class NotificationSettings: ObservableObject {setSound(sound, current: &creditExpirySound, key: Self.creditExpirySoundKey)}+ func setLowBatterySound(_ sound: NotificationSoundOption) {+ setSound(sound, current: &lowBatterySound, key: Self.lowBatterySoundKey)+ }+/// 用户可能在系统设置里改过权限, 回到 App 时需要重新读取func refreshAuthorizationStatus() {authorizationTask?.cancel()@@ -284,6 +296,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 lowBatteryEnabledKey = "Notification.lowBatteryEnabled"private static let lowQuotaThresholdKey = "Notification.lowQuotaThresholdPercent"private static let longTaskThresholdKey = "Notification.longTaskThresholdSeconds"private static let lowQuotaSoundKey = "Notification.lowQuotaSound"@@ -291,4 +304,5 @@ final class NotificationSettings: ObservableObject {private static let longTaskSoundKey = "Notification.longTaskSound"private static let taskWaitingSoundKey = "Notification.taskWaitingSound"private static let creditExpirySoundKey = "Notification.creditExpirySound"+ private static let lowBatterySoundKey = "Notification.lowBatterySound"}diff --git a/CodexBar/Services/Support/AppLog.swift b/CodexBar/Services/Support/AppLog.swiftindex 32e8acb..e0bdd70 100644--- a/CodexBar/Services/Support/AppLog.swift+++ b/CodexBar/Services/Support/AppLog.swift@@ -42,6 +42,8 @@ nonisolated enum LogTrigger: String {case taskChangedcase helperRegisteredcase limitReached+ /// 电量或供电方式变化+ case batterycase statusRefresh}@@ -60,9 +62,14 @@ nonisolated struct LogDuration {/// 重试间隔这类 Duration 走这里, 不必在调用点各写一遍换算static func seconds(_ duration: Duration) -> String {- seconds(- Double(duration.components.seconds)- + Double(duration.components.attoseconds) / 1e18- )+ seconds(TimeInterval(duration))+ }+}++nonisolated extension TimeInterval {+ /// Duration 的 attosecond 分量换算成秒, 全仓库只留这一份+ init(_ duration: Duration) {+ self = Double(duration.components.seconds)+ + Double(duration.components.attoseconds) / 1e18}}diff --git a/CodexBar/Services/Workflow/CodexActivityMonitor.swift b/CodexBar/Services/Workflow/CodexActivityMonitor.swiftindex ad9f698..9c3c166 100644--- a/CodexBar/Services/Workflow/CodexActivityMonitor.swift+++ b/CodexBar/Services/Workflow/CodexActivityMonitor.swift@@ -139,6 +139,8 @@ final class CodexActivityMonitor: ObservableObject {snapshot = .empty}+ // MARK: - 会话生命周期+private func startSessionLifecyclePolling(generation: UInt64) {guard sessionLifecyclePollTask == nil else {return@@ -284,6 +286,8 @@ final class CodexActivityMonitor: ObservableObject {}}+ // MARK: - Hook 事件消费+private func consume(_ batch: HookEventBatch) {switch batch {case .bootstrapStart:@@ -414,6 +418,8 @@ final class CodexActivityMonitor: ObservableObject {return nil}+ // MARK: - 任务状态转换+private func startTask(from event: WorkflowHookEvent) {let key = CodexActivityTaskKey(event: event)let displayID = tasks[key]?.displayID ?? UUID()@@ -690,6 +696,8 @@ final class CodexActivityMonitor: ObservableObject {return tasks[anonymousKey] == nil ? nil : anonymousKey}+ // MARK: - 快照与过期清理+private func refreshSnapshot(now: Date) {pruneExpiredState(now: now)@@ -813,6 +821,8 @@ final class CodexActivityMonitor: ObservableObject {}private extension CodexActivityMonitor {+ // MARK: - 终态判定与记录+/// PermissionRequest 表示进入审批流程; 只有 rollout 明确把审批路由给 user 时才是 UI 等待func resolvePendingApprovalIfPossible(for task: inout CodexActivityTask,@@ -1066,6 +1076,8 @@ private extension CodexActivityMonitor {}}+// MARK: - 内部任务模型+private enum CodexActivityTaskKey: Hashable {case turn(session: String, turn: String)case session(String)diff --git a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swiftindex c85125b..8de9756 100644--- a/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift+++ b/CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift@@ -150,6 +150,8 @@ actor CodexSessionLifecycleReader {recursiveFallbackSessionIds.removeAll()}+ // MARK: - 会话文件定位+private func cursor(for reference: CodexActivityTurnReference) -> SessionFileCursor? {if let cursor = cursorsBySession[reference.sessionId],fileManager.fileExists(atPath: cursor.url.path) {@@ -288,6 +290,8 @@ actor CodexSessionLifecycleReader {return .notFound}+ // MARK: - 增量扫描+private func scanNewLifecycleEvents(into cursor: inout SessionFileCursor) {let stat = WorkflowStorage.fileStat(at: cursor.url)let size = stat?.size ?? 0@@ -360,6 +364,8 @@ private nonisolated enum EffortBackfillResult {case unavailable}+// MARK: - rollout 行解码+/// Codex rollout JSONL 单行的共享解码模型/// Hook 子进程 (WorkflowTurnContextReader) 与 lifecycle reader 共用同一份 schemanonisolated struct CodexRolloutLineEnvelope: Decodable {diff --git a/CodexBar/Services/Workflow/HookEventTailReader.swift b/CodexBar/Services/Workflow/HookEventTailReader.swiftindex 5948323..8e01aa7 100644--- a/CodexBar/Services/Workflow/HookEventTailReader.swift+++ b/CodexBar/Services/Workflow/HookEventTailReader.swift@@ -87,6 +87,8 @@ actor HookEventTailReader {WorkflowStorage.eventLogURL(for: activeDateKey)}+ // MARK: - bootstrap+private func bootstrapRecentActivity() async {for attempt in 0 ..< Self.bootstrapAttemptLimit {guard isRunning, !Task.isCancelled else {@@ -163,6 +165,8 @@ actor HookEventTailReader {)}+ // MARK: - 增量 tail+private func drainNewLines() async {guard isRunning, !Task.isCancelled else {returndiff --git a/CodexBar/Services/Workflow/WorkflowService.swift b/CodexBar/Services/Workflow/WorkflowService.swiftindex 41f251d..7bd888c 100644--- a/CodexBar/Services/Workflow/WorkflowService.swift+++ b/CodexBar/Services/Workflow/WorkflowService.swift@@ -54,6 +54,8 @@ actor WorkflowService {self.syncService = syncService}+ // MARK: - 快照读取+func loadSnapshot(synchronize: Bool = false,trigger: LogTrigger = .auto@@ -181,6 +183,8 @@ actor WorkflowService {return WorkflowDailyAggregate.normalized(aggregates: aggregates)}+ // MARK: - 重建与维护调度+private func rebuildLocalData(for dateKey: String) throws -> WorkflowMaintenanceResult {let task = try prepareRebuildTask(for: dateKey)var aggregates = loadDailyAggregates() ?? []@@ -536,6 +540,8 @@ actor WorkflowService {)}+ // MARK: - 事件文件读取与聚合+private func eventLogURL(for dateKey: String) -> URL {WorkflowStorage.eventLogURL(for: dateKey, in: eventsDirectoryURL)}@@ -687,6 +693,8 @@ actor WorkflowService {return 0}+ // MARK: - 落盘与状态提交+/// 返回是否写入了 daily.jsonlprivate func commit(_ result: WorkflowMaintenanceResult,@@ -849,6 +857,8 @@ actor WorkflowService {}}+ // MARK: - 保留期清理+@discardableResultprivate func pruneExpiredEventFiles() throws -> Int {let cutoffDate = WorkflowStorage.retentionCutoffDate()@@ -894,6 +904,8 @@ nonisolated enum WorkflowStorage {private static let retentionDayCount = 210private static let identifierRetentionDayCount = 3+ // MARK: - 存储路径+static func eventsDirectoryURL() -> URL {directoryURL().appendingPathComponent("events", isDirectory: true)diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex bc4e726..a99644c 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -43,6 +43,8 @@ actor WorkflowSyncService {self.directoryURL = directoryURL}+ // MARK: - 同步入口+func snapshotFromCacheIfEnabled() -> WorkflowSyncSnapshot {guard WorkflowSyncSettings.isEnabled() else {return .disabled@@ -343,6 +345,8 @@ private extension WorkflowSyncService {directoryURL.appendingPathComponent("cursor.data", isDirectory: false)}+ // MARK: - 上传+func uploadChangedAggregates(localByDate: [String: LocalSyncAggregate],remoteRecords: [WorkflowSyncedDailyRecord],@@ -658,6 +662,8 @@ private extension WorkflowSyncService {return confirmedHashes}+ // MARK: - 拉取与缓存+func refreshCacheFromRemote() async throws {guard let token = try loadCursor() else {try await rebuildCacheFromRemote()@@ -874,6 +880,8 @@ private extension WorkflowSyncService {return recordIDs.count}+ // MARK: - 账号与设备标识+func resolveCurrentDeviceId() async throws -> String {let salt = try await accountSalt()let uuid = try Self.ioPlatformUUID()@@ -942,6 +950,8 @@ private extension WorkflowSyncService {throw WorkflowSyncError.missingAccountSalt}+ // MARK: - 记录与 zone 维护+func ensureSyncZoneExists() async throws {guard !isSyncZoneConfirmed else {returndiff --git a/CodexBar/Views/Log/LogView.swift b/CodexBar/Views/Log/LogView.swiftindex 9ed56b0..7fc43bc 100644--- a/CodexBar/Views/Log/LogView.swift+++ b/CodexBar/Views/Log/LogView.swift@@ -75,6 +75,8 @@ struct LogView: View {}}+// MARK: - 单条日志行+/// 单条日志行, 摘要行可展开查看请求和响应预览private struct LogRow: View {let entry: RequestLogEntry@@ -233,6 +235,8 @@ private struct LogRow: View {}()}+// MARK: - 全文查看+/// 预览弹窗数据源private struct FullLogTextItem: Identifiable {let id = UUID()@@ -315,6 +319,8 @@ private struct FullLogTextView: View {}}+// MARK: - JSON 预览与高亮+/// 日志预览文本, JSON 时会带基础语法高亮private struct LogCodePreview {let attributedText: NSAttributedStringdiff --git a/CodexBar/Views/Menu/CodexActivityCard.swift b/CodexBar/Views/Menu/CodexActivityCard.swiftindex 9662117..63c0867 100644--- a/CodexBar/Views/Menu/CodexActivityCard.swift+++ b/CodexBar/Views/Menu/CodexActivityCard.swift@@ -82,7 +82,7 @@ struct CodexActivityCard: View {.font(.system(size: 11, weight: .semibold)).foregroundStyle(Color.teal).transition(.opacity)- .help("已阻止系统休眠")+ .help("已防止系统休眠")}if content.otherTaskCount > 0 {diff --git a/CodexBar/Views/Menu/CodexActivityCenterView.swift b/CodexBar/Views/Menu/CodexActivityCenterView.swiftindex 15401be..f1d6ae1 100644--- a/CodexBar/Views/Menu/CodexActivityCenterView.swift+++ b/CodexBar/Views/Menu/CodexActivityCenterView.swift@@ -41,6 +41,8 @@ struct CodexActivityCenterPanelContext {let preferredSide: UsageHeatmapDetailSide}+// MARK: - 任务中心面板+/// 并发任务中心, 实时展示全部等待; 运行; 最近完成和最近终止任务struct CodexActivityCenterView: View {@ObservedObject var activityMonitor: CodexActivityMonitor@@ -170,6 +172,8 @@ struct CodexActivityCenterView: View {return components.joined(separator: " • ")}+ // MARK: - 分区与行+private func taskSection(title: String,symbolName: String,diff --git a/CodexBar/Views/Menu/CodexStatusMenuSections.swift b/CodexBar/Views/Menu/CodexStatusMenuSections.swiftindex f88fad8..f26a9bc 100644--- a/CodexBar/Views/Menu/CodexStatusMenuSections.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuSections.swift@@ -258,7 +258,6 @@ struct UpdatedAtRow: View {.frame(width: Metrics.syncIconWidth).contentTransition(.opacity).help(syncDisplayState.helpText)- .accessibilityLabel(Text(syncDisplayState.helpText))}.animation(Metrics.statusAnimation, value: updateMessage).animation(Metrics.statusAnimation, value: syncDisplayState)diff --git a/CodexBar/Views/Menu/UsageHeatmap.swift b/CodexBar/Views/Menu/UsageHeatmap.swiftindex 4cb463c..9f12de6 100644--- a/CodexBar/Views/Menu/UsageHeatmap.swift+++ b/CodexBar/Views/Menu/UsageHeatmap.swift@@ -23,6 +23,8 @@ nonisolated struct UsageHeatmapSelection: Equatable {let row: Int}+// MARK: - 摘要区+/// token 摘要和近 30 周热力图的组合区struct UsageSummaryView: View {let usage: CodexUsageSnapshot@@ -232,6 +234,8 @@ struct UsageSummaryView: View {}}+// MARK: - 热力图与 hover 吸附+/// 近 30 周 token 热力图, hover 时把指针吸附到最近的有效日期格struct UsageHeatmap: View {let days: [UsageHeatmapDay?]@@ -430,6 +434,8 @@ extension UsageHeatmap {}}+// MARK: - 单元格+/// 单个热力图方块, 蓝色透明度表示当天 token 强度private struct UsageHeatmapSquare: View {let day: UsageHeatmapDaydiff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 04ae4c3..5c6e430 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -16,11 +16,12 @@ struct AppSettingsView: View {@ObservedObject var keepAliveController: KeepAliveControllerlet onSyncChanged: (Bool) -> Voidlet onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandler- let onNotificationOptionsAction: (NotificationOptionsPanelAction) -> Void+ let onOptionsAction: (SettingsOptionsPanelAction) -> Voidlet onContentHeightChanged: (CGFloat) -> Void@State private var selectedTab = SettingsTab.general@State private var isTabContentSettled = true- @State private var shouldOpenNotificationOptionsAfterAuthorization = false+ @State private var notificationAnchorProvider = ScreenFrameProvider()+ @State private var keepAliveAnchorProvider = ScreenFrameProvider()@State private var rebuildableDates = [String]()@State private var selectedRebuildRange: RebuildDateRange?@State private var isShowingRebuildConfirmation = false@@ -89,8 +90,7 @@ struct AppSettingsView: View {clearRebuildStatus()}.onChange(of: selectedTab) { _, _ in- shouldOpenNotificationOptionsAfterAuthorization = false- onNotificationOptionsAction(.close)+ onOptionsAction(.closeAll)}.task(id: selectedTab) {guard !isTabContentSettled else {@@ -143,9 +143,8 @@ private extension AppSettingsView {static let tabVerticalPadding: CGFloat = 7static let tabContentSpacing = paddingstatic let windowChromeHeight = padding * 2 + tabBarHeight + tabContentSpacing- static let notificationOptionsButtonSize: CGFloat = 22+ static let optionsButtonSize: CGFloat = 22static let menuBarQuotaPickerWidth: CGFloat = 72- static let keepAliveDurationPickerWidth: CGFloat = 88static let syncStatusRowHeight: CGFloat = 16static let syncStatusValueWidth: CGFloat = 160static let tabContentInitialScale = 0.975@@ -158,6 +157,8 @@ private extension AppSettingsView {static let statusAnimation = Animation.codexStatus}+ // MARK: - 分页骨架+var settingsTabBar: some View {HStack(spacing: Metrics.tabSpacing) {ForEach(SettingsTab.allCases) { tab in@@ -187,7 +188,6 @@ private extension AppSettingsView {}.buttonStyle(.plain).frame(maxWidth: .infinity)- .accessibilityAddTraits(isSelected ? .isSelected : [])}}.padding(Metrics.tabBarPadding)@@ -276,6 +276,8 @@ private extension AppSettingsView {}}+ // MARK: - 通用页各行+var launchAtLoginRow: some View {SettingsToggleRow(icon: "power",@@ -377,6 +379,8 @@ private extension AppSettingsView {)}+ // MARK: - 高级页各行+var codexHookRow: some View {VStack(alignment: .leading, spacing: 4) {SettingsToggleRow(@@ -395,43 +399,25 @@ private extension AppSettingsView {}}+ // MARK: - 防休眠+var keepAliveRow: some View {let caption = keepAliveCaptionreturn VStack(alignment: .leading, spacing: 4) {SettingsToggleRow(icon: "moon.zzz",- title: "阻止系统休眠",+ title: "防止系统休眠",isOn: Binding(get: { keepAliveController.isEnabled },set: { keepAliveController.setEnabled($0) }),isEnabled: codexHookSettings.isEnabled && !codexHookSettings.isUpdating) {- if keepAliveController.isEnabled {- HStack(spacing: 6) {- Text("最长阻止时间")- .font(.caption)- .foregroundStyle(.secondary)- .fixedSize()-- Picker(- "最长阻止时间",- selection: Binding(- get: { keepAliveController.maximumDuration },- set: { keepAliveController.setMaximumDuration($0) }- )- ) {- ForEach(KeepAliveController.MaximumDuration.allCases) { duration in- Text(duration.title).tag(duration)- }- }- .labelsHidden()- .pickerStyle(.menu)- .controlSize(.small)- .frame(width: Metrics.keepAliveDurationPickerWidth)- }- .transition(.opacity.combined(with: .move(edge: .trailing)))+ optionsButton(isAvailable: canShowKeepAliveOptions) {+ onOptionsAction(+ .toggle(panel: .keepAlive, anchorProvider: keepAliveAnchorProvider)+ )}}@@ -457,12 +443,42 @@ private extension AppSettingsView {.transition(.opacity)}}+ .background {+ ScreenFrameReader(provider: keepAliveAnchorProvider)+ }.animation(Metrics.statusAnimation, value: caption).animation(Metrics.statusAnimation, value: keepAliveController.isEnabled)+ .onChange(of: canShowKeepAliveOptions) { _, canShowOptions in+ guard !canShowOptions else {+ return+ }++ onOptionsAction(.close(panel: .keepAlive))+ }+ }++ /// 两个子面板入口共用的滑杆按钮; 依赖没就绪时只隐藏入口, 不回写用户保存的开关+ func optionsButton(isAvailable: Bool, action: @escaping () -> Void) -> some View {+ Button(action: action) {+ Image(systemName: "slider.horizontal.3")+ }+ .buttonStyle(.plain)+ .controlSize(.small)+ .foregroundStyle(.tint)+ .frame(width: Metrics.optionsButtonSize, height: Metrics.optionsButtonSize)+ .opacity(isAvailable ? 1 : 0)+ .disabled(!isAvailable)+ .animation(Metrics.statusAnimation, value: isAvailable)+ }++ /// 判定收在 KeepAliveController 里由 sleepBlockReason 派生, 这里只读结论+ /// 在 View 里手抄那几个条件会漏掉后来新增的阻断项, 入口会亮着但点开不生效+ var canShowKeepAliveOptions: Bool {+ keepAliveController.canShowOptions}/// 返回 nil 表示这一行整个收起- /// 正常运行时不必占一行说"一切正常", 是否正在阻止由主面板的咖啡杯标记呈现+ /// 正常运行时不必占一行说"一切正常", 是否正在防休眠由主面板的咖啡杯标记呈现var keepAliveCaption: KeepAliveCaption? {if let errorMessage = keepAliveController.errorMessage {return KeepAliveCaption(message: errorMessage, isError: true)@@ -471,7 +487,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: "电量过低, 已恢复系统休眠")}switch keepAliveController.helperStatus {@@ -488,7 +512,7 @@ private extension AppSettingsView {return nil}return KeepAliveCaption(- message: "已到阻止休眠上限 (\(keepAliveController.maximumDuration.title))"+ message: "已达到防休眠时间上限 (\(keepAliveController.maximumDuration.title))")}}@@ -553,7 +577,6 @@ private extension AppSettingsView {}.frame(height: Metrics.syncStatusRowHeight).opacity(showsSyncStatus ? 1 : 0)- .accessibilityHidden(!showsSyncStatus)}}}@@ -568,6 +591,8 @@ private extension AppSettingsView {)}+ // MARK: - 数据重建+var rebuildWorkflowDataRow: some View {VStack(alignment: .leading, spacing: 4) {HStack(spacing: SettingsRowMetrics.spacing) {@@ -645,10 +670,11 @@ private extension AppSettingsView {rebuildableDates = WorkflowStorage.rebuildableEventDateKeys()}+ /// 防休眠不在这里刷: 控制器自己订阅了 didBecomeActive, 窗口打开也走 refreshSettingsState+ /// 再调一次会让每次激活都多跑一遍电源读取 helper 状态查询和 helper 二进制哈希func refreshStatusRows() {refreshCodexVersionSection()notificationSettings.refreshAuthorizationStatus()- keepAliveController.refresh()refreshRebuildableDates()}@@ -724,6 +750,8 @@ private extension AppSettingsView {rebuildStatus = nil}+ // MARK: - 通知+/// 主开关行保留在设置窗口内, 子选项在右侧子面板中展开var notificationRow: some View {VStack(alignment: .leading, spacing: 4) {@@ -732,26 +760,14 @@ private extension AppSettingsView {title: "系统通知",isOn: Binding(get: { notificationSettings.isEnabled },- set: { setNotificationsEnabled($0) }+ set: { notificationSettings.setEnabled($0) })) {- Button {- onNotificationOptionsAction(.toggle)- } label: {- Image(systemName: "slider.horizontal.3")+ optionsButton(isAvailable: notificationSettings.canShowOptions) {+ onOptionsAction(+ .toggle(panel: .notification, anchorProvider: notificationAnchorProvider)+ )}- .buttonStyle(.plain)- .controlSize(.small)- .foregroundStyle(.tint)- .frame(- width: Metrics.notificationOptionsButtonSize,- height: Metrics.notificationOptionsButtonSize- )- .opacity(notificationSettings.canShowOptions ? 1 : 0)- .disabled(!notificationSettings.canShowOptions)- .accessibilityHidden(!notificationSettings.canShowOptions)- .help("通知选项")- .animation(Metrics.statusAnimation, value: notificationSettings.canShowOptions)}if notificationSettings.isEnabled, notificationSettings.isAuthorizationDenied {@@ -762,34 +778,16 @@ private extension AppSettingsView {}}}+ .background {+ ScreenFrameReader(provider: notificationAnchorProvider)+ }+ // 关掉总开关或被系统拒授权都会让 canShowOptions 转假, 收面板只需要认这一个信号.onChange(of: notificationSettings.canShowOptions) { _, canShowOptions in- guard canShowOptions else {- onNotificationOptionsAction(.close)+ guard !canShowOptions else {return}- if shouldOpenNotificationOptionsAfterAuthorization {- shouldOpenNotificationOptionsAfterAuthorization = false- onNotificationOptionsAction(.open)- }- }- .onChange(of: notificationSettings.isAuthorizationDenied) { _, isDenied in- if isDenied {- shouldOpenNotificationOptionsAfterAuthorization = false- onNotificationOptionsAction(.close)- }- }- }-- func setNotificationsEnabled(_ enabled: Bool) {- notificationSettings.setEnabled(enabled)- if enabled, notificationSettings.canShowOptions {- shouldOpenNotificationOptionsAfterAuthorization = false- onNotificationOptionsAction(.open)- } else {- shouldOpenNotificationOptionsAfterAuthorization = enabled- && !notificationSettings.isAuthorizationDenied- onNotificationOptionsAction(.close)+ onOptionsAction(.close(panel: .notification))}}@@ -809,6 +807,8 @@ private extension AppSettingsView {}}+ // MARK: - 关于页+var versionRow: some View {let status = versionStatusdiff --git a/CodexBar/Views/Settings/KeepAliveOptionsView.swift b/CodexBar/Views/Settings/KeepAliveOptionsView.swiftnew file mode 100644index 0000000..8ea68ef--- /dev/null+++ b/CodexBar/Views/Settings/KeepAliveOptionsView.swift@@ -0,0 +1,108 @@+import SwiftUI++/// 防休眠子选项面板, 挂在设置窗口右侧, 顶边对齐设置页的防休眠主开关行+/// 行样式与度量沿用通知子面板, 只有面板宽度按内容收窄+struct KeepAliveOptionsView: View {+ @ObservedObject var keepAliveController: KeepAliveController++ var body: some View {+ VStack(alignment: .leading, spacing: Metrics.rowSpacing) {+ maximumDurationRow++ // 台式机读不到电池, 这一行整个收起而不是置灰+ if keepAliveController.hasBattery {+ lowBatteryRow+ }+ }+ .padding(.horizontal, Metrics.horizontalPadding)+ .padding(.vertical, Metrics.verticalPadding)+ .frame(width: Metrics.panelWidth, alignment: .topLeading)+ .sidePanelChrome(cornerRadius: Metrics.cornerRadius)+ }++ /// 按有电池时的最大内容给初始值, 实际高度在展开前由 fitting size 覆盖+ static var initialPanelSize: CGSize {+ CGSize(+ width: Metrics.panelWidth,+ height: Metrics.verticalPadding * 2+ + (Metrics.rowHeight + Metrics.captionRowHeight) * 2+ + Metrics.rowSpacing+ )+ }++ private var maximumDurationRow: some View {+ pickerRow(+ title: "最长防休眠时间",+ caption: "防休眠时长超过阈值后自动恢复系统休眠",+ selection: Binding(+ get: { keepAliveController.maximumDuration },+ set: { keepAliveController.setMaximumDuration($0) }+ ),+ options: KeepAliveController.MaximumDuration.allCases,+ label: \.title+ )+ }++ private var lowBatteryRow: some View {+ pickerRow(+ title: "低电量保护",+ caption: "仅在使用电池供电时生效, 充电时自动恢复",+ selection: Binding(+ get: { keepAliveController.lowBatteryThreshold },+ set: { keepAliveController.setLowBatteryThreshold($0) }+ ),+ options: KeepAliveController.LowBatteryThreshold.allCases,+ label: \.title+ )+ }++ /// 第二行的固定说明与通知子面板的音效子行同一套字号和层级+ private func pickerRow<Option: Hashable>(+ title: String,+ caption: String,+ selection: Binding<Option>,+ options: [Option],+ label: KeyPath<Option, String>+ ) -> some View {+ VStack(spacing: 0) {+ HStack(spacing: Metrics.controlSpacing) {+ Text(title)+ .font(.caption)+ .foregroundStyle(.secondary)++ Spacer(minLength: 8)++ SettingsOptionsPicker(+ title: title,+ selection: selection,+ options: options,+ label: { $0[keyPath: label] },+ width: Metrics.pickerWidth,+ alignment: .trailing+ )+ }+ .frame(height: Metrics.rowHeight)++ HStack(spacing: 0) {+ Text(caption)+ .font(.caption2)+ .foregroundStyle(.tertiary)++ Spacer(minLength: 0)+ }+ .frame(height: Metrics.captionRowHeight)+ }+ }++ private enum Metrics {+ static let panelWidth: CGFloat = 250+ static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPadding+ static let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding+ static let rowSpacing = SettingsOptionsPanelMetrics.rowSpacing+ static let rowHeight = SettingsOptionsPanelMetrics.rowHeight+ static let captionRowHeight = SettingsOptionsPanelMetrics.secondaryRowHeight+ static let controlSpacing = SettingsOptionsPanelMetrics.controlSpacing+ static let pickerWidth: CGFloat = 88+ static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius+ }+}diff --git a/CodexBar/Views/Settings/NotificationOptionsView.swift b/CodexBar/Views/Settings/NotificationOptionsView.swiftindex 64cda0a..a9b932e 100644--- a/CodexBar/Views/Settings/NotificationOptionsView.swift+++ b/CodexBar/Views/Settings/NotificationOptionsView.swift@@ -1,12 +1,13 @@import AppKitimport SwiftUI-/// 通知子选项面板, 挂在设置窗口右侧并与设置内容区底边对齐+/// 通知子选项面板, 挂在设置窗口右侧, 顶边对齐设置页的通知主开关行/// 通知开启时展开音效子行, 关闭时连同占位一起收起struct NotificationOptionsView: View {@ObservedObject var notificationSettings: NotificationSettings@ObservedObject var codexHookSettings: CodexHookSettings@ObservedObject var codexCLINotificationSettings: CodexCLINotificationSettings+ @ObservedObject var keepAliveController: KeepAliveController@State private var previewSound: NSSound?var body: some View {@@ -16,6 +17,7 @@ struct NotificationOptionsView: View {lowQuotaRowquotaResetRowcreditExpiryRow+ lowBatteryRowtaskHapticRowcodexCLINotificationRow}@@ -26,10 +28,6 @@ struct NotificationOptionsView: View {.onDisappear(perform: stopPreview)}- static var panelCornerRadius: CGFloat {- Metrics.cornerRadius- }-static var initialPanelSize: CGSize {CGSize(width: Metrics.panelWidth,@@ -40,6 +38,8 @@ struct NotificationOptionsView: View {)}+ // MARK: - 各通知行+private var lowQuotaRow: some View {notificationOptionRow(title: "额度预警通知",@@ -152,6 +152,28 @@ struct NotificationOptionsView: View {)}+ /// 低电量保护关着时显示为关闭并置灰, 不修改持久化的 isLowBatteryEnabled+ /// 保护默认就是关的, 不置灰会让这一行在任何默认安装上都亮着, 而对应通知永远发不出来+ /// "保护是不是真的在起作用"由 KeepAliveController 判定, 这里只读结论+ /// 它同时覆盖了台式机: 那时防休眠面板整行隐藏低电量保护, 而阈值可能是从笔记本迁移过来的非 off 值+ private var lowBatteryRow: some View {+ let isProtectionOn = keepAliveController.isLowBatteryProtectionEnabled+ let isDisplayedOn = isProtectionOn && notificationSettings.isLowBatteryEnabled++ return notificationOptionRow(+ title: "低电量保护通知",+ isOn: Binding(+ get: { isDisplayedOn },+ set: { notificationSettings.setLowBatteryEnabled($0) }+ ),+ isEnabled: isProtectionOn,+ sound: Binding(+ get: { notificationSettings.lowBatterySound },+ set: { notificationSettings.setLowBatterySound($0) }+ )+ )+ }+private var codexCLINotificationRow: some View {optionRow(title: "Codex TUI 通知",@@ -174,6 +196,8 @@ struct NotificationOptionsView: View {}}+ // MARK: - 行构建器+private func optionRow(title: String,isOn: Binding<Bool>,@@ -293,17 +317,17 @@ struct NotificationOptionsView: View {options: [Int],label: @escaping (Int) -> String) -> some View {- Picker(title, selection: selection) {- ForEach(options, id: \.self) { option in- Text(label(option)).tag(option)- }- }- .labelsHidden()- .pickerStyle(.menu)- .controlSize(.small)- .frame(width: Metrics.pickerWidth)+ SettingsOptionsPicker(+ title: title,+ selection: selection,+ options: options,+ label: label,+ width: Metrics.pickerWidth+ )}+ // MARK: - 音效选择与试听+private func soundMenu(selection: Binding<NotificationSoundOption>) -> some View {Menu {soundMenuButton(.systemDefault, selection: selection)@@ -377,21 +401,21 @@ struct NotificationOptionsView: View {private enum Metrics {static let panelWidth: CGFloat = 320- static let horizontalPadding: CGFloat = 12- static let verticalPadding: CGFloat = 10- static let notificationRowCount = 5+ static let horizontalPadding = SettingsOptionsPanelMetrics.horizontalPadding+ static let verticalPadding = SettingsOptionsPanelMetrics.verticalPadding+ static let notificationRowCount = 6static let standardRowCount = 2static let totalRowCount = notificationRowCount + standardRowCount- static let rowSpacing: CGFloat = 5- static let rowHeight: CGFloat = 22- static let soundRowHeight: CGFloat = 18+ static let rowSpacing = SettingsOptionsPanelMetrics.rowSpacing+ static let rowHeight = SettingsOptionsPanelMetrics.rowHeight+ static let soundRowHeight = SettingsOptionsPanelMetrics.secondaryRowHeightstatic let notificationRowHeight = rowHeight + soundRowHeight- static let notificationControlSpacing: CGFloat = 6+ static let notificationControlSpacing = SettingsOptionsPanelMetrics.controlSpacingstatic let pickerWidth: CGFloat = 68static let soundMenuWidth: CGFloat = 160static let soundPreviewButtonSize: CGFloat = 18static let soundPreviewIconSize: CGFloat = 13static let statusIconSize: CGFloat = 16- static let cornerRadius: CGFloat = 12+ static let cornerRadius = SettingsOptionsPanelMetrics.cornerRadius}}diff --git a/CodexBar/Views/Settings/SettingsToggleRow.swift b/CodexBar/Views/Settings/SettingsToggleRow.swiftindex e8561e6..5327691 100644--- a/CodexBar/Views/Settings/SettingsToggleRow.swift+++ b/CodexBar/Views/Settings/SettingsToggleRow.swift@@ -6,6 +6,42 @@ enum SettingsRowMetrics {static let spacing: CGFloat = 10}+/// 设置窗口右侧两个子选项面板共用的度量+/// 两个面板要看起来是同一套控件, 所以除了面板宽度和 picker 宽度以外都从这里取+enum SettingsOptionsPanelMetrics {+ static let horizontalPadding: CGFloat = 12+ static let verticalPadding: CGFloat = 10+ static let rowSpacing: CGFloat = 5+ static let rowHeight: CGFloat = 22+ /// 第二行的高度, 通知面板用于音效子行, 防休眠面板用于固定说明+ static let secondaryRowHeight: CGFloat = 18+ static let controlSpacing: CGFloat = 6+ static let cornerRadius: CGFloat = 12+}++/// 两个子选项面板共用的下拉选择器+/// 只有宽度和对齐各自定义, 其余样式必须同源, 否则两个面板看起来就不是同一套控件+struct SettingsOptionsPicker<Option: Hashable>: View {+ let title: String+ @Binding var selection: Option+ let options: [Option]+ let label: (Option) -> String+ let width: CGFloat+ var alignment: Alignment = .center++ var body: some View {+ Picker(title, selection: $selection) {+ ForEach(options, id: \.self) { option in+ Text(label(option)).tag(option)+ }+ }+ .labelsHidden()+ .pickerStyle(.menu)+ .controlSize(.small)+ .frame(width: width, alignment: alignment)+ }+}+/// 设置页通用开关行, accessory 插入在开关左侧struct SettingsToggleRow<Accessory: View>: View {let icon: Stringdiff --git a/CodexBar/Views/Shared/LiquidGlassStyle.swift b/CodexBar/Views/Shared/LiquidGlassStyle.swiftindex 1701377..9b00fd0 100644--- a/CodexBar/Views/Shared/LiquidGlassStyle.swift+++ b/CodexBar/Views/Shared/LiquidGlassStyle.swift@@ -21,6 +21,8 @@ extension Color {}}+// MARK: - View 修饰符+/// 自绘 Liquid Glass 背景和 stale 状态修饰extension View {func liquidGlassSurface(@@ -117,6 +119,8 @@ struct LiquidGlassDivider: View {}}+// MARK: - 表面绘制+/// 自绘玻璃面板, 由底色, 高光, 纹理, 描边和阴影叠加组成private struct LiquidGlassSurface: View {let cornerRadii: RectangleCornerRadiidiff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex f4ef447..376ef65 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -60,6 +60,8 @@ private enum SleepRestoreTrigger: String {case helperTermination}+// MARK: - pmset 调用+private enum PmsetRunner {static func setSleepDisabled(_ disabled: Bool) -> PmsetResult {run(arguments: ["-a", "disablesleep", disabled ? "1" : "0"])@@ -174,6 +176,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Codeself.listener = listener}+ // MARK: - XPC 接口+func setSleepDisabled(_ disabled: Bool,reply: @escaping @Sendable (Int32, Bool) -> Void@@ -240,6 +244,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code}}+ // MARK: - 休眠切换与恢复+private func disableSleep() -> Int32 {var didCreateSentinel = false// 哨兵记的是接管前系统原本的 SleepDisabled, 恢复要还原到它而不是无脑写 0@@ -372,6 +378,8 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, Code}}+ // MARK: - 恢复哨兵+private func ensureSentinelDirectory() throws {let directoryURL = sentinelURL.deletingLastPathComponent()var info = stat()diff --git a/README.md b/README.mdindex 7ad5211..0c1eb6b 100644--- a/README.md+++ b/README.md@@ -24,7 +24,7 @@ CodexBar 把 Codex 的运行状态收进菜单栏: 账户信息, 剩余额度,## 特性-其中实时任务, 热力图面板中的详细统计数据与阻止系统休眠功能依赖 CodexBar Hook, 开启方式见[关于 Hook](#关于-hook)+其中实时任务, 热力图面板中的详细统计数据与防休眠功能依赖 CodexBar Hook, 开启方式见[关于 Hook](#关于-hook)### 账户信息@@ -50,17 +50,18 @@ CodexBar 把 Codex 的运行状态收进菜单栏: 账户信息, 剩余额度,- 开启 CodexBar Hook 后的会话还可统计对话轮次, 工具调用, 权限请求, 上下文压缩, 子 Agent 等指标- 可选开启 iCloud 同步, 在多台 Mac 之间同步数据-### 阻止系统休眠+### 防止系统休眠需要长时间运行 Codex 任务但是怕系统自动休眠?-- 仅在任务运行期间阻止系统休眠, 任务结束恢复系统休眠设置-- 可设置最长阻止休眠时间 1, 2, 4, 8, 12, 24 小时或无限制-- 阻止休眠状态可在主面板的任务卡片右侧显示一个咖啡杯标记+- 仅在任务运行期间防止系统休眠, 任务结束恢复系统休眠设置+- 可设置最长防休眠时间 1, 2, 4, 8, 12, 24 小时或无限制+- 可开启低电量保护, 使用电池且电量跌破阈值时恢复系统休眠, 接通电源后自动恢复防休眠+- 防休眠状态可在主面板的任务卡片右侧显示一个咖啡杯标记### 通知与提醒-- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期+- 本地通知: 额度预警, 额度重置, 任务等待批准, 任务完成, 手动重置即将过期, 低电量保护生效- 通知音效独立设置- 任务状态变化可设置触摸板震动反馈通知@@ -106,12 +107,12 @@ brew install --cask bob-zebedy/tap/codexbar> [!NOTE]> 不会影响任何原本的 Codex Hook-### 关于阻止系统休眠+### 关于防休眠开启后需要一个 Helper 进行守护, 因此首次开启时 macOS 会要求授权后台项目; 该功能同样依赖 CodexBar Hook> [!WARNING]-> 为了避免异常任务导致系统长时间处于阻止休眠的状态, 建议设置最长阻止休眠时间+> 为了避免异常任务导致系统长时间处于禁止休眠状态, 建议设置最长防休眠时间## 隐私@@ -151,7 +152,7 @@ flowchart LRB2 --> UIC3 --> UIC3 --> N["通知事件"]- C3 --> K["阻止休眠"]+ C3 --> K["防休眠"]```<details>diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftindex 0b0f0ed..358b366 100755--- a/Scripts/cleanup.swift+++ b/Scripts/cleanup.swift@@ -1,12 +1,22 @@#!/usr/bin/env swift+import AppKitimport Darwinimport Foundationimport ServiceManagement-private enum CleanupBuildConfiguration: String {- case debug = "Debug"+private enum CleanupBuildConfiguration: String, CaseIterable {case release = "Release"+ case debug = "Debug"++ var bundleIdentifier: String {+ switch self {+ case .release:+ "app.zabrian.codexbar"+ case .debug:+ "app.zabrian.codexbar.debug"+ }+ }}private struct CleanupTarget {@@ -46,14 +56,14 @@ private enum CleanupError: LocalizedError {}private struct CleanupOptions {- var releaseAppURL = URL(fileURLWithPath: "/Applications/CodexBar.app")- var debugAppURL: URL?- var cleansRelease = true- var cleansDebug = true+ var selectedConfigurations: Set<CleanupBuildConfiguration> = []var signingIdentity = ProcessInfo.processInfo.environment["CODEXBAR_CLEANUP_SIGN_IDENTITY"]?? "Apple Development"- var isDryRun = falsevar isCheckOnly = false++ func includes(_ configuration: CleanupBuildConfiguration) -> Bool {+ selectedConfigurations.isEmpty || selectedConfigurations.contains(configuration)+ }}private final class KeepAliveCleanupCommand {@@ -65,35 +75,18 @@ private final class KeepAliveCleanupCommand {}func run(arguments: [String]) throws {- var options = try parseOptions(arguments)- if options.cleansDebug, options.debugAppURL == nil {- options.debugAppURL = try resolveBuiltAppURL(configuration: .debug)- }-- let requestedTargets = try makeTargets(options: options)- var targets: [CleanupTarget] = []- for target in requestedTargets {- guard try validate(target) else {- print(- "清理跳过: bundle=\(target.bundleIdentifier), reason=App 不存在, path=\(target.appURL.path)"- )- continue- }- targets.append(target)- print("清理目标: bundle=\(target.bundleIdentifier), path=\(target.appURL.path)")- }+ let options = try parseOptions(arguments)+ let targets = try makeTargets(options: options)guard !targets.isEmpty else {print("清理完成: 没有可用目标")return}- if options.isDryRun {- return- }-- if !options.isCheckOnly, isCodexBarRunning() {- throw CleanupError.message("CodexBar 仍在运行")+ let runningTargets = runningTargets(in: targets)+ if !options.isCheckOnly, !runningTargets.isEmpty {+ let bundleIdentifiers = runningTargets.map(\.bundleIdentifier).joined(separator: ", ")+ throw CleanupError.message("CodexBar 仍在运行, bundle=\(bundleIdentifiers)")}let temporaryRoot = fileManager.temporaryDirectory@@ -118,55 +111,25 @@ private final class KeepAliveCleanupCommand {isCheckOnly: options.isCheckOnly)}-- if options.isCheckOnly {- print("清理验证完成: 后台服务未注销")- } else {- print("后台服务已注销: 系统设置记录可能延迟清除")- }}private func parseOptions(_ arguments: [String]) throws -> CleanupOptions {var options = CleanupOptions()- var index = 0-- while index < arguments.count {- switch arguments[index] {- case "--release-app":- index += 1- guard index < arguments.count, !arguments[index].isEmpty else {- throw CleanupError.message("选项参数缺失, option=--release-app")- }- options.releaseAppURL = URL(fileURLWithPath: arguments[index])- case "--debug-app":- index += 1- guard index < arguments.count, !arguments[index].isEmpty else {- throw CleanupError.message("选项参数缺失, option=--debug-app")- }- options.debugAppURL = URL(fileURLWithPath: arguments[index])- case "--release-only":- options.cleansRelease = true- options.cleansDebug = false- case "--debug-only":- options.cleansRelease = false- options.cleansDebug = true- case "--sign-identity":- index += 1- guard index < arguments.count, !arguments[index].isEmpty else {- throw CleanupError.message("选项参数缺失, option=--sign-identity")- }- options.signingIdentity = arguments[index]- case "--dry-run":- options.isDryRun = true++ for argument in arguments {+ switch argument {+ case "--release":+ options.selectedConfigurations.insert(.release)+ case "--debug":+ options.selectedConfigurations.insert(.debug)case "--check":options.isCheckOnly = truecase "-h", "--help":printUsage()Darwin.exit(EXIT_SUCCESS)default:- throw CleanupError.message("未知选项, value=\(arguments[index])")+ throw CleanupError.message("未知选项, value=\(argument)")}- index += 1}return options@@ -180,44 +143,76 @@ private final class KeepAliveCleanupCommand {仅注销 CodexBar 的 Release 和 Debug KeepAlive LaunchDaemonOptions:- --release-app PATH Release CodexBar.app, 默认 /Applications/CodexBar.app- --debug-app PATH Debug CodexBar.app, 默认使用当前 Xcode Debug 产物- --release-only 只移除 Release Helper- --debug-only 只移除 Debug Helper- --sign-identity NAME 临时清理 App 的本机签名身份, 默认 Apple Development- --dry-run 只显示目标- --check 只编译和验证临时清理 App, 不注销服务- -h, --help 显示帮助-- 实际清理前请先退出所有 CodexBar 实例+ --release 只移除 Release Helper+ --debug 只移除 Debug Helper+ --check 只检查目标+ -h, --help 显示帮助++ 不指定 --release 或 --debug 时同时处理两个目标+ 实际清理前请先退出待清理的 CodexBar 实例""")}private func makeTargets(options: CleanupOptions) throws -> [CleanupTarget] {- var targets: [CleanupTarget] = []- if options.cleansRelease {- targets.append(- CleanupTarget(- appURL: options.releaseAppURL,- bundleIdentifier: "app.zabrian.codexbar",- buildConfiguration: .release+ try CleanupBuildConfiguration.allCases+ .filter(options.includes)+ .compactMap { configuration in+ let bundleIdentifier = configuration.bundleIdentifier+ guard let appURL = try resolveAppURL(configuration: configuration) else {+ print("清理跳过: bundle=\(bundleIdentifier), reason=未找到 App")+ return nil+ }++ print("清理目标: bundle=\(bundleIdentifier), path=\(appURL.path)")+ return CleanupTarget(+ appURL: appURL,+ bundleIdentifier: bundleIdentifier,+ buildConfiguration: configuration)- )+ }+ }++ /// 候选按可信度排序, 命中的唯一标准是 Info.plist 里的 CFBundleIdentifier 对得上+ /// 这里就是唯一的 App 校验点: 读到 Info.plist 即说明是个目录, 标识符对上即说明是这个 App+ private func resolveAppURL(configuration: CleanupBuildConfiguration) throws -> URL? {+ let bundleIdentifier = configuration.bundleIdentifier+ var candidates: [URL] = []+ if configuration == .release {+ candidates.append(URL(fileURLWithPath: "/Applications/CodexBar.app"))}- if options.cleansDebug {- guard let debugAppURL = options.debugAppURL else {- throw CleanupError.message("无法定位 Xcode Debug App")+ if let registeredURL = NSWorkspace.shared.urlForApplication(+ withBundleIdentifier: bundleIdentifier+ ) {+ candidates.append(registeredURL)+ }+ if configuration == .release {+ candidates.append(projectURL.appending(path: "build/CodexBar.app"))+ }++ for candidate in candidates {+ if try appBundleIdentifier(at: candidate) == bundleIdentifier {+ return candidate}- targets.append(- CleanupTarget(- appURL: debugAppURL,- bundleIdentifier: "app.zabrian.codexbar.debug",- buildConfiguration: .debug- )- )}- return targets++ // xcodebuild 定位不到是"查不到"而不是数据损坏, 保持非致命+ guard let builtAppURL = try? resolveBuiltAppURL(configuration: configuration) else {+ return nil+ }+ return try appBundleIdentifier(at: builtAppURL) == bundleIdentifier ? builtAppURL : nil+ }++ /// 返回 nil 只代表这个路径下没有 App, 属于正常跳过+ /// 读到了却解析不了必须抛出去: 用 try? 折叠成 nil 会把损坏的安装当成"不是这个 App",+ /// 于是一次什么都没清理的运行照样打印完成并以 0 退出+ private func appBundleIdentifier(at appURL: URL) throws -> String? {+ let infoURL = appURL.appending(path: "Contents/Info.plist")+ guard fileManager.fileExists(atPath: infoURL.path) else {+ return nil+ }++ return try propertyListDictionary(at: infoURL)["CFBundleIdentifier"] as? String}private func resolveBuiltAppURL(configuration: CleanupBuildConfiguration) throws -> URL {@@ -251,27 +246,6 @@ private final class KeepAliveCleanupCommand {.map { String($0.dropFirst(prefix.count)) }}- private func validate(_ target: CleanupTarget) throws -> Bool {- var isDirectory: ObjCBool = false- guard fileManager.fileExists(atPath: target.appURL.path, isDirectory: &isDirectory) else {- return false- }- guard isDirectory.boolValue else {- throw CleanupError.message(- "App 类型错误, actual=file, expected=directory, path=\(target.appURL.path)"- )- }-- let info = try propertyListDictionary(at: target.appURL.appending(path: "Contents/Info.plist"))- let actualIdentifier = info["CFBundleIdentifier"] as? String ?? "missing"- guard actualIdentifier == target.bundleIdentifier else {- throw CleanupError.message(- "App 标识符错误, actual=\(actualIdentifier), expected=\(target.bundleIdentifier), path=\(target.appURL.path)"- )- }- return true- }-private func resolveHelperSourceURL(for target: CleanupTarget) throws -> URL {let bundledHelperURL = helperURL(in: target.appURL)if fileManager.isExecutableFile(atPath: bundledHelperURL.path) {@@ -292,8 +266,12 @@ private final class KeepAliveCleanupCommand {appURL.appending(path: "Contents/Resources/CodexBarHelper")}- private func isCodexBarRunning() -> Bool {- (try? run("/usr/bin/pgrep", ["-x", "CodexBar"], capturesOutput: true).status) == 0+ private func runningTargets(in targets: [CleanupTarget]) -> [CleanupTarget] {+ targets.filter { target in+ !NSRunningApplication.runningApplications(+ withBundleIdentifier: target.bundleIdentifier+ ).isEmpty+ }}private func prepareAndRun(@@ -349,7 +327,7 @@ private final class KeepAliveCleanupCommand {"--sign", signingIdentity,destinationHelperURL.path],- failureReason: "Helper 签名失败"+ failureReason: "签名 Helper 失败")try runCodeSigningChecked([@@ -359,7 +337,7 @@ private final class KeepAliveCleanupCommand {"--sign", signingIdentity,cleanupAppURL.path],- failureReason: "清理 App 签名失败"+ failureReason: "签名 App 失败")let cleanupTeamIdentifier = try signingTeamIdentifier(for: cleanupAppURL)@@ -370,7 +348,7 @@ private final class KeepAliveCleanupCommand {}try runCodeSigningChecked(["--verify", "--strict", "--verbose=2", cleanupAppURL.path],- failureReason: "清理 App 验证失败"+ failureReason: "验证 App 签名失败")if isCheckOnly {diff --git a/appcast.xml b/appcast.xmlindex 68f3ba3..14c2252 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.7</title>+ <sparkle:version>61</sparkle:version>+ <sparkle:shortVersionString>3.5.7</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.7</sparkle:releaseNotesLink>+ <pubDate>Wed, 29 Jul 2026 22:35:50 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.7.dmg" sparkle:edSignature="x7G0gxH2UBgUEKVK25EhibiVyfexk2JOshkWOxXUdjkE/pMsfZuCLwxX+SdSfcvDKsVAFp4Xu0Qfm1lEh4SvCg==" length="5996332" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.5.6</title><sparkle:version>60</sparkle:version>